From a51201d0d02d9020f3ecbcd201de8ffd9b4802c5 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 17:42:09 -0600 Subject: [PATCH 01/30] Record the plan and decisions for the iPhone and Android library. The approved plan for issue 64 goes into the 3.0.0 appendix with its links fixed. D325 to D333 record the choices the plan left for the start of the work: UniFFI bindings in version 3.0.0, built on the core of D312; one reader interface for calculations, with the core holding their arithmetic; the phone storage binding; where a phone keeps its file; the boundary types; the host client and its sign-in; platform floors; release packaging; and one shared test bundle. Co-Authored-By: Claude Opus 5.5 --- build-history/README.md | 2 +- .../v3.0.0/appendix/mobile-library-plan.md | 95 +++++++ build-history/v3.0.0/decisions.md | 261 ++++++++++++++++++ build-history/v3.0.0/progress.md | 6 + 4 files changed, 363 insertions(+), 1 deletion(-) create mode 100644 build-history/v3.0.0/appendix/mobile-library-plan.md diff --git a/build-history/README.md b/build-history/README.md index 4a04d123..22f0e905 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -41,7 +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). | -| [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). | +| [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. The iPhone and Android packages are being built under the same version ([plan](v3.0.0/appendix/mobile-library-plan.md)). 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/v3.0.0/appendix/mobile-library-plan.md b/build-history/v3.0.0/appendix/mobile-library-plan.md new file mode 100644 index 00000000..606e808d --- /dev/null +++ b/build-history/v3.0.0/appendix/mobile-library-plan.md @@ -0,0 +1,95 @@ +# Athletic Standard on iPhone and Android + +The approved implementation plan for [issue 64](https://github.com/mwhitham/ath/issues/64). +It is copied here from the planning draft. Only the links changed, to work from this +folder. D325 to D333 record the decisions it asked for at implementation start. It was +written against 2.1.3; D312 has since made the core it asks for. + +An athlete can create or pick an `.ath.sqlite` file on their phone, record a workout offline, close the app, and reopen the file with the edit intact. An app can also offer **Connect to a host** to sign in and work directly with a hosted record. Swift and Kotlin use the existing Rust store for local files and the storage-free library for in-memory checks and calculations. Both platforms ship with each release. + +## Choosing where to keep the file + +Recommend local storage in the mobile integration guide and picker examples. Keep iCloud Drive selectable wherever the Files picker offers it. Suggested wording: “We recommend keeping your working file on this device. Editing the same file on two devices through iCloud Drive can cause sync conflicts.” + +- **Local folder.** Open the database in place when the app has a stable local path, SQLite locking, and permission to access its companion files. A successful edit commits immediately. Reopening the file must show the edit after an app restart. +- **File picked from another location.** Let the platform handle the user’s file permission. On iOS, coordinate reads and writes to external documents. On Android, use the document provider’s content URI. If the provider only exposes a single document or byte stream, open a self-contained database in a private working folder. Save a verified SQLite snapshot back through the provider. Tell the caller when the local edit has committed and when the selected document has been saved. [Apple document picker](https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller) · [Android document access](https://developer.android.com/training/data-storage/shared/documents-files) +- **Conflicts and interrupted saves.** Check the original document for external changes before replacement, using a provider version or a content digest from open. Where the provider cannot safely replace the checked version, support Save a Copy. Keep local edits if access expires, the provider is offline, or a write fails. File sync can still create competing copies after two offline edits. +- **What travels with the file.** Use the store’s verified backup for a single-file save. Committed edits may still be in SQLite’s companion log. A copy of the main file from an active database can miss them. Attachment records travel in the database, but their files live alongside it. Document the existing complete package export for transfers that include attachment files. [Backup implementation](../../../src/store/backup.rs) · [Portable format and backups](../../../SPEC.md) + +## Connecting to ath-host with WorkOS + +**For the athlete.** Open a local file to work offline without an account. To use a hosted record, tap **Connect to a host**, sign in through the system browser and choose an athlete record. An app with a known host can supply its address in advance. Show the operator information published by that host. + +**For the app developer.** Ship an optional host client with the same short setup in Swift and Kotlin. Give it the host URL, the app’s registered public client ID and callback URL, then call sign in. The client reads the host’s capabilities and sign-in provider, completes browser sign-in, and calls `GET /v1/me` to list owned records. Apps with an existing compatible session can instead supply a callback that returns a fresh access token issued for this host and app. Promote the Swift example’s existing client and test the Kotlin counterpart against the published host API. [Swift example](../../../examples/host-swift/README.md) · [Host API contract](../../../schema/host-api/1/openapi.json) + +**One-time WorkOS setup.** Register the native application as a public OAuth application under WorkOS Connect. Register each callback URL exactly. Set the host’s public HTTPS URL as the WorkOS Resource Indicator and the host’s expected audience. Configure the host with the AuthKit issuer and its `/oauth2/jwks` signing keys. If the host restricts client IDs, include the registered IDs. The host checks the WorkOS user’s identity and applies the athlete’s grants on every request. A coach grant names a client ID; distinct iOS and Android registrations need their own grant for that coach. [Host setup guide](../../../docs/hosting.md#65-recipe-workos-authkit) · [WorkOS public apps](https://workos.com/docs/authkit/connect/oauth) · [WorkOS token claims](https://workos.com/docs/authkit/connect/token-claims) + +**What the client handles.** Use provider discovery and a native OAuth library for the authorization code flow with S256 PKCE. This ties the returned code to the phone that started sign-in. Verify the callback belongs to the pending sign-in. Send only the user access token intended for the host on host requests. Keep refresh credentials in the iOS Keychain or Android Keystore-backed storage, outside athlete files and exports. Support refresh, cancelled sign-in and sign-out. Local record checks and SQLite operations stay usable offline. + +**What happens to an edit.** An online owner write goes through the host API. A correction carries the revision the user edited. Preserve the exact request bytes and retry key across a lost reply, and keep the user’s edit for review if the host reports a stale revision. A coach reads only granted summaries or submits permitted notes and plans. The host enforces those limits. [Owner routes](../../../docs/hosting.md#74-owner-routes) · [Swift grant and retry examples](../../../examples/host-swift/README.md) + +**Offline copies of hosted records.** Connecting and signing in does not link an existing local file or start uploading its contents. Issue 58 tracks owner synchronization for the CLI. Coordinate any later mobile sync work with it: use a verified full export for the first download, track the last verified revision and manifest digest, and preserve both copies when edits diverge. Full export is an owner operation. Direct online access can ship independently. [Refresh rules, D263](../../v2.1.3/decisions.md#d263-a-device-refresh-compares-content-not-only-the-database-revision) · [Issue 58](https://github.com/mwhitham/ath/issues/58) + +## What the app calls + +| Operation | Caller supplies | Library returns | +|---|---|---| +| Connect to a host | Host URL and native sign-in settings, or a callback for an existing host access token | A signed-in host client with owner record selection and a coach roster for granted access | +| Create, open and close a database | A local destination or a document chosen through the phone’s picker, plus the access mode | A store handle with database identity, revision and write availability, or a specific open error | +| Read and edit records | Store handle, record ID or list options, or a create, correct or delete request with the applicable expected revision | Current records or the committed revision; a stale edit returns the existing conflict | +| Calculate from a database | Store handle and the same skill or range request used in memory | The desktop result or receipt from one consistent database read | +| Save a database copy | Store handle and selected destination | A verified single-file snapshot and save status | +| Validate | A published shape name and UTF-8 JSON, with a convenience call for a complete current record | The checked JSON on success, or the ordered issues with field path, code and message | +| Open a calculation snapshot | Current-record JSON, including source and athlete profile records, sample records, IDs, creation times, deletion flags and revision numbers | An immutable, reusable in-memory object owned by Rust | +| Apply | Snapshot, target record ID, and a shipped skill name or explicit calculation skill text | The existing apply result, including fields read, missing inputs, exclusions, method notices and evidence where applicable | +| Calculate | Snapshot and typed range options covering the existing desktop options | The existing calculation receipt with its sources, counts, units and revision references | + +Use generated UniFFI types for operations, options, issues and failure kinds. Carry record bodies and result documents as UTF-8 JSON bytes. This keeps extensions, numeric parsing and the published receipt shapes under Rust’s control. Use the existing JSON parser and writer. Distinguish malformed JSON, invalid records and refused calculations. Preserve string and numeric field-path segments and the existing messages. + +Build the snapshot from batches with an explicit finish operation so apps can supply samples without one large cross-language call. Reject duplicate current IDs and invalid record envelopes before exposing a snapshot. A failed batch must leave the builder usable with its prior contents. Treat supplied records as the complete data available for that calculation. Document how a missing source, linked record or profile affects each operation, using desktop behavior as the reference. A successful single-record check covers the shape and its own rules. Checking a reference to another record requires the referenced data. Database writes, revision history checks at commit, sync and attachment files stay with their current owners. + +## Code ownership and desktop compatibility + +Add a storage-free Rust workspace crate for the model, JSON rules, calculation definitions, methods, calendar arithmetic and receipts. Add a small UniFFI crate depending on that core. Keep the current Rust public module paths available through re-exports. Keep database reads, file discovery, the CLI and host in the existing crates. Use a core error type with an adapter to desktop errors. The current desktop error type includes SQLite and migration state. + +Expose a separate mobile storage binding for the existing Rust store, its checked writes and its backup operation. Isolate the required store dependencies so selecting SQLite does not pull in the CLI, host or network runtime. Serialize calls to each store handle and close it explicitly. Preserve read-only access, stale revision errors and the existing migration preview and verified-backup rules for older databases. File picker code belongs in the platform wrappers. [Store](../../../src/store/mod.rs) · [Checked writes](../../../src/store/write.rs) + +Define the data requests each method needs in Rust. Use the existing indexed SQLite queries for desktop and phone databases. Use immutable indexes for records supplied in memory. Share request validation, ordering rules, arithmetic and receipt construction. Keep database filters and limits inside indexed queries and keep each calculation inside one read snapshot. Test the two readers against the same data whenever SQL implements a filter. + +Embed the shipped calculation descriptions at build time. Desktop keeps its installed-skill lookup and passes the chosen text to the core. Mobile reads shipped text or text supplied by the caller. Pass the profile time zone into calendar logic and use bundled zone data. Audit clock fallbacks so a phone’s current date or system zone cannot silently change an answer. + +Relevant owners today are [the model](../../../src/model/), [single-record input selection](../../../src/calculate/record.rs), [range queries and receipts](../../../src/calculate/range.rs), [calendar rules](../../../src/view/calendar.rs) and [desktop snapshot tests](../../../src/calculate/snapshot_tests.rs). + +## Build order and acceptance tests + +| Step | Deliverable | Pass condition | +|---|---|---| +| 1. Validate from installed packages | Extract the model and build the smallest real Swift package and Android library. Generate bindings and libraries with the same locked UniFFI version. Start the simulator, emulator and local package installation jobs here. | Both consumers accept a measured record with a source, reject a missing required source, and reject an athlete report claiming a source. Both return the desktop issue paths. Build the standalone calculation binding with no SQLite, file access, HTTP client or CLI. | +| 1a. Use a real athlete file | Expose the SQLite binding in both packages. Create a local database, open an existing desktop file from the picker, read a record, write a correction, close, reopen and save a copy. | On each OS, reopen after an app restart, then open the phone-saved file with desktop `ath` and check its ID, records and revisions. Test read-only and outdated files, stale writes, and a verified save with outstanding log entries. Simulate an external change and a failed provider save; recover the local edit. Check the iCloud picker path on a signed-in device before release. | +| 1b. Connect from either phone | Package the host client and browser sign-in helper. Provide one runnable example per platform that signs in, picks an owned record, reads it and saves an edit. | Run both clients against a real `ath-host` in CI with test credentials. Check retry after a lost reply, stale correction, revoked coach access and a disconnected owner app. Before marking WorkOS support verified, run native sign-in, refresh and a host read/write against a live WorkOS test environment on both platforms. Record the result with [issue 57](https://github.com/mwhitham/ath/issues/57), including rejection of an expired token and tokens for the wrong audience, issuer or app. | +| 2. Apply all single-record skills | Add the snapshot and start with a method that reads only the target. Then move linked-workout lookup, earlier windows, same-source sessions, profile lookup and within-session heart-rate samples. Keep the existing operation names and arithmetic, including older methods. | Both phones pass every single-record worked example. Change the supplied revision, remove a linked workout, supply two sources, and edit a skill’s settings. Compare the full results and failures with desktop. Exercise malformed, unknown, coaching and range skill inputs. | +| 3. Calculate over time windows | Move summary, baseline, trend and coverage. Preserve per-source ordering, manual-source exclusion, deleted record filtering, units, grouping and calendar boundaries. | Both phones agree with SQLite for points and samples, tied timestamps, empty windows, daylight-saving changes and a missing profile zone. Keep SDNN and RMSSD distinct. Check the existing 100,000-input limit and the 1,000-reference receipt cap at the boundary and one beyond. Desktop query-plan and concurrent-write snapshot tests still pass. | +| 4. Finish the range operations | Add compare-sources, correlation, workout-drift and provider-period-summary. Reuse the same two-source pairing, daily means, workout bounds and exact provider reporting periods. | All eight range operations run from both bindings. Test mismatched units, unpaired days, a deleted workout, and periods which cross local midnight. Compare the complete receipt, including method text, evidence order, total count and truncation. | +| 5. Prove coverage and publish | Run all applicable existing cases through installed packages. Stage and install both release candidates. Add the two artifacts to the existing release gate. | Publish only the bytes installed and tested. A clean app can resolve each public version, run an offline example, and report the expected library version. | + +Start host client work from the published API while the Rust core is being extracted. Steps 1a, 2 and 3 can proceed independently once step 1 fixes the shared record contract. Start release packaging and namespace setup in step 1. Step 4 uses the range reader from step 3. Step 5 includes the real-file round trip and the host client tests. Run each calculation suite through both the memory and database entry points on both platforms. + +## Test data and verification + +Use one desktop fixture exporter for the existing short-form examples. Reuse the test lab to expand aliases and produce full current records with repeatable IDs. Export requests and expected outcomes, including expected failures. Run the same bundle through ordinary Swift and Kotlin package calls. Keep expected values from the checked-in examples and golden tests as an independent check on the desktop result. Generate test bundles during testing from synthetic inputs. + +The starting inventory is 7,399 cases in 140 model vector files, 32 worked calculation blocks across 24 calculation skills, and 20 coaching record-example blocks. Discover cases each run. Apply the desktop harness’s documented historical exceptions and message adjustments on every platform. Report the exact run, skip and failure counts by suite. Fail on a new skip, a missing skill, or a mismatch. Include the newer record rules covered outside the historical vectors. [Model vector harness](../../../tests/model_vectors.rs) · [Skill example harness](../../../tests/skill_examples.rs) · [Calculation golden tests](../../../tests/calculate_golden.rs) + +Build device and simulator binaries in CI. Execute the full suites on an iPhone simulator and Android emulator, offline after installation. Measure snapshot creation time, peak memory and repeated calls on a synthetic sample-heavy record. Check that releasing the snapshot frees its native allocations. Compare desktop performance before and after on the same workload. Preserve its indexed query checks. Run the repository’s Rust formatting, Clippy, workspace tests and npm checks before each commit. Run the required generated-file check when moving the model. Compare the published schema, protocol and desktop outputs against the starting revision. + +## How a release reaches an app + +**Swift.** Proposed support starts at iOS 17, matching the existing Swift host example. Build arm64 for iPhone and arm64 and x86_64 for simulators. Package device and simulator libraries, headers and module map as an XCFramework. Stage its ZIP and checksum alongside the matching generated Swift sources. Use a dedicated Swift package repository whose root manifest points to the versioned release asset. Its semantic version tag can then point to the finished manifest after the checksum is known. Test the same manifest against a staged copy, compare the checksum, then test version resolution from the public tag. The host example continues to demonstrate network access separately. [Apple binary package guide](https://developer.apple.com/documentation/xcode/distributing-binary-frameworks-as-swift-packages) + +**Android.** Proposed first targets are arm64-v8a for phones and x86_64 for the emulator, with minimum Android API 24. Publish an Android archive containing the generated Kotlin and both native libraries. Declare the pinned binding runtime in the Maven metadata so an app can resolve it. Check 16 KB alignment of every native dependency in the consumer APK and run on a 16 KB emulator. Test a release-mode consumer with shrinking enabled as well as the instrumented test build. Use Maven Central with a verified project namespace. Confirm namespace control, signing and publisher access before promising a public coordinate. [UniFFI Android dependencies](https://mozilla.github.io/uniffi-rs/latest/kotlin/gradle.html) · [Android native library checks](https://developer.android.com/guide/practices/page-sizes) · [Maven Central namespaces](https://central.sonatype.org/register/namespace/) + +**Release sequence.** Use the version already selected by the desktop release job. Pin the Rust, UniFFI, Xcode, Gradle and Android NDK toolchains used to build the artifacts. Produce hashes, source commit, target list and test counts in the release report. A branch run builds and installs from a temporary Swift package repository and local Maven repository without publisher credentials. The release job requires the desktop and mobile validation jobs. Upload the tested archive, publish the checked Maven bundle, tag the tested Swift manifest, then install from both public locations. Preserve the existing npm staging and approval flow. [Current release workflow](../../../.github/workflows/release-cross-platform.yml) + +Public registries can succeed independently. Record each completed publication and its digest. On retry, reuse the staged files, skip a matching published artifact and stop on a version with different bytes. Report a partial release until both public installs pass. A missing registry credential blocks publication only. Local builds, tests and staging can proceed. + +**Decisions to confirm at implementation start.** The mobile platform floors, supported architectures, Swift distribution repository and Maven namespace above are proposals. Check them against the available runners and maintainer-controlled publishing accounts. Record the accepted design and version in the project’s append-only build history before implementing it. This issue calls for new library packages and does not require a change to record fields or a database migration. diff --git a/build-history/v3.0.0/decisions.md b/build-history/v3.0.0/decisions.md index 06aa39d7..c9b30009 100644 --- a/build-history/v3.0.0/decisions.md +++ b/build-history/v3.0.0/decisions.md @@ -556,3 +556,264 @@ they run. The maintainer approved it on 2026-11-28. Rejected alternatives: - API version 2 for 3.0.0. Rejected because nothing an existing app uses changes. + +## D325. Phones get the library through UniFFI, in version 3.0.0 + +An iPhone app and an Android app call the Rust library through bindings that UniFFI +generates. The Swift package and the Android library hold no second implementation of +the record rules, checks, or calculations. Swift and Kotlin code adds only what each +platform owns: file pickers and file access, browser sign-in, and secure token storage. +This is [issue 64](https://github.com/mwhitham/ath/issues/64). The approved plan is +[mobile-library-plan.md](appendix/mobile-library-plan.md). + +This is the iPhone and Android build that D312 left for later. The packages report +library version 3.0.0 and ship with the 3.0.0 release, under the single version rule +(D152). They add no record field and no database migration. + +Rejected alternatives: + +- Write the rules again in Swift and Kotlin. Rejected because two more implementations + would each need every check and calculation kept equal to the desktop one. D208 made + the library the one implementation. +- Run the `ath` executable from the app. Rejected because iOS does not let an app start + another program, and Android apps cannot rely on it. +- Build the library to WebAssembly and run it in a JavaScript engine. Rejected because + it adds a runtime to each app and cannot open the SQLite file directly. +- Write a C interface and its Swift and Kotlin wrappers by hand. Rejected because UniFFI + generates both sides from one Rust definition, so a changed type cannot drift. + +## D326. Calculations ask for their data through one reader interface + +The calculation settings, methods, range arithmetic, receipts, calendar rules, and +shipped skill text move into D312's core, so a phone can calculate without SQLite. The +core gains an error type with the variants a calculation can produce: invalid, not +found, refused, and other. The desktop error type converts from it with the same codes +and messages, and keeps the SQLite, file, and migration variants. The `athleticstandard` +crate re-exports the moved modules, so its public paths stay the same. + +Each calculation names the data it needs as a typed request in the core: one current +record, other current records of the same source, records inside a window before a +record, the athlete profile, heart-rate samples during a session, range inputs, and +provider-period inputs. Two readers answer these requests. + +- The SQLite reader runs the existing indexed queries, unchanged, inside one read + snapshot. Desktop and phone databases both use it. +- The memory reader answers from immutable indexes built over records the caller + supplied. It applies the same filters and the same order as the SQL: deleted records + and manual sources are left out, and ties are broken by record ID. + +The core does everything else once: request checks, calendar boundaries, arithmetic, +limits, and receipts. Tests run both readers on the same data and compare the complete +results, including failures. + +A memory snapshot is built from batches of current records and then finished. A batch +with an invalid record or a duplicate current ID is refused and leaves the builder as +it was. A finished snapshot cannot change. The records supplied are all the data the +calculation sees. A missing source, linked record, or profile has the effect it has in +a database without that record. + +Rejected alternatives: + +- Load supplied records into an in-memory SQLite database. Rejected because the + calculation-only build would then need SQLite. +- Write the queries once in a small query language that both readers interpret. + Rejected because the eight queries are fewer lines than the interpreter, and the SQL + must stay exactly as it is to keep its index plans. + +The calculations 3.0.0 adds that read device recordings, the intensity reference in +effect, or a window of workouts (D302, D305, D322) ask for that data as one request, +which the SQLite reader answers with the queries 3.0.0 already runs. A memory snapshot +does not hold recording blocks yet, so it answers that such a calculation needs a +database, and the phone runs it on a `Database`. The fixture bundle lists those cases +with that reason (D333). + +## D327. Phones open the same SQLite file through the existing store + +The mobile crate, `athleticstandard-mobile` in `mobile/`, has a `sqlite` feature. It +depends on the `athleticstandard` crate with its new default feature, `cli`, turned +off. That feature holds the command line, terminal handling, the network runtime, +provider import readers, prediction and log planning, and the protocol operations that +use them. A phone build therefore compiles the store, files, packages, calculations, +and views, and nothing that reaches the network. + +Phone edits run the protocol's database, record, query, and calculation operations +in-process on an open store. So an edit from a phone gets the same checks, the same +stale-revision refusals, and the same messages as one from the npm client. A store +handle runs one call at a time and is closed explicitly. After it is closed, every +call is refused. A read-only open, the migration preview, and migration only after a +verified backup work as they do on the desktop. + +Each platform gets one native library that holds both the calculation module and the +storage module. An app cannot link two Rust static libraries, because each carries its +own copy of the Rust runtime and the symbols collide. The build without the `sqlite` +feature is still built and tested, and a test checks that its dependency tree has no +SQLite, HTTP, or command-line crate. + +The generated Swift and Kotlin bindings are build output and are not committed. The +release staging step generates them with the locked UniFFI version and records their +hashes. + +Rejected alternatives: + +- Use a platform database library, such as GRDB on iOS or Room on Android. Rejected + because it would write the tables without the one record encoder and its checks. +- Ship two native libraries, one per module. Rejected because of the symbol collision. +- Give each phone call its own open and close, as the protocol worker does. Rejected + because a phone keeps a file open while the person works, and reopening checks the + file again on every tap. + +## D328. Where a phone keeps the file + +The guide and the examples recommend keeping the working file on the device. iCloud +Drive and other locations in the Files picker stay selectable. The suggested wording is: +"We recommend keeping your working file on this device. Editing the same file on two +devices through iCloud Drive can cause sync conflicts." + +- A file in the app's own folders opens in place. An edit is saved when it commits. +- A document picked from another location is copied into a private working folder. + The library records the copy's SHA-256 digest. Edits commit to the working copy. + Saving writes a verified single-file copy of the database (the store's backup), then + replaces the picked document only if its content still has the recorded digest. If it + changed, the save is refused and the app can save a copy instead. A failed save keeps + every local edit. +- The library reports two separate facts: the edit has committed locally, and the + picked document has been saved. +- A single-file save does not carry attachment files. The complete package export + carries them. + +Rejected alternatives: + +- Open every picked document in place. Rejected because a sync provider can replace the + main file while SQLite's companion log holds committed edits, and the log does not + travel with the file. +- Copy the main database file back. Rejected because a copy of an active database can + miss committed edits that are still in the companion log. + +## D329. Values cross the boundary as JSON text, and failures are typed + +Record bodies, results, and receipts cross between Rust and Swift or Kotlin as UTF-8 +JSON bytes, read and written by the library's own JSON code. Options, validation +issues, and failure kinds are generated types. One failure type, +`AthleticStandardError`, has a case for each desktop error code (`invalid`, +`not_found`, `stale`, `refused`, `migration_required`, `database`, `io`, and `error`) +and three cases of its own: `malformed_json`, `unknown_shape`, and `closed`. A +validation issue keeps its path as a list of segments, each either a field name or a +list position, with the desktop code and message. + +Rejected alternatives: + +- Generate a Swift and a Kotlin type for every record shape. Rejected because record + extensions and the exact text of numbers would not survive the round trip, and the + published shapes would have a third definition to keep in step. +- Return one error string. Rejected because an app must tell a stale edit from an + invalid record without reading the message. + +## D330. The packages include a host client with browser sign-in + +Both packages include an optional client for `ath-host`: the `AthleticStandardHost` +Swift module and the `ai.athleticstandard.host` Kotlin package. Local files need no +account and no network. Connecting to a host is something the person chooses. + +An app gives the client the host's address, its registered public client ID, and its +callback address. The client reads the host's protected-resource metadata and the +sign-in provider's discovery document, then runs the authorization code flow with S256 +PKCE in the system browser: `ASWebAuthenticationSession` on iOS and a Custom Tab on +Android, as RFC 8252 asks for native apps. It checks that the callback carries the +`state` of the sign-in it started. It asks for a token for the host's resource +identifier (RFC 8707). It keeps the refresh token in the iOS Keychain or in Android +storage encrypted with a Keystore key, never in an athlete file or export. It +refreshes an expired token and supports cancelled sign-in and sign-out. An app that +already has a session can instead give the client a function that returns a current +access token for this host. + +Writes keep the rules of D261. The client makes one `Idempotency-Key` per edit and +sends the same bytes with it after a lost reply. A correction carries the revision the +person edited. A stale answer keeps the person's edit for review. Connecting does not +link a local file or upload it. Keeping a local copy in step with a host is +[issue 58](https://github.com/mwhitham/ath/issues/58). + +The sign-in code is the library's own, on the platform browser APIs, rather than the +AppAuth libraries, as `ath` does for its own host connection (D313). The flow needs three requests: discovery, the code exchange, and the +refresh. Keeping them in the package means the packages have no third-party +dependency, and the tests run the whole exchange and refresh against a local test +provider on both platforms. + +Rejected alternatives: + +- Use AppAuth for iOS and Android. Rejected because it adds a dependency to every app + for three requests. +- Show a sign-in form in the app. Rejected by RFC 8252 and D260: the app must never see + the password. +- Give the app database credentials. Rejected by D266. + +## D331. Platform floors and targets + +- iOS 17 and later. The XCFramework has an arm64 device library, an arm64 and x86_64 + simulator library, and an arm64 and x86_64 macOS library, so `swift test` runs the + bindings on a Mac without a simulator. iOS 17 matches the Swift host example. +- Android API 24 and later, for arm64-v8a phones and x86_64 emulators. Native code is + built with NDK r29, which aligns libraries for 16 KB memory pages by default. The + Android library compiles against API 36 with JDK 21. +- Rust 1.100.0 (`rust-toolchain.toml`) and UniFFI 0.33.0, locked in `Cargo.lock`. The + Gradle and NDK versions are pinned in the Android build files. + +Rejected alternatives: + +- 32-bit Android ABIs (armeabi-v7a and x86). Rejected because each ABI adds a build and + a test run, and API 24 phones that need them are rare. +- An iOS floor below 17. Rejected because the host client uses Swift concurrency + features from that release, as the example does. + +## D332. How the packages are released + +- **Swift.** The release builds the XCFramework, zips it, and records its SHA-256 + checksum. A separate Swift package repository holds a `Package.swift` that names the + release asset by address and checksum, with the generated Swift sources. Its version + tag points at the commit that names the tested checksum. The proposed repository is + `mwhitham/athleticstandard-swift`. The maintainer creates it. +- **Android.** The release builds an Android archive with the generated Kotlin, both + native libraries, a POM that declares the pinned JNA runtime, and sources and + documentation jars. It is published to Maven Central as + `ai.athleticstandard:athleticstandard`. The `ai.athleticstandard` namespace must be + verified by the maintainer, through the `athleticstandard.ai` domain that already + names the published schemas, before the coordinate is promised. +- A branch run builds both packages, installs them from a temporary Swift package + repository and a local Maven repository, and tests them, without publisher + credentials. The release job requires those tests. It uploads the tested archive, + publishes the checked Maven bundle, tags the tested Swift manifest, and then installs + from both public locations. +- A retry reuses the staged files. It skips an artifact already published with the same + bytes and stops on a published version with different bytes. A missing registry + credential blocks only publication. Publication stays with the maintainer. + +Rejected alternatives: + +- Commit the XCFramework to this repository. Rejected because Swift Package Manager + fetches the whole repository, and binary files would stay in its history. +- Build the Rust code from source inside Swift Package Manager. Rejected because a Swift + package cannot run Cargo. +- Publish through JitPack. Rejected because it builds on its own servers, so the + published bytes would not be the tested ones. +- Publish to GitHub Packages. Rejected because reading from it needs a token. + +## D333. One fixture bundle tests every platform + +A desktop exporter writes a test bundle while the tests run. It holds each model +vector with its expected verdict, issues, and checked output, after the documented +historical exceptions and message changes. It holds each worked calculation example +as complete current records, a SQLite file built from them, the request, and the +desktop result or failure. It holds each coaching record example. Inputs are synthetic. +The bundle is not committed. + +The Swift and Kotlin tests read the bundle and run every case through the installed +packages. Calculation cases run through both the memory and the SQLite entry points. +Each suite reports its run, skip, and failure counts. A new skip, a missing skill, or a +mismatch fails the run. The checked-in examples and golden files stay an independent +check, because the desktop tests already compare the desktop result with them. + +Rejected alternatives: + +- Copy the expected results into Swift and Kotlin test files. Rejected because a third + copy of thousands of results would drift. +- Run only a sample of the cases on phones. Rejected because a rule that differs on one + platform shows up only in the cases that exercise it. diff --git a/build-history/v3.0.0/progress.md b/build-history/v3.0.0/progress.md index 26832c70..4478193a 100644 --- a/build-history/v3.0.0/progress.md +++ b/build-history/v3.0.0/progress.md @@ -15,6 +15,12 @@ Status: **being built; not released.** The plan is [spec.md](spec.md). | 9 | `ath` connects to a host; host permissions; large writes; test kit | done: gate 2 passes, and the test kit passes against `ath-host` in both modes | | 10 | Guides | done: each followed by an independent reader, and fixed | | 11 | Synthetic journey and release evidence | done: gate 6 passes; release notes name step 8 | +| 12 | Phone library plan, decisions D325–D333 ([plan](appendix/mobile-library-plan.md)) | done | +| 13 | UniFFI crate, validation from the Swift package and the Android library | not started | +| 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | not started | +| 15 | Calculations from memory and SQLite through one reader interface | not started | +| 16 | Host client for Swift and Kotlin with browser sign-in | not started | +| 17 | Release packaging, phone test runs, release gate | not started | ## Step 2: what was built From f60a0b20e029e632c43f7973f5509a2092313780 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 09:01:32 -0600 Subject: [PATCH 02/30] Add the UniFFI crate, the Swift package, and the Android library. `mobile/` holds the `athleticstandard-mobile` crate, built with UniFFI 0.33.0, which exposes the record checks: `validate`, `validateCurrentRecord`, and `libraryVersion`. One failure type carries the desktop error code and message, and validation issues keep field names and list positions apart (D329). `mobile/scripts/` builds an XCFramework for iPhone, the iPhone simulator, and macOS, and the Android libraries for arm64-v8a and x86_64 with a 16 KB page alignment check. `mobile/swift/` is the Swift package and `mobile/android/` is the Gradle build of `ai.athleticstandard`. `mobile/tests/fixtures.rs` runs every recorded model vector through the binding and writes the shared phone test bundle (D333). The vector exceptions moved to `tests/vector_rules/`, so the desktop harness and the bundle read one list. All 7,285 run cases match on a Mac through the Swift package and on an Android emulator through the Android library. The iPhone simulator run is not done yet. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 461 ++++++++++++++++++ Cargo.toml | 5 +- build-history/v3.0.0/progress.md | 18 +- docs/architecture.md | 1 + mobile/Cargo.toml | 19 + mobile/README.md | 74 +++ mobile/android/.gitattributes | 4 + mobile/android/.gitignore | 7 + .../android/athleticstandard/build.gradle.kts | 116 +++++ .../athleticstandard/consumer-rules.pro | 6 + .../ai/athleticstandard/FixtureBundle.kt | 27 + .../ai/athleticstandard/ModelVectorTest.kt | 56 +++ .../ai/athleticstandard/ValidationTest.kt | 90 ++++ .../kotlin/ai/athleticstandard/ErrorCodes.kt | 41 ++ mobile/android/build.gradle.kts | 3 + mobile/android/gradle.properties | 5 + .../android/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 49154 bytes .../gradle/wrapper/gradle-wrapper.properties | 10 + mobile/android/gradlew | 248 ++++++++++ mobile/android/gradlew.bat | 112 +++++ mobile/android/settings.gradle.kts | 19 + mobile/bindgen/Cargo.toml | 15 + mobile/bindgen/src/main.rs | 7 + mobile/scripts/build-android.sh | 85 ++++ mobile/scripts/build-apple.sh | 162 ++++++ mobile/scripts/test-android.sh | 28 ++ mobile/scripts/test-apple.sh | 52 ++ mobile/src/error.rs | 138 ++++++ mobile/src/lib.rs | 23 + mobile/src/validate.rs | 40 ++ mobile/swift/.gitignore | 3 + mobile/swift/Package.swift | 25 + .../AthleticStandardError+Code.swift | 40 ++ .../AthleticStandardTests/FixtureBundle.swift | 33 ++ .../ModelVectorTests.swift | 44 ++ .../ValidationTests.swift | 80 +++ mobile/tests/dependencies.rs | 84 ++++ mobile/tests/fixtures.rs | 139 ++++++ mobile/tests/validate.rs | 73 +++ mobile/uniffi.toml | 15 + tests/model_vectors.rs | 106 +--- tests/vector_rules/mod.rs | 104 ++++ 42 files changed, 2514 insertions(+), 104 deletions(-) create mode 100644 mobile/Cargo.toml create mode 100644 mobile/README.md create mode 100644 mobile/android/.gitattributes create mode 100644 mobile/android/.gitignore create mode 100644 mobile/android/athleticstandard/build.gradle.kts create mode 100644 mobile/android/athleticstandard/consumer-rules.pro create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/FixtureBundle.kt create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt create mode 100644 mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/ErrorCodes.kt create mode 100644 mobile/android/build.gradle.kts create mode 100644 mobile/android/gradle.properties create mode 100644 mobile/android/gradle/wrapper/gradle-wrapper.jar create mode 100644 mobile/android/gradle/wrapper/gradle-wrapper.properties create mode 100755 mobile/android/gradlew create mode 100644 mobile/android/gradlew.bat create mode 100644 mobile/android/settings.gradle.kts create mode 100644 mobile/bindgen/Cargo.toml create mode 100644 mobile/bindgen/src/main.rs create mode 100755 mobile/scripts/build-android.sh create mode 100755 mobile/scripts/build-apple.sh create mode 100755 mobile/scripts/test-android.sh create mode 100755 mobile/scripts/test-apple.sh create mode 100644 mobile/src/error.rs create mode 100644 mobile/src/lib.rs create mode 100644 mobile/src/validate.rs create mode 100644 mobile/swift/.gitignore create mode 100644 mobile/swift/Package.swift create mode 100644 mobile/swift/Sources/AthleticStandard/AthleticStandardError+Code.swift create mode 100644 mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift create mode 100644 mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift create mode 100644 mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift create mode 100644 mobile/tests/dependencies.rs create mode 100644 mobile/tests/fixtures.rs create mode 100644 mobile/tests/validate.rs create mode 100644 mobile/uniffi.toml create mode 100644 tests/vector_rules/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 2f8d00f1..27aeae74 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,6 +93,59 @@ dependencies = [ "derive_arbitrary", ] +[[package]] +name = "askama" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4" +dependencies = [ + "askama_macros", + "itoa", + "percent-encoding", + "serde", + "serde_json", +] + +[[package]] +name = "askama_derive" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39" +dependencies = [ + "askama_parser", + "basic-toml", + "glob", + "memchr", + "proc-macro2", + "quote", + "rustc-hash", + "serde", + "serde_derive", + "syn 3.0.10", +] + +[[package]] +name = "askama_macros" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b" +dependencies = [ + "askama_derive", +] + +[[package]] +name = "askama_parser" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583" +dependencies = [ + "rustc-hash", + "serde", + "serde_derive", + "unicode-ident", + "winnow", +] + [[package]] name = "async-stream" version = "0.3.6" @@ -181,6 +234,21 @@ dependencies = [ "zip", ] +[[package]] +name = "athleticstandard-mobile" +version = "3.0.0" +dependencies = [ + "athleticstandard-core", + "uniffi", +] + +[[package]] +name = "athleticstandard-uniffi-bindgen" +version = "3.0.0" +dependencies = [ + "uniffi", +] + [[package]] name = "athleticstandard-wasm" version = "3.0.0" @@ -282,6 +350,15 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "basic-toml" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a" +dependencies = [ + "serde", +] + [[package]] name = "bitflags" version = "2.13.2" @@ -347,6 +424,39 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "cargo_metadata" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "cc" version = "1.11.2" @@ -457,6 +567,17 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -852,6 +973,15 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs-err" +version = "3.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" +dependencies = [ + "autocfg", +] + [[package]] name = "futures" version = "0.3.34" @@ -987,6 +1117,23 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "goblin" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47" +dependencies = [ + "log", + "plain", + "scroll", +] + [[package]] name = "group" version = "0.14.0" @@ -1349,6 +1496,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", + "serde", + "serde_core", ] [[package]] @@ -1622,6 +1771,12 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -1643,6 +1798,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -1908,6 +2073,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2117,6 +2288,12 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustc_version" version = "0.4.1" @@ -2267,6 +2444,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "scroll" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6" +dependencies = [ + "scroll_derive", +] + +[[package]] +name = "scroll_derive" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "sec1" version = "0.8.1" @@ -2309,6 +2506,10 @@ name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] [[package]] name = "serde" @@ -2366,6 +2567,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -2472,6 +2682,12 @@ version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +[[package]] +name = "smawk" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" + [[package]] name = "socket2" version = "0.5.10" @@ -2518,6 +2734,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "strsim" version = "0.11.1" @@ -2569,6 +2791,12 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + [[package]] name = "tempfile" version = "3.27.0" @@ -2582,6 +2810,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "terminal_size" version = "0.4.4" @@ -2592,6 +2829,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "textwrap" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" +dependencies = [ + "smawk", + "unicode-width", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -2724,6 +2971,45 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "1.2.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "tower" version = "0.4.13" @@ -2814,6 +3100,154 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "uniffi" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "555ca4a960ec148b0448352af0e06b41c11c553c544cf729d6309ce5fc31841b" +dependencies = [ + "anyhow", + "camino", + "cargo_metadata", + "clap", + "uniffi_bindgen", + "uniffi_core", + "uniffi_macros", + "uniffi_pipeline", +] + +[[package]] +name = "uniffi_bindgen" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce7d75a679688cd81f926e032fd5240319157193bbae971376cb3136e2a799f7" +dependencies = [ + "anyhow", + "askama", + "camino", + "cargo_metadata", + "fs-err", + "glob", + "goblin", + "heck", + "indexmap", + "once_cell", + "serde", + "tempfile", + "textwrap", + "toml", + "uniffi_internal_macros", + "uniffi_meta", + "uniffi_parse_rs", + "uniffi_pipeline", + "uniffi_udl", +] + +[[package]] +name = "uniffi_core" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcc9bbafb4b538edcfd917ad8d3cc3ad2475fe05d6da7992df17558421d9a9a3" +dependencies = [ + "anyhow", + "async-trait", + "bytes", + "once_cell", + "static_assertions", +] + +[[package]] +name = "uniffi_internal_macros" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a13da6d52fb64a98183c1b6ce8b37ad01acda03c352236ee57955f2284009bc" +dependencies = [ + "anyhow", + "indexmap", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "uniffi_macros" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "892e82e7b88e0867998216064a004a1588b5faa93423f3bbfcaf51a32762614e" +dependencies = [ + "camino", + "fs-err", + "once_cell", + "proc-macro2", + "quote", + "serde", + "syn 2.0.119", + "toml", + "uniffi_meta", +] + +[[package]] +name = "uniffi_meta" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e8f2f688292e9fe840229d24141e0413df248a86dd6866063c8216721b37d86" +dependencies = [ + "anyhow", + "siphasher", + "uniffi_internal_macros", + "uniffi_pipeline", +] + +[[package]] +name = "uniffi_parse_rs" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ac58f04ed5f6bbdc54fa6ad8e6baf6efb0fbfdd6b247536c8d2f5eab3007dc9" +dependencies = [ + "anyhow", + "camino", + "codespan-reporting", + "proc-macro2", + "quote", + "serde", + "syn 2.0.119", + "target-lexicon", + "thiserror 2.0.21", + "toml", + "uniffi_meta", +] + +[[package]] +name = "uniffi_pipeline" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368c2ee526938c4bf06dedd486713506c5453ef9fde3b66c56d9426faa6e6886" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "tempfile", + "uniffi_internal_macros", +] + +[[package]] +name = "uniffi_udl" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c5e85827544ffa991a8c39a6d1a5d4b915cd04b3fc550ad977ddd80e44768f7" +dependencies = [ + "anyhow", + "textwrap", + "uniffi_meta", + "weedle2", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -2980,6 +3414,24 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weedle2" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e" +dependencies = [ + "nom", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -3121,6 +3573,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index 632720c5..7e8fa83d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,8 +8,9 @@ license = "MIT" publish = false [workspace] -members = [".", "core", "host", "wasm"] -default-members = [".", "core", "host", "wasm"] +members = [".", "core", "host", "mobile", "mobile/bindgen", "wasm"] +# The binding generator is built only by the mobile scripts. +default-members = [".", "core", "host", "mobile", "wasm"] resolver = "2" [lib] diff --git a/build-history/v3.0.0/progress.md b/build-history/v3.0.0/progress.md index 4478193a..acaed71a 100644 --- a/build-history/v3.0.0/progress.md +++ b/build-history/v3.0.0/progress.md @@ -16,7 +16,7 @@ Status: **being built; not released.** The plan is [spec.md](spec.md). | 10 | Guides | done: each followed by an independent reader, and fixed | | 11 | Synthetic journey and release evidence | done: gate 6 passes; release notes name step 8 | | 12 | Phone library plan, decisions D325–D333 ([plan](appendix/mobile-library-plan.md)) | done | -| 13 | UniFFI crate, validation from the Swift package and the Android library | not started | +| 13 | UniFFI crate, validation from the Swift package and the Android library | Mac and Android emulator pass; iPhone simulator not run | | 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | not started | | 15 | Calculations from memory and SQLite through one reader interface | not started | | 16 | Host client for Swift and Kotlin with browser sign-in | not started | @@ -690,3 +690,19 @@ These follow the guide and the decisions. Each is open to review. migration step 8 and its one-time rebuild of `records` first. - Step 11 is done, and so is the build of 3.0.0. Nothing was pushed or published. +## Step 13: the UniFFI crate and the first phone builds + +- `mobile/` is the UniFFI crate (UniFFI 0.33.0), built on D312's core. Its record + checks run every recorded model vector: 7,399 cases in 140 files, 7,285 run and 114 + skipped for the four documented reasons. The same counts pass in Rust, through the + Swift package on a Mac (`swift test`), and through the Android library on an API 36 + arm64 emulator. +- The vector exceptions and message changes, including 3.0.0's, moved to + `tests/vector_rules/`, so the desktop harness and the phone bundle read one list. +- A test checks that the build without storage depends on no SQLite, HTTP, or + command-line crate, and that `core/src` names no file, network, or process API. +- Both Android libraries pass a 16 KB page alignment check when they are built. +- The XCFramework is assembled by `mobile/scripts/build-apple.sh`, not by + `xcodebuild -create-xcframework`. The iPhone simulator run needs Xcode's license to be + accepted on the build machine; it has not run yet. + diff --git a/docs/architecture.md b/docs/architecture.md index d79ff61d..40c7e4b1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -37,6 +37,7 @@ Paths below are relative to the repository root. | The npm loader for the WebAssembly core (`athleticstandard/core`) | `packages/npm/src/core.ts` | the WebAssembly core | | Hosting many athletes' records: sign-in checks, grants, the HTTPS API, write receipts, working copies, attachment buckets | `host/` (`ath-host`) | the library with its `changesets` feature | | The npm host connection (`connectHost`) | `packages/npm/src/host.ts` | the host API | +| iPhone and Android bindings: the UniFFI crate, the Swift package, the Android library, their build and test scripts | `mobile/` ([README](../mobile/README.md)) | the core | Rules that keep this table true: diff --git a/mobile/Cargo.toml b/mobile/Cargo.toml new file mode 100644 index 00000000..39d7abc7 --- /dev/null +++ b/mobile/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "athleticstandard-mobile" +version = "3.0.0" +edition = "2021" +rust-version = "1.95" +description = "Athletic Standard for iPhone and Android apps: UniFFI bindings to the record checks, calculations, and SQLite store" +license = "MIT" +publish = false + +[lib] +name = "athleticstandard_mobile" +path = "src/lib.rs" +# `staticlib` for the iOS XCFramework, `cdylib` for Android and for generating +# the bindings, `lib` for the Rust tests. +crate-type = ["lib", "staticlib", "cdylib"] + +[dependencies] +athleticstandard-core = { path = "../core" } +uniffi = "=0.33.0" diff --git a/mobile/README.md b/mobile/README.md new file mode 100644 index 00000000..eb24fd15 --- /dev/null +++ b/mobile/README.md @@ -0,0 +1,74 @@ +# Athletic Standard for iPhone and Android + +This folder builds the Athletic Standard library for iPhone and Android apps +([D325](../build-history/v3.0.0/decisions.md#d325-phones-get-the-library-through-uniffi-in-version-300)). +The rules stay in Rust. UniFFI generates the Swift and Kotlin bindings, so an app +gets the same record checks, messages, and results as the desktop `ath` program. + +| Folder | What it holds | +|---|---| +| `src/` | The `athleticstandard-mobile` Rust crate: the functions and types the bindings expose. | +| `bindgen/` | `uniffi-bindgen`, built from the same locked UniFFI version. | +| `swift/` | The Swift package `AthleticStandard` for iOS 17 and later, and macOS 14 and later for tests. | +| `android/` | The Android library `ai.athleticstandard:athleticstandard` for API 24 and later. | +| `scripts/` | Build and test scripts for both platforms. | +| `tests/` | Rust tests of the binding, and the exporter that writes the phone test bundle. | + +The generated Swift and Kotlin, the XCFramework, and the native Android libraries are +build output. They are not committed +([D327](../build-history/v3.0.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). + +## What an app can call + +- `libraryVersion()`: the version this library writes and reports, such as `3.0.0`. +- `validate(shape:json:)`: check UTF-8 JSON against a published shape, such as + `CurrentRecord` or `WorkoutSessionData`. It returns the checked JSON, or throws + `AthleticStandardError.Invalid` with every issue in the desktop order. +- `validateCurrentRecord(json:)`: check one complete current record, including the + rule that an athlete report never names a source. + +Record bodies and results cross as UTF-8 JSON bytes: `Data` in Swift and `ByteArray` +in Kotlin +([D329](../build-history/v3.0.0/decisions.md#d329-values-cross-the-boundary-as-json-text-and-failures-are-typed)). +Every failure is `AthleticStandardError` in Swift and `AthleticStandardException` in +Kotlin. Each has a `code` that matches the desktop error code, a `detail` with the +desktop message, and, for an invalid value, `issues`. An issue's `path` keeps field +names and list positions apart. + +## Build + +You need the Rust toolchain from `rust-toolchain.toml` with these targets: + +```sh +rustup target add aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios \ + aarch64-apple-darwin x86_64-apple-darwin aarch64-linux-android x86_64-linux-android +``` + +**Swift.** `mobile/scripts/build-apple.sh [debug|release]` builds the static libraries, +generates the Swift bindings, and writes `mobile/swift/build/AthleticStandardFFI.xcframework`. +It needs Xcode's iPhone SDKs. It does not need Xcode's command-line license, because it +assembles the XCFramework itself. + +**Android.** `mobile/android/gradlew :athleticstandard:assembleRelease` runs +`mobile/scripts/build-android.sh`, which builds `libathleticstandard_mobile.so` for +arm64-v8a and x86_64 with NDK 29.0.14206865 and checks that every library is aligned for +16 KB memory pages. Set `ANDROID_HOME` to the SDK and `JAVA_HOME` to JDK 17 or later. +Pass `-Pathleticstandard.rustProfile=debug` for a faster local build. + +## Test + +The tests run one shared bundle of cases that the desktop library writes +([D333](../build-history/v3.0.0/decisions.md#d333-one-fixture-bundle-tests-every-platform)). +`mobile/tests/fixtures.rs` runs every case through the binding's Rust functions during +`cargo test`, and writes the bundle when `ATH_MOBILE_FIXTURES` names a folder. Each +suite file lists its cases, the expected outcome of each, and the skipped cases with +their documented reasons. A phone run must skip exactly those. + +```sh +mobile/scripts/test-apple.sh # this Mac, then an iPhone simulator +mobile/scripts/test-apple.sh --mac-only # this Mac only +mobile/scripts/test-android.sh # a running emulator or a connected phone +``` + +`test-apple.sh` needs a full Xcode whose license has been accepted for the simulator +run. On this Mac it uses `swift test`. diff --git a/mobile/android/.gitattributes b/mobile/android/.gitattributes new file mode 100644 index 00000000..a2b650e8 --- /dev/null +++ b/mobile/android/.gitattributes @@ -0,0 +1,4 @@ +# Gradle wrapper files keep the line endings each platform needs. +gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/mobile/android/.gitignore b/mobile/android/.gitignore new file mode 100644 index 00000000..01208e97 --- /dev/null +++ b/mobile/android/.gitignore @@ -0,0 +1,7 @@ +/build/ +/.gradle/ +/athleticstandard/build/ +/consumer/build/ +/consumer/app/build/ +/consumer/.gradle/ +local.properties diff --git a/mobile/android/athleticstandard/build.gradle.kts b/mobile/android/athleticstandard/build.gradle.kts new file mode 100644 index 00000000..cce4cf36 --- /dev/null +++ b/mobile/android/athleticstandard/build.gradle.kts @@ -0,0 +1,116 @@ +// The Android library: generated Kotlin bindings, the native library for each +// ABI, and hand-written platform code (D325, D331, D332). + +plugins { + id("com.android.library") + `maven-publish` +} + +group = "ai.athleticstandard" +version = providers.gradleProperty("athleticstandard.version").get() + +// `debug` builds the Rust library faster for local test runs. Releases use `release`. +val rustProfile = providers.gradleProperty("athleticstandard.rustProfile").getOrElse("release") +val rustOutput = layout.buildDirectory.dir("rust/$rustProfile") +val repositoryRoot = rootDir.resolve("../..") +// The fixture bundle that mobile/tests/fixtures.rs writes (D333). +val fixtures = providers.gradleProperty("athleticstandard.fixtures") + .getOrElse(repositoryRoot.resolve("target/mobile-fixtures").path) + +android { + namespace = "ai.athleticstandard" + compileSdk = 36 + ndkVersion = "29.0.14206865" + + defaultConfig { + minSdk = 24 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles("consumer-rules.pro") + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + sourceSets { + getByName("main") { + kotlin.directories.add(rustOutput.get().dir("kotlin").asFile.path) + jniLibs.directories.add(rustOutput.get().dir("jniLibs").asFile.path) + } + getByName("androidTest") { + assets.directories.add(fixtures) + } + } + + publishing { + singleVariant("release") { + withSourcesJar() + withJavadocJar() + } + } +} + +// Build the native library and generate the Kotlin bindings before anything +// reads them. The script checks 16 KB page alignment for each ABI. +val buildRust by tasks.registering(Exec::class) { + group = "build" + description = "Builds libathleticstandard_mobile.so for each ABI and generates the Kotlin bindings." + val output = rustOutput.get().asFile + commandLine(repositoryRoot.resolve("mobile/scripts/build-android.sh").path, rustProfile, output.path) + environment("ANDROID_NDK_HOME", androidComponents.sdkComponents.ndkDirectory.get().asFile.path) + inputs.dir(repositoryRoot.resolve("core/src")) + inputs.dir(repositoryRoot.resolve("mobile/src")) + inputs.dir(repositoryRoot.resolve("src")) + inputs.dir(repositoryRoot.resolve("skills")) + inputs.file(repositoryRoot.resolve("Cargo.lock")) + inputs.file(repositoryRoot.resolve("mobile/uniffi.toml")) + outputs.dir(output) +} + +tasks.named("preBuild") { dependsOn(buildRust) } + +dependencies { + // UniFFI's Kotlin calls the native library through JNA. The `aar` build + // carries JNA's own native code for each ABI. The POM declares it, so an + // app resolves it with this library. + api("net.java.dev.jna:jna:5.19.1@aar") + implementation("androidx.annotation:annotation:1.9.1") + + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test.ext:junit:1.3.0") +} + +publishing { + publications { + register("release") { + groupId = "ai.athleticstandard" + artifactId = "athleticstandard" + afterEvaluate { from(components["release"]) } + pom { + name.set("Athletic Standard") + description.set( + "Athletic Standard for Android apps: the record checks, calculations, and SQLite store of the Rust library.", + ) + url.set("https://github.com/mwhitham/ath") + licenses { + license { + name.set("MIT") + url.set("https://github.com/mwhitham/ath/blob/main/LICENSE") + } + } + scm { + url.set("https://github.com/mwhitham/ath") + connection.set("scm:git:https://github.com/mwhitham/ath.git") + } + } + } + } + repositories { + // A branch run publishes here and installs from here (D332). + maven { + name = "staging" + url = uri(rootDir.resolve("build/repository")) + } + } +} diff --git a/mobile/android/athleticstandard/consumer-rules.pro b/mobile/android/athleticstandard/consumer-rules.pro new file mode 100644 index 00000000..e3206cd1 --- /dev/null +++ b/mobile/android/athleticstandard/consumer-rules.pro @@ -0,0 +1,6 @@ +# Rules an app's shrinker applies to this library. +# JNA finds its classes, and UniFFI's generated structures, by name at run time. +-keep class com.sun.jna.** { *; } +-keep class * implements com.sun.jna.** { *; } +-keep class ai.athleticstandard.** { *; } +-dontwarn java.awt.** diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/FixtureBundle.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/FixtureBundle.kt new file mode 100644 index 00000000..45d5c488 --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/FixtureBundle.kt @@ -0,0 +1,27 @@ +package ai.athleticstandard + +import androidx.test.platform.app.InstrumentationRegistry +import org.json.JSONObject + +/** + * The desktop fixture bundle (D333), packaged as test assets from the folder that + * `mobile/tests/fixtures.rs` wrote. + */ +object FixtureBundle { + fun suite(name: String): JSONObject { + val assets = InstrumentationRegistry.getInstrumentation().context.assets + val text = assets.open("$name.json").use { it.readBytes().decodeToString() } + return JSONObject(text) + } + + /** One issue as the bundle prints it: `[path] code message`. */ + fun text(issue: ValidationIssue): String { + val path = issue.path.joinToString(".") { segment -> + when (segment) { + is PathSegment.Field -> segment.name + is PathSegment.Position -> segment.index.toString() + } + } + return "[$path] ${issue.code} ${issue.message}" + } +} diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt new file mode 100644 index 00000000..059d6714 --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt @@ -0,0 +1,56 @@ +package ai.athleticstandard + +import android.util.Log +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Every recorded model vector, through the Android library, compared with the + * desktop outcome in the fixture bundle (D333). + */ +@RunWith(AndroidJUnit4::class) +class ModelVectorTest { + @Test + fun everyModelVectorMatchesTheDesktop() { + val suite = FixtureBundle.suite("model-vectors") + val cases = suite.getJSONArray("cases") + val counts = suite.getJSONObject("counts") + var run = 0 + var skipped = 0 + val failures = mutableListOf() + for (index in 0 until cases.length()) { + val item = cases.getJSONObject(index) + if (item.has("skip")) { + skipped += 1 + continue + } + run += 1 + val schema = item.getString("schema") + val name = item.getString("name") + val input = item.getString("input_text").toByteArray(Charsets.UTF_8) + val expectedIssues = item.getJSONArray("issues").let { list -> List(list.length()) { list.getString(it) } } + val expectedOutput = if (item.isNull("output_text")) null else item.getString("output_text") + try { + val output = validate(schema, input) + if (expectedIssues.isNotEmpty() || expectedOutput == null || + !output.contentEquals(expectedOutput.toByteArray(Charsets.UTF_8)) + ) { + failures += "$schema / $name: accepted, expected $expectedIssues" + } + } catch (error: AthleticStandardException) { + val issues = error.issues.map(FixtureBundle::text) + if (error.code != "invalid" || issues != expectedIssues) { + failures += "$schema / $name: ${error.code} $issues, expected $expectedIssues" + } + } + } + Log.i("AthleticStandard", "model-vectors: $run run, $skipped skipped, ${failures.size} failed") + assertEquals(counts.getInt("run"), run) + assertEquals(counts.getInt("skipped"), skipped) + assertEquals(counts.getInt("cases"), cases.length()) + assertTrue(failures.take(20).joinToString("\n"), failures.isEmpty()) + } +} diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt new file mode 100644 index 00000000..4f09c07a --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt @@ -0,0 +1,90 @@ +package ai.athleticstandard + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith + +/** + * The checks the Rust tests in mobile/tests/validate.rs run, through the Android + * library on a phone or emulator. The fixture bundle runs every recorded vector + * (D333). + */ +@RunWith(AndroidJUnit4::class) +class ValidationTest { + private val measurement = """{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000064","record_type":"point_measurement","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"source_id":"01890f3e-e7d3-7cc0-88c8-000000000003","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","quantity":"hrv_rmssd","input_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"value":{"standard_value":42,"standard_unit":"ms","input_value_missing_reason":"not_provided_by_source","input_unit_missing_reason":"not_provided_by_source"}}}""" + + private val report = """{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000065","record_type":"athlete_report","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"report_type":"note","reported_at":"2026-01-02T03:04:05.678Z","input_reported_at":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"reported_via":"text"}}""" + + private fun issues(body: () -> ByteArray): List { + try { + body() + } catch (error: AthleticStandardException) { + assertEquals("invalid", error.code) + return error.issues + } + fail("expected an invalid record") + return emptyList() + } + + @Test + fun libraryReportsItsVersion() { + assertEquals("3.0.0", libraryVersion()) + } + + @Test + fun measuredRecordWithSourceIsAccepted() { + val expected = measurement + .replace(""""record_type":"point_measurement",""", "") + .replace(""""is_deleted":false,""", """"is_deleted":false,"record_type":"point_measurement",""") + assertEquals(expected, validateCurrentRecord(measurement.toByteArray()).decodeToString()) + } + + @Test + fun measuredRecordWithoutSourceIsRefused() { + val missing = measurement.replace(""""source_id":"01890f3e-e7d3-7cc0-88c8-000000000003",""", "") + val found = issues { validateCurrentRecord(missing.toByteArray()) } + assertEquals(listOf("data.source_id"), found.map { it.pathText }) + assertEquals(listOf("invalid_type"), found.map { it.code }) + assertEquals(listOf("Invalid input: expected string, received undefined"), found.map { it.message }) + } + + @Test + fun athleteReportCannotClaimSource() { + val claimed = report.replace( + """"report_type":"note",""", + """"report_type":"note","source_id":"01890f3e-e7d3-7cc0-88c8-000000000003",""", + ) + val found = issues { validateCurrentRecord(claimed.toByteArray()) } + assertEquals(listOf("data"), found.map { it.pathText }) + assertEquals(listOf("unrecognized_keys"), found.map { it.code }) + assertEquals(listOf("""Unrecognized key: "source_id""""), found.map { it.message }) + } + + @Test + fun pathsKeepFieldNamesAndPositionsApart() { + val data = """{"report_type":"note","reported_at":"2026-01-02T03:04:05.678Z","input_reported_at":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"reported_via":"text","attachment_ids":[7]}""" + val found = issues { validate("AthleteReportData", data.toByteArray()) } + assertEquals(listOf(PathSegment.Field("attachment_ids"), PathSegment.Position(0uL)), found.first().path) + } + + @Test + fun malformedJsonAndUnknownShapesHaveTheirOwnFailures() { + for (bytes in listOf("{".toByteArray(), byteArrayOf(0xff.toByte()))) { + try { + validate("CurrentRecord", bytes) + fail("expected malformed JSON") + } catch (error: AthleticStandardException) { + assertEquals("malformed_json", error.code) + } + } + try { + validate("NoSuchShape", "{}".toByteArray()) + fail("expected an unknown shape") + } catch (error: AthleticStandardException) { + assertEquals("unknown_shape", error.code) + assertEquals("no published shape named NoSuchShape", error.detail) + } + } +} diff --git a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/ErrorCodes.kt b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/ErrorCodes.kt new file mode 100644 index 00000000..43a14493 --- /dev/null +++ b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/ErrorCodes.kt @@ -0,0 +1,41 @@ +package ai.athleticstandard + +/** + * The code a desktop caller sees for the same failure, such as `stale` or `invalid` + * (D329). `malformed_json`, `unknown_shape`, and `closed` exist only in the phone + * library. + */ +val AthleticStandardException.code: String + get() = when (this) { + is AthleticStandardException.MalformedJson -> "malformed_json" + is AthleticStandardException.UnknownShape -> "unknown_shape" + is AthleticStandardException.Invalid -> "invalid" + is AthleticStandardException.NotFound -> "not_found" + is AthleticStandardException.Stale -> "stale" + is AthleticStandardException.Refused -> "refused" + is AthleticStandardException.MigrationRequired -> "migration_required" + is AthleticStandardException.Database -> "database" + is AthleticStandardException.Io -> "io" + is AthleticStandardException.Failed -> "error" + is AthleticStandardException.Closed -> "closed" + } + +/** The desktop message, unchanged. */ +val AthleticStandardException.detail: String + get() = when (this) { + is AthleticStandardException.MalformedJson -> detail + is AthleticStandardException.UnknownShape -> detail + is AthleticStandardException.Invalid -> detail + is AthleticStandardException.NotFound -> detail + is AthleticStandardException.Stale -> detail + is AthleticStandardException.Refused -> detail + is AthleticStandardException.MigrationRequired -> detail + is AthleticStandardException.Database -> detail + is AthleticStandardException.Io -> detail + is AthleticStandardException.Failed -> detail + is AthleticStandardException.Closed -> detail + } + +/** The validation issues of an `Invalid` failure, in the desktop order. */ +val AthleticStandardException.issues: List + get() = (this as? AthleticStandardException.Invalid)?.issues ?: emptyList() diff --git a/mobile/android/build.gradle.kts b/mobile/android/build.gradle.kts new file mode 100644 index 00000000..7c0708d5 --- /dev/null +++ b/mobile/android/build.gradle.kts @@ -0,0 +1,3 @@ +plugins { + id("com.android.library") version "9.5.3" apply false +} diff --git a/mobile/android/gradle.properties b/mobile/android/gradle.properties new file mode 100644 index 00000000..6f5f325b --- /dev/null +++ b/mobile/android/gradle.properties @@ -0,0 +1,5 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +android.useAndroidX=true +# The version the library reports and publishes. It must equal the Rust crates' +# version (D152); the release checks both. +athleticstandard.version=3.0.0 diff --git a/mobile/android/gradle/wrapper/gradle-wrapper.jar b/mobile/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..51cbd2a6f8121b2ce12daf979b128058fb9672ee GIT binary patch literal 49154 zcma&OV|1nKwk@2bVmq0!ZQHhO+h)bKZB(38Y}=`zV%v6Zt-Wr$-@W^sv%dYdHs4?K z&oiDrdLMm^F{gs`H&9d{NJvN^ARxj&pa1Vc1cCyR6;%hzs2^rks%InQpN&4@i?cFB(v z-M(*+9p)GpVFh0|Q&|H$3~7y1>nj^sp)F4KdOQ7ZYY$i0^%@)D?(UUY2Oqa~O-NT) zOS^{7+TjluBM%!>1Kd73v)b$vQy*S0ci;F3fwv}yVk%tAAQYyj^gV6OK1G;!9vdu0 zDox12IZpCz&VtXW6fgH&Xl@*LM0Yw;+=3R@kn&(oL_)MHq-^4h ziloqQ;YM4`)-Q$-`hQ&u4tSU1XfMK*c>%mjH7s9?7CSx&CJU6+zDw09Aczx=7}{5T zB3v9D=x8yX9}pNU69oA*hV2VXuv3BigbBWK56c~ZWUH+)B{KHrxsxO32F zPxY?VAcXf89f7!7=uR{_O69bOCX06}5kzr{TRX!eU2F%pejHDwcs+e<@oy`=fK3mB z!v~EC!tOmi{^pRRN+$uDpuHG?Bn4NKEirR1L-#ch&FlzfeZ$V(G2I3KHA@!Pj-{B2 z=IP@Bd@ODoJsQuXt9tj z*|A7$pyJSQH)T$wB!Ch%2cJ7u+q>KrH$UC^zH?w9>>vfUgwQ4)*oo;^0QsVSwqbE{ zwVf(vdhOWq!5-Y-cG|#w%j__+qTu&ysquQmiJp6wiv&_c^ypd^01}zY@@Y(4Y;YIf zYUCwAzqg+r&(<{@%v7Ase+W+mJPi~_4lz9kBlkLbe4zk;WLHT=JLGVFXY9}Pcn6@s z*(S7<;RsGhRT6OD!DIwparxA!t^$(4E3w;ehI+}{Q3|k#1lEwkmtxu#5@2We)`_zd zLkmW4%~Xj4UPWtCkYA1A2nL}b-*91Qt^qjTs1>KaBk<^t2*T8)0yZRMl9;M}sbz0d_ERfsXTIYPt|* z)<8ts6N!-`35%l^znDvAxyFBuon0Z0`^NMf-z?ySQ)XRYz#XH|{hBX_fX;djHfp_< zA(3FR!PWxv_m_Jil8yvc-0EGD{cg){2h7dm0lFzTCz_e$#fN4=+<(KYh14l?a5-d^ zfPyAsx{9~wTiKh=n!f9Kd+WNWH@TZ(riZ@#202kD!5aU42?!J8IHcN!A{HKf*;RyZ zcv@TE0DWIfeN4fktgpm`@U3HaNC~x`dh6RKX$}yQYfuz+elh_qwPpfzTM@R(nG|U&;*q z_f>>=I}|m`2Nq%wV{1}xfPxt^H&lu=C$D9sM`4P>xY0TcVx&H+W)N@bgrid*x7>d6 zcP>0`lWh!2c{_o@kw+8ddI-~I=v^p^A|euqk~?1|WUhxJ$eV@j<`Q6U=QgqatP=ch zb1lv{F!NOFkGed525LskPL2=tUiBGc^EBe7V5&+c;K-1K`ONhkyI=zFJITG*Uaa3u zg`R=$Sr-L~myczhGI_4H2cK_P>+m`ThR1MBnQ`=&)%wWc1~2E5A@|J}*Pr}b4Ud}* z!1gub9DPDvpr+p(VXXTi5zBpv31|0EW;3L#i^y{|_I#=~{>ni>+Y&Zn--!oE=_ z#;>;{v2%~=9ThJo=QM%cL*d5E7d#$B_#f01z_I1rq9JV~U`m=iG@iQ%av-|5cCQA$ z%G{QYztF-TM=G2h8fg}N8Po3r{a`39QU>obM%$O$&4b$a+4D<*R@+}%;&{r04IQDF z3V)B_4>~Hb*zb$+>Mdfk8W9DeK~I*?-Uda}2jQrIs%pKfc1u(yJHi>L59HS}svrpc zvBHA<%@lg7d?tC;q8R6nl)jFt20p#;xC@bb9;{!jZvfF}uAKnxZ7{N6yQ58`(uawq ztXkVsX4EZG=z9>CLlzWXSMTj8sRXv+Pb7iZT}S}j`_^D2k8M_4Fn^GVs8z@)0cE3B z$;w2NWj^`tD_-5%h=O_TK5L#!u*6zHcRAh@_O=?FxXA4I5BqcYo1^pm#M1#w@*9+t zxw<2^wIm4k2q|OykPmJISDH}7MuheOj-AUn(>3D3p?I;3mG-Mq%*X>7cenDI>L{3}EHRWf zxQ@vi1gliTBw|r8zRft7o$cr*5fUZuq*qZUR#}78Sor0;7gm#7eR-L7WoI7mBmeC; z_QLd4Kr;6l`AiKg2%X7zhUu7oM)|Cl)OA5s`G|~Q8C@otpyX~gJIbD5Ond->kT^y6 za7{+~1bVlHIy77S9K}gp&Uo3qpX9h2fmq#1oS-bgMW$H}JyRsbTQMxpi6IYEGk19b zIC<8!A3&4Qp#nT}fUTXatqER}Cfnv?@6adpAX$nS@Etxr2Moma0Sm!1y8Fa|4+4%E z8HTg~s%y&`BlOwT?r?HT1g|wER+#UYQ0Xob*0dsahE}L*&x8$sBD9L?eZ#0HN!)~t zwEU9xo;5?E?g5vBh#%!anPan@YEjh~+v1GG2&B&83uE0g($Zv`VGxK}M}{m@O>kzA zr#H6jW+c?}a&xyZLP=e)F(vdt21pKEKZ9B!oL{_#DR!TwVF_xYt9N_B;;KIdDQfI8 zQpQ&>i>O3ac53$~LyaVFdPs%Hv(=StN*X$QLru2A!DNF&nv5#Okp(a@D0fhdlFqU3 zZRPeZ3-nYG0oLB;ahxB?<&^0a7$X&PK`%K;C$a0Z=P^$7(@>3V*vri&C7timgKN~V zqGhUV=1bc8&=UPe1{iFV!Kqfrnz&vM(>J=v7Iqc==FluAnKj%dcMUNKR(2syhYBSh zq+rYVwn6*B^FWAVgP|4Vi~O>pUjA3uf>;^eA51|WAe$D5m2UI5UGtV#J69l|;0lu=f(ZgBOa_IT5y zSMm??r&VI-b7$Ir&vW29otI?UkxGe?R0f~RRsqlE5=xRTEesva6{f+w^Yi@LX$GpS z)uUIxTAo;>Z|T{pxrDiSyLjEG%|F;ZItV-Xz(*CjN_(nYgY)+_*fI6dsp>OCz(=>f zxiS2>v2&hSOtpu>?$iYO@Lo|_sQ$Jw>7dR5hjE?F+O;S#bJEKyg3&E>lZMEim3G@W z$GI)yu@1DniqycZe7Zu$T>j>*mN|TgQGGN;GqTBlc+HuPis3u!REgcrqi=M8Cg9&5 zaBl#(E-x@7KZeY4W3z%{*F+Q$=3_ekRWsMyE#;~^xOQp8G#-R zwHtC6o!+Yg@8qNTfinqO|y@AtSZlvRVOQ-t;<-Z@nCvF-tjay z^T48yk;B7oj>jx?+y*B6N)F?qAp6VtH8ZN|!V_{?@F_2$yuEym#^Cf(vgKjn7RxZQZPsJ*>Q-@A>t8&x<&9 zD7$J*SkdPhP;y5__KhyGZrI42Ej{Q3gf;%r0+|NM_oSssc8bV_Ws-{M;C^J$yh$~H zJjNZ)tuZ#&M%fZ83v~}LhP~7NW1ZF1c#8Nli=pJ{qNbDPN%>gdqyp*@vy`y%p_g?J z?|Tzs+~aU`3APxM&v;Q|G3+8boZgm7?5fJNZt$nm9tCL#$hwvyyc0Mepl)&?AcgzQ5_8J(v>y2ENiG+cWHyOJ;b8uW zz4)YZqH_R`YraE9{5<ePTBdC<>YrPjp<>p9ec?P00Q%m<0rl!(T0Yi-P>yDVjqTIHWYcQ z1fZaIRkx9LjfB7(lVyshjBKcsMMaWkwCx@hxVkTm4g2F~5TY-KUFa;JIGcOW#6fg1 zW+~K7CH{WO0(U~(x_ZzY9GRb@MG>hM4rBf5`4edfNZKPW5#&EnSO3Szll^1l<^Q{In<{C`qX?pYhNjZl zrb$nTUI(`7SrnKm3Q%L}LsCfs8$*HaO}MzP!k?G?-Y6WF*qyn?c&IXOl=EWd_xbXQ+e?Fvxp{HHOWieBvA%*7`(w&lOqSXr)SA6y=-UaG z=o%~7BCjFTB@CC1LyrYZaQ$A3jeb_G;{*m+wI=;)r)DzJNaJ>srkqBt%e=m|COVp1 z$Po%Pnv}A$GPCpQ8XZHZ%8;#Rs0RscAH$)SYuBaY0&=^dr0-ml?Pa>@NqCbPM^Ye% z@D|(FLHkfnd$-yKx>!CzUw$i6zxgq}_;)n|+7GBFY&4`>%0m>KcfDYS9|d;^1P(Zpefo9hSS0F z$lSeQMy#hsM@~e%S}mb~;aSoF8VBCc0-bK#*#rLvFf?`t=9sfq*M6r%9l_Z3k`{fm z+Q4J28C4krrWhV*mTZ(12)Wj^&5-o6{IJ#&=32M&(m?LPVc8@@2KR1um5d=Bi&tb=JSf{LTDzFP$7LDIiw6JB$$mzH?)mLbD^2S?A1AO z>xhOl2?DXVy|IXD42a{e(7x(#uouS9C^hGMr(f@@gu{UGq%aDm&XG}2(H4N8f!P6b zD2%>?{oTM^ZJfwrz+0o)oMW(~3&pX@DCGMv#o>=!f*lVQ5t{ztPmsUR%rg^Q?Fa${ zl>P0Wc!c>M(X3$Thw3Vo&SwVQj~T7f;R60dMaH>3DI+PYv5y2CZuG^ zFsP)DRd2Y_cvQxv+{FCGZ!MAQ~b8I}4wm6Q>YGV^gv5sr5GLv_&TAxob_hcq_Ry9l4~VwZX)#^cK!pZ>G-L z>A3tZzQ%1sxcbS_b{*%pcE2y3c~Co>MxiPz$Zx7=9Y^b_ljW=S%jsxnd9;}LVgneD zvGvMjZr0sEg?}qwNNGDxAfYYPQ&;AmIaw~+QtCMzz_7N=LkDYJJ>I`yA;Xpw5Y9Cq zT?<%Xnqsnl31UXS0s{HgxkQzXF@24sxjn`i^047&?3o6gU#3u9id`(yB@AK5NW|g| z(_LQll;g3`L`DqKrx)Fy>1sK2nyIk^8caJ_0TUSn81N>#6bP0JuhaSs1hGT-qntHz3%NDqb&CUp-x2--EXfJ&H}OA!%>w-= z!1DYjfE6+|vv)ETvvhKHQFb-@-@^EB$Zb-!RbJ3Q^`j%8tS?91a(A^p*RsH_xFu5X z0Y*iIX^o;+9swM&b=eYI&Pysenww|*&a2;gf~ez$W_B}s$YTC1ca={p6i9eBElVnX zT0hEuTX)WLz8vx2`ut`9%Fp=T-Tis@Tq~7eUD;1VnG~s}#uRC`c-r2lyTP=WsfujU z5<=KYY|$`|t6B+dyJ-0f$FyM*PTVBfOSJl?z2c3L4n_}eC%9>(jfk?Bk_2u zti_t6I@ZuqXE0r;bwT%ptG)Ju^}3y=n$9IO)CTN^ovJ%>8X(z6BORxp%thJVo?#Lp zc;Jc1$Jr8sj{TV<64J}d0dkJQ1Sgen2U57!6j^u;&V!i;ceH1l-g9Z&jI?8SwOw

D4ii5U)8pSQ%EF)}Pk=FpU6G*dMWV z=Tz*G&b=b4GdF4%cKUIfrQ7(}IxE#7w%{j`PN+0@1RaJxIeV8hTrzUUb#jmJzfG-7t}@^-6aQZRI272}=n)<#_!)zZXE zLXawGEbW%d%s>9BQHKP70+ORnL^8DQ#Oum|ZFtUJP@( zNeRWCRFIWIjt5bk2hfK(5aHX5seqNn7ztIOrdO*RMjR0~YOws8Jc3i&iMR~lN)$#~ zUq{(-?!rYiT#aHFKy<9OrNqa#a3?&sUB9VwW(wt9+POIYR2OlM+nKrUZmi5k;JO8R z;vYNgjt1KYw40sOQs_5OKZ zkz$d~O7atAQWbCIv*-NopX=e_Nj=$+-IDWqb%@UG-LsEe5Z$t>i1_SJJaW8c_0r#a zncLZ@CTeOEV{60i#75glbN;kG;(9iyyZ4AmGq+`7A8n8lc zIr+}(mVd|pS61t0B%~Vuk)TJcQ>tmbX`<)F80X%wx^RxmH(eKx!_!5(^50cH&OnB_@5 zDWDAg%J?o?`v9{GUW2?kE2{yattuS@Awrw$t#rEawo5?zHR|%7bWYA%| zI^=w$HHw#YZ{MnCAs(1b<&eg)A216Q#RC$4_HXv`9`$lOo!rOKUMHS6#kQ1=p&eyv zoR+ViI=I#Mf+y*%UBZ;IhC1Zawj$TE>I)lfGL$oB@8Q@z6jmbs8LD`F>2^o2*5OrL@YXt zoJ}oeI4-tu+{pAo!;TY*JC$qIZe_CS)1r-z1!BsVL!u+ZS^ipfnKP=GFKi0oeo|p; zpE?(v%Edz1U$;NG%cm?Y9nJ{)NcMD|JVzD1YhkRxmDL_BO}WX%&NLlPy>ACdGZscn zGbHY+JYgx3Y#Z?v4)YlQz22ZdjAnt6sCNP_g17HNckAeT2XYW!56})Ic~A>I_P?SD zF*w>mePV5o-0A#{cQI=1m8p%)1z6>V3o&<|4pvf90;t=Pnr9emWtOEFE-1bCN1eF@ z?=Du&t3=gk`lS(FkgZM=xEWwTl^r_$A_MF?ORChbm5IUYM{R)Ya)nluE@_dN5l$8_ zei7b72lIt$jnKIMFr7-#9)0v$C$M=7TA|aRzsg)QtteKNm0I0zHcF4(Eickhi~*d4 zAIT=06)vexoE(JVMnVP^|K<)Ew0l%gTaOk@Kx<*J$z+G|Vp$`L)Eh_1-10+EnBhO0 zzPmCbC@cbZL=+Zb9mug(?MP-90!e*nl5+c=hfk*6V1i@p zDdLd&!)2!Hdix>7-+<<#y2&eYFr{Y9z*!W|u_YtrqvD<%^*;i5sBbShtsc-Oko6#U zMf+?|&Xq|zWj+-fI?_M_zM>>gNjN=J)7IpBx`%P$fp&B+=w$7`~QBQ$l=hO$Mp%x>T@iP{KRJsDp_6xO$-)@NrXljrnLj5%h39>gW190b>FNR_#T zaMZfe@5dM#UwF-;Q7bO61riMc-$h+uQR^>$DzD^{R4#6m)e&=Iaw_;gpw>_pdgphS zh4Y#;xI?r1DI2mXG)Sdt&PAv`4<4vIkoTYI_&v~Z_ti(@RFOe}47&0+KkIl~#oF^-lwFaR=yPJf2yb323DD(SqFvY?VnG!hIG7Be0j+ZS*KY$(Lig2@pn zeB8h$l8lBnds~59HUy(1tG9)zs0s%ZZ`WZ@B!rr2Y@$jgifj}s1TKY0@G5VES&VI7 zDPTmwBoK{Zp6pYuphS=s)xX+EiY_QS&Io+intCC>ixO#7!qkD;-3uV0j0L-&=4ivT zX5m%BgHxpWYCSyV_7)~t{0LwEa28$s=G996NQ!5!A{V2G#XEIP```-_7lp&g`SCOC z!v~3;w6NQh2>F3F%PZWZ_WJrE0A!P-2zmV;;ReteD*$}O0v^fXX!Ba;0gNAh69)Q8 z9H8$*RPVTc4N%V==7JKJ6HdH7#&5l531oSOu|Clk`g9*$ zN4y+~j11P6elt!^&9W#>iX@hQ;1ulRlQQ&8thiIHnAtP&3_QKVsF>ELeC|;^{fq!_ zhMri#YPYF%cdXQ{S^WA}LjuOZDQy%S2*@1%pS1Hos)%JRot-W1%>P!;KkcFaPC9dv zbnO=yP($@wv=_`Mtzp21mkDfUujFP0n+OqQ98}pv<`6ram0Mt>v#BJ>2?t3&5in!| zi5&Y7w#5nM8c=P^=lP7r+_H~+%%9H2PSFdQ=oFGh(UwNcK=L3y-mE_3us zwy{#eh@o&b`pa%LsIm!OcUrOR4D^Ov*MB*HsRxmq!7|6{xbHu=zMLRG5lf>*u5osMeRny* zW+GmvQWtCeKl0#Ondo%z1+a`vZ!J5 z;p5v+`l{UNtYN4L>MAr9VktK@XwJc19-C6zrNRX6D`5t%1txc_$69v?t+iB^R@0%j z8AhdRQ4Y!KMVzt5O7=x9WY;-e&Ub6D!Xo29TB1-x9U?PF`~W;8VMO=!Xx2!{cFzCt zYTBtKCX%;-go&92Jyju!N9RZ!RAcY*u}|iez$WvDok^cc25Q9g=r6Hcf@tV^v2QQb2&uyp}1WE z-#-@+pnk{TQ(qXFHNGwC%;zaluEiJ-;OH7b@R;9Lqij2o*r1{n+hnHLLE}c27wKx1 zbz3Hc4uvvu3TwB6UlO(%z*EHo1oUE|{p*x}1#S{_3;}ed-jTD2RiF|{Mo+Z~0 zkf=Py*QvojtsJr%&SAu{3ag+Z46vB}WOg`(J5B4AMQ^q2)2j_)4LdDK?D1NG(BIP` zT+4k^@K}UrRZT0*^hR-Jumf}TAY=({F@l@mRBN4v9@FkG+&xh21E4?eox zqxL!956jJc!ChkX1A)_jM+mQoaU)&jb_w;?KOU`jRV1Yo7L-({CeZ*g!0XqP+`yd!BEbfI@d^uYDIB z`*RyEJxmd$f|LR~(4BBh_F_om-4W|(>`hkB7DwbkIrC_$Qd#m_Y+y0C3`-l7*sRg6 z(vK;8aw$dzLX@9W-!7_`mh2`xDFP4`@PZ?5jy0%|>rk+^9^hh8+j0{x6){1}#d&|6 zz{<*)U9d=1`=Wh|N{x)iQ0VA`YKLyR%7wQd{V7TTNpUVod(r(}$M?etUW!3ElqeZY zMQBRL_|3%}A)4NxqkHqs`M$P5_Yv2slnmICdb@7(&5@x_%&Oj-q9r0Me&>;rysH71BQ_P2Ojb&J#PF1OUvZ)q#bQjCKL zd}8A~7(Z<6W^beckqf^6K@B|hs`jyy`bY;h9BC{)p{6){$y~nfiOh z)i#TJgLeT5Lg!Ve=E|F}NsU0Ztd^j!&SOyCV_;XVr+$kQ`Ol1D4DqO8CVuM;7boqU zfn=i`j5AJV1Qw4udHkp6Pl<#0)l}**Dmvn%&_HS`B@K;UQkn{hxGo-HDu)p?Sm}dt z9&koo`JGe!Uu78WVu8=VX#rp3u;8#0&gH6ll^T69EH!&%!Z%ybNd=a!Au0}U{0Dz@ zptwG=g9PM>2a8{lpWYQblVwY>KJ=k(h!;&-1HKFSTamXaCUOUhN2m=)^U)tM-k08l z8p*N*yI;+9q+cZ#52U=uG2Tx|+&>V)B@RXsPdNv_kP2S_X;^f71Nj}}yl-_x;X@W) zAjT&7#o^l)KT$j?5Xh6S$tz5!kF&D`QROpa)$vNE-}&7wv>)-$Q`{rM{sLSMTCrQsr?K{h1uE$hMc4^Y;f~Ug3}oG%eXToN z@%-W9isy}9Oa?-EFSA8qu@fOa~?)OmKXQ_rnnu|D<}(J zOW%7eriLK8KwmSBU0R7k-S7#0A?JhCFwB}U=(8lH5atR2D>vzejsjSpXcuM=b>=bo z=0dJfrhop+CwxZ=x$*x)G?D*EH2nX`J*(PT|3_UmW!pbvA4I>@X4G*_ngdy|A(SRs z+c*jlP~$+7;X&|dRhfv0-uK7ss`9WN4pXDqJJlRn*TGldBq$z@?xb{as>w9{VAJmOeqrAnpNb3B3Jd|TRZ?TWh;V^;CN zsRZXilpF-$-3RM`KQotjE|^fLxhFXetYH{zWdVp$ar?wsv$@MwV@XV~QnD8383KOY zO(Mn34avuUlBZgO$pb_#{f9R}(@^rZNM73BO9NSIO5;Vu1fhk4BnT=6`ch`Gl^MSG z&1M-$WD$AveW+SCQ6|a)q8w(ZHhs+$&c-9qF7Nt^NN5v|Mn_=O;~LyYfM&L6d`ya&%j#p*xdK`+ z0sQWMb|)z83HTvLw=hNuE#B%nD><|6rrv(#}BqSLA@$D}W-T3LEZ1xA&t^a5({&^_>H+lV=Zu+WftD~r+ ze#Sz{h1W}6&ub*dTcLmus?`yBL?Kb5AyZMr7%dF!$4ASU?M{m1>uK4332arw`QDUR zKNP|>*OpY>(hxs@N`XJOFJ9 zX5m9PFaYtpNsPONHn05p?X8^BLAg<$dbOpYNqWn^m&516aK0r(26n|n@lcZwLTW@@ zD_mjCywX-O2#nL`?S~`A0)(Gw%8)}Mud5S^QjeWgZ@cl$HAM0Wx5AP`hxvTMD8TUQ zH2)Nrks?JRUpz9aIFroB!(VpqR~O}R349~29p_{5Ve*nAs}NDm-gB?~(;;Yt;vu{) zNK}D4E1T}_QfsR&S|}A;f=Q!aI00z6kdhyUDIy0{ z4~eo#ggCMy8+ksBBVjbUs3SHyGraXNmt$8WtwbNOZwaY4_`i>JsCJh4dBh*m=)&Ky z9L?2>UxJGxLRq=WwF5EG`@tB6r!)u%Vj`Dhy)^oMVVi5ZwW;K>Y0X~*B%9uVweRLh z7F-}rxl!!0su$0#Rklm_Q_NYG`#C6BY8jtxEm?EyiQ^R~8?g=ldQD)XBS{L?o(j(1 zV5mNB3S^=zQsiwlo(EgO(8e9VZpe|4QF&)@$RcdL=>l=8nQb8@&%3QH18O2rX)6j-cEU3plH* zQ7Y5Q!%Q^ghlr&K>C4dzIVA#j2s?EqmWayPy_$MVYE&dGGZYe96cA^L2Iw+K#YctYO(y?8HCKF$V`FV1)Aucfx;y>mJtx{f6RN6>0A2 z(93zu=3IHi?T&HBcW#@j!9a|n;0@CYVx51W zKE%Y^6UbI`2Yd?XhxW_4EME`pFO>MV`xg&3?-26N2)b!<~aKRsj($bi&F1q;#n#@hsh`Ba32QdPcJNk}xR^vG)I zM^YLaw}DIWzSZ1Uh|XpHS#2JOf>BN_`_AiUh|YU+j{?WdsZu!EX~i)^bEb@prwq@- zoR5bqd_PczXmVJ6USBT$M~+4!bGFu+;9=p6MFo~*Mki0zB-_PVV@}~66ZW=Y)2M|w z>jt!ms+-AB)ltoY8&%Dp9xTZ-!%j|orCgkJj-IX>WctokI6YdkEKD|z3x!oCnAkV~ z94shaOHku$T1+tJ0s9Ipb4V;Rwp>4K(&4MI(xDVe;O~q4*jDrzn1o=18pn3Qg>A59cfl7(0gdLt$#XwQVCmc?xQbXv?Y2s zt%0Jd8(5Cxb2 z>Mg`4pFIo;1`^grlY=VrwGi)(6Jud5z%#Gtq{s-S!=Hwx$IlE|*7kdrUR_gBhx0%V z|P2f<*Zi`^-RsG#jwfE zCRk#aATa283)auMq!0IVRq1D{bt|2Qcix|77=sO80ku1vs(GstClm@bI-JsQE)z@4 zF63Ih4XFU=(PUQhSYQQZ_A2keKqCe1_3FTmk!TT&(@#JPsG{qf0rBN5$M_46u0yDX z{{!VBL`RqcE3-tTvl&1`pZL&1!KTQkDK_bZ>~2qZGAbU7pN!$8=;k%NVC>?HqffI? zTNx(A8GD}S9#|C(4zI_G$mw@Ieos>WXFN0wZf|_K=C*$phM<2c%10OLajoPdG*h6B zl}&jdcp(e5wdpZ?GxIv`i0Y~SNjZV5bIhZpz5@Gse!n_YFw;u7D}F=aCz+-rwTXvD zQ87DpMa_Xfs&2iCREj1ttofTQx=Kn=1FMZk&2t_P$sO9Ym- zMsu9=S5jKWBxiy<9FjBi$7?gFs`9s*B-wKG_}jmbRu{&;xrlU&A0bUcf8d;Kpn1(8 zO~detybk%^lM{zwnmmIqOSJW0BM*pU%Ff_zZ}3JZ2~(*#QGDXXw&6uMUg2?dbk6zu z)ZKSJkGKaHz{j2Z{w9wE^$UqEA{F;jNTHwNhp5)@?v?cGQ^FllN<7(b61sTp>E&NQ z2xGsmkxCbsAzF82adz1TY<>-Syy!H-628#-?DTH<7N?d!_wp8q3>Fo8A@$vaCkHeA|SyseLWlcxbcWNHL@$E3;<1M@XWRWiyDC%PmVDB2J+|Jrp(+89DP`BSHA{v(Uh{8u0LUs&|-e$T&g zsqMcSd8pYz7FE?Lmue$+=*ek1yjdX#6&Wp*iHuc)*ZC8 zY%9A#%0;{^C$?qF@{P@Osi~|>qumgfod}w}DMt6h0iIFhFf)K6U1Oo(Mi%z29AsBi@ItSOp(C@SXm;_l+P zLHua5Y*KV+&=ArT%4JZ94;gtB!Vl__V`cs0{dG(_5t2md!1bH4qHoyTY&0C85B~4y zk2c9W92A8r{cIJWFV@cJ6{Yo))DePW6NtZyGql(@2%W%zn}!`?Hsq7TTC7#DuFAWB zGq}x9(Vcq!QaYQ(hiJh+UODL>mwf-NDQ9W-X93dA(1za3^3Srhf}x9rij$$6sgtvz zjj)BOv9+nwzg<;~>V`9lD(cq;`igC)kY;yDKQgLNCK~~&)QbXS{#>KMw_gTL>vndD zC0QG$?h8sth&|Uy>S260!=x4wW3@a>q_JNsL(U{g`)^X#7j+`>FJaj4i)ZckI#tM(60At#L`!%iKr$Ra)p!!+(~5si3?%yxX51 z2Wx&9z$RoXKfpSUH-ZYM?WHJ@#$nJTFkJ|Eu(c?ODwRxM=ld+}AqQ()W&~ZM(imIx z432n?@48XCdfg{7fPhg$vL;~z#$mHLc$19{Ffa@G=%JyQdZ|$@#ChIU=rKG>b-5bP zEayuNWOxj4#Y070Kr=AiG+>PTJeFF?-%WJ_)Q@9R2eVD9Ye+~P> zt}etvKQ0hU6UE2KaI11dX2nMoVnAp+0{OyD>}H5Dg%Kb3Az1}V>Lj9R#LHpQF;kbh z=nYEGf2`>IBEN^8SE1Vd`re8x;)qpQzu4Z6)Y$!hOV%`WmnNwdH!!c2T+>lBP3gHzNm zxq;V29dZbwwP&>Pjn1j3QQTFd+YaFH973$Y@dG1<#YQjl?6lGXw@h2Xfbio}NY057hi=aDPuEHD5#%7XV2owY8!Qg?A^l7+Dtt#;J8b znnPu?it}Zij}hu(+BgB5!|l4TY)d}dMwb>m&0Ay>3zH+{nbf{_LN_PZ5@Dwz&mR~m zBhPE2@$;v^Ik)`2!@Hej(e8MXw(&fIh-e=-Z1vzObM78AeR}k+Zljn3+VWwQaJMOL z&_sQgU<|K#rSt^dlHw)%jUUYB07Nh*ho-rZhvn)_T-vJ88R?HlB)(LZR#8p)bho~Y zYgHd99l3@6QeQzChT+#X@6@>Ql1?h?Rik_@0Gb{}K}iP=^hY#0IrSH z`~_<$zT-Bq9P_Vu>~?kkxs_5<^er|a8C)aH%K zugqsJaEv=<%qjP1ixA6jtVt|7S>tG@+Th5Y!SKUiEPDxps@h*RpfE_+q#w3~-kFeE zE3%F6nT!&#Ek87S48ZUbbdo1t)~5|$mD5S$>1Y!>*wnzD#gTQVD}1vRFi;ZIJ< zmW}h_snQZ6b|iZF?&sZT`R-(KfVonB(IP~^+|88vNKe1`nfo+Z{Cxk)ShoFB_SVze zrTN=h4}w2P9fm%`db^)*@sSltkyXLX1dU9BN>m%#}Hh!%dWVoYYr} z>fREIK1J?FY35Ng2*SWBl&h31CKaK)Ia%u=g~m|bX};a*G-2ql#Yh{FkH$q92*0qk zV9waJ-vHIkPtzRkVc3CT3#r6oH6grmK+uz0Ht}_XEtoZCXQl_70j(N)0a!KcSuUsG z19ow=PcWNdSLGYAc;|^M=>@;W7Ix{2zwQJxP@=y<~IyE z6GIym6C@;!dI{M<#5g(#y5;IjqR8bsVGZw`z6D#0Bt8*KoaQaW&*O6E6%mm~(7c?$q2$cqFrN__WklD|_h2C8;-5 zDj-s@w;!A=S(Who6>BQE6HA<`o+Ryw2QWXrOlzLN?4Gt|`QZuLikHRBrQqo)I3#{E zt1e(Ii2g2LgZRb~-16Z86V`?3Pb&`39{BOXJg}7Zm>p;gYul6@S8ldM)w*}sycU5K za4nCmE}Mi+3J~mhE8Hd-I7}g=#4-aDhJ|}m!@nKNx2*>Daby zyOR!Ye*1jqj{EI<&K_f}QR5x&TK`nlQ&rD==A2bYBr$9z6+%tc-rTqgQ1^gBo6>eq zUuKxA^PvvKr=@$LlfFQ6g+(u7RBeE>7N7O{zH;?T)zCo;Fmm{i@}AzKMlY%sm{fLN z*xFZDxlMz+S_j}Z_Au%b_c9J`T)ag4kVcI<85#b~en7zzy1^ z5VZyGR;68Nz?q;VNncl6^nZy{mQZOQ4IdAMYZ(TMx>{Eb7sxGJDD;)2WltgrkD-wB zHM8mxbS~V}X~YeJNtkhdA$^aiENpS4{ock;L`#_TB&=#N25y3SJ!Y z@hObNytE?t@qB;$EP;y1Ktib@ZSF=}ylmqQVrcTN_K6dUw7L83)(jm(ShA#)EC06= zW`etrWSAjo$xOw7ZrgBp#tBmr`n`OrpfIRCD{ze)QSU;i937!~*m}>&z)&@LN_T2c zHw40t)*Uy^V+?B7soi<-7w78%`xi~Ku&YJU=dgy%zVc*1rZ+JoDWiEV&z>w09Ib?I zKP;p8JYNQJ%kpTlG->!C2IR$dJxecHyyvfb`5`+|FmoT zn-J2?6=2Kw|85k2%U_OXW#1w96$MObH6=a*LH)hgc4%c=y!Q{zB_x0DG#?LLVJWP+P1P+Wwv#e z(l%S*)MsbxlC`u>rGQW#rmI9$nCjs(qPc`RN@~o)cCu#^#vUg7%DI@>9?Q6=i8O1x zRs}SdpObM-SA&R?3;V2JHRp8nYjzsJefT$8RlFsXx`dSjVuvK@$&2niXO|vYEmk&I z(D?o5RPMa&-E{f-;dP59P&VLt8^^rJYiNh8Ivoz^H0_|-;Rx1?S(!sr?$7+!=VE64 z;Akb2gGv!FT2q)BC`2dyCuc4c!j48%?n{8FsBkq>*o-mD?x7hj)Nh4zr7u* zM;NEr$>SaUVIC)2`2*I!qZ-O6o84#`9Y%A8B&eo+VN>CryJM0O;sysCyl*c=DLW_G z+*HQ{)ryDrXEWNjg`xzEsiEh{u1xF*Y%Oy#N$#QQ-1$LFztn-p!ZkH#urMl_my2U% zlE_w9QXuYgC;H-w_M6ygD$lcS0B6L8sW?TmFpa#cQ2sfVpR8tq>b));fOnLOz zr?3cfrzQgAr02IzXT-a!#Uh*9pus`MMaF0gDkJojp+&i7)Sq+!AT2vkun(PwOx^4c z7s5`FjK6NY@Ftzb@lMhogH93jv%RRnY6(UJO%5tYP?6%NQ1EIxRinnCpWozn2pkYDhY{tmd!){O^D%$!QMd8{(+;R z1(eq)d~yCbe?kLLx8}4uSNWCBo*Owcue4NE{qNa5(!HzaaOY{FbjA@wxx86{ZChHH z+>7c>Fb+Gv2+M9Lg82wDUW;G;SuNH**GQ=^}OGtnIie<$n z^`}y@ROWpN25)~Ad-tXrCtF}^t`|GZwL1`5n&q;(iS~->V~ss~OIg>dL)V4dKPfcU zOHjEdjc#0kd(%tIPG!cYx!r-L8ua0u=1BvlrWMp5#0PR8Z{9A?tS~ag z6UKCnQf8Z|wpI!6$&s6AKW!Nd>4@~}UB6icLZ)XJapilNS~3)MpF5XN!>F%O_3-S3*Cn&jFWH~QZLoL~)d(=s?LZrMR_5g(>nIdgDZx)ZUE z-k<<=N&}%6T~Kdqr2Oe?s}^X67YL2<(+4yS$?L+JM~1V2z~?(- z_$3WEc^E3V__6twZ5qh+pnh`O_SkB2zC7O_N5A;+tTRMxpx1-#$S-2%3PZY{oW9P} zg~U18VUoGF@J$JOJ5{bg5Efs>JmETQynHwm9I|$P@GS;cP2l#AECrD4R8js4-tw%W zQkk*-WFXj~*=Sb6A#Zt}gj~5Ow91xf9@6HJ5%eia7;P$IesR$q8cPylf_(T;Dbq)| zXxg_%f|_9{R3J8+acFS)cTX|jH=#B4kU9At6thjmbDpyuJ@6BvQLve~6ShBd($k@Q z{endjJ5d55l1A}!*ZkR^&^F)M;<6Pwtz3)yaI{GNN(4rqV}Aa)|Mifg*5?PUqfwh;`fAn^Qam zHTHB%k6J?RfhgNNhW@+A1i4crR=8u7yEL4LALD^zn&<$nJH!76cHepG4)rzuAIlRz z4{4<%`5;)l^cjwctIvW`%qAG+e5TVEs%@xMU4=tE1^?xMe-fAAsd8uBF9Nm;?0?#V z1pe>D<$v6Q!~iZ|V#GehIM>wRORak`kHc3R%{`&dQQEd^M7kFQi}(sbY;7x#xbMgGdh-gtFBj zYHFd=)I>HnufXf!dU*V|Ql{yfqsQ~ZJ=vn(tm%+>78!{~J2@=*mSb%W&D8S)AA4CO zhEV!eMyl0A|KF?Vla~H7_pvHj>%Y^PIu(8ocXcivb1{1QM5$KOeVjQ!Hp}<85c`>s z=W}uMdjZxwQ@)u>Eo}&K40e7|D++0OL*owUb?H|u>8jI?t>9HP+y%9WP)>=2}lD~zroG*xt( zwdR-sPm2+or+TI{oM~24D09d^@ycsx>BZ?@S=S#!br&(4}NqCc`Ozq~K>h7r@J-x#F+>F*tQ-M3^t1rrR;QC;+Q|KiTl zld$dGt>E%7`%wg|2!ao8#TchUOOx9)P zzhbD)=|lW_!{&OI!zdOnP8f&&RYnzr*!D@8Xb`_i%8ai)vg62X-Y1B<5R7gh{|POI zE-UV%FJ8ywf8=#A{@JHyoBDv3*U7Oqt1J@L3dtSnsFPzJxKx{dfQ5i6(V5 zN7Znir)<@5UB&5u&+jV(z@E#=N#*k~K~k?8U|jd*c+K{WIgaI8!aM+F03gZikfNMS zOYnyZ(M)ml-WTck!#z!|2FD)*oY_2(fn^EJjWe>T`SI!+A;x%5WHnng!-~Bn6Ib`c z4O%3BLjh9bC#YSr5Py?0mi8GIx`ECZi+O(+n_JudxWkdj?IbIuD3Rf|e1CyX%zdXRDT;#LU->$L>+(j7d^=5Zfp>{&T190pNJCWSljaBbJ} zb82@O*Ur)n<#It048u?sA`AlBVE|%sasEr<2|aIU-KE1f0p-ceoq7av-*hcPo8Iq> z-Kd3xwR*f*5T(pO$uwoiF)(8H_ieO=rpO3S-)~@mUr8w`-5Ynh!8d)@W~zzt5fdNeSLt> z-Fy5ujQX*g!7d-%rs*nr`)jCf(`qgE<;=#5d_hNkg0?`zQ%HPae`>y7QQ#OaRn`HAA;>z{&>6&k+9?xyr#b;e_>^pjzx{& zBxoZ_=xaK1jmjbCDtLe%e9D_izD!6B-t;T?T|Ydg^ilN*d}du9 z(K_sr!UIgf;7=vts)XP5oc%bx({^od(cx1#uvG@wWz5`~>DjA0Y z#&ferTaLE-Jj-*x!taWZ)?R$>5g-2;`$7L|(4^FSo>X^lUhBEJoRHp;UHG0}Q7O?&4PLEINIa^tR;a652@`7wH3U}; z_ndH}X;8@Ti6<3Hp&M#5;(g>Yn)C@1nZtmdw(D-FM;r{c50L6-cLh&Ewzf{oeGL~UxQCrN5GmSmlqglj%&52)kY>j*{B~-FWBP{w*HGb(8g`<7G9S`ZMj%spv3$krv^84{bFgu~j z70;21E*#kzaUQAHFF~T~O5+80tva71^$Gnb&x${;n6Ow-GG7!hW3bRl%65T`;}SNr zKDtw3=1}op7C5!0_$Gp1Y+>-Py!(GgYT5qhRr$ZelX?a9##&!G@`ZkBVQl!?BQkhHStesG(d!}{#0To)^NWa5C}UeUDm zFEQyD#mwiT1y*o5U8x7-E9WVXrPrLlf6vD?za2A=-*}sor+HN{I^JhE!n~y0V?2h~ zx2JrGqqm)N%m(S9fU?H0SI{b{ZE0-deZEJFG`RvA2hEfy-c89>H`a63&s_ALw|taU z6SixZHqG)u;>7%SGC^|IWN!9i0qEaNm5w(v*#_muG2o~*Q|HJ>VVk8Gr46cKGJan% za5s;`in`4C)$?iJkN4fuC%x9F&GgniQ5zlrB%e4YyA&V)RrWH^PZQyXY#}QA&pzF6^AXg^%ot!#u(EblKava>xB>& z{1uDm*!hXz5L@BHApw+YCH9?b0a$gIOmJW!wUA9G4HW<;8C(p3^~)kQXdjMWxWD+k zqtu4=VvDW0O;u+471#+37KW>saSAdv?D(TI*#H}4@RSS#s_fnMgIpny7+~wxwD=mv z4<2dC<(NnWQ~L9J6M?6QM1o1g^A(R)|0xkFs3le*{V!$5I4j{MCETq2EnQCpv%MzpH0uTOJ`BE{V3!zQOrXwnpEr99$3!Yks^42eno_nF7XDc z>{`=nNId^&6F$S?dY<}6(w8NpgYdj65)H`)L3vqxOF>f9KF*j!%WhM)Erj+3h|G_` znvcj+cD+f}h;!(^O>a!Y!ApFR>*HJy(~dQG93dh>#nO+HCsE!lR> zwmHLg?!taf8g$p<&()RL@ggs)*Dp3Dq7mItmEt=zc5vkN%nAE;sUVr4h$!_)Ey4&G z8j=WgVbF7rtDMywKQ^Kxr_ayq&(Gd@*K|=md?QbpP(=Y^rZr0mJl3DRuk<7fT z3wU-4aGWiilntkPEavFIRXIr>UNh9|73%e|bv?YMJN!sxUglKB()-C-W7?FK^(+@s zd;sloqAQ@PrFwUr{>qI*a|#htm6{}ORUua`a%H2f-lc!&Xjm?SXeN)I2iixH#T-_{ zJSVXRc^F4#ReuJx0ATJXDhvas&Ve1n3}^yHK148LZTIK=gwadt^w%MKpK}bJq-LC zl%u@o!6??*H@xO^XsN%G{&6Ei;SY2?=COy%fEw@+dq89g!0hnBU2NFKn>URcM2o2~O+ zPQC4hny9Rd6nf!}AGn}eu~}fTti0|zf0gfSjbe?Q#@pY8>G~(Xvzb;CvH9rs@&Fs) zJ4KAvGJ;$hwo8p-8?Q*CFq@3@zqJ&mY)tB~%uF?o23=}}(#hBRF0F2{>@+)O z*rx2nZs$hxqxA^m!4wj}d!O3`K^a#}8I12>)1x`(#B88aLf$u0}@;!!l zlKu)J%zrt1U%RxVQ=jTQ4!TCpW=kV&r{57|B(T@^pxW4HM!KCQM}WDtwuQtE91X0} z7<3rCNljajRyb3^O@;pw>}&Tm!F0E{4<#}<-X*wq^l6O4#OxC8BygBX86KzAFlLM3 z^y=8Y_+WuQ5Qw4zxIKj*&qGM&_e5KZntr7|MnoSM`^YHk^skQ?~~ zqf<-2)l;6tU!&bPvGNMyiI`gq6FxR|v=pSB`jBtdEE|1^Q4QW}9TQkK#=Y%aZe2^l zsWvBjsD(s05DxMz?wg)L&CikSdME6Q=0S628r1aO+%H4ubRjZ3s`NVt6x0X$&}9`a zRIZLZLPE}$FM=cv94on-zO zW~f=K#y|G3B6E7Rvb$!`tmgS=(>B!3yk}UGkww#snb)$*cVC!pZeAo4h$-g0ItYtq zOIGY7h!$EcZpp9=b{W>V$Zs-SiuP3n1wT(*<7;$h^zKio6qBA~Xs%nd5>PZ~l+A`M zY+%+n_8>;V;ZXz`SU9Pg`^B@KFVFZ`qRRuf$*GSL{r>ce^BPjWQi8X9h$)xy>GvIe z6NqP2;z6OA&%ILdrSED#jehpqd?5ch)isGja}BkJ*i|C&$0J6taSWtwm#A*I z9q~8xV4;4Fen(w-=wmyE`NG>z2*Y{Q0NE_DutuC?=Gc&KR98CJVRq{GV3n7l>?ByU z>c5nq%8DOJ{@x(ZKko>2h{~{@Ip&9dp}#cxlB&sRmvmmwM6rpdlvYgs3{h_C8UKXe zR(<{81@#+vMAUc`nV5>Pf`3M2-#Na`3lc|k!+jRO4;wC54;UBS)ZzNT{Y33S*UMQ< zPc+u$eIsOcB9DqIrAK6MVZ5u;4Z83o|3R%i06OZ+sO^|-Qe%V&K3K+WEA!@mk_Yi) zsP=$ zq)HV4M>1UPOUB(VUq(&*oseN%i}SB5^cc)z3%oNwG=<7)Cw_9unyg`>x{OT`x9_00U;TQ;~3+aXt&l6APj)LnBz zh7h~KeI49pMW!x*8vxaD*Zu$}a#M1KJ9g}8!p8e+eyk33yf)Un(R6U53HGfj7?jfG zk7CP-zSm{r`BANXi%NxmJ5nsChuE}>ZawSmIVF0P`6-1Rm-!vHtMjIs==r^$qFGNY zG};IhrCFdyzVQDPN)wAVh%FAtS^Jx)cb$`Fn)+?jrjjzwP1ZUJA2#rI$(!;K7oAXJII?0lbb=RjUx$~^bceAgZF&ZWOQabj5cUraJ zaioSvS0k7#lHE&ube6HckoUuO8@jR=F7nGy?A0+Z6i69jE_`Q%!}R38a)xQaXEPlq zy_n{Gzisk#NID{~@7o z*=}!VpK@4PUYlK8;)&}zuDiyAm@@w4=HrSCzHN5ue8EG=3tmj7GCp9bfql&aX6uW* zlMQ)#;$=Xi<&rN)ALP6dh)tr||4=rq^Tb&>`LN-rgMKD%hqEO$iQ@U0)6$y-x-IDl zqgx^O-cN2cwn%-T|3=qqa;D`77ky(eW%H=Le~NfbYUbE!i9)$oeJdI+yloPP;ebq?rTXX7xkapu^ zX`FHcdG$1&*AGi5r1&b{snnM@cx^p^DG-&(y22G%J4AVF;=8yT=k(?VZRqgwit-z~ zhI%(o_IZix<4}aoR?N@x=J4+Mf{h3jichQ{w1V=gHhhZ}~vsXYfjr^B9?-wfaW`lq3MK2iVr zMP7f%KTqI)&SAb9^gsFkG#)qnUw_+8GfRX$mrA$0cMjcD-hDJ_b8b(h*_R zlPic31J#5}hGXf6(%Wb7B=!Q2Dt7ohN3&FazH_hf_3$1fYHXCIcfo{v6Y`z+By>yx z|79FC%aTWg2!6Dwc%ZW2Db*MCM@t8;2uBvjJZ^`l58xDtD zL`j}T#wN|7UcAC0iI!P>3?}^_1Xz3?B>NGs|OLNp5Cb!l2M0`bL1v@#0p9NlA z-{AdLq!#zXC-zEs(kmuu19+?~dq5;M1NqRdX}5>O<_lWn{eroVCl;1@82X>+82#DE zY6bLA&Z)(C*=*fU)$0?;(wV2mZparx&D30iv4KU(hBmmtP}^|QV;yX4i9+r0NwH((>I z#b@4ue}8F7d?EEU#lwePmcwO>LjP{;6a1e70+Nyb(cYIaQVZUHf~x5M=ge91U$)um zU*@(_4tC~p4h}YMj{lZL$ExTnE(oFV_k&#e=eHK-KZ~ntp|rCj1L09nlfem6joh_S z^EgC#*XemL+2%1sW5_j3ua_}I?wjG%K7`}{a*81rIwkehxeL& zXFWn2FIu8ywXXfPPQ4!bP~ZU|pM+N}H@_7_%l=gC zXkbGyEW*p%wk{vCrCwk~%|2lQx(_!m`IgQLl>FTo;7PWz&_mY0q2c1wxXyEO`HQnf zXVRc$-uB7;>FX+z#U%$Z%0=M=L1QLPJ!~=Im*fH^UH?(0SC837x`f;r2pYH~TrWHD zG$jUOm^ADtZ0SlwsjNuafbz3!vI;18J#(s862AiU$)sE+x+Ml0?cZ2GcW`Rbn1Z#f z`E(=>m{&eS-zzex?01f&PWa@{7N#|A_BgyMco@yoE8ZLb>Tlo@W704w)0u!gVGrfa zXU$zv8qElr3@Eg1uqcaUT!kOd8^_QYeZZC)_zk!=y+FHIwyJlD4r5m#dfpI>7=!Z+ zD?R_qo=8LngK7Ay7?JTGixL0EB>L}S#D7hd|HCBur`|*+Z2CV~shgrsE zt|d*^c`B{Bg6l$cdCexFp*`?z%FWqvu9|aJ1Zmwg@jZVNNag}KA@sj(Pkgcpb{lSg zV+t+!F}-=k9FQivfNKrIoz|XgTA_a#JGj(JQK>IH0jk|6)v0GZ@euVu;qI1vk78F` z|Ddi>G(91(pIMhpvK{ueZRozlvZ4}^Jw}u_LBYxTm-!p9(epuj{^^t!3X^kzih55U z&>Q}QAKa}wjS=$kM`>H@;=2zu9xRvPK1Rx5sY>)=rfXJT#gF7IDGz!`iZsn>I0d56 z-(b2Bj!TLOj)Fl4|1#<|#wBn+{&J{C{f`m~n*S7e|DW#sx3HVk_VHCc{QD^&otcyi zK}C%Y0#cynBVQR2A-o_0t2Wn1r36ZqO;Kh?Hd-+Xt#o~o&C}AB<&tB6-%y>ERsjbz zDJyrG$YVM7pK6PCdCFSf7}R%FZ9nFx1SE0LKfj(2m;E~KyuRnVcIoasZrhLN|87)K zl3e$hX~RL^-B2hCeWhVq0Ana#*HQSJq+I;94_O@1hS@<4wxW|jlk_K0$*WOQ+B3Mz z+R=jqTVCzCJw-~Sy7uJ!Rw6~fVI|)w?58WEIu^%ozUb|o7%@-dcpOD0bpx#}NB4eh zOHIAYZ^#D-^w@|$ZTgT?lqv>&aD4V;s0ul*Vrl*StUH~mZ`T07o2Ylw!Eg&6Sj^++ zu#`>sV{zLVRD;{WczZDp{radE*WXQF@xA%*&b5^rQ<%OO(QabWWMm^D4Fu}jSj(;y zeQ)eG6tPifI7t#B@D%&TUENN66EKw7=@dm^^U$!RVJSU0c|(xZ7CGrCs0ulb11k)u z9tCnkauXyI8E`Uv)FCJo=gUE1lUmH$h0N*>8x5n=AxAy*rW{8o*=@Wi3gl>~YpL?p zs53g)cHc3^(h(H}bSgt&M40nddux!)nJvtfU79Y%$Q6?6vC10N+gDo=)Q+_$Lz0wa z>nhVIS5u%47e8(-^pzVYBfUM%7YYLH%$-q|aKI;rVxzXkCHR7k%)?d!e%^))(AKAy`iT6j87kUMKZAzx zd#Wek-_+Si+MRSsM0s)@ZYrl7nVlc}JE3|gR2EY$;^zJx6&ATOl+Q5;h4r{mpxL;C zs6N=J!rF0X&Izr-Jrmf+AS_JGQ)HV^b8hb&=ycrq6l@F~vf4Y`ZeimX;^H|U0&Zbv7K#OlgNdq{E zwy6^0ucE-)!E$Lx6Guy|--q_sHxSxNn*A328`4Ky>zY(82M<{^n-(ldGjnwTP13Ug zRdZjj-UYrlX+N`9D*fJ^?dO1qzdM426x48=g3{Oh8G<#(Od2G}cGsyZSLw~1&Al@; zl%#tD_x>AN6HJ6VEd-GEN3KS|M~aN77R_j9omZlB*>l#UYi@AZ_yA}BiFqwd!oF~D zPQnb}D?D~|Kyr2dfDcd^!`~%I}g* zQ!^9)84j0oHg9IJTr+(ou!HMM?+Enfnma+HY%TYXt1A>;L?sw>nO)+DhrS+d73(h3 z2}y5PjQk_M;2qz>y~fzAA@TY|l~}CPPwd2*hoXYo>&aC_s!6QbiunX>(49b!3;`*B z+d4OW`YuZ%gc?NH2k^p~il0$#&e%!2MaK?q4JZ_V$AmhxQtu0{>S2aCPZnd0rrWLD zU`qcob2#JFHn+Sz7Hy{X^W7lzRO1>8gbwl4?Gwi6QIZk~v1VwgY?2b2q*z9qV?i*E z*r{QFGnMEuWg!@1&OmY0X&U3!0HGxJ`xH`j4W4h(W7CLS(0P2x4 zdF*YzfR<-IK)}bIKpcAe=wg`OuA^O%GYSRr&Ev)d+Mvgy4G@Vv{&!M-Xgk{zdK=Y| zv9Vhs<%1zbG3p$bg}|UrjrCUZ1{8bvMw9`=pcYi{$izuRII}%tQ%(VRgNpo(vhqG} z%oASF6uWEdGOebwcq-8FMpkXM%|VvymbO+#i^p0b?ea{B-E!WYKrpC|}i9=wX!eMSn_e@ml|g(%ZiVkdsC!PB}*h$>?*^ ztha?b)8->neU7Iy>Xef#$#RF;w4~NmlGp4e4U5u^0EF|X4PPLJ%`yx6n)H20_Haaa zx=OHu1~ol11|YEfYS^kks(fPKi?V11I*?5xry>ZIhMpqZ-Ectd_3d=c%={-4)2;ZGo zWCD*#4J7|%fOL1P*c=9j(iHtM)~dtgO-^Zd;Gf2Uq{ugaw~}1mpS^{GM_BZJ{461g z=0Ry!P(64NnWM+jXnb7!Bcd%FkToJ6nQE2CWeX{Zy*Nvror1DU%k|sc8SA#M2AW$y zGLzvuvRTP-GQeKIJ2@gzZzv35FV`h^^k=wiIb~+di7|p%{OS=KSGi=VJ#z=$git6O z`z~^@PHltaBUQaWYBI4GTSca8`bJ-v_OSb{&Ds^24NV_)MVq<&JjUlyjtwU}`>U?I z{i)UJFPF`*W(>-~*4Sbyz)^{m#{E7V&!Ch@nyOxU#G)ZjZhJ8BLPSm@_R?w205!o9 z(?>7X+DEHbGkq!nU*6f5tNR#teHXO0)CMfa=H5Awsm1<5;+J9Rd1z5Ptkp>E<3q%X zS9dwzx}4$X4>`^``H&|!4m)cHJHvCpWu#L8<{elPbWWL}Y9+z$_17m?>gXuqcu&it zm6F=1zaH9AAU@cB*FT-y=1j&4ncyI{5~h7I9p_XuJAgzdK1m>mJt%a2plM1#!SW)P z5EZ&RQb3`cib(vZJ%6wjAIU8gGF3bD7x`?NS-Ys&{m&pTt4?S6P`D9S-rI6h&O=hP z&btw&dY&TC!HHK_Ouy#zSudze&2JSM!-El}A!O|xb+DL)G_zfJ7kuN_i+dfM;YB|w z8aSMCUP1io)31scvAG>oTxzY@4__MOo@O*<>JyoG3&lD_WXwO_70EHf)?rX^%5Kp^ z?IS4!yJs|PG|*{bur1i!9NgxD9};3nUe4fn`6oV@+#R`^CD*GtUf`A2)bvj^f+qC3 z#p0dWB!@AehMkMJgNL!YbVleXBV|~1(aIH*h@+@qKAQmq-0b#~1DlI7WOK+E?>K(3 z2xG245b9-ALUun5DSYCef^n@zz-NqeXIWlz>k0ZuueA8p%gBEY{R~VbZH2nwvN;w` zE<^2W18;adPz~@03CPYxlAlHH+Yk{MM&Y3~C@j0X2A9Y}RR9!D#=2w6k8)Bp6Qc5E zir!|i@QX@9rzxN}Q`YrHrjO!1R()xsTf&@~YMh1bIj+Q}a>mT>RM(!zZM}2jpn=;M zr@R}7`PYthp%)zYFz-UyFZ~yX4o69$PECiFq0r}VT6#}jEO|_C3f}U* zM_O`%hY*$<=2{s0$9mclSrgg#PP@Q!d2Zc_amG_kmiHk4OR)jpm+Ay_pAXGc={ot! zcY{*R)5lH@ ze!Aaqndot3VJA55Lhr4TCCIYWxJT30$|0DqUC%jTld}Oi6OKfsG4}9GN|&9u$ z5=0yP>ISXrM=_#9hj$B&#AM4Aq6g;5x~z@cbTn*6rADOmC60@|9}L*n>CKx?+sXl| z3aIEX(d#KS#j_TX56e4sBO8s8*Pgci2w6M!1fU$zaq+rz%;L?IMf%o!jVe4C=3&Lq z1eei7!f%a*SO_1A7?j;zebX8rxNhhrOr)WAXh$V=R6B|VW9msF``@h3!yNw@-?$zT zhE%#>$p<#Kqh-!(Xf=_XX=ZlQT~kTM;W^5gs-?xg(~ z={HvhWZ11zk0tI<|MzQQU;5B~fG>Y6X}>4U4((mL9e~dTYZ}?tz2%*W%LQTP{)*)G z&95&>ZjG|!rs#Y7Hhr4`dkl*URxNXl(EHz=5oUu=bC_=IA6c_x9Ea!jk?NlkFkkKw z@Ns-2ub*sxa0mQP$Iw2yQ5#-Yg*_RtB(iAp~IG&fSyTs zBsx-f+)lC3uyp8#1&$)-%QIr}|#7Zn3PfioGXY zOfhL($c3ggbd=VGWeYTO$xasHI2*X30qu}DDpwxRJMgdest97xf4yamZ4EM zndCSj)UG(K77KwgPe$H7cUA^)w1M~JiBZYej=Sn z#hr+Knqc2wLE4H5%=n1Odq*JvI?DCI_V8*^6xi?1{X|ZVToCB1m{LYc?FI8B|HSWI z0}%=s1&MX6q05bdh18w}?Ih7obg(Ll_ z!wPMqEA+1j`7bXp+)x2CWd;hO84Dw1(A1l`j&f#BhGJv}N$#jpT<}VXQEtg(jQ!Pe zHb|vu_Ap+dkFN9<9HV{|hT2M_VVU4k?Ji|CHRbywg_7XQ$%hWLSl6bnET@T(lOl$Qy({elPebpw{qBr`HZf!rvd83w< zA1c8*wU(Lg4;Wp1jCCAk054?O>eTRQbF{Mgyt3VTIL>-gd6RxT&$``2E!~h+BMvaw z>sKS5WccZ+(4~U=q9w?=c&f~NOJ@_nJC2`2oUsa17{jWPz6g_h2oAB>7lZhC`)bRGhIldz~r2=o^{1pp7YK9-$EaWX;u4W6b=7_IuPN;UL?$(XT4Ghq=xG|)Rn5&xu zeSqS>G5iN-?&-;Ui$(eN?U~{~;mjoeGukEn-<-&QL%G;v7EGmfFbLGK{HF%8!!5@4tJmAs)wjB!$RBy=j zf!>Px)GigY*s^vy>r4bV^W@dk)Q*yJC)6Rj50P8It=Hd=EVT*zgL6yL(HwveL5z?^ z7|~_(TE9hBNJp~cew%Nrd^wD&UKu}-nBF(m8lKvI>4RlNF}H z=3u1X8}SL0ncbUSXxxhtkzzQ>V@WM0>f7 z$IpTDj&Ec#C3_iiCY&az7`!6eBHJ*OSo9r{o)Zc16{KuK5)+ zy^6)_cdG8~J}%LwX~_*$K7_7ld&B39Q0Y6r*gP`izZTOl5)=kk+hr0xB{26BldyDN}JviUAHlzl=(ukp@k37|4eXe zqJ>{tUr_GUe}r?1{+9{)AqY4+9k%{zV2D8zZaw2 zCJ-j=ue0^JJNUOYQ6n=er1&%z@vrNca_b6HGk!6xnp0G+byWSS9(DC_b}yfgp{O2P z<=6e$KAHP7qR=VR+&vdyVrSxHA7IIYGuXpHn+T>3M^|H@Pm^qkx#lSR zfn%F#acLD_nv`gF#^H8(sll>pH6%Bt|2|wMNL*2L=c=CRdP1YYdprY@XksM?jmE}ocqW>$%RFkwVt6DxFxeo{m*K-BN z!`+Rv00iz-5`D9FNeN?<94J}k19QZ9d^E*?6=KEo^kJ<61d7bn^ma;X@dGvo>E!VJ z%`-72_4Kl1Fk4$3d2OriZRv~yr{iTM^R`ecYk{muXCIhdi^bsG5yV*4<90V-wA6!D9jNoRK7*h{5L%;EcK&21y&X)4BK(bZy0lw+V^xjak& zt3!#J53>N*cE|c3fWC6>oGCLJYzqA}sq{0s9P6%MQfQiJ(lrreJ=%P;=S7VdUuK%Z zji3TMjCNR;^0Ehemh&pBh_bkXK&PB3(>c=76lY#S`XVoJHOcXe(m0Hn23N8*;xWTW zQw>@_Fy1>foNR}gGiAI3*K)bqE!oNw-xD!cEYL>v&{P7>WPVI%n|ul4*#R{{!4>2d zV6PS*x^4WhiUk=4n`zh1aH`yZj0U9U)rs)%8C2h~@!a(gVdMo&In=N2qbhE5iXS8{ipv$_vdHxd4T)*-8Ji&F)ZdFi80ys(qF8bg%XGMhzowF!kZ>e>qD}7x%R9L zpU^PsOKTn@5Vi@GDKY_Y(@r0x(|IL+fY!{#jt}eziZ6Se;=HhdC0v~{sU{S~RlImR z0jFo+Npf&q%u>uaUCH;>Cpo^qP6sOZu;u>peejBOUY@}eDiejqr2HP1_V*$6huT20}kkr1qHK)N-VpvbzM^&Asmm1JGES`noIx@?~_h(eYOp zLYbo5#*=;pD}KfLB_6$=mc)qA?wKQtwpU%Dls>*F^8>AcQ?(UNAZjkQomPR(6(hY)iNq0&~H%N%mA>C|J z!hd`2y`OPCNAEuw3k)3i1*oO}g1c#96bNY8@li3|SQFcTWPfIPqxThf#_1oht6o1)`tz!9Z3W z*B8!GNutS9lM=Cih>=@wy^*62k{MBvg_Bf~iN9=wje^H%Mk$)cRdUU!zN&*?o#=m5 zB0}2pz;uW$*M{A4d~)#Fl>u|NF%CmV+jaM9%0C$ROqxG^T0j7<>m`(C4z%bIroc`~^}J2u;VjA8YZ4!&@-L+RA^~2R9mn}%t{);l z0bz|u3EwbG^|;EuHR5;O3n8BpI(XeeGi6GhAVk+y5V0V1Ic0io=ubaffJ8c z8CCeEBAAWO=^pZ4{QVc#UJ)-j*Uyg4yn8kMp4~dQ4Xq-WgC{OSLsMgr_c(}h_q#k!MhChDj0 z1BO>fHx$z|;p2m`rc1s&m4uF8D(chhQah$K{LyDi{4)c{z^&ePhNX|R z!u3p?)+4xtk$Re$+)n{G#AEGJtJ{ZIanUIMQ2~(D(&=@Pp2w zhR98d>wBgVNj#HLBb%%{7zXEkungTwQ(v-RawhU=y(1iek$*(TLl2s5%NjhWPLm#g)VdDK%2MV{rfgc4`X&B8Y>CXu5pNZ2(K zBL+mNWn^`llU|SZAgnyRX5_m&Mrf4C-=1pu+LPF9h1A(^v3BeHYJ^~dp z!6&a;w2+hYN5!8^ipF2RaC>%|A|AZ^X)1o65x?TVx$?vrSCfpUVBKwOWPd-S?v?sN z_iGXTcg-fbZ;N|UbUDjQb?i=X8v&^oMUX2wR|rx`gY#>dDatq7MD1|g98dQy z-01N%92~3-T6}@&Zqf8e28`oXy>kimXtwK*f;Oa*x%4Ksy{|D05UdTVeV1)nyMMsKjw9ZKn$;Q=iVkai~|Z zC@$&EV~3y0J6Z!TBHmt*aVK_n?c;k-5-Fa{-b6~Yl72+H`e16mIJscj-XwE7hBX?I0z=P1>gP=|VguvtOn9ua#y8;(SyqlAHo)d>;g zEx$IM3;wWnU4Nz_Y93K=1$ltNi`SjdQRAUc81`PI3nzUH$zK>$K5;t&o)O+fui2Ok z4#m);wB0ej2we%qL*Kiw6F7o zBgyz;=t`Jr=(YL9U|s(W_lqlFyTJpKrJmWB;I0Pa^qt++G*%egr`t9Ul3sZ^h(i5*q@!vuCVk9J& z6`;S5D|vujgAFDg0cNzd^U8tGl0&>pi_J#e@O$MKmMvsrg|&xx5BvHC)aduVG^%UjZGc_NfNnQ*$pY5QRv z;ZuJP&r;{L!qDPFCOtKfjxDY9j-<;GVh(;-i}!0M9mEihS&Cy%Em-nOsQ?7rot_o`GOd3uQ9#yhB}jCRZCk z4Mn@r&Q*uP3okFB}}&Q=-pBnVtcfi2?XbnufKM7zKRY zNOz_ztk~m)ZE0}N5976@0NzuRfz9SesZdFeZZ1jKY$d(S`{p-g`isZjZw)@Q2uC+c zGa$5uy4xJV=^S<|P|^?HYZT=A(xj{pMfI6JJ}Ej=t$tqz?N^T&}@~oR~ZPXGsl2j>Mhs(yw zQ!qGWKyo{tnPQc5u`em-vFvqpDVtHv2u45TuhO7C9#Ztu=BVG4xBODIydpW3NX>0e zDQ#1x>=GR{@k;KrkDbwrEPE`Vd8tlc>@!y;AU;a79bfJVm-Q8 z`@v1-n>f=2@PmDd;MRu~c8@^2RYF>#2PnDCU72)grm4rmnb#I^Fe_BU#~({C-f_>y z6vJ5w1mEw}xU)V_{?t#DXXM4*R+3FcTtK_laL>_jX8^CZC^t=iT=-J`YKrz&&GS+k zveDxV{MC*mUm?F3(2?pGY_|L`-{l=2dE4b<=PRTR9p5;t5d2%~(_9yV2E|U7EuwVo zBM&CnFg;wI+Q_zKZ~#x!g$?x;lAvKr;~iLq(Y!=4QGxoJLgM@L>G=r63fs(c!JAR# zk@=t*ysb0eRx9TB28b^X1$|E`p|JRnmBS=arU($n;ll7oKuN+h7E4E@EIlT39UY2_ zcv?Hg{gKng<8)=O!5hpoHD0Xq_(Wo!hn(wEn4u=;6vu>7tBh0Y1V_};cPC9zR;X;# zuIY(~7&4Z*dj$Ea!1t1O*708cg<(~I>3O^0(G%+Twx zs3mIr_-0xWl8(9pJc8yU2Q#0XRo}70#0DRigPy5s3%F<25ELEv!Awkmm{~~5Md2gL ziA9_o5L1+@ur*;_atvPdO>N8w1h?$U%-!#4s9bw_6cY6m`v;B}@5&xAf3EWovO+xm6o-?f5f%S^?ZUJ_P}4~Eoj?scKKW4vV?Rcy|)3dJ&)TPY>xlv+F@y`GyQDb{`E9;bNONG?nul`o%goNp9Ie4DPv05{6Ij z`F0fXur3|IQKdmGE6D=OUYf*cW}fi{bf1$zhB*1j@{lu3HQahK(QH=8o+VTr^7aox?UIZWa=fse^;VIKEQ| zi_o|R#{^0XJs6l?^4hfMIGO<%14I|($;Bul^Y}?ZP#XuqWM)HkNXGs6*ge32HJlMW z4ZfKRqS&9`nX@A3aXG{pO)PB76}yu>^V$>mFo61P3u(dCyH8;Kc6QHUO^*?FF~L2A zv7IqR?S&k1$Y?I9F^uO$RaPb{*5cyHwJ9hvKEI|g`b1NS9-*)a-cA?0EJ40&-q{)| zeOxRoJdox8rgmNMh-&x*=JDkvJXxtOUWOd^3)CXcVwYQF0wSH9*c#yg8@Q{KD_|IM z4+~m7M97tU>#IujLnPNS8~c2p7ZK3bC0$u^mI~V@nM(0Wbf&Dr$4}EogQ}w*A=Ely zlbiOwN@v*-c5n3@wKo5}9lw2TJ&JoUf|eGiL=ska3IEcdFoC8P+`t~Tl$*x{EVKgX zz6pj6K}g^P7VH7Px`5~@PrG^yh|-H7ggfZKzp{b%ExJqSs zq3rzX89-x;*Tvr4;#&3Nth&~{we}bnq5`RrKbs0)2U@XxV}MU`%(A#wU^UMq-81y? z7n&1o5(G1w+ylpID^V}*o>#b7@F>EzI27igEz=T3lsj&L`LTXVL0Kv^@fdW1TpSC( z9HVTbHzIK$?*sEK;{b_obvJ#m_+V4FY{MSzd44Lvgv^uK&}x|N#V4Tmlt@FHuv;qB z5#Kol@mOQ-VK2@_`Y5iQcT4WtJ$@X_k6nq0o%j>m5YM$@G69z6Adw#Zr-MWcC>TJo z8*xlB0`x2P`&PZdI24ouoU_(Vn+#Ej82^AWuXKHI=E^2!<>37_e*q5T2-|6}E2XV~ zL9)47UX%SPe;`XR;E7Mf10t(mXh+U`hEX46BP1N}-D}I!pStYOmWv4Ob+l=R_`FJ81Pm)!7f?d^n@6=ZTPq{zEvlYGHf6aJ?eber}ljMKIEK0ed zN`M8$51vhD9+C5I`w@{i;XT-wn4yO=DH)IPBu8f1j-W{I;kp!@lddU4yff_u)OY~t zu2+3q9{kpeG`6lPHH&Mpz&Z6h*XuQgHpzGpG5?rW5V`>yg4j8i>_>!qd1XE+BgMs zB0CKkoL`}JyCYu2!=#F&p%PM z0xQ?CPt6`98t82SXp;*Xk~4<@p$K zSCS`3DRYHg9}mh270lD`$j%x_aFx1KFBQz|S~b~pig=W`GaqUm2GKwk_#_dj9&Vhw z%nC~RsT@Y0m)aQSdlab0kyX4EnH}F`S6>*$KCNrZ=XNFZBuZ>z^Q}6Btq|c_6;V^o6?Dyhhr!)wG@C(*qRRXqU}7Om)A{uW#Qc3JbHzD|tx{=6{gj`qx5hmdylFC&?$sDN3e9u@Bs|+{@QsEKIS>CUV@5Se%5uUbK&WsD=Uz(;x@< zbX69Eul0+H0_*Kw^ztcbGO9=t9>JcM^Lr8!sDS<2BrC zGd_BZ1GCt9*jN1g?xBs4C_|gV!jwj;W_jnXf~S?a)Y?lbOIvNdi~7W--QXJ+Pz!Fm z(fCp8Kdg(0IKufbhaU(pSvk|AmX%s!*d1YxHcH8yY~dAabpl4Y$VbT5gs;I{5|o)L zu^p?*93|i4tUuv8b35&-hwN$F$4_4ahEmq23SRNA*{aX61Xme_8=IsOJB_W!T8I3e0 z>VOtvkMwlJCLSXD$GsPhjOPjiuceRFkQy{aXzZZadz&9`zT71#Dig@Pj-z>dDEkPT z1-pk~3%BSwB+VcTO%?_Nb%2EYK#jkg8k?hISgvbp${5y_t%(p?3=>_8P1TqtPCYP= zU4ls@*{h0eac{)I{zAbM2zV_uZ2s~L`ibD1k8@r}$2usWR7oqh(qYON#G)w53(Bdk zi+ZO#w~ISt2D<#Vgm67OZkJSNK}7L-@S3Ud;E0NrLP^Z)=*m)Z3R7yyx6dRxB_PUM^uJ`+YjbTtc?kcU6YF!R zYGuxNyP9$Q0PPpV-0uTzh1ON5ZOg`fyU+w2Yq~o2`*KF_4+rQuIeEA*EO9i2GSI_* zZ)3-+!O)jblc(>7m?+oNsG{zz9=C*9w3n zz>n{V@2*qW!qIxQC)XoC;j)b;R)9N~!|sZ=Y@mC1`tHqR@ySB+s6@p3=nuFH93^ao zqtlaPsA%d^4yux&)2BTWWIG~NG1EJyJGR2nf=^!M)}|tj#2v$!AB#I-1@S^V#Te(b z^h9l5vr+56EyFW-I*Uxm0_&qbfI80Zn#O5p&b{Dd6M+IS6q8TJwcvirVXq{95=zG( z{CIe2$1TPilQ$x?Ip*oCnj<}xmq-nl%y2Y}Uv93u$IMJQ22@sUqYJOyP{UZ@qWmP2s1-gCwBWA4qHy-D$SX z^`83n0;K1~qm7eMZjZEwt|0WLbJuvqK6sNho}xO`4?0ii_b5!YP`A*xV~S}=3!mom zB=>H`y*nipH1Qk)A}sqN+@Frt2$-=}wPAxpo}iH0*S!MYoU+K z`Sj?i?}s)MX1VDvL_25%W2$e6JI#2pw!TACSV~5H|FF3ay3xpP8_P)%z&V8_J_Nsi%qHqZ$I zq2dF2!Lti;5i)V?9;)`J{6y5%ZE>Vx-{4D(dnI?)xCu*-lQX8!Goa}Zzy#(Uohl|pLC-t(h? z=Ib9!r_Kpw)*zbmljDc-OYn(OPN)@Hk>Ke>AkS`|tLuO$gKmO$w1dH)C>au*w_eE& z7ZDHg#^~`Bu0S!R@bvR14)n%v9DI(HxyIW+S!t}+<1e`Y=C@`;NN9w2==+)e{kzH& z7FPBGMA2M(GmB+bTq{AFY%7*2J^$6L=)LRfu)HeV2;_}18EfCuu$qI2rQ3-#R z*(Pis!q{V0L7i(R52QXGZ~bh-^OSU0NlzH;a8+CqXT+%%}djJnWnkkaHFg=`qLK$A5VjLLtPom zYeR|~@NOqcY&km>u1p4JANZcoT3(IMwQm|^lM2y4xdpVJmG7e9qGgXg{e)5dno|K? ziGat`5;VsI0SAU+w4KF%dch>T zqP#=X32KCv!YR2Cu;kgIyTE7j|*Ie(E=V)CWVbV3~eU`-VqG@crJ21Lq2}HrUfAoR3FV5_N4pZMEhoS6m5<;f9fYN-onG69={f#GCPp83pKpgB1a<0cwZdlHL2eiQz4 z_YB4Ib{Aux#)JvgXT#Ma^|F2Amz9^}l{*_EumQ?br5~&}eAyjg#TohL;_EKtmv?ZQ zE>wo9`H0T?eb6Oa*R>iSb#@J-f2M6GufldAgppLlv6d1cR7kdqlpf$1eq?*~CN08r zix1gg_83j8BmC?Y(^Xv2EU7u!-joKb?G~iY)k>ODY-Gs?hu5F-mMq@6Ucz!TF*Imq zNbNrcHbV6z5QHihNw%ZPB z7F#WPwKn=D8^bEyW7h&U`eol@<@VwzQculbgN-5ZV7HMNhGK{0 zO5I0TbKmwckH47!&?C;GG~WB8S)h@=RfD@5q||2K%#%puy>Tnl0d<0_tgM_W;welwZdO!uN=omnmmuJVl{|!ldS(!QmRLh}OOQ zkfY5~9)T_{B79y-)0GfDmEgN+FCCzuTYL`a*!Qlyt zb`mAgnmS}dc;6y&6xT=Y$q_8W-%nO7#GcRB?=y!rX^mzf#2rmdxmH|IGyn2vbtGX@ zGX-_tR=bV#LrRuKubwC{9X~Fw*z&{<*05&|7jhwIo(AT$En>SpyuB+;_TrO)fg()p zN5S!qf^|yA%M662?kBB|WcEpImDh{`{d;P1idcj`dGIIpTkntd4#L$A?y^WaHfCqR zs(8v?ueUM8x?CTbFn>8HT1_6bbsoEd;$#>{QHwx!$%}Zq|LE#c_wm&#`9={t9xgi- z`IzqTSbVK!o+OnC7CG=xsMb?cqPAQK`y){=%16*ioBm|xeDuC&^6(oH+osN@6LPOt zLda`KAN5MRdAV(LH$I2AaV=woUuh)+s8s4-g&*ub+5MoUVoL#9bWcE4WLTIYCoON9Q_>h2h!<-mzi0Ak^`U z6{H!W0(IiohqR;Q#u$iFhZE<~)v{jpX$ow*sCY@{u)4WaNoNV80$JWI?iX1NY@wI<}Rw zIi}zqdfn!+>r*a{p}Sxl{?@B61oqSY~lP7$B_)>7$UMCAOGL zttBXY)g8x&yivfH(nrM;K^5;b;Lf@l1F`;^uM_cjdVwT~e)NJD3OwX0sarAc1g#gd zEz%q)o4aZk8|Z?hSuJ9tM`@g~IjU5}vJ1#c;9fP<3NxHMBd!r6yY581O-pD$N%Z#T z-#@|86nYC{o1ySYr~OQjcn(FiF(N-zCqD_4e>aDdKlifPQKV-%f z=d_;ZfM6D11r_4_$Jwh`ccHz$BQT4{PV~O9un+zU*XZQ;mTWf&4n2l7P<~?Q4>1;Z zLCmlG*gk&|LCij@>3fdl2GE_&*FQ0))HqRZh_I|nK`D`RjiAb!Kz4m0(h(Wstci3M zuz`styQu2Fph7c+X)=v=o=$82FDVMKE#SRlF`D;h~dNT%pgaL*D z1`7)k2m~Vqt8U6C+C>5b>!1b$Lj~QAe>4RNH4#P`MM-9P88Hb(RS9)9C@|3W_P^ag zro$GLf?kIN{T1T}H!L9Dp#O8DAfhNEDWR&yq#*gXt{AtUi=%f>@<1jyx{{iH`u{?~O&HsFuC>kBeZlJ*D0pW80FtrGv59r?q|G(qr zf1OoW%(O{t5R^73fPM_qW12sPQw6E*I9UE>{rn$?oce(V76C$I`(a>CptAOF2lnSP zxK!t=Y5@Xi1_g@H4?tRse*mQJVEg|Qo*PiyJaC{mK?Hr&f4rD*u>2nNH*@#B*7=Xl z)1Um8^S@@w?7QpYZ=8QG(*0E~{hO`w{@(e&0`4~u-)qwT7-hlyKS2DSnBbpkfB$@C z`d-KItKi8uyB7Her2kp*_GjGh#jAe2XE90tfcs0qs=wDv{2AwaC7-WSSl_Hh@%K1? zD2(+p==b_EUqynx8KTM$p#P~m{E=kP&nVx^Vf?ss`>MZ0`A@s&|EOH^Gw%1Q0AIy6 zzFD5;KjZ#ZdgEuP?`agj$_#unblrc1`pxI-d(OSD$9UgN!RD8K|A3P5=lA|S5#5gw z?rHZA82>)X`Fk$EpK-o#0scyB_ss_E{|x6hll6W3?AK1>Z`R=dOMt)YEB^VNf8X2r z<0{Mt{MzyFdvSlp_`Y8KwM+Dyr3C#G#&722`zqttV)r+r%KoL>UzWaqezV^f#D2VO z4dnjP>p#^ie|G-;q4w9B+Bb8~|F!c!sIdJE^8G31k4uX1`j;Soa9aK|#`l}EujirP o%n!7o`Ytj0&(-zc7=Lp*sw@Wu%FMyQ$U$GLpnV-;?bqM_A9CD*LjV8( literal 0 HcmV?d00001 diff --git a/mobile/android/gradle/wrapper/gradle-wrapper.properties b/mobile/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..2f9728a9 --- /dev/null +++ b/mobile/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,10 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=4f2135b741f272acc88c168a52202a0a63fceee0cd61ee753da79694cd2b1e4b +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.3-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/mobile/android/gradlew b/mobile/android/gradlew new file mode 100755 index 00000000..249efbb0 --- /dev/null +++ b/mobile/android/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/mobile/android/gradlew.bat b/mobile/android/gradlew.bat new file mode 100644 index 00000000..3185a43f --- /dev/null +++ b/mobile/android/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/mobile/android/settings.gradle.kts b/mobile/android/settings.gradle.kts new file mode 100644 index 00000000..a3822764 --- /dev/null +++ b/mobile/android/settings.gradle.kts @@ -0,0 +1,19 @@ +// The Android library for Athletic Standard (D325, D331). See README.md. +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "athleticstandard-android" +include(":athleticstandard") diff --git a/mobile/bindgen/Cargo.toml b/mobile/bindgen/Cargo.toml new file mode 100644 index 00000000..aa445e51 --- /dev/null +++ b/mobile/bindgen/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "athleticstandard-uniffi-bindgen" +version = "3.0.0" +edition = "2021" +rust-version = "1.95" +description = "Generates the Swift and Kotlin bindings for athleticstandard-mobile with the locked UniFFI version" +license = "MIT" +publish = false + +[[bin]] +name = "uniffi-bindgen" +path = "src/main.rs" + +[dependencies] +uniffi = { version = "=0.33.0", features = ["cli"] } diff --git a/mobile/bindgen/src/main.rs b/mobile/bindgen/src/main.rs new file mode 100644 index 00000000..5306cdc7 --- /dev/null +++ b/mobile/bindgen/src/main.rs @@ -0,0 +1,7 @@ +//! `uniffi-bindgen` built from the same locked UniFFI version as the mobile +//! library, so the generated Swift and Kotlin match the library's scaffolding +//! (D327). Run it through `mobile/scripts/`. + +fn main() { + uniffi::uniffi_bindgen_main() +} diff --git a/mobile/scripts/build-android.sh b/mobile/scripts/build-android.sh new file mode 100755 index 00000000..09fe19f6 --- /dev/null +++ b/mobile/scripts/build-android.sh @@ -0,0 +1,85 @@ +#!/bin/bash +# Build the native library and Kotlin bindings for the Android library (D331). +# +# Builds libathleticstandard_mobile.so for arm64-v8a and x86_64 with the Android +# NDK, aligned for 16 KB memory pages, and generates the Kotlin bindings with the +# locked UniFFI version. The Gradle build runs this script; it can also run alone. +# +# Usage: mobile/scripts/build-android.sh [debug|release] [output directory] +# +# The output directory gets jniLibs//libathleticstandard_mobile.so and +# kotlin/ai/athleticstandard/athleticstandard_mobile.kt. Neither is committed +# (D327). ANDROID_NDK_HOME names the NDK; otherwise ANDROID_HOME/ndk/. + +set -euo pipefail + +PROFILE="${1:-release}" +case "$PROFILE" in + debug) CARGO_PROFILE=dev; PROFILE_DIR=debug ;; + release) CARGO_PROFILE=release; PROFILE_DIR=release ;; + *) echo "usage: $0 [debug|release] [output directory]" >&2; exit 2 ;; +esac + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +OUT="${2:-$ROOT/mobile/android/athleticstandard/build/rust}" +NDK_VERSION=29.0.14206865 +API=24 + +if ! command -v cargo > /dev/null && [ -x "$HOME/.cargo/bin/cargo" ]; then + export PATH="$HOME/.cargo/bin:$PATH" +fi + +NDK="${ANDROID_NDK_HOME:-${ANDROID_HOME:-}/ndk/$NDK_VERSION}" +if [ ! -d "$NDK/toolchains/llvm/prebuilt" ]; then + echo "no Android NDK at $NDK; set ANDROID_NDK_HOME or ANDROID_HOME" >&2 + exit 1 +fi +case "$(uname -s)" in + Darwin) HOST_TAG=darwin-x86_64 ;; + Linux) HOST_TAG=linux-x86_64 ;; + *) echo "unsupported build machine $(uname -s)" >&2; exit 1 ;; +esac +TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/$HOST_TAG/bin" + +build_abi() { + local target="$1" abi="$2" clang="$3" + local variable + variable="$(echo "$target" | tr '[:lower:]-' '[:upper:]_')" + echo "building $target for $abi" + export "CARGO_TARGET_${variable}_LINKER=$TOOLCHAIN/$clang" + export "CC_${target//-/_}=$TOOLCHAIN/$clang" + export "AR_${target//-/_}=$TOOLCHAIN/llvm-ar" + # 16 KB pages: NDK r29 links this way by default; the flag keeps it explicit. + RUSTFLAGS="${RUSTFLAGS:-} -C link-arg=-Wl,-z,max-page-size=16384" \ + cargo rustc --locked -p athleticstandard-mobile --lib --crate-type cdylib \ + --target "$target" --profile "$CARGO_PROFILE" --manifest-path "$ROOT/Cargo.toml" + mkdir -p "$OUT/jniLibs/$abi" + cp "$ROOT/target/$target/$PROFILE_DIR/libathleticstandard_mobile.so" "$OUT/jniLibs/$abi/" + if [ "$PROFILE" = release ]; then + "$TOOLCHAIN/llvm-strip" --strip-debug "$OUT/jniLibs/$abi/libathleticstandard_mobile.so" + fi + # Every loadable segment must allow 16 KB pages. + if "$TOOLCHAIN/llvm-readelf" -lW "$OUT/jniLibs/$abi/libathleticstandard_mobile.so" \ + | awk '$1 == "LOAD" && $NF != "0x4000" && $NF != "0x10000" { bad = 1 } END { exit bad }'; then + echo "$abi: every LOAD segment is aligned for 16 KB pages" + else + echo "$abi: a LOAD segment is not aligned for 16 KB pages" >&2 + exit 1 + fi +} + +cd "$ROOT" +rm -rf "$OUT/jniLibs" "$OUT/kotlin" +build_abi aarch64-linux-android arm64-v8a "aarch64-linux-android$API-clang" +build_abi x86_64-linux-android x86_64 "x86_64-linux-android$API-clang" + +# The bindings come from the metadata in a library built for this machine. +cargo build --locked -p athleticstandard-mobile --profile "$CARGO_PROFILE" +cargo build --locked -p athleticstandard-uniffi-bindgen +case "$(uname -s)" in + Darwin) HOST_LIBRARY="$ROOT/target/$PROFILE_DIR/libathleticstandard_mobile.dylib" ;; + *) HOST_LIBRARY="$ROOT/target/$PROFILE_DIR/libathleticstandard_mobile.so" ;; +esac +"$ROOT/target/debug/uniffi-bindgen" generate --no-format --language kotlin \ + --library "$HOST_LIBRARY" --out-dir "$OUT/kotlin" +echo "wrote $OUT" diff --git a/mobile/scripts/build-apple.sh b/mobile/scripts/build-apple.sh new file mode 100755 index 00000000..7e5faec5 --- /dev/null +++ b/mobile/scripts/build-apple.sh @@ -0,0 +1,162 @@ +#!/bin/bash +# Build the native library for the Swift package (D331, D332). +# +# Builds static libraries for iPhone (arm64), the iPhone simulator (arm64 and +# x86_64), and macOS (arm64 and x86_64), generates the Swift bindings with the +# locked UniFFI version, and assembles them as +# mobile/swift/build/AthleticStandardFFI.xcframework. The generated Swift goes to +# mobile/swift/Sources/AthleticStandard/Generated/. Neither is committed (D327). +# +# Usage: mobile/scripts/build-apple.sh [debug|release] +# +# The XCFramework is assembled directly rather than with +# `xcodebuild -create-xcframework`, so the same files give the same bytes and the +# build does not need Xcode's command-line license. The iPhone SDKs come from the +# Xcode installation named by DEVELOPER_DIR, or from /Applications/Xcode.app. + +set -euo pipefail + +PROFILE="${1:-release}" +case "$PROFILE" in + debug) CARGO_PROFILE=dev; PROFILE_DIR=debug ;; + release) CARGO_PROFILE=release; PROFILE_DIR=release ;; + *) echo "usage: $0 [debug|release]" >&2; exit 2 ;; +esac + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +SWIFT_DIR="$ROOT/mobile/swift" +OUT="$SWIFT_DIR/build" +FRAMEWORK="$OUT/AthleticStandardFFI.xcframework" +GENERATED="$SWIFT_DIR/Sources/AthleticStandard/Generated" +LIB=libathleticstandard_mobile.a +IOS_FLOOR=17.0 +MACOS_FLOOR=14.0 + +# The Xcode installation that holds the iPhone SDKs. +if [ -z "${DEVELOPER_DIR:-}" ]; then + selected="$(xcode-select -p 2>/dev/null || true)" + if [ -d "$selected/Platforms/iPhoneOS.platform" ]; then + DEVELOPER_DIR="$selected" + else + DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer + fi +fi + +sdk_path() { + local sdk="$1" platform="$2" + local found + if found="$(DEVELOPER_DIR="$DEVELOPER_DIR" xcrun --sdk "$sdk" --show-sdk-path 2>/dev/null)" && [ -d "$found" ]; then + echo "$found" + return + fi + found="$DEVELOPER_DIR/Platforms/$platform.platform/Developer/SDKs/$platform.sdk" + if [ ! -d "$found" ]; then + echo "no $platform SDK at $found; set DEVELOPER_DIR to an Xcode installation" >&2 + exit 1 + fi + echo "$found" +} + +IPHONEOS_SDK="$(sdk_path iphoneos iPhoneOS)" +SIMULATOR_SDK="$(sdk_path iphonesimulator iPhoneSimulator)" +MACOS_SDK="$(xcrun --sdk macosx --show-sdk-path)" + +build_static() { + local target="$1" sdk="$2" + echo "building $target" + SDKROOT="$sdk" IPHONEOS_DEPLOYMENT_TARGET="$IOS_FLOOR" MACOSX_DEPLOYMENT_TARGET="$MACOS_FLOOR" \ + cargo rustc --locked -p athleticstandard-mobile --lib --crate-type staticlib \ + --target "$target" --profile "$CARGO_PROFILE" --manifest-path "$ROOT/Cargo.toml" +} + +cd "$ROOT" +build_static aarch64-apple-ios "$IPHONEOS_SDK" +build_static aarch64-apple-ios-sim "$SIMULATOR_SDK" +build_static x86_64-apple-ios "$SIMULATOR_SDK" +build_static aarch64-apple-darwin "$MACOS_SDK" +build_static x86_64-apple-darwin "$MACOS_SDK" + +# The bindings come from the metadata in a library built for this Mac. They do +# not depend on the target, so one copy serves every slice. +cargo build --locked -p athleticstandard-mobile --profile "$CARGO_PROFILE" +cargo build --locked -p athleticstandard-uniffi-bindgen +BINDINGS="$OUT/bindings" +rm -rf "$BINDINGS" +mkdir -p "$BINDINGS" +"$ROOT/target/debug/uniffi-bindgen" generate --no-format --language swift \ + --library "$ROOT/target/$PROFILE_DIR/libathleticstandard_mobile.dylib" --out-dir "$BINDINGS" + +rm -rf "$FRAMEWORK" "$GENERATED" +mkdir -p "$FRAMEWORK" "$GENERATED" +cp "$BINDINGS/AthleticStandard.swift" "$GENERATED/AthleticStandard.swift" + +slice() { + local identifier="$1" + shift + local dir="$FRAMEWORK/$identifier" + mkdir -p "$dir/Headers" + cp "$BINDINGS/AthleticStandardFFI.h" "$dir/Headers/AthleticStandardFFI.h" + cp "$BINDINGS/AthleticStandardFFI.modulemap" "$dir/Headers/module.modulemap" + if [ "$#" -eq 1 ]; then + cp "$ROOT/target/$1/$PROFILE_DIR/$LIB" "$dir/$LIB" + else + local inputs=() + for target in "$@"; do inputs+=("$ROOT/target/$target/$PROFILE_DIR/$LIB"); done + lipo -create "${inputs[@]}" -output "$dir/$LIB" + fi +} + +slice ios-arm64 aarch64-apple-ios +slice ios-arm64_x86_64-simulator aarch64-apple-ios-sim x86_64-apple-ios +slice macos-arm64_x86_64 aarch64-apple-darwin x86_64-apple-darwin + +library_entry() { + local identifier="$1" platform="$2" variant="$3" + shift 3 + echo " " + echo " BinaryPath" + echo " $LIB" + echo " HeadersPath" + echo " Headers" + echo " LibraryIdentifier" + echo " $identifier" + echo " LibraryPath" + echo " $LIB" + echo " SupportedArchitectures" + echo " " + for architecture in "$@"; do echo " $architecture"; done + echo " " + echo " SupportedPlatform" + echo " $platform" + if [ -n "$variant" ]; then + echo " SupportedPlatformVariant" + echo " $variant" + fi + echo " " +} + +{ + echo '' + echo '' + echo '' + echo '' + echo ' AvailableLibraries' + echo ' ' + library_entry ios-arm64 ios "" arm64 + library_entry ios-arm64_x86_64-simulator ios simulator arm64 x86_64 + library_entry macos-arm64_x86_64 macos "" arm64 x86_64 + echo ' ' + echo ' CFBundlePackageType' + echo ' XFWK' + echo ' XCFrameworkFormatVersion' + echo ' 1.0' + echo '' + echo '' +} > "$FRAMEWORK/Info.plist" +plutil -lint "$FRAMEWORK/Info.plist" > /dev/null + +for identifier in ios-arm64 ios-arm64_x86_64-simulator macos-arm64_x86_64; do + echo "$identifier: $(lipo -archs "$FRAMEWORK/$identifier/$LIB")" +done +echo "wrote $FRAMEWORK" +echo "wrote $GENERATED/AthleticStandard.swift" diff --git a/mobile/scripts/test-android.sh b/mobile/scripts/test-android.sh new file mode 100755 index 00000000..e1d25379 --- /dev/null +++ b/mobile/scripts/test-android.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# Test the Android library on a connected phone or a running emulator: the +# fixture bundle, then the instrumented tests (D333). +# +# Usage: mobile/scripts/test-android.sh [debug|release] +# +# ANDROID_HOME names the SDK and JAVA_HOME a JDK 17 or later. ANDROID_SERIAL +# picks the device when more than one is connected. + +set -euo pipefail + +PROFILE="${1:-debug}" +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +FIXTURES="$ROOT/target/mobile-fixtures" + +if ! command -v cargo > /dev/null && [ -x "$HOME/.cargo/bin/cargo" ]; then + export PATH="$HOME/.cargo/bin:$PATH" +fi + +rm -rf "$FIXTURES" +ATH_MOBILE_FIXTURES="$FIXTURES" cargo test --locked -p athleticstandard-mobile --test fixtures \ + --manifest-path "$ROOT/Cargo.toml" + +cd "$ROOT/mobile/android" +./gradlew --no-daemon :athleticstandard:connectedDebugAndroidTest \ + -Pathleticstandard.rustProfile="$PROFILE" -Pathleticstandard.fixtures="$FIXTURES" +report="$(ls athleticstandard/build/outputs/androidTest-results/connected/debug/TEST-*.xml | head -n 1)" +grep -o ']*>' "$report" diff --git a/mobile/scripts/test-apple.sh b/mobile/scripts/test-apple.sh new file mode 100755 index 00000000..434b1987 --- /dev/null +++ b/mobile/scripts/test-apple.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Test the Swift package: the fixture bundle, then the Swift tests on this Mac and +# on an iPhone simulator (D333). +# +# Usage: mobile/scripts/test-apple.sh [--mac-only] [debug|release] +# +# The simulator run needs a full Xcode whose license has been accepted +# (`sudo xcodebuild -license accept`). `--mac-only` leaves it out and says so. +# SIMULATOR names the simulator device (default: the first available iPhone). + +set -euo pipefail + +MAC_ONLY=0 +if [ "${1:-}" = "--mac-only" ]; then + MAC_ONLY=1 + shift +fi +PROFILE="${1:-debug}" +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +FIXTURES="$ROOT/target/mobile-fixtures" + +if ! command -v cargo > /dev/null && [ -x "$HOME/.cargo/bin/cargo" ]; then + export PATH="$HOME/.cargo/bin:$PATH" +fi + +"$ROOT/mobile/scripts/build-apple.sh" "$PROFILE" +rm -rf "$FIXTURES" +ATH_MOBILE_FIXTURES="$FIXTURES" cargo test --locked -p athleticstandard-mobile --test fixtures \ + --manifest-path "$ROOT/Cargo.toml" + +cd "$ROOT/mobile/swift" +ATH_MOBILE_FIXTURES="$FIXTURES" swift test + +if [ "$MAC_ONLY" = 1 ]; then + echo "iPhone simulator tests not run (--mac-only)" + exit 0 +fi +if ! xcodebuild -version > /dev/null 2>&1; then + echo "iPhone simulator tests cannot run: xcodebuild is not usable here." >&2 + echo "Select Xcode (sudo xcode-select -s /Applications/Xcode.app) and accept its license" >&2 + echo "(sudo xcodebuild -license accept), or pass --mac-only." >&2 + exit 1 +fi +SIMULATOR="${SIMULATOR:-$(xcrun simctl list devices available | awk -F'[()]' '/iPhone/ { print $2; exit }')}" +if [ -z "$SIMULATOR" ]; then + echo "no available iPhone simulator" >&2 + exit 1 +fi +# xcodebuild passes TEST_RUNNER_ variables to the test process without the prefix. +TEST_RUNNER_ATH_MOBILE_FIXTURES="$FIXTURES" xcodebuild test -scheme AthleticStandard \ + -destination "platform=iOS Simulator,id=$SIMULATOR" -derivedDataPath "$ROOT/mobile/swift/.build/xcode" \ + | tail -n 40 diff --git a/mobile/src/error.rs b/mobile/src/error.rs new file mode 100644 index 00000000..47d75013 --- /dev/null +++ b/mobile/src/error.rs @@ -0,0 +1,138 @@ +//! The one failure type every binding call returns (D329). +//! +//! Each desktop error code has a case, so an app can tell a stale edit from an +//! invalid record without reading the message. `detail` is the desktop +//! message, unchanged. Three cases exist only at the boundary: +//! `MalformedJson`, `UnknownShape`, and `Closed`. + +use athleticstandard_core::model::{self, ValidationError}; + +/// Why a call did not return a result. +#[derive(Debug, Clone, PartialEq, uniffi::Error)] +pub enum AthleticStandardError { + /// The bytes are not UTF-8 JSON text the library's reader accepts. + MalformedJson { detail: String }, + /// No published shape has this name. + UnknownShape { detail: String }, + /// The value does not match its shape. `issues` are in the desktop order; + /// `detail` is the first one as a person reads it. + Invalid { detail: String, issues: Vec }, + /// A named record, file, or setting does not exist. + NotFound { detail: String }, + /// The database changed, or an expected revision is not current. + Stale { detail: String }, + /// The operation is refused to protect data or files. + Refused { detail: String }, + /// The database needs a migration first. `preview` is the desktop + /// migration preview as JSON. + MigrationRequired { detail: String, preview: Vec }, + /// SQLite reported an error. + Database { detail: String }, + /// A file operation failed. + Io { detail: String }, + /// Any other failure, with the desktop message (desktop code `error`). + Failed { detail: String }, + /// The database handle was closed. + Closed { detail: String }, +} + +impl AthleticStandardError { + /// The code a desktop caller sees for the same failure. + pub fn code(&self) -> &'static str { + match self { + AthleticStandardError::MalformedJson { .. } => "malformed_json", + AthleticStandardError::UnknownShape { .. } => "unknown_shape", + AthleticStandardError::Invalid { .. } => "invalid", + AthleticStandardError::NotFound { .. } => "not_found", + AthleticStandardError::Stale { .. } => "stale", + AthleticStandardError::Refused { .. } => "refused", + AthleticStandardError::MigrationRequired { .. } => "migration_required", + AthleticStandardError::Database { .. } => "database", + AthleticStandardError::Io { .. } => "io", + AthleticStandardError::Failed { .. } => "error", + AthleticStandardError::Closed { .. } => "closed", + } + } + + /// The message a person reads. + pub fn detail(&self) -> &str { + match self { + AthleticStandardError::MalformedJson { detail } + | AthleticStandardError::UnknownShape { detail } + | AthleticStandardError::Invalid { detail, .. } + | AthleticStandardError::NotFound { detail } + | AthleticStandardError::Stale { detail } + | AthleticStandardError::Refused { detail } + | AthleticStandardError::MigrationRequired { detail, .. } + | AthleticStandardError::Database { detail } + | AthleticStandardError::Io { detail } + | AthleticStandardError::Failed { detail } + | AthleticStandardError::Closed { detail } => detail, + } + } + + pub(crate) fn malformed(detail: impl Into) -> Self { + AthleticStandardError::MalformedJson { detail: detail.into() } + } +} + +impl std::fmt::Display for AthleticStandardError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.detail()) + } +} + +impl std::error::Error for AthleticStandardError {} + +impl From for AthleticStandardError { + fn from(error: ValidationError) -> Self { + AthleticStandardError::Invalid { + detail: error.to_string(), + issues: error.issues.iter().map(ValidationIssue::from).collect(), + } + } +} + +impl From for AthleticStandardError { + fn from(error: athleticstandard_core::json::JsonError) -> Self { + AthleticStandardError::malformed(error.message) + } +} + +/// One step of an issue's path: a field name or a list position. The two +/// stay distinct, so field `"0"` and position 0 are different paths. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum PathSegment { + Field { name: String }, + Position { index: u64 }, +} + +/// One validation issue, as the desktop validator reports it. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ValidationIssue { + pub path: Vec, + /// The issue code, such as `invalid_type` or `custom`. + pub code: String, + pub message: String, + /// The path as the desktop prints it, such as `data.value.standard_unit`, + /// or `record` for the top level. + pub path_text: String, +} + +impl From<&model::Issue> for ValidationIssue { + fn from(issue: &model::Issue) -> Self { + ValidationIssue { + path: issue + .path + .iter() + .map(|segment| match segment { + model::PathSegment::Key(name) => PathSegment::Field { name: name.clone() }, + model::PathSegment::Index(index) => PathSegment::Position { index: *index as u64 }, + }) + .collect(), + code: issue.code.as_str().to_string(), + message: issue.message.clone(), + path_text: issue.path_text(), + } + } +} diff --git a/mobile/src/lib.rs b/mobile/src/lib.rs new file mode 100644 index 00000000..2de8332b --- /dev/null +++ b/mobile/src/lib.rs @@ -0,0 +1,23 @@ +//! Athletic Standard for iPhone and Android apps (D325). +//! +//! UniFFI generates the Swift and Kotlin bindings from this crate. Every rule +//! lives in Rust: this crate only turns calls and values into the generated +//! types. Record bodies and results cross as UTF-8 JSON bytes (D329). +//! +//! Without the `sqlite` feature the crate depends only on the storage-free +//! core: it checks records and runs calculations on records the app supplies. + +uniffi::setup_scaffolding!(); + +mod error; +mod validate; + +pub use error::{AthleticStandardError, PathSegment, ValidationIssue}; +pub use validate::{validate, validate_current_record}; + +/// The Athletic Standard version this library writes and reports, such as +/// `3.0.0`. The packages and the desktop program share it (D152). +#[uniffi::export] +pub fn library_version() -> String { + athleticstandard_core::model::package::ATHLETIC_STANDARD_VERSION.to_string() +} diff --git a/mobile/src/validate.rs b/mobile/src/validate.rs new file mode 100644 index 00000000..2fe9f6d7 --- /dev/null +++ b/mobile/src/validate.rs @@ -0,0 +1,40 @@ +//! Record checks with no storage (D329). +//! +//! The same validator the desktop runs checks UTF-8 JSON against a published +//! shape. A value that passes comes back as the checked JSON the shape +//! outputs, which is what the desktop stores and exports. + +use athleticstandard_core::json::{self, Value}; +use athleticstandard_core::model::{registry, CurrentRecord}; + +use crate::error::AthleticStandardError; + +/// Read UTF-8 JSON bytes with the library's JSON reader. +pub(crate) fn parse_json(bytes: &[u8]) -> Result { + let text = std::str::from_utf8(bytes) + .map_err(|error| AthleticStandardError::malformed(format!("JSON text must be UTF-8: {error}")))?; + Ok(json::parse(text)?) +} + +/// Check `json` against the published shape named `shape`, such as +/// `CurrentRecord`, `WorkoutSessionData`, or `RecordRevision`. Returns the +/// checked JSON on success, or every issue in the desktop order. +#[uniffi::export] +pub fn validate(shape: String, json: Vec) -> Result, AthleticStandardError> { + let schema = registry::shape(&shape) + .ok_or_else(|| AthleticStandardError::UnknownShape { detail: format!("no published shape named {shape}") })?; + let value = parse_json(&json)?; + schema.validate(&value)?; + Ok(json::to_string(&schema.output(&value)).into_bytes()) +} + +/// Check one complete current record: its envelope, its data for its record +/// type, and the record rules, including the rule that an athlete report never +/// names a source. This checks the record alone. A reference to another record +/// is checked only where that record is available, such as in a database. +#[uniffi::export] +pub fn validate_current_record(json: Vec) -> Result, AthleticStandardError> { + let value = parse_json(&json)?; + let record = CurrentRecord::from_value(&value)?; + Ok(json::to_string(&record.to_value()).into_bytes()) +} diff --git a/mobile/swift/.gitignore b/mobile/swift/.gitignore new file mode 100644 index 00000000..3b63cef7 --- /dev/null +++ b/mobile/swift/.gitignore @@ -0,0 +1,3 @@ +/build/ +/.build/ +/Sources/AthleticStandard/Generated/ diff --git a/mobile/swift/Package.swift b/mobile/swift/Package.swift new file mode 100644 index 00000000..acbc14d4 --- /dev/null +++ b/mobile/swift/Package.swift @@ -0,0 +1,25 @@ +// swift-tools-version: 6.0 +// Athletic Standard for iPhone apps (D325, D331). +// +// This manifest builds against the XCFramework that mobile/scripts/build-apple.sh +// writes to build/. Released versions come from a separate package repository whose +// manifest names the release asset by address and checksum (D332). + +import PackageDescription + +let package = Package( + name: "AthleticStandard", + platforms: [.iOS(.v17), .macOS(.v14)], + products: [ + .library(name: "AthleticStandard", targets: ["AthleticStandard"]), + ], + targets: [ + .binaryTarget(name: "AthleticStandardFFI", path: "build/AthleticStandardFFI.xcframework"), + .target( + name: "AthleticStandard", + dependencies: ["AthleticStandardFFI"], + linkerSettings: [.linkedFramework("CoreFoundation"), .linkedLibrary("iconv")] + ), + .testTarget(name: "AthleticStandardTests", dependencies: ["AthleticStandard"]), + ] +) diff --git a/mobile/swift/Sources/AthleticStandard/AthleticStandardError+Code.swift b/mobile/swift/Sources/AthleticStandard/AthleticStandardError+Code.swift new file mode 100644 index 00000000..2165cd53 --- /dev/null +++ b/mobile/swift/Sources/AthleticStandard/AthleticStandardError+Code.swift @@ -0,0 +1,40 @@ +import Foundation + +extension AthleticStandardError { + /// The code a desktop caller sees for the same failure, such as `stale` or + /// `invalid` (D329). `malformed_json`, `unknown_shape`, and `closed` exist only in + /// the phone library. + public var code: String { + switch self { + case .MalformedJson: "malformed_json" + case .UnknownShape: "unknown_shape" + case .Invalid: "invalid" + case .NotFound: "not_found" + case .Stale: "stale" + case .Refused: "refused" + case .MigrationRequired: "migration_required" + case .Database: "database" + case .Io: "io" + case .Failed: "error" + case .Closed: "closed" + } + } + + /// The desktop message, unchanged. + public var detail: String { + switch self { + case let .MalformedJson(detail), let .UnknownShape(detail), let .NotFound(detail), + let .Stale(detail), let .Refused(detail), let .Database(detail), let .Io(detail), + let .Failed(detail), let .Closed(detail): + detail + case let .Invalid(detail, _), let .MigrationRequired(detail, _): + detail + } + } + + /// The validation issues of an `Invalid` failure, in the desktop order. + public var issues: [ValidationIssue] { + if case let .Invalid(_, issues) = self { return issues } + return [] + } +} diff --git a/mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift b/mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift new file mode 100644 index 00000000..32c81812 --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift @@ -0,0 +1,33 @@ +import AthleticStandard +import Foundation + +/// The desktop fixture bundle (D333). `ATH_MOBILE_FIXTURES` names the folder that +/// `mobile/tests/fixtures.rs` wrote. `mobile/scripts/test-apple.sh` sets it. +enum FixtureBundle { + struct Missing: Error, CustomStringConvertible { + let description: String + } + + static func suite(_ name: String) throws -> [String: Any] { + guard let folder = ProcessInfo.processInfo.environment["ATH_MOBILE_FIXTURES"] else { + throw Missing(description: "set ATH_MOBILE_FIXTURES to the folder mobile/tests/fixtures.rs writes") + } + let url = URL(fileURLWithPath: folder).appendingPathComponent("\(name).json") + let data = try Data(contentsOf: url) + guard let suite = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw Missing(description: "\(url.path) is not a suite object") + } + return suite + } + + /// One issue as the bundle prints it: `[path] code message`. + static func text(_ issue: ValidationIssue) -> String { + let path = issue.path.map { segment in + switch segment { + case let .field(name): name + case let .position(index): String(index) + } + } + return "[\(path.joined(separator: "."))] \(issue.code) \(issue.message)" + } +} diff --git a/mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift b/mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift new file mode 100644 index 00000000..6e22c2b4 --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift @@ -0,0 +1,44 @@ +import AthleticStandard +import Foundation +import Testing + +/// Every recorded model vector, through the Swift package, compared with the +/// desktop outcome in the fixture bundle (D333). +struct ModelVectorTests { + @Test func everyModelVectorMatchesTheDesktop() throws { + let suite = try FixtureBundle.suite("model-vectors") + let cases = try #require(suite["cases"] as? [[String: Any]]) + let counts = try #require(suite["counts"] as? [String: Int]) + var run = 0 + var skipped = 0 + var failures: [String] = [] + for item in cases { + if item["skip"] is String { + skipped += 1 + continue + } + run += 1 + let schema = item["schema"] as! String + let name = item["name"] as! String + let input = Data((item["input_text"] as! String).utf8) + let expectedIssues = item["issues"] as! [String] + let expectedOutput = (item["output_text"] as? String).map { Data($0.utf8) } + do { + let output = try validate(shape: schema, json: input) + if !expectedIssues.isEmpty || output != expectedOutput { + failures.append("\(schema) / \(name): accepted, expected \(expectedIssues)") + } + } catch let error as AthleticStandardError { + let issues = error.issues.map(FixtureBundle.text) + if error.code != "invalid" || issues != expectedIssues { + failures.append("\(schema) / \(name): \(error.code) \(issues), expected \(expectedIssues)") + } + } + } + print("model-vectors: \(run) run, \(skipped) skipped, \(failures.count) failed") + #expect(run == counts["run"]) + #expect(skipped == counts["skipped"]) + #expect(cases.count == counts["cases"]) + #expect(failures.isEmpty, "\(failures.prefix(20).joined(separator: "\n"))") + } +} diff --git a/mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift b/mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift new file mode 100644 index 00000000..2497b86a --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift @@ -0,0 +1,80 @@ +import AthleticStandard +import Foundation +import Testing + +/// The checks the Rust tests in mobile/tests/validate.rs run, through the Swift +/// package. The fixture bundle runs every recorded vector (D333). +struct ValidationTests { + static let measurement = #"{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000064","record_type":"point_measurement","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"source_id":"01890f3e-e7d3-7cc0-88c8-000000000003","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","quantity":"hrv_rmssd","input_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"value":{"standard_value":42,"standard_unit":"ms","input_value_missing_reason":"not_provided_by_source","input_unit_missing_reason":"not_provided_by_source"}}}"# + + static let report = #"{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000065","record_type":"athlete_report","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"report_type":"note","reported_at":"2026-01-02T03:04:05.678Z","input_reported_at":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"reported_via":"text"}}"# + + func issues(_ body: () throws -> Data) -> [ValidationIssue] { + do { + _ = try body() + } catch let error as AthleticStandardError { + #expect(error.code == "invalid") + return error.issues + } catch { + Issue.record("unexpected error \(error)") + } + return [] + } + + @Test func libraryReportsItsVersion() { + #expect(libraryVersion() == "3.0.0") + } + + @Test func measuredRecordWithSourceIsAccepted() throws { + let checked = try validateCurrentRecord(json: Data(Self.measurement.utf8)) + let expected = Self.measurement + .replacingOccurrences(of: #""record_type":"point_measurement","#, with: "") + .replacingOccurrences( + of: #""is_deleted":false,"#, with: #""is_deleted":false,"record_type":"point_measurement","#) + #expect(String(decoding: checked, as: UTF8.self) == expected) + } + + @Test func measuredRecordWithoutSourceIsRefused() { + let missing = Self.measurement.replacingOccurrences( + of: #""source_id":"01890f3e-e7d3-7cc0-88c8-000000000003","#, with: "") + let found = issues { try validateCurrentRecord(json: Data(missing.utf8)) } + #expect(found.map(\.pathText) == ["data.source_id"]) + #expect(found.map(\.code) == ["invalid_type"]) + #expect(found.map(\.message) == ["Invalid input: expected string, received undefined"]) + } + + @Test func athleteReportCannotClaimSource() { + let claimed = Self.report.replacingOccurrences( + of: #""report_type":"note","#, + with: #""report_type":"note","source_id":"01890f3e-e7d3-7cc0-88c8-000000000003","#) + let found = issues { try validateCurrentRecord(json: Data(claimed.utf8)) } + #expect(found.map(\.pathText) == ["data"]) + #expect(found.map(\.code) == ["unrecognized_keys"]) + #expect(found.map(\.message) == [#"Unrecognized key: "source_id""#]) + } + + @Test func pathsKeepFieldNamesAndPositionsApart() { + let data = #"{"report_type":"note","reported_at":"2026-01-02T03:04:05.678Z","input_reported_at":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"reported_via":"text","attachment_ids":[7]}"# + let found = issues { try validate(shape: "AthleteReportData", json: Data(data.utf8)) } + #expect(found.first?.path == [.field(name: "attachment_ids"), .position(index: 0)]) + } + + @Test func malformedJsonAndUnknownShapesHaveTheirOwnFailures() { + #expect(throws: AthleticStandardError.self) { try validate(shape: "CurrentRecord", json: Data("{".utf8)) } + do { + _ = try validate(shape: "CurrentRecord", json: Data([0xff])) + } catch let error as AthleticStandardError { + #expect(error.code == "malformed_json") + } catch { + Issue.record("unexpected error \(error)") + } + do { + _ = try validate(shape: "NoSuchShape", json: Data("{}".utf8)) + } catch let error as AthleticStandardError { + #expect(error.code == "unknown_shape") + #expect(error.detail == "no published shape named NoSuchShape") + } catch { + Issue.record("unexpected error \(error)") + } + } +} diff --git a/mobile/tests/dependencies.rs b/mobile/tests/dependencies.rs new file mode 100644 index 00000000..58c79a77 --- /dev/null +++ b/mobile/tests/dependencies.rs @@ -0,0 +1,84 @@ +//! The calculation-only build reaches no storage, network, or command line +//! (D312, D327). +//! +//! Without the `sqlite` feature, the phone library's dependency tree must hold +//! no SQLite, HTTP, terminal, or command-line crate, and the core's source must +//! name no file, network, or process API. + +use std::path::PathBuf; +use std::process::Command; + +fn repository() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..") +} + +/// The normal dependencies of the phone library for an Android phone. +fn dependency_names(features: &[&str]) -> Vec { + let mut command = Command::new(env!("CARGO")); + command + .current_dir(repository()) + .args(["tree", "--locked", "--offline", "-p", "athleticstandard-mobile", "-e", "normal"]) + .args(["--target", "aarch64-linux-android", "--prefix", "none", "--format", "{p}"]) + .arg("--no-default-features"); + if !features.is_empty() { + command.arg("--features").arg(features.join(",")); + } + let output = command.output().expect("run cargo tree"); + assert!(output.status.success(), "cargo tree failed: {}", String::from_utf8_lossy(&output.stderr)); + let mut names: Vec = String::from_utf8(output.stdout) + .unwrap() + .lines() + .filter_map(|line| line.split_whitespace().next().map(str::to_string)) + .collect(); + names.sort(); + names.dedup(); + names +} + +/// Crates that a phone build must not contain without storage. +const STORAGE_OR_NETWORK: &[&str] = &[ + "rusqlite", + "libsqlite3-sys", + "libsql", + "ureq", + "reqwest", + "hyper", + "tokio", + "axum", + "clap", + "terminal_size", + "zip", + "quick-xml", + "athleticstandard", +]; + +#[test] +fn the_calculation_only_build_has_no_storage_network_or_command_line() { + let names = dependency_names(&[]); + assert!(names.contains(&"athleticstandard-core".to_string()), "the core is a dependency: {names:?}"); + let found: Vec<&String> = names.iter().filter(|name| STORAGE_OR_NETWORK.contains(&name.as_str())).collect(); + assert!(found.is_empty(), "the calculation-only build depends on {found:?}"); +} + +#[test] +fn the_core_names_no_file_network_or_process_api() { + let mut files = Vec::new(); + let mut folders = vec![repository().join("core/src")]; + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + folders.push(path); + } else if path.extension().is_some_and(|extension| extension == "rs") { + files.push(path); + } + } + } + assert!(files.len() > 10, "found the core's source files"); + for file in files { + let text = std::fs::read_to_string(&file).unwrap(); + for forbidden in ["std::fs", "std::net", "std::process", "std::env::var", "File::open", "File::create"] { + assert!(!text.contains(forbidden), "{} names {forbidden}", file.display()); + } + } +} diff --git a/mobile/tests/fixtures.rs b/mobile/tests/fixtures.rs new file mode 100644 index 00000000..536e542d --- /dev/null +++ b/mobile/tests/fixtures.rs @@ -0,0 +1,139 @@ +//! The phone test bundle (D333). +//! +//! Every suite runs here through the binding's Rust functions, the same calls +//! the Swift and Kotlin bindings make. With `ATH_MOBILE_FIXTURES=` set, +//! each suite is also written there as JSON, for the Swift and Kotlin tests to +//! run through the installed packages. Inputs are synthetic. +//! +//! Each suite file holds its cases, the expected outcome of each, the cases +//! skipped with their documented reason, and the counts. A phone run must skip +//! exactly the listed cases and match every other one. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use athleticstandard_core::json::{self, Map, Value}; +use athleticstandard_mobile::{validate, AthleticStandardError, PathSegment}; + +#[path = "../../tests/vector_rules/mod.rs"] +mod vector_rules; + +fn repository() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..") +} + +/// Write a suite when `ATH_MOBILE_FIXTURES` names a folder. +fn export(name: &str, suite: Value) { + let Some(folder) = std::env::var_os("ATH_MOBILE_FIXTURES") else { + return; + }; + let folder = Path::new(&folder); + std::fs::create_dir_all(folder).unwrap(); + std::fs::write(folder.join(format!("{name}.json")), json::to_string(&suite)).unwrap(); +} + +/// An issue as the phone tests print it: `[path] code message`, the format +/// `tests/vector_rules` uses for the recorded vectors. +fn binding_issue_text(path: &[PathSegment], code: &str, message: &str) -> String { + let path: Vec = path + .iter() + .map(|segment| match segment { + PathSegment::Field { name } => name.clone(), + PathSegment::Position { index } => index.to_string(), + }) + .collect(); + format!("[{}] {code} {message}", path.join(".")) +} + +/// What a phone compares: the issue texts, and the checked output when valid. +fn binding_outcome(schema: &str, input_text: &str) -> Result<(Vec, Option), String> { + match validate(schema.to_string(), input_text.as_bytes().to_vec()) { + Ok(output) => Ok((Vec::new(), Some(String::from_utf8(output).unwrap()))), + Err(AthleticStandardError::Invalid { issues, .. }) => Ok(( + issues.iter().map(|issue| binding_issue_text(&issue.path, &issue.code, &issue.message)).collect(), + None, + )), + Err(other) => Err(format!("{}: {}", other.code(), other.detail())), + } +} + +/// The skips the desktop harness documents, with their counts. A new skip +/// fails here and on every phone. +const MODEL_VECTOR_SKIPS: &[(&str, usize)] = &[ + ("a __proto__ key is kept and checked like any other key instead of being dropped", 51), + ("a number too large for a double is refused when the JSON is read", 31), + ("lone UTF-16 surrogates cannot be held in Rust text; the reader refuses them", 4), + ("version 2.1.1 is accepted, so the version list in messages names it", 28), +]; + +#[test] +fn every_model_vector_runs_through_the_binding() { + let folder = repository().join("tests/vectors/model"); + let mut files: Vec = std::fs::read_dir(&folder).unwrap().map(|entry| entry.unwrap().path()).collect(); + files.sort(); + let mut cases = Vec::new(); + let mut skipped: BTreeMap<&'static str, usize> = BTreeMap::new(); + let mut failures = Vec::new(); + let mut run = 0usize; + for file in &files { + let document = json::parse(&std::fs::read_to_string(file).unwrap()).unwrap(); + let schema = document["schema"].as_str().unwrap().to_string(); + for case in document["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap().to_string(); + let input_text = match case.get("input_text").and_then(Value::as_str) { + Some(text) => text.to_string(), + None => json::to_string(&case["input"]), + }; + let mut item = Map::new(); + item.insert("schema".into(), Value::String(schema.clone())); + item.insert("name".into(), Value::String(name.clone())); + item.insert("input_text".into(), Value::String(input_text.clone())); + if let Some(reason) = vector_rules::deliberate_difference(&schema, case) { + *skipped.entry(reason).or_default() += 1; + item.insert("skip".into(), Value::String(reason.to_string())); + cases.push(Value::Object(item)); + continue; + } + let issues: Vec = + case["issues"].as_array().unwrap().iter().map(vector_rules::expected_issue_text).collect(); + let output = if case["valid"].as_bool() == Some(true) { + Some(match case.get("output_text").and_then(Value::as_str) { + Some(text) => text.to_string(), + None => json::to_string(&case["output"]), + }) + } else { + None + }; + run += 1; + match binding_outcome(&schema, &input_text) { + Ok((actual_issues, actual_output)) => { + if actual_issues != issues || actual_output != output { + failures.push(format!( + "{schema} / {name}: expected {issues:?} {output:?}, got {actual_issues:?} {actual_output:?}" + )); + } + } + Err(error) => failures.push(format!("{schema} / {name}: {error}")), + } + item.insert("issues".into(), Value::Array(issues.into_iter().map(Value::String).collect())); + item.insert("output_text".into(), output.map(Value::String).unwrap_or(Value::Null)); + cases.push(Value::Object(item)); + } + } + let expected_skips: BTreeMap<&str, usize> = MODEL_VECTOR_SKIPS.iter().copied().collect(); + assert_eq!(skipped, expected_skips, "the documented skips changed"); + assert!(failures.is_empty(), "{} of {run} cases differ:\n{}", failures.len(), failures.join("\n")); + assert_eq!(cases.len(), run + skipped.values().sum::()); + eprintln!("model vectors: {} files, {} cases, {run} run, {} skipped", files.len(), cases.len(), cases.len() - run); + + let mut counts = Map::new(); + counts.insert("files".into(), Value::from(files.len() as u64)); + counts.insert("cases".into(), Value::from(cases.len() as u64)); + counts.insert("run".into(), Value::from(run as u64)); + counts.insert("skipped".into(), Value::from((cases.len() - run) as u64)); + let mut suite = Map::new(); + suite.insert("suite".into(), Value::String("model-vectors".into())); + suite.insert("counts".into(), Value::Object(counts)); + suite.insert("cases".into(), Value::Array(cases)); + export("model-vectors", Value::Object(suite)); +} diff --git a/mobile/tests/validate.rs b/mobile/tests/validate.rs new file mode 100644 index 00000000..c5da3e4c --- /dev/null +++ b/mobile/tests/validate.rs @@ -0,0 +1,73 @@ +//! The binding's record checks agree with the desktop validator on the cases +//! the phone tests also run (D329). The fixture bundle covers every vector. + +use athleticstandard_mobile::{validate, validate_current_record, AthleticStandardError, PathSegment}; + +const MEASUREMENT: &str = r#"{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000064","record_type":"point_measurement","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"source_id":"01890f3e-e7d3-7cc0-88c8-000000000003","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","quantity":"hrv_rmssd","input_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"value":{"standard_value":42,"standard_unit":"ms","input_value_missing_reason":"not_provided_by_source","input_unit_missing_reason":"not_provided_by_source"}}}"#; + +const REPORT: &str = r#"{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000065","record_type":"athlete_report","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"report_type":"note","reported_at":"2026-01-02T03:04:05.678Z","input_reported_at":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"reported_via":"text"}}"#; + +fn issues(error: AthleticStandardError) -> Vec<(String, String, String)> { + match error { + AthleticStandardError::Invalid { issues, .. } => { + issues.into_iter().map(|issue| (issue.path_text, issue.code, issue.message)).collect() + } + other => panic!("expected an invalid record, got {other:?}"), + } +} + +#[test] +fn a_measured_record_with_a_source_is_accepted() { + // The checked JSON uses the order the desktop stores and exports. + let expected = MEASUREMENT + .replace(r#""record_type":"point_measurement","#, "") + .replace(r#""is_deleted":false,"#, r#""is_deleted":false,"record_type":"point_measurement","#); + let checked = validate_current_record(MEASUREMENT.as_bytes().to_vec()).unwrap(); + assert_eq!(String::from_utf8(checked).unwrap(), expected); + let checked = validate("CurrentRecord".into(), MEASUREMENT.as_bytes().to_vec()).unwrap(); + assert_eq!(String::from_utf8(checked).unwrap(), expected); +} + +#[test] +fn a_measured_record_without_its_source_is_refused() { + let missing = MEASUREMENT.replace(r#""source_id":"01890f3e-e7d3-7cc0-88c8-000000000003","#, ""); + let found = issues(validate_current_record(missing.into_bytes()).unwrap_err()); + assert_eq!( + found, + vec![( + "data.source_id".into(), + "invalid_type".into(), + "Invalid input: expected string, received undefined".into() + )] + ); +} + +#[test] +fn an_athlete_report_cannot_claim_a_source() { + let claimed = REPORT.replace( + r#""report_type":"note","#, + r#""report_type":"note","source_id":"01890f3e-e7d3-7cc0-88c8-000000000003","#, + ); + let found = issues(validate_current_record(claimed.into_bytes()).unwrap_err()); + assert_eq!(found, vec![("data".into(), "unrecognized_keys".into(), r#"Unrecognized key: "source_id""#.into())]); +} + +#[test] +fn paths_keep_field_names_and_list_positions_apart() { + let error = validate("AthleteReportData".into(), br#"{"report_type":"note","reported_at":"2026-01-02T03:04:05.678Z","input_reported_at":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"reported_via":"text","attachment_ids":[7]}"#.to_vec()).unwrap_err(); + let AthleticStandardError::Invalid { issues, .. } = error else { panic!("expected invalid") }; + assert_eq!( + issues[0].path, + vec![PathSegment::Field { name: "attachment_ids".into() }, PathSegment::Position { index: 0 }] + ); +} + +#[test] +fn malformed_json_and_unknown_shapes_have_their_own_failures() { + let error = validate("CurrentRecord".into(), b"{".to_vec()).unwrap_err(); + assert_eq!(error.code(), "malformed_json"); + let error = validate("CurrentRecord".into(), vec![0xff]).unwrap_err(); + assert_eq!(error.code(), "malformed_json"); + let error = validate("NoSuchShape".into(), b"{}".to_vec()).unwrap_err(); + assert_eq!(error, AthleticStandardError::UnknownShape { detail: "no published shape named NoSuchShape".into() }); +} diff --git a/mobile/uniffi.toml b/mobile/uniffi.toml new file mode 100644 index 00000000..4cea9f3a --- /dev/null +++ b/mobile/uniffi.toml @@ -0,0 +1,15 @@ +# Settings for the generated Swift and Kotlin bindings (D327, D331). + +[bindings.swift] +# The Swift module apps import, and the C module the XCFramework provides. +module_name = "AthleticStandard" +ffi_module_name = "AthleticStandardFFI" +ffi_module_filename = "AthleticStandardFFI" +generate_immutable_records = true + +[bindings.kotlin] +package_name = "ai.athleticstandard" +cdylib_name = "athleticstandard_mobile" +# Use the Android system cleaner where the phone has one (API 34 and later). +android = true +generate_immutable_records = true diff --git a/tests/model_vectors.rs b/tests/model_vectors.rs index 180ba683..16af8f5c 100644 --- a/tests/model_vectors.rs +++ b/tests/model_vectors.rs @@ -8,105 +8,17 @@ use std::collections::BTreeMap; use std::path::PathBuf; +#[path = "vector_rules/mod.rs"] +mod vector_rules; + use athleticstandard::json::{self, Value}; use athleticstandard::model::registry; +use vector_rules::{deliberate_difference, expected_issue_text, issue_text}; fn vectors_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/vectors/model") } -/// Cases where 2.1.1 or later differs on purpose. Each entry names the reason. -fn deliberate_difference(schema: &str, case: &Value) -> Option<&'static str> { - let name = case["name"].as_str().unwrap_or_default(); - let text = case.get("input_text").and_then(Value::as_str).unwrap_or_default(); - if text.contains("\\ud8") || text.contains("\\udc") || text.contains("\\uD8") || text.contains("\\uDC") { - return Some("lone UTF-16 surrogates cannot be held in Rust text; the reader refuses them"); - } - if text.contains("__proto__") || json::to_string(&case["input"]).contains("\"__proto__\"") { - return Some("a __proto__ key is kept and checked like any other key instead of being dropped"); - } - if schema == "RecordFormatVersion" || name.contains("2.1.1") || name.starts_with("athleticstandard_version:") { - return Some("version 2.1.1 is accepted, so the version list in messages names it"); - } - if text.contains("1e400") { - return Some("a number too large for a double is refused when the JSON is read"); - } - None -} - -/// The one message 2.1.2 changes on purpose: the report-type list names -/// `session_effort` (D238). Every case still runs, with that list extended. -fn as_2_1_2_issue(text: String) -> String { - const REPORT_TYPES: &str = r#""sleep_quality"|"soreness"|"stress"|"mood"|"energy"|"note""#; - if text.contains(REPORT_TYPES) && !text.contains("session_effort") { - return text.replace(REPORT_TYPES, &format!(r#"{REPORT_TYPES}|"session_effort""#)); - } - text -} - -/// The one message 2.1.3 changes on purpose: the author-type list names -/// `coach` (D255). Every case still runs, with that list extended. -/// The one message 3.0.0 changes on purpose: the record-type list names the -/// four record types 3.0.0 adds. Every case still runs, with that list extended. -fn as_3_0_0_issue(text: String) -> String { - // 3.0.0 also adds report types, score types, and score fields (D304, D310). - let text = text - .replace(r#""note"|"session_effort""#, r#""note"|"session_effort"|"injury"|"illness""#) - .replace(r#"\"note\"|\"session_effort\""#, r#"\"note\"|\"session_effort\"|\"injury\"|\"illness\""#) - .replace(r#""time"|"reps"|"load""#, r#""time"|"reps"|"load"|"power"|"distance"|"energy""#) - .replace(r#"\"time\"|\"reps\"|\"load\""#, r#"\"time\"|\"reps\"|\"load\"|\"power\"|\"distance\"|\"energy\""#) - .replace( - "A score needs duration_s, reps, or weight_kg", - "A score needs duration_s, reps, weight_kg, power_w, distance_m, or energy_kcal", - ); - // Only a list of every record type, which starts with athlete_profile, - // changes. A message that names one type stays as it was. - if text.contains("intensity_reference") || !text.contains("athlete_profile") { - return text; - } - // Error lists quote the types two ways: 'a' | 'b' and "a"|"b". - for (last, added) in [ - ( - "'nutrition_model_interpretation'", - " | 'intensity_reference' | 'event' | 'approval' | 'calculation_result' | 'device_recording'", - ), - ( - r#"\"nutrition_model_interpretation\""#, - r#"|\"intensity_reference\"|\"event\"|\"approval\"|\"calculation_result\"|\"device_recording\""#, - ), - ( - r#""nutrition_model_interpretation""#, - r#"|"intensity_reference"|"event"|"approval"|"calculation_result"|"device_recording""#, - ), - ] { - if text.contains(last) { - return text.replacen(last, &format!("{last}{added}"), 1); - } - } - text -} - -fn as_2_1_3_issue(text: String) -> String { - const AUTHOR_TYPES: &str = "Expected 'athlete' | 'agent' | 'tool'"; - if text.ends_with(AUTHOR_TYPES) { - return format!("{text} | 'coach'"); - } - text -} - -fn issue_text(issue: &Value) -> String { - let path: Vec = issue["path"] - .as_array() - .unwrap() - .iter() - .map(|segment| match segment { - Value::String(text) => text.clone(), - other => json::to_string(other), - }) - .collect(); - format!("[{}] {} {}", path.join("."), issue["code"].as_str().unwrap(), issue["message"].as_str().unwrap()) -} - #[test] fn every_recorded_vector_matches() { let mut files: Vec = @@ -138,15 +50,7 @@ fn every_recorded_vector_matches() { }; checked += 1; let actual: Vec = shape.issues(&input).iter().map(|issue| issue_text(&issue.to_json())).collect(); - let expected: Vec = case["issues"] - .as_array() - .unwrap() - .iter() - .map(issue_text) - .map(as_2_1_2_issue) - .map(as_2_1_3_issue) - .map(as_3_0_0_issue) - .collect(); + let expected: Vec = case["issues"].as_array().unwrap().iter().map(expected_issue_text).collect(); if actual != expected { failures.push(format!("{schema_name} / {name}:\n expected {expected:?}\n actual {actual:?}")); continue; diff --git a/tests/vector_rules/mod.rs b/tests/vector_rules/mod.rs new file mode 100644 index 00000000..1b50f1f4 --- /dev/null +++ b/tests/vector_rules/mod.rs @@ -0,0 +1,104 @@ +//! The documented differences between the recorded 2.1.0 vectors and this +//! validator. `tests/model_vectors.rs` and the phone fixture exporter in +//! `mobile/tests/fixtures.rs` read the same list, so every platform skips and +//! adjusts the same cases (D333). + +use athleticstandard_core::json::{self, Value}; + +/// Cases where 2.1.1 or later differs on purpose. Each entry names the reason. +pub fn deliberate_difference(schema: &str, case: &Value) -> Option<&'static str> { + let name = case["name"].as_str().unwrap_or_default(); + let text = case.get("input_text").and_then(Value::as_str).unwrap_or_default(); + if text.contains("\\ud8") || text.contains("\\udc") || text.contains("\\uD8") || text.contains("\\uDC") { + return Some("lone UTF-16 surrogates cannot be held in Rust text; the reader refuses them"); + } + if text.contains("__proto__") || json::to_string(&case["input"]).contains("\"__proto__\"") { + return Some("a __proto__ key is kept and checked like any other key instead of being dropped"); + } + if schema == "RecordFormatVersion" || name.contains("2.1.1") || name.starts_with("athleticstandard_version:") { + return Some("version 2.1.1 is accepted, so the version list in messages names it"); + } + if text.contains("1e400") { + return Some("a number too large for a double is refused when the JSON is read"); + } + None +} + +/// The one message 2.1.2 changes on purpose: the report-type list names +/// `session_effort` (D238). Every case still runs, with that list extended. +pub fn as_2_1_2_issue(text: String) -> String { + const REPORT_TYPES: &str = r#""sleep_quality"|"soreness"|"stress"|"mood"|"energy"|"note""#; + if text.contains(REPORT_TYPES) && !text.contains("session_effort") { + return text.replace(REPORT_TYPES, &format!(r#"{REPORT_TYPES}|"session_effort""#)); + } + text +} + +/// The one message 2.1.3 changes on purpose: the author-type list names +/// `coach` (D255). Every case still runs, with that list extended. +pub fn as_2_1_3_issue(text: String) -> String { + const AUTHOR_TYPES: &str = "Expected 'athlete' | 'agent' | 'tool'"; + if text.ends_with(AUTHOR_TYPES) { + return format!("{text} | 'coach'"); + } + text +} + +pub fn issue_text(issue: &Value) -> String { + let path: Vec = issue["path"] + .as_array() + .unwrap() + .iter() + .map(|segment| match segment { + Value::String(text) => text.clone(), + other => json::to_string(other), + }) + .collect(); + format!("[{}] {} {}", path.join("."), issue["code"].as_str().unwrap(), issue["message"].as_str().unwrap()) +} + +/// The one message 3.0.0 changes on purpose: the record-type list names the +/// four record types 3.0.0 adds. Every case still runs, with that list extended. +pub fn as_3_0_0_issue(text: String) -> String { + // 3.0.0 also adds report types, score types, and score fields (D304, D310). + let text = text + .replace(r#""note"|"session_effort""#, r#""note"|"session_effort"|"injury"|"illness""#) + .replace(r#"\"note\"|\"session_effort\""#, r#"\"note\"|\"session_effort\"|\"injury\"|\"illness\""#) + .replace(r#""time"|"reps"|"load""#, r#""time"|"reps"|"load"|"power"|"distance"|"energy""#) + .replace(r#"\"time\"|\"reps\"|\"load\""#, r#"\"time\"|\"reps\"|\"load\"|\"power\"|\"distance\"|\"energy\""#) + .replace( + "A score needs duration_s, reps, or weight_kg", + "A score needs duration_s, reps, weight_kg, power_w, distance_m, or energy_kcal", + ); + // Only a list of every record type, which starts with athlete_profile, + // changes. A message that names one type stays as it was. + if text.contains("intensity_reference") || !text.contains("athlete_profile") { + return text; + } + // Error lists quote the types two ways: 'a' | 'b' and "a"|"b". + for (last, added) in [ + ( + "'nutrition_model_interpretation'", + " | 'intensity_reference' | 'event' | 'approval' | 'calculation_result' | 'device_recording'", + ), + ( + r#"\"nutrition_model_interpretation\""#, + r#"|\"intensity_reference\"|\"event\"|\"approval\"|\"calculation_result\"|\"device_recording\""#, + ), + ( + r#""nutrition_model_interpretation""#, + r#"|"intensity_reference"|"event"|"approval"|"calculation_result"|"device_recording""#, + ), + ] { + if text.contains(last) { + return text.replacen(last, &format!("{last}{added}"), 1); + } + } + text +} + +/// The expected issue text after the message changes 2.1.2, 2.1.3, and 3.0.0 +/// made on purpose. +pub fn expected_issue_text(issue: &Value) -> String { + as_3_0_0_issue(as_2_1_3_issue(as_2_1_2_issue(issue_text(issue)))) +} From 91a56eadfdd80d1ae3708ebc5eba85ff11601f5c Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 09:22:51 -0600 Subject: [PATCH 03/30] Put the command line behind a default feature, and run protocol operations in process. The `athleticstandard` crate gains a `cli` feature, on by default, that holds the command line, terminal handling, provider import readers, prediction and log planning, and the network runtime. Without it the crate builds the store, files, packages, calculations, and views, which is what a phone needs (D327). The two provider-import operations and the prediction operations are left out of that build; the operation order the npm client is generated from does not change. `protocol::run_in_process` runs one protocol operation on a store the caller keeps open and returns its output and streamed items. The worker keeps its events in memory for such a call. An operation that calls back to its client is refused. Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 19 +++++++---- docs/architecture.md | 8 +++++ src/assets/mod.rs | 1 + src/lib.rs | 5 +++ src/package/mod.rs | 1 + src/protocol/mod.rs | 2 +- src/protocol/ops/mod.rs | 42 ++++++++++++++++++++++++ src/protocol/ops/package.rs | 8 +++++ src/protocol/ops/prediction.rs | 40 +---------------------- src/protocol/ops/records.rs | 2 +- src/protocol/worker.rs | 60 +++++++++++++++++++++++++++++++++- tests/protocol_in_process.rs | 51 +++++++++++++++++++++++++++++ 12 files changed, 191 insertions(+), 48 deletions(-) create mode 100644 tests/protocol_in_process.rs diff --git a/Cargo.toml b/Cargo.toml index 7e8fa83d..553585b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ path = "src/lib.rs" [[bin]] name = "ath" path = "src/main.rs" +required-features = ["cli"] # Native library latency for the release performance report. See # performance/README.md. `cargo test` also runs its test, which measures every @@ -28,29 +29,35 @@ path = "src/main.rs" name = "performance-library" path = "tools/performance/library.rs" test = true +required-features = ["cli"] [dependencies] athleticstandard-core = { path = "core" } chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } chrono-tz = { version = "0.10.4", features = ["case-insensitive"] } -clap = { version = "4.6.7", features = ["derive", "wrap_help"] } -quick-xml = "0.37" +clap = { version = "4.6.7", features = ["derive", "wrap_help"], optional = true } +quick-xml = { version = "0.37", optional = true } rusqlite = { version = "0.42", features = ["bundled", "backup"] } ryu-js = "1.0.3" serde = { version = "1.0.229", features = ["derive"] } serde_json = { version = "1.0.154", features = ["preserve_order", "float_roundtrip"] } sha2 = "0.11.0" -terminal_size = "0.4.4" -ureq = "2.12" +terminal_size = { version = "0.4.4", optional = true } +ureq = { version = "2.12", optional = true } uuid = { version = "1.29", features = ["v7"] } -zip = "2.2" -flate2 = "1.1" +zip = { version = "2.2", optional = true } +flate2 = { version = "1.1", optional = true } [[test]] name = "replica" required-features = ["changesets"] [features] +# The command line, terminal handling, provider import readers, prediction and +# log planning, and the network runtime. Phone builds turn it off, so they hold +# the store and calculations without any network code (D327). +default = ["cli"] +cli = ["dep:clap", "dep:flate2", "dep:quick-xml", "dep:terminal_size", "dep:ureq", "dep:zip"] # Record the rows a write changes and replay them on another copy (D268). # Only the host program turns this on. changesets = [] diff --git a/docs/architecture.md b/docs/architecture.md index 40c7e4b1..fecfdde1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -52,6 +52,14 @@ Rules that keep this table true: arithmetic, or history rule. It parses, calls one library operation, and renders the result. - Local record commands never start a network client or a credential store. +- The `cli` feature, on by default, holds `src/cli/`, `src/import/`, + `src/runtime/`, `src/prediction/`, `src/log.rs`, package zips + (`src/package/zipped.rs`), and the protocol operations that use them. The phone storage binding builds the library without it, so + the store, packages, calculations, and views must not depend on those + modules (D327). `mobile/tests/dependencies.rs` checks the result. +- `protocol::run_in_process` runs a protocol operation on a store the caller + holds open. The phone binding uses it, so phone edits get the same handlers + as the npm client. - `host/` never writes record tables with its own SQL. It calls the library for every record operation. In remote mode it sends the row changes the library recorded (D268). [`hosting.md`](hosting.md) is the guide for operators and app diff --git a/src/assets/mod.rs b/src/assets/mod.rs index 2bd0b202..83d5f503 100644 --- a/src/assets/mod.rs +++ b/src/assets/mod.rs @@ -10,6 +10,7 @@ //! `ath apply ` read `.agents/` first. `ath calculate` reads only //! the shipped calculation file. +#[cfg(feature = "cli")] pub mod reference; pub mod skill; diff --git a/src/lib.rs b/src/lib.rs index fefcd472..368fb1ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,18 +6,23 @@ pub mod assets; pub mod calculate; +#[cfg(feature = "cli")] pub mod cli; pub mod error; pub mod files; pub mod follow_up; pub mod ids; +#[cfg(feature = "cli")] pub mod import; pub mod input_policy; +#[cfg(feature = "cli")] pub mod log; pub use athleticstandard_core::{json, model, model_enum, model_object}; pub mod package; +#[cfg(feature = "cli")] pub mod prediction; pub mod protocol; +#[cfg(feature = "cli")] pub mod runtime; pub mod store; pub mod text; diff --git a/src/package/mod.rs b/src/package/mod.rs index 205e6bc0..f2fd3c34 100644 --- a/src/package/mod.rs +++ b/src/package/mod.rs @@ -19,6 +19,7 @@ pub mod load; pub mod restore; pub(crate) mod series; pub mod sync; +#[cfg(feature = "cli")] pub mod zipped; #[cfg(test)] diff --git a/src/protocol/mod.rs b/src/protocol/mod.rs index f4fe2231..4e646e31 100644 --- a/src/protocol/mod.rs +++ b/src/protocol/mod.rs @@ -74,7 +74,7 @@ pub mod typescript; pub mod worker; pub use definition::{Kind, Operation, TargetUse, OPERATIONS}; -pub use worker::serve; +pub use worker::{run_in_process, serve, Failure, LocalOutput}; /// The protocol version. A request naming another version is refused. pub const PROTOCOL_VERSION: u32 = 1; diff --git a/src/protocol/ops/mod.rs b/src/protocol/ops/mod.rs index c7b3f800..d5fb2335 100644 --- a/src/protocol/ops/mod.rs +++ b/src/protocol/ops/mod.rs @@ -7,12 +7,51 @@ mod database; mod helpers; mod package; +#[cfg(feature = "cli")] mod prediction; mod query; mod records; use super::definition::Operation; +/// Decode standard base64 with padding. +pub(crate) fn base64_decode(text: &str) -> Option> { + let value = |byte: u8| -> Option { + Some(match byte { + b'A'..=b'Z' => byte - b'A', + b'a'..=b'z' => byte - b'a' + 26, + b'0'..=b'9' => byte - b'0' + 52, + b'+' => 62, + b'/' => 63, + _ => return None, + } as u32) + }; + let bytes = text.as_bytes(); + if !bytes.len().is_multiple_of(4) { + return None; + } + let mut out = Vec::with_capacity(bytes.len() / 4 * 3); + for chunk in bytes.chunks(4) { + let padding = chunk.iter().rev().take_while(|byte| **byte == b'=').count(); + if padding > 2 { + return None; + } + let mut n = 0u32; + for (index, byte) in chunk.iter().enumerate() { + let digit = if index >= 4 - padding { 0 } else { value(*byte)? }; + n = (n << 6) | digit; + } + out.push((n >> 16) as u8); + if padding < 2 { + out.push((n >> 8) as u8); + } + if padding < 1 { + out.push(n as u8); + } + } + Some(out) +} + /// Every operation, in a stable order. pub fn all() -> Vec { let mut out = Vec::new(); @@ -20,8 +59,11 @@ pub fn all() -> Vec { out.extend_from_slice(database::OPERATIONS); out.extend_from_slice(records::OPERATIONS); out.extend_from_slice(query::OPERATIONS); + #[cfg(feature = "cli")] out.extend_from_slice(prediction::OPERATIONS); out.extend_from_slice(package::OPERATIONS); + #[cfg(feature = "cli")] + out.extend_from_slice(package::PROVIDER_OPERATIONS); let mut names: Vec<&str> = out.iter().map(|operation| operation.name).collect(); names.sort_unstable(); names.dedup(); diff --git a/src/protocol/ops/package.rs b/src/protocol/ops/package.rs index ee3ab0fd..997fc53f 100644 --- a/src/protocol/ops/package.rs +++ b/src/protocol/ops/package.rs @@ -169,6 +169,12 @@ pub const OPERATIONS: &[Operation] = &[ callbacks: &[], run: erase_apply, }, +]; + +/// Provider imports read export files with the import readers, which only the +/// `cli` build has (D327). +#[cfg(feature = "cli")] +pub const PROVIDER_OPERATIONS: &[Operation] = &[ Operation { name: "provider.preview", kind: Kind::Async, @@ -568,6 +574,7 @@ fn erase_apply(call: &mut Call<'_>) -> Outcome { /// `previewProviderImport(database, inputPath, options)`. Planned records /// stream one per line. +#[cfg(feature = "cli")] fn provider_preview(call: &mut Call<'_>) -> Outcome { let input_path = input::required_string(&call.input, "input_path")?; let received_at = match input::get(&call.input, "received_at") { @@ -610,6 +617,7 @@ fn provider_preview(call: &mut Call<'_>) -> Outcome { /// previewed again at the caller's import time. A database or export that /// changed after the caller's preview is refused. The export's fingerprint /// must match the preview's before and after it is read again. +#[cfg(feature = "cli")] fn provider_import(call: &mut Call<'_>) -> Outcome { let request = call.input.clone(); let input_path = input::required_string(&request, "input_path")?; diff --git a/src/protocol/ops/prediction.rs b/src/protocol/ops/prediction.rs index 7c1fe9e7..2274ab65 100644 --- a/src/protocol/ops/prediction.rs +++ b/src/protocol/ops/prediction.rs @@ -402,44 +402,6 @@ pub(crate) fn base64(bytes: &[u8]) -> String { out } -/// Decode standard base64 with padding. -pub(crate) fn base64_decode(text: &str) -> Option> { - let value = |byte: u8| -> Option { - Some(match byte { - b'A'..=b'Z' => byte - b'A', - b'a'..=b'z' => byte - b'a' + 26, - b'0'..=b'9' => byte - b'0' + 52, - b'+' => 62, - b'/' => 63, - _ => return None, - } as u32) - }; - let bytes = text.as_bytes(); - if !bytes.len().is_multiple_of(4) { - return None; - } - let mut out = Vec::with_capacity(bytes.len() / 4 * 3); - for chunk in bytes.chunks(4) { - let padding = chunk.iter().rev().take_while(|byte| **byte == b'=').count(); - if padding > 2 { - return None; - } - let mut n = 0u32; - for (index, byte) in chunk.iter().enumerate() { - let digit = if index >= 4 - padding { 0 } else { value(*byte)? }; - n = (n << 6) | digit; - } - out.push((n >> 16) as u8); - if padding < 2 { - out.push((n >> 8) as u8); - } - if padding < 1 { - out.push(n as u8); - } - } - Some(out) -} - /// `answers` and `assumed`: objects from a follow-up question ID to its value /// (3.0.0 spec section 8). fn log_answers(request: &Value) -> crate::error::Result { @@ -465,7 +427,7 @@ mod tests { fn base64_round_trips() { for text in ["", "f", "fo", "foo", "foob", "fooba", "foobar"] { let encoded = super::base64(text.as_bytes()); - assert_eq!(super::base64_decode(&encoded).unwrap(), text.as_bytes()); + assert_eq!(super::super::base64_decode(&encoded).unwrap(), text.as_bytes()); } assert_eq!(super::base64(b"foobar"), "Zm9vYmFy"); assert_eq!(super::base64(b"fo"), "Zm8="); diff --git a/src/protocol/ops/records.rs b/src/protocol/ops/records.rs index b8b09479..b423b17e 100644 --- a/src/protocol/ops/records.rs +++ b/src/protocol/ops/records.rs @@ -125,7 +125,7 @@ fn apply_with_files(call: &mut Call<'_>, changes: Changes) -> Result>>, + /// In-process calls keep their events here instead of writing them. + kept: Option>>>, } impl Events { @@ -119,6 +121,10 @@ impl Events { } fn write(&self, event: Map, flush: bool) { + if let Some(kept) = &self.kept { + kept.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push(event); + return; + } let line = self.line(event); let mut out = self.out.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); // A client that went away cannot read anything more; the operation @@ -286,7 +292,8 @@ pub fn serve_streams( let request = match request { Ok(request) => request, Err((code, message, id)) => { - let events = Events { id, out: Mutex::new(BufWriter::with_capacity(EVENT_BUFFER_BYTES, output)) }; + let events = + Events { id, out: Mutex::new(BufWriter::with_capacity(EVENT_BUFFER_BYTES, output)), kept: None }; write_error(&events, protocol_error(&code, &message)); flush(&events); return EXIT_PROTOCOL; @@ -295,6 +302,7 @@ pub fn serve_streams( let events = Arc::new(Events { id: request.id.clone(), out: Mutex::new(BufWriter::with_capacity(EVENT_BUFFER_BYTES, output)), + kept: None, }); let finished = Arc::new(AtomicBool::new(false)); @@ -369,6 +377,56 @@ fn finish_store(store: Option, outcome: Outcome) -> std::result::Result<( Ok((output, database_id)) } +/// What an operation run in this process returned: its output and the items +/// it streamed, in order. +#[derive(Debug, Clone, PartialEq)] +pub struct LocalOutput { + pub output: Value, + pub items: Vec, +} + +/// Run one operation in this process on a store the caller holds open (D327). +/// +/// The handler is the one the worker runs, so the checks, refusals, and +/// messages are the same as for the npm client. The store is handed to the +/// operation and back: it stays open after the call, and `store` is `None` +/// afterwards only if it was `None` before and the operation needs no +/// database. An operation that asks the caller for a callback is refused. +pub fn run_in_process( + name: &str, + input: Value, + store: &mut Option, +) -> std::result::Result { + let operation = definition::find(name).ok_or_else(|| Failure::Input(format!("unknown operation {name:?}")))?; + if !operation.callbacks.is_empty() { + return Err(Failure::Input(format!("{name} calls back to its client and cannot run in this process"))); + } + let events = Events { + id: String::new(), + out: Mutex::new(BufWriter::new(Box::new(std::io::sink()))), + kept: Some(Mutex::new(Vec::new())), + }; + let mut call = Call { + input, + operation, + target: None, + store: store.take(), + events: &events, + callbacks: Callbacks { operation, events: &events, answers: None, next_callback: std::cell::Cell::new(0) }, + }; + let outcome = (operation.run)(&mut call); + *store = call.store.take(); + let output = outcome?; + let kept = + events.kept.map(|kept| kept.into_inner().unwrap_or_else(|poisoned| poisoned.into_inner())).unwrap_or_default(); + let items = kept + .into_iter() + .filter(|event| event.get("type").and_then(Value::as_str) == Some("item")) + .filter_map(|mut event| event.remove("item")) + .collect(); + Ok(LocalOutput { output, items }) +} + fn flush(events: &Events) { let mut out = events.out.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let _ = out.flush(); diff --git a/tests/protocol_in_process.rs b/tests/protocol_in_process.rs new file mode 100644 index 00000000..e8175361 --- /dev/null +++ b/tests/protocol_in_process.rs @@ -0,0 +1,51 @@ +//! Protocol operations run in this process on an open store (D327). The phone +//! binding calls these, so a phone edit gets the npm client's checks. + +use athleticstandard::json::{self, Value}; +use athleticstandard::protocol::{run_in_process, Failure}; +use athleticstandard::store::{CreateOptions, Store}; + +fn request(text: &str) -> Value { + json::parse(text).unwrap() +} + +#[test] +fn a_write_and_a_read_share_one_open_store() { + let folder = tempfile::tempdir().unwrap(); + let path = std::fs::canonicalize(folder.path()).unwrap().join("athlete.ath.sqlite"); + let mut store = Some(Store::create(&path, CreateOptions::default()).unwrap()); + let written = run_in_process( + "records.write", + request( + r#"{"inputs":[{"record_type":"source","data":{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"},"changed_by":{"author_type":"athlete"}}]}"#, + ), + &mut store, + ) + .unwrap(); + assert_eq!(written.output["database_revision"], Value::from(1)); + assert!(store.is_some(), "the store stays open after the call"); + let listed = run_in_process("records.list", request("{}"), &mut store).unwrap(); + assert_eq!(listed.output, Value::Null); + assert_eq!(listed.items.len(), 1); + assert_eq!(listed.items[0]["record_type"], Value::from("source")); + store.unwrap().close().unwrap(); +} + +#[test] +fn unknown_and_callback_operations_are_refused() { + let mut store = None; + assert!(matches!(run_in_process("records.nothing", Value::Null, &mut store), Err(Failure::Input(_)))); + let Err(Failure::Input(message)) = run_in_process("backtest.run", Value::Null, &mut store) else { + panic!("an operation that calls back ran in process"); + }; + assert_eq!(message, "backtest.run calls back to its client and cannot run in this process"); +} + +#[test] +fn an_operation_that_needs_a_store_says_so() { + let mut store = None; + let Err(Failure::Error(error)) = run_in_process("records.list", request("{}"), &mut store) else { + panic!("a database operation ran without a database"); + }; + assert_eq!(error.to_string(), "records.list needs a database target"); +} From 653561ac6f3d7f574c56a57a54c80ea19bc5167e Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 09:23:07 -0600 Subject: [PATCH 04/30] Open, edit, and save athlete files from the phone packages. The phone binding gains `Database`, behind the mobile crate's default `sqlite` feature. It creates and opens `.ath.sqlite` files through the desktop store, reads records, runs the npm client's record operations in process, previews and runs migrations after a verified backup, and writes verified single-file copies that include edits still in the companion log. A closed handle refuses every call (D327). `PickedDocument` in Swift and Kotlin works on a picked document through a private copy and saves it back only when the document still has the content it started from (D328). `FileLocationAdvice` holds the suggested wording that recommends local storage. Tests run the same storage steps in Rust, Swift, and Kotlin: create, edit, close, reopen, a stale correction, a read-only open, an outdated 2.1.0 file, and a copy taken while edits were in the log. `roundtrip.sh` has the desktop `ath` create a file and then check the file the phone library saved. The round trip passed on a Mac and on Android emulators with 4 KB and 16 KB pages. A dependency test checks that the storage build has SQLite and no command-line or network crate. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 + build-history/v3.0.0/progress.md | 27 +- mobile/Cargo.toml | 18 + mobile/README.md | 52 +++ .../ai/athleticstandard/DocumentTest.kt | 91 ++++ .../ai/athleticstandard/RoundTripTest.kt | 63 +++ .../kotlin/ai/athleticstandard/StoreTest.kt | 155 +++++++ .../ai/athleticstandard/PickedDocument.kt | 198 ++++++++ mobile/scripts/roundtrip.sh | 73 +++ mobile/scripts/test-android.sh | 20 +- mobile/scripts/test-apple.sh | 14 +- mobile/src/lib.rs | 9 + mobile/src/store.rs | 438 ++++++++++++++++++ .../AthleticStandard/PickedDocument.swift | 205 ++++++++ .../AthleticStandardTests/DocumentTests.swift | 79 ++++ .../AthleticStandardTests/FixtureBundle.swift | 17 +- .../RoundTripTests.swift | 55 +++ .../AthleticStandardTests/StoreTests.swift | 130 ++++++ mobile/tests/dependencies.rs | 14 + mobile/tests/fixtures.rs | 14 + mobile/tests/store.rs | 237 ++++++++++ mobile/uniffi.toml | 5 + 22 files changed, 1910 insertions(+), 7 deletions(-) create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/DocumentTest.kt create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt create mode 100644 mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/PickedDocument.kt create mode 100755 mobile/scripts/roundtrip.sh create mode 100644 mobile/src/store.rs create mode 100644 mobile/swift/Sources/AthleticStandard/PickedDocument.swift create mode 100644 mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift create mode 100644 mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift create mode 100644 mobile/swift/Tests/AthleticStandardTests/StoreTests.swift create mode 100644 mobile/tests/store.rs diff --git a/Cargo.lock b/Cargo.lock index 27aeae74..f7111811 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -238,7 +238,10 @@ dependencies = [ name = "athleticstandard-mobile" version = "3.0.0" dependencies = [ + "athleticstandard", "athleticstandard-core", + "sha2", + "tempfile", "uniffi", ] diff --git a/build-history/v3.0.0/progress.md b/build-history/v3.0.0/progress.md index acaed71a..92f88eb9 100644 --- a/build-history/v3.0.0/progress.md +++ b/build-history/v3.0.0/progress.md @@ -17,7 +17,7 @@ Status: **being built; not released.** The plan is [spec.md](spec.md). | 11 | Synthetic journey and release evidence | done: gate 6 passes; release notes name step 8 | | 12 | Phone library plan, decisions D325–D333 ([plan](appendix/mobile-library-plan.md)) | done | | 13 | UniFFI crate, validation from the Swift package and the Android library | Mac and Android emulator pass; iPhone simulator not run | -| 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | not started | +| 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | Mac and two Android emulators pass; iPhone simulator and iCloud not run | | 15 | Calculations from memory and SQLite through one reader interface | not started | | 16 | Host client for Swift and Kotlin with browser sign-in | not started | | 17 | Release packaging, phone test runs, release gate | not started | @@ -706,3 +706,28 @@ These follow the guide and the decisions. Each is open to review. `xcodebuild -create-xcframework`. The iPhone simulator run needs Xcode's license to be accepted on the build machine; it has not run yet. +## Step 14: real athlete files on phones + +- `Database` in the phone binding holds one open file through the desktop store. Its + edits run the npm client's record operations in process + (`protocol::run_in_process`), so the inputs, outputs, refusals, and messages are the + npm client's. Kotlin names its close `closeDatabase()`, because Kotlin's `close()` + frees the native object. +- The `athleticstandard` crate's default `cli` feature holds the command line, the + import readers, the network runtime, prediction and log planning, and package zips. + The phone build turns it off. +- Phones put app folders behind system links (`/var` on iOS, `/data/user/0` on + Android). The binding resolves the folder before it opens a file; a database file + that is itself a link is still refused. +- `PickedDocument` (Swift and Kotlin) copies a picked document into a working folder, + records its SHA-256, and saves back a verified single-file copy only if the document + still has that content. Tests cover a document changed by another device, a provider + that refuses the write, and resuming after a restart. +- An outdated 2.1.0 file is refused until it is migrated, after a verified backup, to + SQL step 8. +- The desktop round trip runs on each platform: the desktop `ath` creates the file, the + phone library corrects one reading, closes and resumes the file, and saves it, and the + desktop `ath` checks the saved file. Results are in step 17. +- Not run: the iPhone simulator (it needs Xcode's license accepted on this machine), + and the iCloud Drive picker on a signed-in device. + diff --git a/mobile/Cargo.toml b/mobile/Cargo.toml index 39d7abc7..8b6fa281 100644 --- a/mobile/Cargo.toml +++ b/mobile/Cargo.toml @@ -14,6 +14,24 @@ path = "src/lib.rs" # the bindings, `lib` for the Rust tests. crate-type = ["lib", "staticlib", "cdylib"] +[features] +# The SQLite store: create, open, edit, and save `.ath.sqlite` files. Without +# it the library checks records and calculates on records the app supplies, +# with no SQLite, file, or network code (D327). +default = ["sqlite"] +sqlite = ["dep:athleticstandard", "dep:sha2"] + [dependencies] athleticstandard-core = { path = "../core" } +# The desktop library without its `cli` feature: the store, files, packages, +# calculations, and views, and no command line or network runtime. +athleticstandard = { path = "..", default-features = false, optional = true } +sha2 = { version = "0.11.0", optional = true } uniffi = "=0.33.0" + +[dev-dependencies] +tempfile = "3.27.0" + +[[test]] +name = "store" +required-features = ["sqlite"] diff --git a/mobile/README.md b/mobile/README.md index eb24fd15..63889425 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -35,6 +35,52 @@ Kotlin. Each has a `code` that matches the desktop error code, a `detail` with t desktop message, and, for an invalid value, `issues`. An issue's `path` keeps field names and list positions apart. +## Real athlete files + +`Database` opens one `.ath.sqlite` file through the desktop store +([D327](../build-history/v3.0.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). +Edits run the same record operations the npm client runs, with the same inputs and +outputs as UTF-8 JSON, so they get the same checks and messages: + +| Call | What it does | +|---|---| +| `Database.create(path, options)` / `Database.open(path, options)` | Create a new file, or open one. Options: `readOnly`, `allowOutdatedSchema`, `expectedDatabaseId`. An outdated file is refused with `MigrationRequired`, which carries the desktop migration preview. | +| `info()` | The database ID, revision, versions, and whether it takes writes. | +| `getRecord`, `listRecords`, `recordRevisions` | Read current records and history as JSON. | +| `writeRecords`, `writeRecordChanges`, `correctRecord`, `deleteRecord` | Edit records. A correction carries the revision the person edited; a stale one is refused with `Stale` and changes nothing. | +| `runOperation(name, input)` | Any other listed record, query, view, or calculation operation of the npm client. | +| `migrationPreview()`, `migrate(backupPath)` | Preview a migration, then run it after a verified backup. | +| `saveCopy(destination)` | Write a verified single-file copy, including edits still in SQLite's companion log, with its SHA-256. | +| `close()` | Close the file. In Kotlin this is `closeDatabase()`, because Kotlin's `close()` frees the native object. | + +A handle runs one call at a time. Calls do file and SQLite work on the calling +thread, so call them away from the main thread. The binding resolves the system links +in front of app folders (`/var` on iOS, `/data/user/0` on Android) before it opens a +file. The desktop store refuses a path through a symbolic link. + +### Where to keep the file + +Recommend local storage, and keep iCloud Drive and other locations selectable +([D328](../build-history/v3.0.0/decisions.md#d328-where-a-phone-keeps-the-file)). +`FileLocationAdvice.recommendation` holds the suggested wording: "We recommend +keeping your working file on this device. Editing the same file on two devices +through iCloud Drive can cause sync conflicts." + +- A file in the app's own folder (`FileLocationAdvice.localFolder`) opens in place with + `Database.open`. An edit is saved when it commits. +- A document picked from another location opens with `PickedDocument.open`. It copies + the document into a working folder (with file coordination on iOS, through the + content URI on Android) and records its SHA-256. Edits commit to the working copy. + `save()` writes a verified copy and replaces the document only if it still has the + recorded content. Otherwise it throws `DocumentChangedElsewhere` (Swift) or + `DocumentChangedElsewhereException` (Kotlin), and `saveCopy(to:)` writes a new + document instead. A failed save keeps every local edit. +- `hasUnsavedEdits()` tells the two facts apart: the edit committed locally, and the + picked document received it. +- `state` and `PickedDocument.resume` reopen the working copy after the app restarts. + On Android, take a persistable permission for the document's URI. +- A single-file save does not carry attachment files. Use a package export for them. + ## Build You need the Rust toolchain from `rust-toolchain.toml` with these targets: @@ -70,5 +116,11 @@ mobile/scripts/test-apple.sh --mac-only # this Mac only mobile/scripts/test-android.sh # a running emulator or a connected phone ``` +Both scripts also run the desktop round trip. `mobile/scripts/roundtrip.sh create` has +the desktop `ath` create a file with one reading. The phone tests open it as a picked +document, correct the reading, close and resume it, and save it. Then +`roundtrip.sh verify` has the desktop `ath` check the saved file: the same database ID, +the reading at revision 2, revision 1 kept, and `ath check` passing. + `test-apple.sh` needs a full Xcode whose license has been accepted for the simulator run. On this Mac it uses `swift test`. diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/DocumentTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/DocumentTest.kt new file mode 100644 index 00000000..e7963f83 --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/DocumentTest.kt @@ -0,0 +1,91 @@ +package ai.athleticstandard + +import android.net.Uri +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** + * A picked document worked on through a private copy (D328). A file URI in a separate + * folder stands in for a document from another provider. + */ +@RunWith(AndroidJUnit4::class) +class DocumentTest { + private val context = InstrumentationRegistry.getInstrumentation().targetContext + + private fun pickedDocument(): File { + val provider = StoreTest.folder() + val document = File(provider, "Picked.ath.sqlite") + val database = StoreTest.create(File(provider, "seed.ath.sqlite")) + StoreTest.writeWorkout(database) + database.saveCopy(document.path) + database.closeDatabase() + return document + } + + @Test + fun editSaveAndReopen() { + val document = pickedDocument() + val picked = PickedDocument.open(context, Uri.fromFile(document), StoreTest.folder()) + StoreTest.correctWorkout(picked.database, 1, "2026-01-02T04:30:05.678Z") + assertTrue(picked.hasUnsavedEdits()) + val saved = picked.save() + assertFalse(picked.hasUnsavedEdits()) + assertEquals(fileSha256(document.path), saved.sha256) + picked.close() + + PickedDocument.open(context, Uri.fromFile(document), StoreTest.folder()).use { again -> + assertEquals("2026-01-02T04:30:05.678Z", StoreTest.endAt(again.database)) + } + } + + @Test + fun aDocumentChangedElsewhereIsNotReplaced() { + val document = pickedDocument() + val picked = PickedDocument.open(context, Uri.fromFile(document), StoreTest.folder()) + StoreTest.correctWorkout(picked.database, 1, "2026-01-02T04:30:05.678Z") + // Another device saves its own edit to the same document. + PickedDocument.open(context, Uri.fromFile(document), StoreTest.folder()).use { other -> + StoreTest.correctWorkout(other.database, 1, "2026-01-02T04:50:05.678Z") + other.save() + } + try { + picked.save() + fail("a document changed elsewhere was replaced") + } catch (expected: DocumentChangedElsewhereException) { + } + val check = Database.open(document.path, OpenDatabaseOptions(readOnly = true)) + assertEquals("2026-01-02T04:50:05.678Z", StoreTest.endAt(check)) + check.closeDatabase() + assertEquals("2026-01-02T04:30:05.678Z", StoreTest.endAt(picked.database)) + val copy = File(StoreTest.folder(), "Copy.ath.sqlite").apply { createNewFile() } + assertEquals(2uL, picked.saveCopy(Uri.fromFile(copy)).databaseRevision) + picked.close() + } + + @Test + fun aFailedSaveKeepsTheLocalEdit() { + val document = pickedDocument() + val picked = PickedDocument.open(context, Uri.fromFile(document), StoreTest.folder()) + StoreTest.correctWorkout(picked.database, 1, "2026-01-02T04:30:05.678Z") + // The provider stops accepting writes, as an offline provider does. + assertTrue(document.setWritable(false)) + try { + picked.save() + fail("a read-only document was written") + } catch (expected: java.io.IOException) { + } + assertTrue(picked.hasUnsavedEdits()) + assertEquals("2026-01-02T04:30:05.678Z", StoreTest.endAt(picked.database)) + assertTrue(document.setWritable(true)) + picked.save() + assertFalse(picked.hasUnsavedEdits()) + picked.close() + } +} diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt new file mode 100644 index 00000000..97f7b9e4 --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt @@ -0,0 +1,63 @@ +package ai.athleticstandard + +import android.net.Uri +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** + * The phone half of the desktop round trip (D328). `mobile/scripts/roundtrip.sh create` + * made the desktop file with the desktop `ath`. This test edits it as a picked + * document, closes it, resumes it, and saves it as `phone-edited.ath.sqlite` in the + * test's additional output folder, which the Gradle run copies back to the computer. + * `roundtrip.sh verify` then checks it with the desktop `ath`. + */ +@RunWith(AndroidJUnit4::class) +class RoundTripTest { + @Test + fun desktopFileEditedOnThePhone() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val context = instrumentation.targetContext + val facts = instrumentation.context.assets.open("roundtrip/desktop.json").use { + JSONObject(it.readBytes().decodeToString()) + } + val recordId = facts.getString("record_id") + val output = InstrumentationRegistry.getArguments().getString("additionalTestOutputDir") + ?.let(::File) ?: File(context.getExternalFilesDir(null), "roundtrip") + output.mkdirs() + val document = File(output, "phone-edited.ath.sqlite") + document.delete() + StoreTest.fixture("roundtrip/desktop.ath.sqlite", StoreTest.folder()).copyTo(document) + + val picked = PickedDocument.open(context, Uri.fromFile(document), StoreTest.folder()) + assertEquals(facts.getString("database_id"), picked.database.info().databaseId) + val record = JSONObject(picked.database.getRecord(recordId)!!.decodeToString()) + assertEquals(1, record.getInt("current_revision")) + val data = record.getJSONObject("data") + data.getJSONObject("value").put("standard_value", 63).put("input_value", 63) + val request = JSONObject() + .put("record_id", recordId) + .put("expected_revision", 1) + .put("data", data) + .put("changed_by", JSONObject().put("author_type", "athlete")) + picked.database.correctRecord(request.toString().toByteArray()) + + // Close the working copy and resume it, as after the app restarts. + val state = picked.state + picked.close(removingWorkingCopy = false) + PickedDocument.resume(context, state).use { resumed -> + assertEquals( + 2, + JSONObject(resumed.database.getRecord(recordId)!!.decodeToString()).getInt("current_revision"), + ) + assertTrue(resumed.hasUnsavedEdits()) + val saved = resumed.save() + assertEquals(fileSha256(document.path), saved.sha256) + } + } +} diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt new file mode 100644 index 00000000..0ddcc803 --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt @@ -0,0 +1,155 @@ +package ai.athleticstandard + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.util.UUID + +/** The storage steps mobile/tests/store.rs runs, through the Android library (D327). */ +@RunWith(AndroidJUnit4::class) +class StoreTest { + companion object { + const val SOURCE_ID = "01890f3e-e7d3-7cc0-88c8-000000000003" + const val WORKOUT_ID = "01890f3e-e7d3-7cc0-88c8-000000000064" + + fun folder(): File { + val context = InstrumentationRegistry.getInstrumentation().targetContext + return File(context.cacheDir, "athleticstandard-${UUID.randomUUID()}").apply { mkdirs() } + } + + fun workoutData(endAt: String) = + """{"source_id":"$SOURCE_ID","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","start_at":"2026-01-02T03:04:05.678Z","end_at":"$endAt","input_start_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"input_end_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"source_reported_summaries":[]}""" + + fun create(file: File): Database = Database.create( + file.path, + CreateDatabaseOptions("01890f3e-e7d3-7cc0-88c8-0000000000aa", "2026-01-02T03:04:05.678Z"), + ) + + fun writeWorkout(database: Database) { + val request = """{"inputs":[{"record_id":"$SOURCE_ID","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","data":{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"},"changed_by":{"author_type":"athlete"}},{"record_id":"$WORKOUT_ID","record_type":"workout_session","created_at":"2026-01-02T03:04:05.678Z","data":${workoutData("2026-01-02T04:04:05.678Z")},"changed_by":{"author_type":"athlete"}}]}""" + database.writeRecords(request.toByteArray()) + } + + fun correctWorkout(database: Database, expectedRevision: Int, endAt: String): ByteArray { + val request = """{"record_id":"$WORKOUT_ID","expected_revision":$expectedRevision,"data":${workoutData(endAt)},"changed_by":{"author_type":"athlete"},"became_known_at":"2026-01-03T00:00:00.000Z"}""" + return database.correctRecord(request.toByteArray()) + } + + fun endAt(database: Database): String = + JSONObject(database.getRecord(WORKOUT_ID)!!.decodeToString()).getJSONObject("data").getString("end_at") + + /** Copy a file from the fixture bundle into the app's storage. */ + fun fixture(name: String, into: File): File { + val assets = InstrumentationRegistry.getInstrumentation().context.assets + val target = File(into, name.substringAfterLast('/')) + assets.open(name).use { input -> target.outputStream().use { input.copyTo(it) } } + return target + } + } + + @Test + fun createEditCloseAndReopen() { + val file = File(folder(), "athlete.ath.sqlite") + val database = create(file) + assertEquals(0uL, database.info().databaseRevision) + assertTrue(database.info().writable) + writeWorkout(database) + correctWorkout(database, 1, "2026-01-02T04:30:05.678Z") + assertEquals(2uL, database.info().databaseRevision) + database.closeDatabase() + assertTrue(database.isClosed()) + try { + database.info() + fail("a closed database answered") + } catch (error: AthleticStandardException) { + assertEquals("closed", error.code) + } + + val reopened = Database.open(file.path, OpenDatabaseOptions()) + val record = JSONObject(reopened.getRecord(WORKOUT_ID)!!.decodeToString()) + assertEquals(2, record.getInt("current_revision")) + assertEquals("2026-01-02T04:30:05.678Z", endAt(reopened)) + assertEquals(2, JSONArray(reopened.recordRevisions(WORKOUT_ID).decodeToString()).length()) + assertNull(reopened.getRecord("01890f3e-e7d3-7cc0-88c8-0000000000ff")) + reopened.closeDatabase() + } + + @Test + fun staleCorrectionIsRefused() { + val database = create(File(folder(), "athlete.ath.sqlite")) + writeWorkout(database) + correctWorkout(database, 1, "2026-01-02T04:30:05.678Z") + try { + correctWorkout(database, 1, "2026-01-02T04:45:05.678Z") + fail("a stale correction was accepted") + } catch (error: AthleticStandardException) { + assertEquals("stale", error.code) + assertEquals("Record $WORKOUT_ID is at revision 2, not expected revision 1", error.detail) + } + assertEquals(2uL, database.info().databaseRevision) + database.closeDatabase() + } + + @Test + fun readOnlyOpenRefusesWrites() { + val file = File(folder(), "athlete.ath.sqlite") + create(file).apply { writeWorkout(this); closeDatabase() } + val readOnly = Database.open(file.path, OpenDatabaseOptions(readOnly = true)) + assertFalse(readOnly.info().writable) + try { + correctWorkout(readOnly, 1, "2026-01-02T04:30:05.678Z") + fail("a read-only database accepted a write") + } catch (error: AthleticStandardException) { + assertEquals("refused", error.code) + } + readOnly.closeDatabase() + } + + @Test + fun outdatedFileNeedsMigrationWithBackup() { + val folder = folder() + val file = fixture("outdated-2-1-0.ath.sqlite", folder) + try { + Database.open(file.path, OpenDatabaseOptions()) + fail("an outdated database opened without a migration") + } catch (error: AthleticStandardException) { + assertEquals("migration_required", error.code) + } + val outdated = Database.open(file.path, OpenDatabaseOptions(allowOutdatedSchema = true)) + val backup = File(folder, "before-migration.ath.sqlite") + val result = JSONObject(outdated.migrate(backup.path).decodeToString()) + assertTrue(result.getBoolean("migrated")) + outdated.closeDatabase() + assertTrue(backup.exists()) + val migrated = Database.open(file.path, OpenDatabaseOptions()) + assertEquals(8u, migrated.info().sqlSchemaVersion) + migrated.closeDatabase() + } + + @Test + fun savedCopyHoldsEditsStillInTheLog() { + val folder = folder() + val file = File(folder, "athlete.ath.sqlite") + val database = create(file) + writeWorkout(database) + correctWorkout(database, 1, "2026-01-02T04:30:05.678Z") + assertTrue(File(file.path + "-wal").exists()) + val saved = database.saveCopy(File(folder, "saved.ath.sqlite").path) + assertEquals(2uL, saved.databaseRevision) + assertEquals(fileSha256(saved.path), saved.sha256) + assertFalse(File(saved.path + "-wal").exists()) + val copy = Database.open(saved.path, OpenDatabaseOptions(readOnly = true)) + assertEquals(2, JSONObject(copy.getRecord(WORKOUT_ID)!!.decodeToString()).getInt("current_revision")) + copy.closeDatabase() + database.closeDatabase() + } +} diff --git a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/PickedDocument.kt b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/PickedDocument.kt new file mode 100644 index 00000000..32dd070c --- /dev/null +++ b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/PickedDocument.kt @@ -0,0 +1,198 @@ +package ai.athleticstandard + +import android.content.ContentResolver +import android.content.Context +import android.net.Uri +import java.io.File +import java.io.FileOutputStream +import java.io.InputStream +import java.security.MessageDigest +import java.util.UUID + +/** Where to keep a working file (D328). */ +object FileLocationAdvice { + /** The wording the guide suggests showing next to the file picker. */ + const val RECOMMENDATION = + "We recommend keeping your working file on this device. Editing the same file on two devices through iCloud Drive can cause sync conflicts." + + /** A folder in the app's own storage for working files. Files here open in place. */ + fun localFolder(context: Context): File = + File(context.filesDir, "athleticstandard").apply { mkdirs() } +} + +/** + * The picked document changed after it was copied, so saving would replace someone + * else's edits. The local edits are still in the working copy. Save a copy instead, or + * open the document again. + */ +class DocumentChangedElsewhereException(val documentUri: Uri) : + Exception("The document changed since it was opened. Your edits are kept on this device; save a copy instead.") + +/** + * A `.ath.sqlite` document the person picked through the system file picker, worked on + * through a private copy (D328). + * + * Opening copies the document's bytes, through its content URI, into a working folder + * and records their SHA-256. Edits commit to the working copy through [database]. + * [save] writes a verified single-file copy of the database and replaces the document + * only if the document still has the recorded content. A failed save keeps every local + * edit; call [save] again when the provider is reachable, or [saveCopy]. + * + * Take a persistable permission for the URI (`takePersistableUriPermission`) to keep + * access after a restart. Files in the app's own folders do not need this class: open + * them in place with `Database.open`. + */ +class PickedDocument private constructor( + private val resolver: ContentResolver, + val documentUri: Uri, + val workingFile: File, + val database: Database, + documentDigest: String, + savedRevision: ULong, +) : AutoCloseable { + /** The SHA-256 of the document's content when it was copied or last saved. */ + var documentDigest: String = documentDigest + private set + + /** The database revision the document last received. */ + var savedRevision: ULong = savedRevision + private set + + /** + * What an app keeps to resume after it restarts. Store it with the app's settings, + * never inside an athlete file. + */ + data class State( + val documentUri: String, + val workingPath: String, + val documentDigest: String, + val savedRevision: ULong, + ) + + val state: State + get() = State(documentUri.toString(), workingFile.path, documentDigest, savedRevision) + + /** True when the working copy has commits the document has not received. */ + fun hasUnsavedEdits(): Boolean = database.info().databaseRevision != savedRevision + + /** + * Save the working copy back to the picked document. + * + * Throws [DocumentChangedElsewhereException] when the document's content is no + * longer the content this copy started from. Any other exception means the provider + * could not be written. In both cases the local edits stay in the working copy. + */ + @Synchronized + fun save(): SavedCopy { + val snapshot = File(workingFile.parentFile, "${UUID.randomUUID()}.save.ath.sqlite") + try { + val saved = database.saveCopy(snapshot.canonicalPath) + val current = resolver.openInputStream(documentUri)?.use(::digest) + ?: throw java.io.FileNotFoundException("cannot read $documentUri") + if (current != documentDigest) throw DocumentChangedElsewhereException(documentUri) + write(documentUri, snapshot) + documentDigest = saved.sha256 + savedRevision = saved.databaseRevision + return saved + } finally { + snapshot.delete() + } + } + + /** + * Write a verified copy to a new document, such as one the person named with + * `ACTION_CREATE_DOCUMENT`. The picked document is not changed. + */ + fun saveCopy(target: Uri): SavedCopy { + val snapshot = File(workingFile.parentFile, "${UUID.randomUUID()}.copy.ath.sqlite") + try { + val saved = database.saveCopy(snapshot.canonicalPath) + write(target, snapshot) + return saved + } finally { + snapshot.delete() + } + } + + /** Close the database and remove the working copy. Unsaved edits are lost, so save first. */ + fun close(removingWorkingCopy: Boolean) { + database.close() + if (removingWorkingCopy) { + for (suffix in listOf("", "-wal", "-shm")) File(workingFile.path + suffix).delete() + } + } + + override fun close() = close(removingWorkingCopy = true) + + private fun write(uri: Uri, snapshot: File) { + // "wt" truncates the document before writing, so a shorter database leaves no tail. + val descriptor = resolver.openFileDescriptor(uri, "wt") + ?: throw java.io.FileNotFoundException("cannot write $uri") + descriptor.use { + FileOutputStream(it.fileDescriptor).use { output -> + snapshot.inputStream().use { input -> input.copyTo(output) } + output.flush() + output.fd.sync() + } + } + } + + companion object { + /** Copy the picked document into [workingFolder] and open the copy. */ + @JvmStatic + @JvmOverloads + fun open( + context: Context, + documentUri: Uri, + workingFolder: File = File(FileLocationAdvice.localFolder(context), "working"), + readOnly: Boolean = false, + ): PickedDocument { + val resolver = context.contentResolver + workingFolder.mkdirs() + val workingFile = File(workingFolder.canonicalFile, "${UUID.randomUUID()}.ath.sqlite") + val digest = MessageDigest.getInstance("SHA-256") + val input = resolver.openInputStream(documentUri) + ?: throw java.io.FileNotFoundException("cannot read $documentUri") + input.use { source -> + FileOutputStream(workingFile).use { output -> + val buffer = ByteArray(64 * 1024) + while (true) { + val read = source.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + output.write(buffer, 0, read) + } + output.fd.sync() + } + } + val database = Database.open(workingFile.path, OpenDatabaseOptions(readOnly, false, null)) + return PickedDocument( + resolver, documentUri, workingFile, database, hex(digest.digest()), database.info().databaseRevision, + ) + } + + /** Open the working copy again from a saved [State], with its unsaved edits. */ + @JvmStatic + @JvmOverloads + fun resume(context: Context, state: State, readOnly: Boolean = false): PickedDocument { + val database = Database.open(state.workingPath, OpenDatabaseOptions(readOnly, false, null)) + return PickedDocument( + context.contentResolver, Uri.parse(state.documentUri), File(state.workingPath), database, + state.documentDigest, state.savedRevision, + ) + } + + internal fun digest(input: InputStream): String { + val digest = MessageDigest.getInstance("SHA-256") + val buffer = ByteArray(64 * 1024) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + } + return hex(digest.digest()) + } + + private fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) } + } +} diff --git a/mobile/scripts/roundtrip.sh b/mobile/scripts/roundtrip.sh new file mode 100755 index 00000000..c6774058 --- /dev/null +++ b/mobile/scripts/roundtrip.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# The desktop half of the phone round trip (D328). +# +# mobile/scripts/roundtrip.sh create +# The desktop `ath` creates /desktop.ath.sqlite with one manual RMSSD +# reading of 61 ms, and writes /desktop.json naming its database ID and +# the reading's record ID. The phone tests read both. +# +# mobile/scripts/roundtrip.sh verify +# The desktop `ath` checks the file the phone saved: the same database ID, the +# reading at revision 2 with 63 ms, its first revision kept, and every rule of +# the format. +# +# ATH names the executable (default: target/debug/ath). The data is synthetic. + +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +ATH="${ATH:-$ROOT/target/debug/ath}" +COMMAND="${1:-}" +FOLDER="${2:-}" +if [ -z "$FOLDER" ]; then + echo "usage: $0 create | verify " >&2 + exit 2 +fi +mkdir -p "$FOLDER" +FOLDER="$(cd "$FOLDER" && pwd -P)" +DATABASE="$FOLDER/desktop.ath.sqlite" + +json_field() { + python3 -I -c 'import json, sys +value = json.load(sys.stdin) +for key in sys.argv[1:]: + value = value[int(key)] if isinstance(value, list) else value[key] +print(value if not isinstance(value, bool) else str(value).lower())' "$@" +} + +case "$COMMAND" in + create) + chmod 700 "$FOLDER" + rm -f "$DATABASE" "$DATABASE-wal" "$DATABASE-shm" "$FOLDER/desktop.json" + "$ATH" init --yes --name "Synthetic athlete" --timezone UTC --no-skill --file "$DATABASE" > /dev/null + "$ATH" log RMSSD 61 ms --at 2026-11-01T07:00:00.000Z --file "$DATABASE" --yes > /dev/null + database_id="$("$ATH" stats --file "$DATABASE" --json | json_field database_id)" + record_id="$("$ATH" records list --file "$DATABASE" --type point_measurement --json | json_field records 0 record_id)" + printf '{"database_id":"%s","record_id":"%s"}\n' "$database_id" "$record_id" > "$FOLDER/desktop.json" + echo "desktop created $DATABASE with reading $record_id" + ;; + verify) + PHONE_FILE="${3:?the phone file}" + database_id="$(json_field database_id < "$FOLDER/desktop.json")" + record_id="$(json_field record_id < "$FOLDER/desktop.json")" + check="$("$ATH" check "$PHONE_FILE" --json)" + [ "$(echo "$check" | json_field valid)" = true ] || { echo "ath check failed: $check" >&2; exit 1; } + [ "$(echo "$check" | json_field metadata database_id)" = "$database_id" ] || { + echo "the phone file has another database ID" >&2 + exit 1 + } + shown="$("$ATH" records show "$record_id" --file "$PHONE_FILE" --history --json)" + revision="$(echo "$shown" | json_field record current_revision)" + value="$(echo "$shown" | json_field record data value standard_value)" + first="$("$ATH" records show "$record_id" --file "$PHONE_FILE" --revision 1 --json | + json_field shown_revision data value standard_value)" + [ "$revision" = 2 ] || { echo "expected revision 2, found $revision" >&2; exit 1; } + [ "$value" = 63 ] || { echo "expected 63 ms, found $value" >&2; exit 1; } + [ "$first" = 61 ] || { echo "expected revision 1 to keep 61 ms, found $first" >&2; exit 1; } + echo "desktop verified $PHONE_FILE: database $database_id, reading $record_id at revision 2 with 63 ms, revision 1 kept with 61 ms, ath check passed" + ;; + *) + echo "usage: $0 create | verify " >&2 + exit 2 + ;; +esac diff --git a/mobile/scripts/test-android.sh b/mobile/scripts/test-android.sh index e1d25379..25627e65 100755 --- a/mobile/scripts/test-android.sh +++ b/mobile/scripts/test-android.sh @@ -20,9 +20,25 @@ fi rm -rf "$FIXTURES" ATH_MOBILE_FIXTURES="$FIXTURES" cargo test --locked -p athleticstandard-mobile --test fixtures \ --manifest-path "$ROOT/Cargo.toml" +# The desktop half of the round trip: the desktop `ath` creates the file. +cargo build --locked --bin ath --manifest-path "$ROOT/Cargo.toml" +"$ROOT/mobile/scripts/roundtrip.sh" create "$FIXTURES/roundtrip" cd "$ROOT/mobile/android" +rm -rf athleticstandard/build/outputs/connected_android_test_additional_output ./gradlew --no-daemon :athleticstandard:connectedDebugAndroidTest \ -Pathleticstandard.rustProfile="$PROFILE" -Pathleticstandard.fixtures="$FIXTURES" -report="$(ls athleticstandard/build/outputs/androidTest-results/connected/debug/TEST-*.xml | head -n 1)" -grep -o ']*>' "$report" +for report in athleticstandard/build/outputs/androidTest-results/connected/debug/TEST-*.xml; do + grep -o ']*>' "$report" +done +# The desktop `ath` checks the file each device saved. The Gradle run copies the +# tests' additional output folder back from the device. +found=0 +while IFS= read -r -d '' phone_file; do + "$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$phone_file" + found=$((found + 1)) +done < <(find athleticstandard/build/outputs/connected_android_test_additional_output -name phone-edited.ath.sqlite -print0) +if [ "$found" -eq 0 ]; then + echo "no device saved phone-edited.ath.sqlite" >&2 + exit 1 +fi diff --git a/mobile/scripts/test-apple.sh b/mobile/scripts/test-apple.sh index 434b1987..223b33eb 100755 --- a/mobile/scripts/test-apple.sh +++ b/mobile/scripts/test-apple.sh @@ -27,9 +27,17 @@ fi rm -rf "$FIXTURES" ATH_MOBILE_FIXTURES="$FIXTURES" cargo test --locked -p athleticstandard-mobile --test fixtures \ --manifest-path "$ROOT/Cargo.toml" +# The desktop half of the round trip: the desktop `ath` creates the file. +cargo build --locked --bin ath --manifest-path "$ROOT/Cargo.toml" +"$ROOT/mobile/scripts/roundtrip.sh" create "$FIXTURES/roundtrip" +ROUNDTRIP_OUT="$ROOT/target/mobile-roundtrip" +rm -rf "$ROUNDTRIP_OUT" +mkdir -p "$ROUNDTRIP_OUT" cd "$ROOT/mobile/swift" -ATH_MOBILE_FIXTURES="$FIXTURES" swift test +ATH_MOBILE_FIXTURES="$FIXTURES" ATH_MOBILE_ROUNDTRIP_OUT="$ROUNDTRIP_OUT/mac" swift test +# The desktop `ath` checks the file the phone library saved. +"$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$ROUNDTRIP_OUT/mac/phone-edited.ath.sqlite" if [ "$MAC_ONLY" = 1 ]; then echo "iPhone simulator tests not run (--mac-only)" @@ -47,6 +55,8 @@ if [ -z "$SIMULATOR" ]; then exit 1 fi # xcodebuild passes TEST_RUNNER_ variables to the test process without the prefix. -TEST_RUNNER_ATH_MOBILE_FIXTURES="$FIXTURES" xcodebuild test -scheme AthleticStandard \ +TEST_RUNNER_ATH_MOBILE_FIXTURES="$FIXTURES" TEST_RUNNER_ATH_MOBILE_ROUNDTRIP_OUT="$ROUNDTRIP_OUT/simulator" \ + xcodebuild test -scheme AthleticStandard \ -destination "platform=iOS Simulator,id=$SIMULATOR" -derivedDataPath "$ROOT/mobile/swift/.build/xcode" \ | tail -n 40 +"$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$ROUNDTRIP_OUT/simulator/phone-edited.ath.sqlite" diff --git a/mobile/src/lib.rs b/mobile/src/lib.rs index 2de8332b..c1b306cd 100644 --- a/mobile/src/lib.rs +++ b/mobile/src/lib.rs @@ -6,13 +6,22 @@ //! //! Without the `sqlite` feature the crate depends only on the storage-free //! core: it checks records and runs calculations on records the app supplies. +//! With it, `Database` opens and edits `.ath.sqlite` files through the +//! desktop store (D327). uniffi::setup_scaffolding!(); mod error; +#[cfg(feature = "sqlite")] +mod store; mod validate; pub use error::{AthleticStandardError, PathSegment, ValidationIssue}; +#[cfg(feature = "sqlite")] +pub use store::{ + file_sha256, CreateDatabaseOptions, Database, DatabaseInfo, ListRecordsOptions, OpenDatabaseOptions, + OperationOutput, SavedCopy, +}; pub use validate::{validate, validate_current_record}; /// The Athletic Standard version this library writes and reports, such as diff --git a/mobile/src/store.rs b/mobile/src/store.rs new file mode 100644 index 00000000..b3bbdde8 --- /dev/null +++ b/mobile/src/store.rs @@ -0,0 +1,438 @@ +//! The SQLite store on a phone (D327). +//! +//! A `Database` holds one open `.ath.sqlite` file through the desktop store. +//! Edits run the protocol's record operations in this process, so a phone edit +//! gets the same checks, stale-revision refusals, and messages as the npm +//! client. One call runs at a time. `close` ends the handle; every later call +//! is refused with `Closed`. +//! +//! Calls do file and SQLite work on the calling thread. Call them away from an +//! app's main thread. +//! +//! Phones reach an app's folders through system links: `/var` on iOS and +//! `/data/user/0` on Android. The desktop store refuses any path through a +//! symbolic link, so the binding resolves the folder's real path first. A +//! database file that is itself a link is still refused. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard}; + +use athleticstandard::json::{self, Value}; +use athleticstandard::protocol::{run_in_process, Failure, LocalOutput}; +use athleticstandard::store::{CreateOptions, OpenOptions, Store}; +use athleticstandard::Error; +use sha2::{Digest, Sha256}; + +use crate::error::AthleticStandardError; +use crate::validate::parse_json; + +impl From for AthleticStandardError { + fn from(error: Error) -> Self { + let detail = error.to_string(); + match error { + Error::Invalid(validation) => validation.into(), + Error::NotFound(_) => AthleticStandardError::NotFound { detail }, + Error::Stale(_) => AthleticStandardError::Stale { detail }, + Error::Refused(_) => AthleticStandardError::Refused { detail }, + Error::MigrationRequired(preview) => AthleticStandardError::MigrationRequired { + detail, + preview: json::to_string(&json::to_value(preview.as_ref())).into_bytes(), + }, + Error::Database(_) => AthleticStandardError::Database { detail }, + Error::Io(_) => AthleticStandardError::Io { detail }, + Error::Other(_) => AthleticStandardError::Failed { detail }, + } + } +} + +impl From for AthleticStandardError { + fn from(failure: Failure) -> Self { + match failure { + Failure::Error(error) => error.into(), + Failure::Input(detail) => AthleticStandardError::Failed { detail }, + Failure::PackageRepresentation(details) => { + AthleticStandardError::Refused { detail: json::to_string(&details) } + } + } + } +} + +/// How to open a database. +#[derive(Debug, Clone, uniffi::Record)] +pub struct OpenDatabaseOptions { + /// Open read-only. A read-only open never changes the file. + #[uniffi(default = false)] + pub read_only: bool, + /// Open a database that still needs a migration, to preview or run it. + #[uniffi(default = false)] + pub allow_outdated_schema: bool, + /// Refuse a different database at the same path, for example after the + /// person replaced the file. + #[uniffi(default = None)] + pub expected_database_id: Option, +} + +/// Options for a new database. Both are chosen by the library when absent. +#[derive(Debug, Clone, uniffi::Record)] +pub struct CreateDatabaseOptions { + #[uniffi(default = None)] + pub database_id: Option, + #[uniffi(default = None)] + pub created_at: Option, +} + +/// What an open handle holds. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct DatabaseInfo { + pub path: String, + pub database_id: String, + /// Advances once with every committed change. + pub database_revision: u64, + pub athleticstandard_version: String, + pub sql_schema_version: u32, + pub created_at: String, + /// False for a read-only open. Writes are refused. + pub writable: bool, + /// Notes the store made when it opened the file. + pub warnings: Vec, +} + +/// Which current records to list. +#[derive(Debug, Clone, uniffi::Record)] +pub struct ListRecordsOptions { + /// A record type, such as `workout_session`. All types when absent. + #[uniffi(default = None)] + pub record_type: Option, + #[uniffi(default = false)] + pub include_deleted: bool, + /// From 1 to 10,000. The desktop default, 100, when absent. + #[uniffi(default = None)] + pub limit: Option, +} + +/// A verified single-file copy of the database (D328). +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct SavedCopy { + pub path: String, + pub database_id: String, + /// The revision the copy holds. + pub database_revision: u64, + pub record_count: u64, + /// The SHA-256 of the copy's bytes, as lowercase hexadecimal. + pub sha256: String, + pub byte_count: u64, +} + +/// The output of one operation, and the items it streamed. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct OperationOutput { + /// UTF-8 JSON. + pub output: Vec, + /// Each streamed item as UTF-8 JSON, in order. + pub items: Vec>, +} + +/// The path with its folder resolved to the real folder. The file name is +/// kept, so a link at the file itself is still refused by the store. +fn resolve(path: &str) -> Result { + let path = Path::new(path); + let name = path + .file_name() + .ok_or_else(|| AthleticStandardError::Refused { detail: format!("{} does not name a file", path.display()) })?; + let folder = match path.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent, + _ => Path::new("."), + }; + let folder = std::fs::canonicalize(folder).map_err(Error::from)?; + Ok(folder.join(name)) +} + +/// Protocol operations a phone may run on an open database with +/// `run_operation`. They read or edit records, views, and calculations of +/// this one file. Operations that read export folders, prompt a model, or +/// call back to a client are not listed. +const PHONE_OPERATIONS: &[&str] = &[ + "database.metadata", + "database.check", + "database.stats", + "records.write", + "records.write_changes", + "records.correct", + "records.delete", + "records.read", + "records.list", + "records.revisions", + "records.links", + "query.measurements", + "query.series", + "query.sessions", + "query.as_of", + "view.series", + "view.calendar_range", + "view.as_of_time", + "calculate.range", +]; + +/// Operations that change the file. +const WRITE_OPERATIONS: &[&str] = &["records.write", "records.write_changes", "records.correct", "records.delete"]; + +/// One open `.ath.sqlite` file. +#[derive(uniffi::Object)] +pub struct Database { + store: Mutex>, +} + +impl Database { + fn wrap(store: Store) -> Arc { + Arc::new(Database { store: Mutex::new(Some(store)) }) + } + + fn lock(&self) -> MutexGuard<'_, Option> { + self.store.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn with_store( + &self, + body: impl FnOnce(&mut Option) -> Result, + ) -> Result { + let mut guard = self.lock(); + if guard.is_none() { + return Err(AthleticStandardError::Closed { detail: "this database was closed".into() }); + } + body(&mut guard) + } + + fn operation(&self, name: &str, input: Value) -> Result { + self.with_store(|store| { + if WRITE_OPERATIONS.contains(&name) && store.as_ref().is_some_and(Store::is_read_only) { + return Err(AthleticStandardError::Refused { + detail: "this database was opened read-only; open it again for writing to change it".into(), + }); + } + let output = run_in_process(name, input, store)?; + if store.is_none() { + return Err(AthleticStandardError::Closed { detail: "the operation closed the database".into() }); + } + Ok(output) + }) + } + + fn json_operation(&self, name: &str, request: &[u8]) -> Result, AthleticStandardError> { + let input = parse_json(request)?; + Ok(json::to_string(&self.operation(name, input)?.output).into_bytes()) + } + + fn items_operation(&self, name: &str, input: Value) -> Result, AthleticStandardError> { + let output = self.operation(name, input)?; + Ok(json::to_string(&Value::Array(output.items)).into_bytes()) + } +} + +#[uniffi::export] +impl Database { + /// Create a new, empty database at `path`. The file must not exist. + #[uniffi::constructor] + pub fn create(path: String, options: CreateDatabaseOptions) -> Result, AthleticStandardError> { + let store = Store::create( + resolve(&path)?, + CreateOptions { database_id: options.database_id, created_at: options.created_at }, + )?; + Ok(Database::wrap(store)) + } + + /// Open the database at `path`. A database that needs a migration is + /// refused with `MigrationRequired` unless `allow_outdated_schema` is set. + #[uniffi::constructor] + pub fn open(path: String, options: OpenDatabaseOptions) -> Result, AthleticStandardError> { + let store = Store::open( + resolve(&path)?, + OpenOptions { read_only: options.read_only, allow_outdated_schema: options.allow_outdated_schema }, + )?; + if let Some(expected) = &options.expected_database_id { + if &store.metadata().database_id != expected { + let found = store.metadata().database_id.clone(); + store.close()?; + return Err(AthleticStandardError::Refused { + detail: format!( + "The database at {path} is not the one expected: database ID {found} differs from {expected}" + ), + }); + } + } + if !options.read_only && !options.allow_outdated_schema { + store.enable_wal()?; + } + Ok(Database::wrap(store)) + } + + /// The database's identity, revision, and whether it takes writes. + pub fn info(&self) -> Result { + self.with_store(|store| { + let store = store.as_mut().expect("checked open"); + if !store.is_read_only() { + store.reload_metadata()?; + } + let metadata = store.metadata().clone(); + Ok(DatabaseInfo { + path: store.path().display().to_string(), + database_id: metadata.database_id, + database_revision: store.database_revision()?, + athleticstandard_version: metadata.athleticstandard_version, + sql_schema_version: metadata.sql_schema_version, + created_at: metadata.created_at, + writable: !store.is_read_only(), + warnings: store.warnings.clone(), + }) + }) + } + + /// The current record with this ID as UTF-8 JSON, or `None`. + pub fn get_record(&self, record_id: String) -> Result>, AthleticStandardError> { + let mut input = json::Map::new(); + input.insert("record_id".into(), Value::String(record_id)); + let output = self.operation("records.read", Value::Object(input))?.output; + Ok((!output.is_null()).then(|| json::to_string(&output).into_bytes())) + } + + /// Current records in creation order, as a UTF-8 JSON array. + pub fn list_records(&self, options: ListRecordsOptions) -> Result, AthleticStandardError> { + let mut input = json::Map::new(); + if let Some(record_type) = options.record_type { + input.insert("record_type".into(), Value::String(record_type)); + } + input.insert("include_deleted".into(), Value::Bool(options.include_deleted)); + if let Some(limit) = options.limit { + input.insert("limit".into(), Value::from(limit)); + } + self.items_operation("records.list", Value::Object(input)) + } + + /// Every retained revision of a record, oldest first, as a UTF-8 JSON array. + pub fn record_revisions(&self, record_id: String) -> Result, AthleticStandardError> { + let mut input = json::Map::new(); + input.insert("record_id".into(), Value::String(record_id)); + self.items_operation("records.revisions", Value::Object(input)) + } + + /// Write new records in one change: the npm client's `writeRecords` input + /// and output, as UTF-8 JSON. + pub fn write_records(&self, request: Vec) -> Result, AthleticStandardError> { + self.json_operation("records.write", &request) + } + + /// Corrections and new records in one change: `writeRecordChanges`. + pub fn write_record_changes(&self, request: Vec) -> Result, AthleticStandardError> { + self.json_operation("records.write_changes", &request) + } + + /// A new revision of one record: `correctRecord`. A correction whose + /// `expected_revision` is not current is refused with `Stale`. + pub fn correct_record(&self, request: Vec) -> Result, AthleticStandardError> { + self.json_operation("records.correct", &request) + } + + /// A normal deletion that keeps history: `deleteRecord`. + pub fn delete_record(&self, request: Vec) -> Result, AthleticStandardError> { + self.json_operation("records.delete", &request) + } + + /// Run one of the protocol operations a phone may run on this database, + /// with the npm client's input and output shapes as UTF-8 JSON. + pub fn run_operation(&self, name: String, input: Vec) -> Result { + if !PHONE_OPERATIONS.contains(&name.as_str()) { + return Err(AthleticStandardError::Refused { + detail: format!("{name} is not an operation a phone runs on an open database"), + }); + } + let input = parse_json(&input)?; + let output = self.operation(&name, input)?; + Ok(OperationOutput { + output: json::to_string(&output.output).into_bytes(), + items: output.items.iter().map(|item| json::to_string(item).into_bytes()).collect(), + }) + } + + /// The migration this database needs, as the desktop preview in UTF-8 + /// JSON. Open with `allow_outdated_schema` to read it. + pub fn migration_preview(&self) -> Result, AthleticStandardError> { + self.with_store(|store| { + let preview = + athleticstandard::store::migrate::migration_preview(store.as_ref().expect("checked open"), None)?; + Ok(json::to_string(&json::to_value(&preview)).into_bytes()) + }) + } + + /// Make a verified backup at `backup_path`, then apply every pending + /// migration step in one transaction. The desktop rules apply: no backup, + /// no migration. + pub fn migrate(&self, backup_path: String) -> Result, AthleticStandardError> { + self.with_store(|store| { + let store = store.as_mut().expect("checked open"); + let options = athleticstandard::store::migrate::MigrationOptions { + backup_path: Some(resolve(&backup_path)?), + now_millis: None, + }; + let result = athleticstandard::store::migrate::execute_confirmed_migration(store, &options)?; + Ok(json::to_string(&json::to_value(&result)).into_bytes()) + }) + } + + /// Write a verified single-file copy to `destination`, which must not + /// exist (D328). Committed edits still in SQLite's companion log are in + /// the copy. Attachment files are not: use a package export for them. + pub fn save_copy(&self, destination: String) -> Result { + self.with_store(|store| { + let destination = resolve(&destination)?; + let verified = store.as_ref().expect("checked open").create_verified_backup(&destination)?; + let (sha256, byte_count) = file_digest(&verified.path)?; + Ok(SavedCopy { + path: verified.path.display().to_string(), + database_id: verified.database_id, + database_revision: verified.database_revision, + record_count: verified.record_count, + sha256, + byte_count, + }) + }) + } + + /// Close the database. Committed edits are in the file; the companion + /// log is checkpointed. Later calls are refused with `Closed`. + pub fn close(&self) -> Result<(), AthleticStandardError> { + let store = self.lock().take(); + match store { + Some(store) => Ok(store.close()?), + None => Ok(()), + } + } + + /// True after `close`. + pub fn is_closed(&self) -> bool { + self.lock().is_none() + } +} + +/// The SHA-256 of a file as lowercase hexadecimal, and its length. Apps use +/// it to tell whether a picked document changed since it was copied (D328). +#[uniffi::export] +pub fn file_sha256(path: String) -> Result { + Ok(file_digest(Path::new(&path))?.0) +} + +fn file_digest(path: &Path) -> Result<(String, u64), AthleticStandardError> { + use std::io::Read; + let mut file = std::fs::File::open(path).map_err(Error::from)?; + let mut hasher = Sha256::new(); + let mut buffer = vec![0u8; 64 * 1024]; + let mut total = 0u64; + loop { + let read = file.read(&mut buffer).map_err(Error::from)?; + if read == 0 { + break; + } + total += read as u64; + hasher.update(&buffer[..read]); + } + let digest = hasher.finalize(); + Ok((digest.iter().map(|byte| format!("{byte:02x}")).collect(), total)) +} diff --git a/mobile/swift/Sources/AthleticStandard/PickedDocument.swift b/mobile/swift/Sources/AthleticStandard/PickedDocument.swift new file mode 100644 index 00000000..e7c4edbc --- /dev/null +++ b/mobile/swift/Sources/AthleticStandard/PickedDocument.swift @@ -0,0 +1,205 @@ +import CryptoKit +import Foundation + +/// Where to keep a working file (D328). +public enum FileLocationAdvice { + /// The wording the guide suggests showing next to the file picker. + public static let recommendation = + "We recommend keeping your working file on this device. Editing the same file on two devices through iCloud Drive can cause sync conflicts." + + /// A folder in the app's own storage for working files, created if needed. Files + /// here open in place. + public static func localFolder(fileManager: FileManager = .default) throws -> URL { + let support = try fileManager.url( + for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) + let folder = support.appendingPathComponent("AthleticStandard", isDirectory: true) + try fileManager.createDirectory(at: folder, withIntermediateDirectories: true) + return folder + } +} + +/// The picked document changed after it was copied, so saving would replace someone +/// else's edits. The local edits are still in the working copy. Save a copy instead, +/// or open the document again. +public struct DocumentChangedElsewhere: Error, CustomStringConvertible { + public let documentURL: URL + public var description: String { + "\(documentURL.lastPathComponent) changed since it was opened. Your edits are kept on this device; save a copy instead." + } +} + +/// A `.ath.sqlite` document the person picked in the Files app, worked on through a +/// private copy (D328). +/// +/// Opening copies the document into a working folder under file coordination and +/// records the SHA-256 of what it copied. Edits commit to the working copy through +/// `database`. `save()` writes a verified single-file copy of the database and +/// replaces the document only if the document still has the recorded content. A +/// failed save keeps every local edit; call `save()` again when the location is +/// reachable, or `saveCopy(to:)`. +/// +/// Files in the app's own folders do not need this type: open them in place with +/// `Database.open`. +public final class PickedDocument: @unchecked Sendable { + public let documentURL: URL + public let workingURL: URL + public let database: Database + /// The SHA-256 of the document's content when it was copied or last saved. + public private(set) var documentDigest: String + /// The database revision the document last received. + public private(set) var savedRevision: UInt64 + private let lock = NSLock() + + private init(documentURL: URL, workingURL: URL, database: Database, digest: String, revision: UInt64) { + self.documentURL = documentURL + self.workingURL = workingURL + self.database = database + self.documentDigest = digest + self.savedRevision = revision + } + + /// Copy the picked document into `workingFolder` and open the copy. The folder + /// defaults to a folder in the app's own storage. + public static func open( + documentURL: URL, workingFolder: URL? = nil, readOnly: Bool = false + ) throws -> PickedDocument { + let folder = try workingFolder ?? FileLocationAdvice.localFolder() + .appendingPathComponent("Working", isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let workingURL = folder.appendingPathComponent("\(UUID().uuidString).ath.sqlite") + let bytes = try coordinatedRead(documentURL) + try bytes.write(to: workingURL, options: .withoutOverwriting) + let database = try Database.open( + path: workingURL.path, + options: OpenDatabaseOptions(readOnly: readOnly, allowOutdatedSchema: false, expectedDatabaseId: nil)) + let revision = try database.info().databaseRevision + return PickedDocument( + documentURL: documentURL, workingURL: workingURL, database: database, digest: Self.digest(bytes), + revision: revision) + } + + /// What an app keeps to resume after it restarts: a bookmark to the document, the + /// working copy's path, and what the document last received. Store it with the + /// app's settings, never inside an athlete file. + public struct State: Codable, Equatable, Sendable { + public var documentBookmark: Data? + public var documentPath: String + public var workingPath: String + public var documentDigest: String + public var savedRevision: UInt64 + } + + public var state: State { + State( + documentBookmark: try? documentURL.bookmarkData(), + documentPath: documentURL.path, + workingPath: workingURL.path, + documentDigest: documentDigest, + savedRevision: savedRevision) + } + + /// Open the working copy again from a saved `state`, with its unsaved edits. + public static func resume(_ state: State, readOnly: Bool = false) throws -> PickedDocument { + var documentURL = URL(fileURLWithPath: state.documentPath) + if let bookmark = state.documentBookmark { + var stale = false + if let resolved = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale) { + documentURL = resolved + } + } + let workingURL = URL(fileURLWithPath: state.workingPath) + let database = try Database.open( + path: workingURL.path, + options: OpenDatabaseOptions(readOnly: readOnly, allowOutdatedSchema: false, expectedDatabaseId: nil)) + return PickedDocument( + documentURL: documentURL, workingURL: workingURL, database: database, digest: state.documentDigest, + revision: state.savedRevision) + } + + /// True when the working copy has commits the document has not received. + public func hasUnsavedEdits() throws -> Bool { + try database.info().databaseRevision != savedRevision + } + + /// Save the working copy back to the picked document. + /// + /// Throws `DocumentChangedElsewhere` when the document's content is no longer the + /// content this copy started from. Any other error means the location could not be + /// written. In both cases the local edits stay in the working copy. + @discardableResult + public func save() throws -> SavedCopy { + lock.lock() + defer { lock.unlock() } + let snapshotURL = workingURL.deletingLastPathComponent() + .appendingPathComponent("\(UUID().uuidString).save.ath.sqlite") + defer { try? FileManager.default.removeItem(at: snapshotURL) } + let saved = try database.saveCopy(destination: snapshotURL.path) + let bytes = try Data(contentsOf: snapshotURL) + try coordinatedReplace(documentURL, with: bytes, expectedDigest: documentDigest) + documentDigest = saved.sha256 + savedRevision = saved.databaseRevision + return saved + } + + /// Write a verified copy to a new document, such as one the person named with + /// `UIDocumentPickerViewController(forExporting:)`. The picked document is not + /// changed. + @discardableResult + public func saveCopy(to url: URL) throws -> SavedCopy { + let snapshotURL = workingURL.deletingLastPathComponent() + .appendingPathComponent("\(UUID().uuidString).copy.ath.sqlite") + defer { try? FileManager.default.removeItem(at: snapshotURL) } + let saved = try database.saveCopy(destination: snapshotURL.path) + let bytes = try Data(contentsOf: snapshotURL) + try coordinatedReplace(url, with: bytes, expectedDigest: nil) + return saved + } + + /// Close the database and remove the working copy. Unsaved edits are lost, so + /// save first. + public func close(removingWorkingCopy: Bool = true) throws { + try database.close() + if removingWorkingCopy { + for suffix in ["", "-wal", "-shm"] { + try? FileManager.default.removeItem(atPath: workingURL.path + suffix) + } + } + } + + static func digest(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + } + + private static func coordinatedRead(_ url: URL) throws -> Data { + let accessing = url.startAccessingSecurityScopedResource() + defer { if accessing { url.stopAccessingSecurityScopedResource() } } + var coordinationError: NSError? + var result: Result = .failure(CocoaError(.fileReadUnknown)) + NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &coordinationError) { readURL in + result = Result { try Data(contentsOf: readURL) } + } + if let coordinationError { throw coordinationError } + return try result.get() + } + + private func coordinatedReplace(_ url: URL, with bytes: Data, expectedDigest: String?) throws { + let accessing = url.startAccessingSecurityScopedResource() + defer { if accessing { url.stopAccessingSecurityScopedResource() } } + var coordinationError: NSError? + var result: Result = .success(()) + NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { + writeURL in + result = Result { + if let expectedDigest { + let current = try Data(contentsOf: writeURL) + if Self.digest(current) != expectedDigest { + throw DocumentChangedElsewhere(documentURL: url) + } + } + try bytes.write(to: writeURL, options: .atomic) + } + } + if let coordinationError { throw coordinationError } + try result.get() + } +} diff --git a/mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift b/mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift new file mode 100644 index 00000000..54afbb34 --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift @@ -0,0 +1,79 @@ +import AthleticStandard +import Foundation +import Testing + +/// A picked document worked on through a private copy (D328). A file in a separate +/// folder stands in for a document from another location. +@Suite(.serialized) +struct DocumentTests { + /// A picked document holding the source and workout from `StoreTests`. + static func pickedDocument() throws -> (document: URL, working: URL) { + let provider = try StoreTests.folder() + let document = provider.appendingPathComponent("Picked.ath.sqlite") + let database = try StoreTests.create(provider.appendingPathComponent("seed.ath.sqlite")) + try StoreTests.writeWorkout(database) + _ = try database.saveCopy(destination: document.path) + try database.close() + return (document, try StoreTests.folder()) + } + + static func endAt(_ database: Database) throws -> String? { + let record = try StoreTests.object(try #require(try database.getRecord(recordId: StoreTests.workoutID))) + return (record["data"] as? [String: Any])?["end_at"] as? String + } + + @Test func editSaveAndReopen() throws { + let (document, working) = try Self.pickedDocument() + let picked = try PickedDocument.open(documentURL: document, workingFolder: working) + try StoreTests.correctWorkout(picked.database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + #expect(try picked.hasUnsavedEdits()) + let saved = try picked.save() + #expect(try !picked.hasUnsavedEdits()) + #expect(saved.sha256 == (try fileSha256(path: document.path))) + try picked.close() + + let again = try PickedDocument.open(documentURL: document, workingFolder: working) + #expect(try Self.endAt(again.database) == "2026-01-02T04:30:05.678Z") + try again.close() + } + + @Test func aDocumentChangedElsewhereIsNotReplaced() throws { + let (document, working) = try Self.pickedDocument() + let picked = try PickedDocument.open(documentURL: document, workingFolder: working) + try StoreTests.correctWorkout(picked.database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + // Another device saves its own edit to the same document. + let other = try PickedDocument.open(documentURL: document, workingFolder: try StoreTests.folder()) + try StoreTests.correctWorkout(other.database, expectedRevision: 1, endAt: "2026-01-02T04:50:05.678Z") + try other.save() + try other.close() + + #expect(throws: DocumentChangedElsewhere.self) { try picked.save() } + // The other device's edit stays in the document, and this one stays local. + let check = try Database.open(path: document.path, options: OpenDatabaseOptions(readOnly: true)) + #expect(try Self.endAt(check) == "2026-01-02T04:50:05.678Z") + try check.close() + #expect(try Self.endAt(picked.database) == "2026-01-02T04:30:05.678Z") + let copy = try StoreTests.folder().appendingPathComponent("Copy.ath.sqlite") + let saved = try picked.saveCopy(to: copy) + #expect(saved.databaseRevision == 2) + try picked.close() + } + + @Test func aFailedSaveKeepsTheLocalEdit() throws { + let (document, working) = try Self.pickedDocument() + let picked = try PickedDocument.open(documentURL: document, workingFolder: working) + try StoreTests.correctWorkout(picked.database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + let provider = document.deletingLastPathComponent() + // The location stops accepting writes, as an offline provider does. + try FileManager.default.setAttributes([.posixPermissions: 0o444], ofItemAtPath: document.path) + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: provider.path) + #expect(throws: (any Error).self) { try picked.save() } + #expect(try picked.hasUnsavedEdits()) + #expect(try Self.endAt(picked.database) == "2026-01-02T04:30:05.678Z") + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: provider.path) + try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: document.path) + try picked.save() + #expect(try !picked.hasUnsavedEdits()) + try picked.close() + } +} diff --git a/mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift b/mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift index 32c81812..62a209d3 100644 --- a/mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift +++ b/mobile/swift/Tests/AthleticStandardTests/FixtureBundle.swift @@ -8,11 +8,24 @@ enum FixtureBundle { let description: String } - static func suite(_ name: String) throws -> [String: Any] { + static func folder() throws -> URL { guard let folder = ProcessInfo.processInfo.environment["ATH_MOBILE_FIXTURES"] else { throw Missing(description: "set ATH_MOBILE_FIXTURES to the folder mobile/tests/fixtures.rs writes") } - let url = URL(fileURLWithPath: folder).appendingPathComponent("\(name).json") + return URL(fileURLWithPath: folder, isDirectory: true) + } + + /// A file the bundle holds, such as `outdated-2-1-0.ath.sqlite`. + static func file(_ name: String) throws -> URL { + let url = try folder().appendingPathComponent(name) + guard FileManager.default.fileExists(atPath: url.path) else { + throw Missing(description: "the fixture bundle has no \(name)") + } + return url + } + + static func suite(_ name: String) throws -> [String: Any] { + let url = try folder().appendingPathComponent("\(name).json") let data = try Data(contentsOf: url) guard let suite = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw Missing(description: "\(url.path) is not a suite object") diff --git a/mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift b/mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift new file mode 100644 index 00000000..1fae257c --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift @@ -0,0 +1,55 @@ +import AthleticStandard +import Foundation +import Testing + +/// The phone half of the desktop round trip (D328). `mobile/scripts/roundtrip.sh +/// create` made the desktop file with the desktop `ath`. This test edits it as a +/// picked document, closes it, reopens it, and saves it. `roundtrip.sh verify` then +/// checks the saved file with the desktop `ath`. +/// +/// `ATH_MOBILE_ROUNDTRIP_OUT` names the folder for the saved file. The script reads +/// `phone-edited.ath.sqlite` from it. +@Suite(.serialized) +struct RoundTripTests { + @Test func desktopFileEditedOnThePhone() throws { + let desktop = try FixtureBundle.file("roundtrip/desktop.ath.sqlite") + let facts = try StoreTests.object(try Data(contentsOf: try FixtureBundle.file("roundtrip/desktop.json"))) + let recordID = try #require(facts["record_id"] as? String) + let databaseID = try #require(facts["database_id"] as? String) + let out = try #require( + ProcessInfo.processInfo.environment["ATH_MOBILE_ROUNDTRIP_OUT"], + "set ATH_MOBILE_ROUNDTRIP_OUT to the folder roundtrip.sh verify reads") + let outFolder = URL(fileURLWithPath: out, isDirectory: true) + try FileManager.default.createDirectory(at: outFolder, withIntermediateDirectories: true) + let document = outFolder.appendingPathComponent("phone-edited.ath.sqlite") + try? FileManager.default.removeItem(at: document) + try FileManager.default.copyItem(at: desktop, to: document) + + let working = try StoreTests.folder() + let picked = try PickedDocument.open(documentURL: document, workingFolder: working) + #expect(try picked.database.info().databaseId == databaseID) + var record = try StoreTests.object(try #require(try picked.database.getRecord(recordId: recordID))) + #expect(record["current_revision"] as? Int == 1) + var data = try #require(record["data"] as? [String: Any]) + var value = try #require(data["value"] as? [String: Any]) + value["standard_value"] = 63 + value["input_value"] = 63 + data["value"] = value + let request: [String: Any] = [ + "record_id": recordID, "expected_revision": 1, "data": data, + "changed_by": ["author_type": "athlete"], + ] + _ = try picked.database.correctRecord(request: try JSONSerialization.data(withJSONObject: request)) + + // Close the working copy and resume it, as after the app restarts. + let state = picked.state + try picked.close(removingWorkingCopy: false) + let resumed = try PickedDocument.resume(state) + record = try StoreTests.object(try #require(try resumed.database.getRecord(recordId: recordID))) + #expect(record["current_revision"] as? Int == 2) + #expect(try resumed.hasUnsavedEdits()) + let saved = try resumed.save() + #expect(saved.sha256 == (try fileSha256(path: document.path))) + try resumed.close() + } +} diff --git a/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift b/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift new file mode 100644 index 00000000..c6b32ded --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift @@ -0,0 +1,130 @@ +import AthleticStandard +import Foundation +import Testing + +/// The storage steps mobile/tests/store.rs runs, through the Swift package (D327). +@Suite(.serialized) +struct StoreTests { + static let sourceID = "01890f3e-e7d3-7cc0-88c8-000000000003" + static let workoutID = "01890f3e-e7d3-7cc0-88c8-000000000064" + + static func folder() throws -> URL { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("athleticstandard-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + static func workoutData(endAt: String) -> String { + #"{"source_id":"\#(sourceID)","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","start_at":"2026-01-02T03:04:05.678Z","end_at":"\#(endAt)","input_start_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"input_end_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"source_reported_summaries":[]}"# + } + + static func create(_ url: URL) throws -> Database { + try Database.create( + path: url.path, + options: CreateDatabaseOptions( + databaseId: "01890f3e-e7d3-7cc0-88c8-0000000000aa", createdAt: "2026-01-02T03:04:05.678Z")) + } + + static func writeWorkout(_ database: Database) throws { + let request = #"{"inputs":[{"record_id":"\#(sourceID)","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","data":{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"},"changed_by":{"author_type":"athlete"}},{"record_id":"\#(workoutID)","record_type":"workout_session","created_at":"2026-01-02T03:04:05.678Z","data":\#(workoutData(endAt: "2026-01-02T04:04:05.678Z")),"changed_by":{"author_type":"athlete"}}]}"# + _ = try database.writeRecords(request: Data(request.utf8)) + } + + @discardableResult + static func correctWorkout(_ database: Database, expectedRevision: Int, endAt: String) throws -> Data { + let request = #"{"record_id":"\#(workoutID)","expected_revision":\#(expectedRevision),"data":\#(workoutData(endAt: endAt)),"changed_by":{"author_type":"athlete"},"became_known_at":"2026-01-03T00:00:00.000Z"}"# + return try database.correctRecord(request: Data(request.utf8)) + } + + static func object(_ data: Data) throws -> [String: Any] { + try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + @Test func createEditCloseAndReopen() throws { + let url = try Self.folder().appendingPathComponent("athlete.ath.sqlite") + let database = try Self.create(url) + #expect(try database.info().databaseRevision == 0) + #expect(try database.info().writable) + try Self.writeWorkout(database) + try Self.correctWorkout(database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + #expect(try database.info().databaseRevision == 2) + try database.close() + #expect(database.isClosed()) + #expect(throws: AthleticStandardError.self) { try database.info() } + + let reopened = try Database.open(path: url.path, options: OpenDatabaseOptions()) + let record = try Self.object(try #require(try reopened.getRecord(recordId: Self.workoutID))) + #expect(record["current_revision"] as? Int == 2) + #expect((record["data"] as? [String: Any])?["end_at"] as? String == "2026-01-02T04:30:05.678Z") + let revisions = try JSONSerialization.jsonObject(with: try reopened.recordRevisions(recordId: Self.workoutID)) + #expect((revisions as? [Any])?.count == 2) + try reopened.close() + } + + @Test func staleCorrectionIsRefused() throws { + let database = try Self.create(try Self.folder().appendingPathComponent("athlete.ath.sqlite")) + try Self.writeWorkout(database) + try Self.correctWorkout(database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + do { + try Self.correctWorkout(database, expectedRevision: 1, endAt: "2026-01-02T04:45:05.678Z") + Issue.record("a stale correction was accepted") + } catch let error as AthleticStandardError { + #expect(error.code == "stale") + #expect(error.detail == "Record \(Self.workoutID) is at revision 2, not expected revision 1") + } + #expect(try database.info().databaseRevision == 2) + } + + @Test func readOnlyOpenRefusesWrites() throws { + let url = try Self.folder().appendingPathComponent("athlete.ath.sqlite") + let database = try Self.create(url) + try Self.writeWorkout(database) + try database.close() + let readOnly = try Database.open(path: url.path, options: OpenDatabaseOptions(readOnly: true)) + #expect(try !readOnly.info().writable) + do { + try Self.correctWorkout(readOnly, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + Issue.record("a read-only database accepted a write") + } catch let error as AthleticStandardError { + #expect(error.code == "refused") + } + } + + @Test func outdatedFileNeedsMigrationWithBackup() throws { + let fixture = try FixtureBundle.file("outdated-2-1-0.ath.sqlite") + let folder = try Self.folder() + let url = folder.appendingPathComponent("outdated.ath.sqlite") + try FileManager.default.copyItem(at: fixture, to: url) + do { + _ = try Database.open(path: url.path, options: OpenDatabaseOptions()) + Issue.record("an outdated database opened without a migration") + } catch let error as AthleticStandardError { + #expect(error.code == "migration_required") + } + let outdated = try Database.open(path: url.path, options: OpenDatabaseOptions(allowOutdatedSchema: true)) + let backup = folder.appendingPathComponent("before-migration.ath.sqlite") + let result = try Self.object(try outdated.migrate(backupPath: backup.path)) + #expect(result["migrated"] as? Bool == true) + try outdated.close() + #expect(FileManager.default.fileExists(atPath: backup.path)) + let migrated = try Database.open(path: url.path, options: OpenDatabaseOptions()) + #expect(try migrated.info().sqlSchemaVersion == 8) + } + + @Test func savedCopyHoldsEditsStillInTheLog() throws { + let folder = try Self.folder() + let url = folder.appendingPathComponent("athlete.ath.sqlite") + let database = try Self.create(url) + try Self.writeWorkout(database) + try Self.correctWorkout(database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + #expect(FileManager.default.fileExists(atPath: url.path + "-wal")) + let saved = try database.saveCopy(destination: folder.appendingPathComponent("saved.ath.sqlite").path) + #expect(saved.databaseRevision == 2) + #expect(saved.sha256 == (try fileSha256(path: saved.path))) + #expect(!FileManager.default.fileExists(atPath: saved.path + "-wal")) + let copy = try Database.open(path: saved.path, options: OpenDatabaseOptions(readOnly: true)) + let record = try Self.object(try #require(try copy.getRecord(recordId: Self.workoutID))) + #expect(record["current_revision"] as? Int == 2) + } +} diff --git a/mobile/tests/dependencies.rs b/mobile/tests/dependencies.rs index 58c79a77..a8e0e1e7 100644 --- a/mobile/tests/dependencies.rs +++ b/mobile/tests/dependencies.rs @@ -60,6 +60,20 @@ fn the_calculation_only_build_has_no_storage_network_or_command_line() { assert!(found.is_empty(), "the calculation-only build depends on {found:?}"); } +/// Crates that a phone build must not contain even with storage: the command +/// line, terminal handling, import readers, and every network client. +const COMMAND_LINE_OR_NETWORK: &[&str] = + &["libsql", "ureq", "reqwest", "hyper", "tokio", "axum", "clap", "terminal_size", "zip", "quick-xml"]; + +#[test] +fn the_storage_build_has_sqlite_and_no_command_line_or_network() { + let names = dependency_names(&["sqlite"]); + assert!(names.contains(&"rusqlite".to_string()), "the store is a dependency: {names:?}"); + assert!(names.contains(&"athleticstandard".to_string()), "the store is a dependency: {names:?}"); + let found: Vec<&String> = names.iter().filter(|name| COMMAND_LINE_OR_NETWORK.contains(&name.as_str())).collect(); + assert!(found.is_empty(), "the storage build depends on {found:?}"); +} + #[test] fn the_core_names_no_file_network_or_process_api() { let mut files = Vec::new(); diff --git a/mobile/tests/fixtures.rs b/mobile/tests/fixtures.rs index 536e542d..b098fc5a 100644 --- a/mobile/tests/fixtures.rs +++ b/mobile/tests/fixtures.rs @@ -137,3 +137,17 @@ fn every_model_vector_runs_through_the_binding() { suite.insert("cases".into(), Value::Array(cases)); export("model-vectors", Value::Object(suite)); } + +/// Files the storage tests open. The 2.1.0 database is an approved synthetic +/// fixture (`tools/public-data-allowlist.json`); the phones open a copy to test +/// the migration rules. +#[test] +fn storage_files_are_exported() { + let outdated = repository().join("tests/fixtures/version-2-1-0/athlete.ath.sqlite"); + assert!(outdated.exists(), "the 2.1.0 database fixture is present"); + if let Some(folder) = std::env::var_os("ATH_MOBILE_FIXTURES") { + let folder = Path::new(&folder); + std::fs::create_dir_all(folder).unwrap(); + std::fs::copy(&outdated, folder.join("outdated-2-1-0.ath.sqlite")).unwrap(); + } +} diff --git a/mobile/tests/store.rs b/mobile/tests/store.rs new file mode 100644 index 00000000..aab1678f --- /dev/null +++ b/mobile/tests/store.rs @@ -0,0 +1,237 @@ +//! The phone storage binding on real `.ath.sqlite` files (D327, D328). +//! +//! The Swift and Kotlin tests run the same steps through the packages. + +use std::path::{Path, PathBuf}; + +use athleticstandard::store::{OpenOptions, Store, SQL_SCHEMA_VERSION}; +use athleticstandard_core::json::{self, Value}; +use athleticstandard_mobile::{ + AthleticStandardError, CreateDatabaseOptions, Database, ListRecordsOptions, OpenDatabaseOptions, +}; + +const SOURCE_ID: &str = "01890f3e-e7d3-7cc0-88c8-000000000003"; +const WORKOUT_ID: &str = "01890f3e-e7d3-7cc0-88c8-000000000064"; + +fn create_options() -> CreateDatabaseOptions { + CreateDatabaseOptions { + database_id: Some("01890f3e-e7d3-7cc0-88c8-0000000000aa".into()), + created_at: Some("2026-01-02T03:04:05.678Z".into()), + } +} + +fn open_options() -> OpenDatabaseOptions { + OpenDatabaseOptions { read_only: false, allow_outdated_schema: false, expected_database_id: None } +} + +fn workout_data(end_at: &str) -> String { + format!( + r#"{{"source_id":"{SOURCE_ID}","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","start_at":"2026-01-02T03:04:05.678Z","end_at":"{end_at}","input_start_timestamp":{{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"}},"input_end_timestamp":{{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"}},"source_reported_summaries":[]}}"# + ) +} + +/// A source and one workout from it, written in one change. +fn write_workout(database: &Database) -> Value { + let request = format!( + r#"{{"inputs":[{{"record_id":"{SOURCE_ID}","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","data":{{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"}},"changed_by":{{"author_type":"athlete"}}}},{{"record_id":"{WORKOUT_ID}","record_type":"workout_session","created_at":"2026-01-02T03:04:05.678Z","data":{},"changed_by":{{"author_type":"athlete"}}}}]}}"#, + workout_data("2026-01-02T04:04:05.678Z") + ); + parse(database.write_records(request.into_bytes()).unwrap()) +} + +fn correct_workout( + database: &Database, + expected_revision: u64, + end_at: &str, +) -> Result, AthleticStandardError> { + let request = format!( + r#"{{"record_id":"{WORKOUT_ID}","expected_revision":{expected_revision},"data":{},"changed_by":{{"author_type":"athlete"}},"became_known_at":"2026-01-03T00:00:00.000Z"}}"#, + workout_data(end_at) + ); + database.correct_record(request.into_bytes()) +} + +fn parse(bytes: Vec) -> Value { + json::parse(std::str::from_utf8(&bytes).unwrap()).unwrap() +} + +/// A path in the test's folder. The folder is resolved, as the desktop store +/// that checks the phone's files refuses a path through a symbolic link. +fn path_in(folder: &Path, name: &str) -> String { + std::fs::canonicalize(folder).unwrap().join(name).display().to_string() +} + +#[test] +fn create_edit_close_and_reopen() { + let folder = tempfile::tempdir().unwrap(); + let path = path_in(folder.path(), "athlete.ath.sqlite"); + let database = Database::create(path.clone(), create_options()).unwrap(); + let info = database.info().unwrap(); + assert_eq!(info.database_id, "01890f3e-e7d3-7cc0-88c8-0000000000aa"); + assert_eq!(info.database_revision, 0); + assert!(info.writable); + + let written = write_workout(&database); + assert_eq!(written["database_revision"], Value::from(1)); + let corrected = parse(correct_workout(&database, 1, "2026-01-02T04:30:05.678Z").unwrap()); + assert_eq!(corrected["record"]["current_revision"], Value::from(2)); + assert_eq!(database.info().unwrap().database_revision, 2); + database.close().unwrap(); + assert!(database.is_closed()); + assert!(matches!(database.info(), Err(AthleticStandardError::Closed { .. }))); + + let reopened = Database::open(path.clone(), open_options()).unwrap(); + let record = parse(reopened.get_record(WORKOUT_ID.into()).unwrap().unwrap()); + assert_eq!(record["current_revision"], Value::from(2)); + assert_eq!(record["data"]["end_at"], Value::from("2026-01-02T04:30:05.678Z")); + let revisions = parse(reopened.record_revisions(WORKOUT_ID.into()).unwrap()); + assert_eq!(revisions.as_array().unwrap().len(), 2); + let listed = parse( + reopened + .list_records(ListRecordsOptions { + record_type: Some("workout_session".into()), + include_deleted: false, + limit: None, + }) + .unwrap(), + ); + assert_eq!(listed.as_array().unwrap().len(), 1); + assert_eq!(reopened.get_record("01890f3e-e7d3-7cc0-88c8-0000000000ff".into()).unwrap(), None); + reopened.close().unwrap(); + + // The desktop store reads what the phone binding wrote. + let store = Store::open(&path, OpenOptions { read_only: true, allow_outdated_schema: false }).unwrap(); + assert_eq!(store.get_record(WORKOUT_ID).unwrap().unwrap().current_revision, 2); + store.close().unwrap(); +} + +#[test] +fn a_stale_correction_is_refused_and_changes_nothing() { + let folder = tempfile::tempdir().unwrap(); + let database = Database::create(path_in(folder.path(), "athlete.ath.sqlite"), create_options()).unwrap(); + write_workout(&database); + correct_workout(&database, 1, "2026-01-02T04:30:05.678Z").unwrap(); + let error = correct_workout(&database, 1, "2026-01-02T04:45:05.678Z").unwrap_err(); + assert_eq!( + error, + AthleticStandardError::Stale { + detail: format!("Record {WORKOUT_ID} is at revision 2, not expected revision 1") + } + ); + assert_eq!(database.info().unwrap().database_revision, 2); +} + +#[test] +fn an_invalid_edit_returns_the_desktop_issues() { + let folder = tempfile::tempdir().unwrap(); + let database = Database::create(path_in(folder.path(), "athlete.ath.sqlite"), create_options()).unwrap(); + write_workout(&database); + let error = correct_workout(&database, 1, "2026-01-01T00:00:00.000Z").unwrap_err(); + let AthleticStandardError::Invalid { detail, issues } = error else { panic!("expected an invalid record") }; + assert_eq!(detail, "data.end_at: Workout session end cannot precede its start"); + assert_eq!(issues[0].path_text, "data.end_at"); +} + +#[test] +fn a_read_only_open_refuses_writes() { + let folder = tempfile::tempdir().unwrap(); + let path = path_in(folder.path(), "athlete.ath.sqlite"); + let database = Database::create(path.clone(), create_options()).unwrap(); + write_workout(&database); + database.close().unwrap(); + let read_only = Database::open(path, OpenDatabaseOptions { read_only: true, ..open_options() }).unwrap(); + assert!(!read_only.info().unwrap().writable); + let error = correct_workout(&read_only, 1, "2026-01-02T04:30:05.678Z").unwrap_err(); + assert!(matches!(error, AthleticStandardError::Refused { .. }), "{error:?}"); + assert_eq!(read_only.info().unwrap().database_revision, 1); +} + +#[test] +fn another_database_at_the_same_path_is_refused() { + let folder = tempfile::tempdir().unwrap(); + let path = path_in(folder.path(), "athlete.ath.sqlite"); + Database::create(path.clone(), create_options()).unwrap().close().unwrap(); + let error = Database::open( + path, + OpenDatabaseOptions { + expected_database_id: Some("01890f3e-e7d3-7cc0-88c8-0000000000bb".into()), + ..open_options() + }, + ) + .err() + .unwrap(); + assert!(matches!(error, AthleticStandardError::Refused { .. }), "{error:?}"); +} + +fn outdated_copy(folder: &Path) -> String { + let source = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../tests/fixtures/version-2-1-0/athlete.ath.sqlite"); + let path = folder.join("outdated.ath.sqlite"); + std::fs::copy(source, &path).unwrap(); + path.display().to_string() +} + +#[test] +fn an_outdated_file_needs_a_migration_with_a_verified_backup() { + let folder = tempfile::tempdir().unwrap(); + let path = outdated_copy(folder.path()); + let error = Database::open(path.clone(), open_options()).err().unwrap(); + let AthleticStandardError::MigrationRequired { preview, .. } = error else { panic!("expected a migration") }; + let preview = parse(preview); + assert_eq!(preview["target_sql_schema_version"], Value::from(SQL_SCHEMA_VERSION)); + + let outdated = + Database::open(path.clone(), OpenDatabaseOptions { allow_outdated_schema: true, ..open_options() }).unwrap(); + let preview = parse(outdated.migration_preview().unwrap()); + assert!(preview["source_sql_schema_version"].as_u64().unwrap() < u64::from(SQL_SCHEMA_VERSION)); + let backup = path_in(folder.path(), "before-migration.ath.sqlite"); + let result = parse(outdated.migrate(backup.clone()).unwrap()); + assert_eq!(result["migrated"], Value::Bool(true), "{result:?}"); + assert!(result["backup_path"].as_str().unwrap().ends_with("/before-migration.ath.sqlite"), "{result:?}"); + outdated.close().unwrap(); + assert!(Path::new(&backup).exists()); + + let migrated = Database::open(path, open_options()).unwrap(); + assert_eq!(migrated.info().unwrap().sql_schema_version, SQL_SCHEMA_VERSION); +} + +#[test] +fn a_saved_copy_holds_edits_still_in_the_companion_log() { + let folder = tempfile::tempdir().unwrap(); + let path = path_in(folder.path(), "athlete.ath.sqlite"); + let database = Database::create(path.clone(), create_options()).unwrap(); + write_workout(&database); + correct_workout(&database, 1, "2026-01-02T04:30:05.678Z").unwrap(); + assert!(Path::new(&format!("{path}-wal")).exists(), "the edit is still in the companion log"); + + // Copying only the main file of an open database can miss the edit. + let raw = path_in(folder.path(), "raw-copy.ath.sqlite"); + std::fs::copy(&path, &raw).unwrap(); + let raw_revision = Store::open(&raw, OpenOptions { read_only: true, allow_outdated_schema: false }) + .map(|store| store.database_revision().unwrap_or(0)) + .unwrap_or(0); + assert!(raw_revision < 2, "the main file alone lags the edit"); + + let saved = database.save_copy(path_in(folder.path(), "saved.ath.sqlite")).unwrap(); + assert_eq!(saved.database_revision, 2); + assert_eq!(saved.database_id, "01890f3e-e7d3-7cc0-88c8-0000000000aa"); + assert_eq!(saved.sha256, athleticstandard_mobile::file_sha256(saved.path.clone()).unwrap()); + assert!(!Path::new(&format!("{}-wal", saved.path)).exists(), "the copy is one self-contained file"); + let copy = Store::open(&saved.path, OpenOptions { read_only: true, allow_outdated_schema: false }).unwrap(); + assert_eq!(copy.get_record(WORKOUT_ID).unwrap().unwrap().current_revision, 2); + + // A copy is never written over an existing file. + let error = database.save_copy(saved.path.clone()).unwrap_err(); + assert!(matches!(error, AthleticStandardError::Refused { .. }), "{error:?}"); +} + +#[test] +fn only_listed_operations_run_on_a_phone() { + let folder = tempfile::tempdir().unwrap(); + let database = Database::create(path_in(folder.path(), "athlete.ath.sqlite"), create_options()).unwrap(); + let stats = database.run_operation("database.stats".into(), b"{}".to_vec()).unwrap(); + assert!(!stats.output.is_empty()); + let error = database.run_operation("backtest.run".into(), b"{}".to_vec()).unwrap_err(); + assert!(matches!(error, AthleticStandardError::Refused { .. }), "{error:?}"); + let error = database.run_operation("records.read".into(), b"{".to_vec()).unwrap_err(); + assert!(matches!(error, AthleticStandardError::MalformedJson { .. }), "{error:?}"); +} diff --git a/mobile/uniffi.toml b/mobile/uniffi.toml index 4cea9f3a..b7e5aafd 100644 --- a/mobile/uniffi.toml +++ b/mobile/uniffi.toml @@ -13,3 +13,8 @@ cdylib_name = "athleticstandard_mobile" # Use the Android system cleaner where the phone has one (API 34 and later). android = true generate_immutable_records = true + +# Kotlin objects already have `close()`, which frees the native object +# (`AutoCloseable`). The database's own close is `closeDatabase()` there. +[bindings.kotlin.rename] +"Database.close" = "closeDatabase" From 21f2f78254ca487ab108a94669aa8bb7c41fbaa2 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 18:18:55 -0600 Subject: [PATCH 05/30] Move the calculations into the core, and read their data through one interface. The calculation settings, methods, range arithmetic, and receipts move to `core/src/calculate/`, with the calendar rules in `core/src/calendar.rs` and the shipped skills in `core/src/assets.rs` (D312). The core has its own error type; the desktop error converts from it with the same codes and messages. Every calculation now asks for its data through `CalculationReader` (D326). The desktop's SQLite reader in `src/calculate/sqlite.rs` runs the same indexed queries as before, inside one read snapshot. A memory snapshot in the core answers the same requests from supplied records, with the same filters and order. A batch with an invalid record or a repeated ID is refused and leaves the builder as it was. The 3.0.0 workout operations and threshold methods ask for their recordings, intensity references, and workout windows as one request each. The SQLite reader answers with the 3.0.0 queries, unchanged, in `src/calculate/recorded.rs`, `recorded_inputs.rs`, and `window.rs`; the arithmetic, results, and `apply_with` move to the core. A memory snapshot does not hold recordings yet, so it refuses those calculations and says to run them on a database. `tests/calculate_readers.rs` runs every worked example and a set of synthetic edge cases on both readers and compares the complete results, including failures and the input limit at 100,000 and 100,001 inputs. A calculation that reads recordings must get exactly the documented refusal from the snapshot: 30 worked examples and 69 case requests agree, and 12 examples and 2 requests need a database. Every existing calculation, golden, and query-plan test passes unchanged. Co-Authored-By: Claude Opus 5.5 --- build.rs | 11 +- core/build.rs | 66 +++ core/src/assets.rs | 170 +++++++ {src => core/src}/calculate/definition.rs | 17 + {src => core/src}/calculate/hyrox.rs | 0 core/src/calculate/memory.rs | 500 +++++++++++++++++++++ {src => core/src}/calculate/methods.rs | 2 +- core/src/calculate/mod.rs | 197 ++++++++ {src => core/src}/calculate/range.rs | 401 ++++------------- core/src/calculate/reader.rs | 172 +++++++ {src => core/src}/calculate/record.rs | 199 +++----- core/src/calculate/recorded.rs | 271 +++++++++++ core/src/calculate/recorded_inputs.rs | 164 +++++++ core/src/calculate/window.rs | 96 ++++ {src => core/src}/calculate/workout_ops.rs | 4 +- core/src/calendar.rs | 254 +++++++++++ core/src/error.rs | 68 +++ core/src/lib.rs | 12 +- docs/architecture.md | 19 +- src/assets/mod.rs | 42 +- src/assets/skill.rs | 107 +---- src/calculate/mod.rs | 210 ++------- src/calculate/recorded.rs | 277 +----------- src/calculate/recorded_inputs.rs | 161 +------ src/calculate/sqlite.rs | 455 +++++++++++++++++++ src/calculate/window.rs | 85 +--- src/error.rs | 12 + src/protocol/worker.rs | 6 + src/store/query.rs | 6 +- src/view/calendar.rs | 237 +--------- tests/calculate_readers.rs | 322 +++++++++++++ tests/calculation_support/cases.rs | 338 ++++++++++++++ tests/calculation_support/mod.rs | 132 +++++- 33 files changed, 3490 insertions(+), 1523 deletions(-) create mode 100644 core/build.rs create mode 100644 core/src/assets.rs rename {src => core/src}/calculate/definition.rs (97%) rename {src => core/src}/calculate/hyrox.rs (100%) create mode 100644 core/src/calculate/memory.rs rename {src => core/src}/calculate/methods.rs (99%) create mode 100644 core/src/calculate/mod.rs rename {src => core/src}/calculate/range.rs (73%) create mode 100644 core/src/calculate/reader.rs rename {src => core/src}/calculate/record.rs (81%) create mode 100644 core/src/calculate/recorded.rs create mode 100644 core/src/calculate/recorded_inputs.rs create mode 100644 core/src/calculate/window.rs rename {src => core/src}/calculate/workout_ops.rs (99%) create mode 100644 core/src/calendar.rs create mode 100644 core/src/error.rs create mode 100644 src/calculate/sqlite.rs create mode 100644 tests/calculate_readers.rs create mode 100644 tests/calculation_support/cases.rs diff --git a/build.rs b/build.rs index f2081811..cabbb27c 100644 --- a/build.rs +++ b/build.rs @@ -1,9 +1,10 @@ -//! Embed the shipped skills and mapping files in the library. +//! Embed the shipped mapping files in the library. The core embeds the skills. //! //! An `ath` executable copied into an empty directory must still install the //! agent skill and read its shipped mappings. This script lists every file -//! under `skills/` and `mappings/` and writes a table of `include_bytes!` -//! entries into `OUT_DIR`. The compiler then stores the bytes in the binary. +//! under `mappings/` and writes a table of `include_bytes!` entries into +//! `OUT_DIR`. The compiler then stores the bytes in the binary. The skills are +//! embedded the same way by `core/build.rs`, so every platform has them. //! //! Hidden names, such as `.DS_Store`, are skipped. A symbolic link stops the //! build, because the embedded set must be the files that are actually in the @@ -18,8 +19,8 @@ fn main() { let manifest = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")); let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR")); - let mut generated = String::from("// Generated by build.rs from skills/ and mappings/. Do not edit.\n\n"); - for (constant, directory) in [("SKILL_FILES", "skills"), ("MAPPING_FILES", "mappings")] { + let mut generated = String::from("// Generated by build.rs from mappings/. Do not edit.\n\n"); + for (constant, directory) in [("MAPPING_FILES", "mappings")] { let root = asset_root(&manifest, directory); println!("cargo:rerun-if-changed={}", root.display()); let mut files = Vec::new(); diff --git a/core/build.rs b/core/build.rs new file mode 100644 index 00000000..66d4cb7c --- /dev/null +++ b/core/build.rs @@ -0,0 +1,66 @@ +//! Embed the shipped skills in the core (D312). +//! +//! Every file under the repository's `skills/` folder is compiled in, so the +//! calculation files and their worked examples are available on every +//! platform without file access. Hidden names, such as `.DS_Store`, are +//! skipped. A symbolic link stops the build, because the embedded set must be +//! the files that are actually in the repository. + +use std::env; +use std::fmt::Write as _; +use std::fs; +use std::path::{Path, PathBuf}; + +fn main() { + let manifest = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")); + let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR")); + let root = manifest.join("../skills"); + if !root.is_dir() { + panic!("the shipped skills/ directory was not found at {}", root.display()); + } + let root = fs::canonicalize(&root).expect("canonical skills directory"); + println!("cargo:rerun-if-changed={}", root.display()); + let mut files = Vec::new(); + collect(&root, &root, &mut files); + files.sort(); + let mut generated = String::from("// Generated by core/build.rs from skills/. Do not edit.\n\n"); + writeln!(generated, "pub static SKILL_FILES: &[EmbeddedFile] = &[").unwrap(); + for relative in &files { + let absolute = root.join(relative); + println!("cargo:rerun-if-changed={}", absolute.display()); + let absolute = absolute.to_str().expect("skill paths are UTF-8"); + writeln!(generated, " EmbeddedFile {{ path: {relative:?}, bytes: include_bytes!({absolute:?}) }},").unwrap(); + } + writeln!(generated, "];").unwrap(); + fs::write(out_dir.join("embedded_skills.rs"), generated).expect("write embedded skill table"); + println!("cargo:rerun-if-changed=build.rs"); +} + +/// Every regular file under `directory`, as a `/`-separated path relative to `root`. +fn collect(root: &Path, directory: &Path, out: &mut Vec) { + let mut entries: Vec<_> = fs::read_dir(directory) + .unwrap_or_else(|error| panic!("read {}: {error}", directory.display())) + .map(|entry| entry.expect("directory entry")) + .collect(); + entries.sort_by_key(|entry| entry.file_name()); + for entry in entries { + let name = entry.file_name(); + let name = name.to_str().unwrap_or_else(|| panic!("skill file name is not UTF-8 in {}", directory.display())); + if name.starts_with('.') { + continue; + } + let path = entry.path(); + let file_type = fs::symlink_metadata(&path).expect("skill file metadata").file_type(); + if file_type.is_symlink() { + panic!("refusing to embed a symbolic link: {}", path.display()); + } + if file_type.is_dir() { + collect(root, &path, out); + } else if file_type.is_file() { + let relative = path.strip_prefix(root).expect("skill file under its root"); + let parts: Vec<&str> = + relative.components().map(|component| component.as_os_str().to_str().expect("UTF-8")).collect(); + out.push(parts.join("/")); + } + } +} diff --git a/core/src/assets.rs b/core/src/assets.rs new file mode 100644 index 00000000..d8a581b2 --- /dev/null +++ b/core/src/assets.rs @@ -0,0 +1,170 @@ +//! The shipped skills, compiled into the core (D312). +//! +//! `core/build.rs` embeds every file under `skills/`. Calculations read their +//! shipped text from here on every platform. The desktop crate adds the +//! installed copies in a working directory and the mapping files. + +use std::collections::BTreeMap; + +/// One file compiled into the library. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EmbeddedFile { + /// The path below `skills/` or `mappings/`, with `/` separators. + pub path: &'static str, + pub bytes: &'static [u8], +} + +include!(concat!(env!("OUT_DIR"), "/embedded_skills.rs")); + +/// Every shipped file under `skills/`, sorted by path. +pub fn skill_files() -> &'static [EmbeddedFile] { + SKILL_FILES +} + +/// The shipped text of `skills//SKILL.md`. Installed copies are not read. +pub fn shipped_calculation(name: &str) -> Option<&'static str> { + if name.is_empty() || name.contains('/') { + return None; + } + let wanted = format!("{name}/SKILL.md"); + find_text(SKILL_FILES, &wanted) +} + +/// The skill name `ath apply` reads from its argument: a trailing `.md` and +/// any leading folders are dropped. +pub fn calculation_name(name: &str) -> &str { + let name = name.strip_suffix(".md").unwrap_or(name); + name.rsplit(['/', '\\']).next().unwrap_or(name) +} + +/// The shipped text of a calculation skill named as `ath apply` names it, or +/// the desktop refusal. +pub fn resolve_shipped_calculation(name: &str) -> crate::Result<&'static str> { + let skill_name = calculation_name(name); + shipped_calculation(skill_name) + .ok_or_else(|| crate::Error::not_found(format!("no calculation skill named {skill_name}"))) +} + +/// The text of a file in a sorted table of embedded files. +pub fn find_text(files: &'static [EmbeddedFile], path: &str) -> Option<&'static str> { + files + .binary_search_by(|file| file.path.cmp(path)) + .ok() + .and_then(|index| std::str::from_utf8(files[index].bytes).ok()) +} + +/// The names of the shipped calculation skills: each `SKILL.md` that holds an +/// `ath-calculation` block, sorted. +pub fn shipped_calculation_names() -> Vec<&'static str> { + SKILL_FILES + .iter() + .filter(|file| file.path.ends_with("/SKILL.md")) + .filter(|file| std::str::from_utf8(file.bytes).is_ok_and(|text| text.contains("```ath-calculation"))) + .filter_map(|file| file.path.strip_suffix("/SKILL.md")) + .collect() +} + +/// A frontmatter value: text, or one nested level of `key: value` pairs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FrontmatterValue { + Text(String), + Map(BTreeMap), +} + +/// The frontmatter of a `SKILL.md`: top-level `key: value` pairs and one +/// nested level. Text without a leading `---` block has none. +pub fn read_frontmatter(text: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + let Some(block) = frontmatter_block(text) else { + return out; + }; + let mut nested: Option = None; + for raw in split_lines(block) { + if raw.trim().is_empty() { + continue; + } + let indented = raw.starts_with(char::is_whitespace); + let Some((key, value)) = key_value(raw) else { + continue; + }; + match (&nested, indented) { + (Some(parent), true) => { + if let Some(FrontmatterValue::Map(map)) = out.get_mut(parent) { + map.insert(key.to_string(), unquote(value)); + } + } + _ if value.is_empty() => { + out.insert(key.to_string(), FrontmatterValue::Map(BTreeMap::new())); + nested = Some(key.to_string()); + } + _ => { + nested = None; + out.insert(key.to_string(), FrontmatterValue::Text(unquote(value))); + } + } + } + out +} + +/// `/^---\r?\n([\s\S]*?)\r?\n---/`: the text between the opening `---` line +/// and the first later line that starts with `---`. +fn frontmatter_block(text: &str) -> Option<&str> { + let start = if text.starts_with("---\r\n") { + 5 + } else if text.starts_with("---\n") { + 4 + } else { + return None; + }; + let rest = &text[start..]; + let mut index = 0; + while index <= rest.len() { + let tail = &rest[index..]; + if tail.starts_with("\r\n---") || tail.starts_with("\n---") { + return Some(&rest[..index]); + } + index += tail.chars().next().map_or(1, char::len_utf8); + } + None +} + +/// `text.split(/\r?\n/)`. +fn split_lines(text: &str) -> impl Iterator { + text.split('\n').map(|line| line.strip_suffix('\r').unwrap_or(line)) +} + +/// `/^\s*([A-Za-z_][\w-]*):\s*(.*)$/`. +fn key_value(line: &str) -> Option<(&str, &str)> { + let trimmed = line.trim_start(); + let mut chars = trimmed.char_indices(); + let (_, first) = chars.next()?; + if !(first.is_ascii_alphabetic() || first == '_') { + return None; + } + let mut end = first.len_utf8(); + for (index, character) in chars { + if character.is_ascii_alphanumeric() || character == '_' || character == '-' { + end = index + character.len_utf8(); + } else { + break; + } + } + let rest = trimmed[end..].strip_prefix(':')?; + let value = rest.trim_start(); + if value.contains('\r') || value.contains('\u{2028}') || value.contains('\u{2029}') { + return None; + } + Some((&trimmed[..end], value)) +} + +/// Trim, then remove one pair of matching surrounding quotes. +fn unquote(value: &str) -> String { + let value = value.trim(); + let quoted = value.len() >= 2 + && ((value.starts_with('"') && value.ends_with('"')) || (value.starts_with('\'') && value.ends_with('\''))); + if quoted { + value[1..value.len() - 1].to_string() + } else { + value.to_string() + } +} diff --git a/src/calculate/definition.rs b/core/src/calculate/definition.rs similarity index 97% rename from src/calculate/definition.rs rename to core/src/calculate/definition.rs index f227d98d..b5fec2ff 100644 --- a/src/calculate/definition.rs +++ b/core/src/calculate/definition.rs @@ -249,6 +249,23 @@ impl OneRecordCalculation { } } + /// True for the 3.0.0 methods that read device recordings, the intensity + /// references in effect, or a window of workouts (D302, D322). A memory + /// snapshot refuses them, so they run on a database (D326). + pub fn reads_recordings(&self) -> bool { + use OneRecordCalculation::*; + matches!( + self, + BestMeanEfforts { .. } + | TimeInPowerZones { .. } + | TimeInZonesFromMaximumReference { .. } + | BanisterTrimpFromReferences { .. } + | WorkCapacityBalance { .. } + | PlannedBlocksAgainstLaps + | Thresholds { .. } + ) + } + /// For an operation replaced in 2.1.2, what replaced it and why (D230). pub fn method_notice(&self) -> Option { use OneRecordCalculation::*; diff --git a/src/calculate/hyrox.rs b/core/src/calculate/hyrox.rs similarity index 100% rename from src/calculate/hyrox.rs rename to core/src/calculate/hyrox.rs diff --git a/core/src/calculate/memory.rs b/core/src/calculate/memory.rs new file mode 100644 index 00000000..2fda183f --- /dev/null +++ b/core/src/calculate/memory.rs @@ -0,0 +1,500 @@ +//! Calculations on records an app supplied (D326). +//! +//! A [`SnapshotBuilder`] takes batches of current records, checks each one as +//! a complete current record, and refuses a batch with an invalid record or an +//! ID it already holds. A refused batch leaves the builder as it was. +//! [`SnapshotBuilder::finish`] gives an immutable [`RecordSnapshot`] that +//! answers every calculation request the way the SQLite reader does: the same +//! filters on the same typed fields, and the same order. +//! +//! The supplied records are all the data a calculation sees. A missing source, +//! linked record, or athlete profile has the effect it has in a database that +//! lacks that record: a range input whose source is missing is left out, as +//! the SQL join leaves it out, and a missing profile means no saved timezone. +//! Deleted records may be supplied. They are never inputs, but a deleted +//! source still names its type, as its typed row does in a database. +//! +//! A snapshot does not hold the readings of device recordings yet. A +//! calculation that reads recordings or the intensity reference in effect, +//! such as the 3.0.0 workout operations and the threshold methods, is refused +//! with a message that says to run it on a database. + +use std::collections::{HashMap, HashSet}; + +use super::definition::OneRecordCalculation; +use super::methods::Profile; +use super::range::RecordKind; +use super::reader::{ + CalculationReader, HeartRateRequest, InputRequest, MeasurementType, PeriodRequest, RangeInput, RelatedRequest, + SampleRow, SessionType, +}; +use super::record::{RecordedInputs, StoredRecord}; +use super::window::{ThresholdRequest, ThresholdRun}; +use crate::error::{Error, Result}; +use crate::json::{self, Value}; +use crate::model::{CurrentRecord, PathSegment, RecordData, SourceType}; + +/// One supplied record: what a calculation reads, and the typed record its +/// filters read, as the store's typed tables hold it. +#[derive(Debug, Clone)] +struct Entry { + stored: StoredRecord, + created_at: String, + is_deleted: bool, + record: RecordData, +} + +impl Entry { + fn new(record: CurrentRecord) -> Result { + // The same JSON text the store writes and a calculation reads back. + let data = json::parse(&record.data.to_json())?; + let extensions = match &record.extensions { + Some(map) => Some(json::parse(&json::to_string(&Value::Object(map.clone())))?), + None => None, + }; + Ok(Entry { + stored: StoredRecord { + record_id: record.record_id.clone(), + record_type: record.record_type().as_str().to_string(), + revision: record.current_revision, + data, + extensions, + }, + created_at: record.created_at, + is_deleted: record.is_deleted, + record: record.data, + }) + } + + fn id(&self) -> &str { + &self.stored.record_id + } + + /// The typed value row of a measurement, score, or summary record. + fn value_row(&self) -> Option> { + Some(match &self.record { + RecordData::PointMeasurement(d) => ValueRow { + table: Table::Points, + source_id: &d.source_id, + key: d.quantity.as_str(), + recorded_at: d.recorded_at.as_deref(), + value: d.value.standard_value, + unit: &d.value.standard_unit, + }, + RecordData::MeasurementSample(d) => ValueRow { + table: Table::Samples, + source_id: &d.source_id, + key: d.quantity.as_str(), + recorded_at: Some(&d.recorded_at), + value: d.value.standard_value, + unit: &d.value.standard_unit, + }, + RecordData::ProviderScore(d) => ValueRow { + table: Table::Scores, + source_id: &d.source_id, + key: &d.metric, + recorded_at: d.recorded_at.as_deref(), + value: d.value.standard_value, + unit: &d.value.standard_unit, + }, + RecordData::ProviderSummary(d) => ValueRow { + table: Table::Summaries, + source_id: &d.source_id, + key: &d.summary_type, + recorded_at: d.recorded_at.as_deref(), + value: d.value.standard_value, + unit: &d.value.standard_unit, + }, + _ => return None, + }) + } + + fn input(&self, source_id: &str, recorded_at: &str, value: f64, unit: &str, period: Option) -> RangeInput { + RangeInput { + record_id: self.id().to_string(), + revision: self.stored.revision, + source_id: source_id.to_string(), + recorded_at: recorded_at.to_string(), + value, + unit: unit.to_string(), + period, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Table { + Points, + Samples, + Scores, + Summaries, +} + +/// The typed columns a range filter reads. +struct ValueRow<'a> { + table: Table, + source_id: &'a str, + /// The quantity, metric, or summary type. + key: &'a str, + recorded_at: Option<&'a str>, + value: f64, + unit: &'a str, +} + +/// Collects batches of current records for a [`RecordSnapshot`]. +#[derive(Debug, Default)] +pub struct SnapshotBuilder { + entries: Vec, + ids: HashSet, +} + +impl SnapshotBuilder { + pub fn new() -> Self { + SnapshotBuilder::default() + } + + /// The number of records added so far. + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Add one batch: a JSON array of current records, the shape + /// `ath records list --json` prints and a package holds. Every record is + /// checked as a complete current record. A batch with an invalid record, + /// or a record ID already added, is refused, and nothing in it is added. + /// Returns the number of records held after the batch. + pub fn add_batch(&mut self, batch: &Value) -> Result { + let Value::Array(items) = batch else { + return Err(Error::other("a batch of records must be a JSON array of current records")); + }; + let mut staged = Vec::with_capacity(items.len()); + let mut seen = HashSet::with_capacity(items.len()); + for (index, item) in items.iter().enumerate() { + let record = CurrentRecord::from_value(item) + .map_err(|error| Error::Invalid(error.under(&[PathSegment::Index(index)])))?; + if self.ids.contains(&record.record_id) || !seen.insert(record.record_id.clone()) { + return Err(Error::refused(format!( + "record {} is already in this snapshot; each current record is supplied once", + record.record_id + ))); + } + staged.push(Entry::new(record)?); + } + self.ids.extend(seen); + self.entries.extend(staged); + Ok(self.entries.len()) + } + + /// The finished snapshot. It cannot change. + pub fn finish(self) -> RecordSnapshot { + let by_id = self.entries.iter().enumerate().map(|(index, entry)| (entry.id().to_string(), index)).collect(); + let source_types = self + .entries + .iter() + .filter_map(|entry| match &entry.record { + RecordData::Source(source) => Some((entry.id().to_string(), source.source_type)), + _ => None, + }) + .collect(); + RecordSnapshot { entries: self.entries, by_id, source_types } + } +} + +/// Records an app supplied, ready for calculations. Immutable and safe to share +/// between threads. +#[derive(Debug)] +pub struct RecordSnapshot { + entries: Vec, + by_id: HashMap, + /// Every supplied source, deleted ones included, by record ID. + source_types: HashMap, +} + +impl RecordSnapshot { + /// The number of records supplied, deleted ones included. + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + fn current(&self) -> impl Iterator { + self.entries.iter().filter(|entry| !entry.is_deleted) + } + + /// A range input's source must exist and must not be a manual source, as + /// the SQL join on `sources` requires. + fn device_source(&self, source_id: &str) -> bool { + self.source_types.get(source_id).is_some_and(|source_type| *source_type != SourceType::Manual) + } + + fn first_profile(&self) -> Option<&Entry> { + self.current() + .filter(|entry| matches!(entry.record, RecordData::AthleteProfile(_))) + .min_by(|left, right| (&left.created_at, left.id()).cmp(&(&right.created_at, right.id()))) + } +} + +/// Sort by a text key that may be absent (absent first, as SQL sorts NULL), +/// then by record ID. The sort is stable. +fn sort_by_key_then_id(items: &mut [T], key: impl Fn(&T) -> (Option<&str>, &str)) { + items.sort_by(|left, right| key(left).cmp(&key(right))); +} + +fn within(at: &str, from: &str, to: &str) -> bool { + at >= from && at <= to +} + +/// The refusal for a calculation that reads device recordings or intensity +/// references, which a snapshot does not hold yet (D326). +fn needs_database(operation: &str) -> Error { + Error::refused(format!( + "{operation} reads device recordings and intensity references, which a record snapshot does not hold; run it on a database" + )) +} + +impl CalculationReader for RecordSnapshot { + type Error = Error; + + fn current_record(&self, record_id: &str) -> Result> { + Ok(self + .by_id + .get(record_id) + .map(|index| &self.entries[*index]) + .filter(|entry| !entry.is_deleted) + .map(|entry| entry.stored.clone())) + } + + fn related_records(&self, request: &RelatedRequest<'_>) -> Result> { + let mut found: Vec<(Option<&str>, &Entry)> = Vec::new(); + for entry in self.current() { + let key = match (request, &entry.record) { + (RelatedRequest::PointsOfQuantity { source_id, quantity }, RecordData::PointMeasurement(d)) + if d.source_id == *source_id && d.quantity.as_str() == *quantity => + { + Some(d.recorded_at.as_deref()) + } + ( + RelatedRequest::SessionsOfSource { session_type: SessionType::Sleep, source_id }, + RecordData::SleepSession(d), + ) if d.source_id == *source_id => Some(Some(entry.created_at.as_str())), + ( + RelatedRequest::SessionsOfSource { session_type: SessionType::Workout, source_id }, + RecordData::WorkoutSession(d), + ) if d.source_id == *source_id => Some(Some(entry.created_at.as_str())), + ( + RelatedRequest::MeasurementsInWindow { + measurement_type: MeasurementType::Point, + source_id, + quantity, + from, + to, + }, + RecordData::PointMeasurement(d), + ) if d.source_id == *source_id + && d.quantity.as_str() == *quantity + && d.recorded_at.as_deref().is_some_and(|at| within(at, from, to)) => + { + Some(d.recorded_at.as_deref()) + } + ( + RelatedRequest::MeasurementsInWindow { + measurement_type: MeasurementType::Sample, + source_id, + quantity, + from, + to, + }, + RecordData::MeasurementSample(d), + ) if d.source_id == *source_id + && d.quantity.as_str() == *quantity + && within(&d.recorded_at, from, to) => + { + Some(Some(d.recorded_at.as_str())) + } + (RelatedRequest::SleepStartingInWindow { source_id, from, to }, RecordData::SleepSession(d)) + if d.source_id == *source_id && within(&d.start_at, from, to) => + { + Some(Some(d.start_at.as_str())) + } + _ => None, + }; + if let Some(key) = key { + found.push((key, entry)); + } + } + sort_by_key_then_id(&mut found, |(key, entry)| (*key, entry.id())); + Ok(found.into_iter().map(|(_, entry)| entry.stored.clone()).collect()) + } + + fn heart_rate_samples(&self, request: &HeartRateRequest<'_>) -> Result> { + let mut rows: Vec = self + .current() + .filter_map(|entry| match &entry.record { + RecordData::MeasurementSample(d) + if d.source_id == request.source_id + && d.quantity.as_str() == "heart_rate" + && within(&d.recorded_at, request.start_at, request.end_at) => + { + Some(SampleRow { + recorded_at: d.recorded_at.clone(), + value: d.value.standard_value, + record_id: entry.id().to_string(), + revision: entry.stored.revision, + }) + } + _ => None, + }) + .collect(); + sort_by_key_then_id(&mut rows, |row| (Some(row.recorded_at.as_str()), row.record_id.as_str())); + Ok(rows) + } + + fn athlete_profile(&self) -> Result { + let Some(profile) = self.first_profile() else { + return Ok(Profile::default()); + }; + let text = |key: &str| profile.stored.data.get(key).and_then(Value::as_str).map(str::to_string); + Ok(Profile { + time_zone: text("default_time_zone"), + sex: text("sex"), + birth_year: profile.stored.data.get("birth_year").and_then(Value::as_i64).map(|year| year as i32), + }) + } + + fn saved_time_zone(&self) -> Result> { + Ok(self.first_profile().and_then(|profile| match &profile.record { + RecordData::AthleteProfile(d) => d.default_time_zone.clone(), + _ => None, + })) + } + + fn range_inputs(&self, request: &InputRequest<'_>) -> Result> { + let tables: &[Table] = match request.record_kind { + RecordKind::ProviderScore => &[Table::Scores], + RecordKind::ProviderSummary => &[Table::Summaries], + _ => &[Table::Points, Table::Samples], + }; + let mut rows = Vec::new(); + for entry in self.current() { + let Some(row) = entry.value_row() else { + continue; + }; + let Some(at) = row.recorded_at else { + continue; + }; + if !tables.contains(&row.table) + || row.key != request.quantity + || request.source_id.is_some_and(|source| row.source_id != source) + || request.from.is_some_and(|from| at < from) + || request.to.is_some_and(|to| at > to) + || !self.device_source(row.source_id) + { + continue; + } + rows.push(entry.input(row.source_id, at, row.value, row.unit, None)); + } + rows.sort_by(|left, right| { + (&left.source_id, &left.recorded_at, &left.record_id).cmp(&( + &right.source_id, + &right.recorded_at, + &right.record_id, + )) + }); + rows.truncate(request.limit); + Ok(rows) + } + + fn period_inputs(&self, request: &PeriodRequest<'_>) -> Result> { + // Each base row: the record, its source, and one value, in the order + // of the SQL union. + let mut base: Vec<(&Entry, &str, f64, String)> = Vec::new(); + match request.record_kind { + RecordKind::SessionSummary => { + for wanted in [SessionType::Sleep, SessionType::Workout] { + for entry in &self.entries { + let source_id = match (&entry.record, wanted) { + (RecordData::SleepSession(d), SessionType::Sleep) => &d.source_id, + (RecordData::WorkoutSession(d), SessionType::Workout) => &d.source_id, + _ => continue, + }; + let summaries = entry.stored.data.get("source_reported_summaries").and_then(Value::as_array); + for summary in summaries.into_iter().flatten() { + if summary.get("summary_type").and_then(Value::as_str) != Some(request.quantity) { + continue; + } + let value = summary.get("standard_value").and_then(Value::as_f64).unwrap_or(0.0); + let unit = summary.get("standard_unit").and_then(Value::as_str).unwrap_or("").to_string(); + base.push((entry, source_id, value, unit)); + } + } + } + } + kind => { + let tables: &[Table] = match kind { + RecordKind::ProviderScore => &[Table::Scores], + RecordKind::ProviderSummary => &[Table::Summaries], + _ => &[Table::Points, Table::Samples], + }; + for table in tables { + for entry in &self.entries { + if let Some(row) = entry.value_row() { + if row.table == *table && row.key == request.quantity { + base.push((entry, row.source_id, row.value, row.unit.to_string())); + } + } + } + } + } + } + let mut rows: Vec<(Option, RangeInput)> = Vec::new(); + for (entry, source_id, value, unit) in base { + if entry.is_deleted + || !self.device_source(source_id) + || request.source_id.is_some_and(|source| source_id != source) + { + continue; + } + for period in entry.record.provider_reporting_periods() { + if period.period_type != request.period_type { + continue; + } + let key = period.provider_date.clone().or_else(|| period.start_at.clone()); + let inside = |bound: Option<&str>, keep: fn(&str, &str) -> bool| match bound { + None => true, + Some(bound) => key.as_deref().is_some_and(|key| keep(key, bound)), + }; + if !inside(request.from, |key, from| key >= from) || !inside(request.to, |key, to| key <= to) { + continue; + } + // The same JSON text the store keeps for the period. + let period_value = json::parse(&json::encode(period))?; + rows.push((key, entry.input(source_id, "", value, &unit, Some(period_value)))); + } + } + rows.sort_by(|left, right| { + (&left.1.source_id, &left.0, &left.1.record_id).cmp(&(&right.1.source_id, &right.0, &right.1.record_id)) + }); + rows.truncate(request.limit); + Ok(rows.into_iter().map(|(_, row)| row).collect()) + } + + fn recorded_inputs( + &self, + calculation: &OneRecordCalculation, + _record: &StoredRecord, + _profile: &Profile, + ) -> Result { + Err(needs_database(calculation.operation())) + } + + fn threshold(&self, request: &ThresholdRequest<'_>, _profile: &Profile) -> Result { + Err(needs_database(request.operation)) + } +} diff --git a/src/calculate/methods.rs b/core/src/calculate/methods.rs similarity index 99% rename from src/calculate/methods.rs rename to core/src/calculate/methods.rs index 246b4005..8adeb990 100644 --- a/src/calculate/methods.rs +++ b/core/src/calculate/methods.rs @@ -95,7 +95,7 @@ fn instant(data: &Value, field: &str) -> Option { } /// Heart-rate samples `(offset_ms, bpm)`, sorted by offset. -pub(super) fn sorted_samples(value: &Value) -> Vec<(i64, f64)> { +pub fn sorted_samples(value: &Value) -> Vec<(i64, f64)> { let mut samples: Vec<(i64, f64)> = value .as_array() .map(|items| { diff --git a/core/src/calculate/mod.rs b/core/src/calculate/mod.rs new file mode 100644 index 00000000..333daeeb --- /dev/null +++ b/core/src/calculate/mod.rs @@ -0,0 +1,197 @@ +//! Calculations: typed calculation settings, arithmetic, and receipts (D326). +//! +//! `range` runs the eight named calculations over many records and returns a +//! receipt naming every input revision. `record` runs one editable calculation +//! file on one record. `definition` reads calculation files into typed +//! settings. `recorded`, `workout_ops`, and `window` hold the 3.0.0 methods +//! that read device recordings and intensity references (D302, D322). Every +//! calculation reads through a [`CalculationReader`]: the desktop crate's +//! SQLite reader, or a [`memory::RecordSnapshot`] of records an app supplied. +//! Reading a calculation never writes an athlete record. + +pub mod definition; +pub mod hyrox; +pub mod memory; +pub mod methods; +pub mod range; +pub mod reader; +pub mod record; +pub mod recorded; +mod recorded_inputs; +pub mod window; +pub mod workout_ops; + +use std::collections::BTreeMap; + +pub use definition::{CalculationFile, OneRecordCalculation}; +pub use memory::{RecordSnapshot, SnapshotBuilder}; +pub use range::{ + render_calculation, CalculateOptions, CalculationReceipt, CalculationResult, Group, Operation, RecordKind, + MAX_RECEIPT_REFERENCES, MAX_RUNTIME_INPUTS, +}; +pub use reader::CalculationReader; +pub use record::{ApplyResult, FieldRead, OneRecordResult, StoredRecord, UNKNOWN_OPERATION_HINT}; +pub use window::{ThresholdRequest, ThresholdRun}; + +use crate::error::Error; + +/// Run a named range calculation on what `reader` holds. +pub fn calculate_range( + reader: &R, + options: &CalculateOptions, +) -> Result { + range::calculate(reader, options) +} + +/// Run the calculation skill text `text` on one current record. This is the +/// shared part of `ath apply`: the desktop chooses the installed or shipped +/// file and passes its text; a phone passes a shipped name's text or its own. +/// +/// The order is the 2.1.0 one: find the record, then read the file. A coaching +/// skill and a range calculation are refused with the command that runs them. +/// A threshold file runs on the record as [`apply_with`] runs it. +pub fn apply_text(reader: &R, text: &str, record_id: &str) -> Result { + apply_with(reader, text, Some(record_id), &BTreeMap::new()) +} + +/// A calculation that is not a threshold file, on one record. +fn apply_one(reader: &R, text: &str, record_id: &str) -> Result { + let record = record::stored_record(reader, record_id)?; + let parsed = CalculationFile::parse(text).map_err(|error| coaching_refusal(text).unwrap_or(error))?; + if let OneRecordCalculation::Range(name) = &parsed.calculation { + return Err(range_refusal(name).into()); + } + reader.after_target_read()?; + record::apply_to(reader, &parsed, record) +} + +/// `ath apply` with its 3.0.0 options: a threshold calculation may read a +/// window of records instead of one, and takes `name=value` parameters +/// (D322). Every other calculation needs a record and takes no parameters, +/// and keeps the order of [`apply_text`]. +pub fn apply_with( + reader: &R, + text: &str, + record_id: Option<&str>, + parameters: &BTreeMap, +) -> Result { + let parsed = match CalculationFile::parse(text) { + Ok(parsed) if matches!(parsed.calculation, OneRecordCalculation::Thresholds { .. }) => parsed, + other => { + if let (Some(record_id), true) = (record_id, parameters.is_empty()) { + return apply_one(reader, text, record_id); + } + let parsed = other.map_err(|error| coaching_refusal(text).unwrap_or(error))?; + if !parameters.is_empty() { + return Err(Error::refused(format!( + "{} takes no --set parameters; only threshold calculations do", + parsed.name + )) + .into()); + } + return Err(Error::refused(format!("{} runs on one record: pass --record ", parsed.name)).into()); + } + }; + let OneRecordCalculation::Thresholds { operations, max_gap_s } = &parsed.calculation else { + unreachable!("only a threshold file reaches here") + }; + let operation = parameters.get("operation").cloned().or_else(|| operations.first().cloned()).unwrap_or_default(); + if !operations.contains(&operation) || !window::is_threshold_operation(&operation) { + return Err(Error::refused(format!( + "{} runs one of: {}; {operation} is not one of them", + parsed.name, + operations.join(", ") + )) + .into()); + } + let mut rest = parameters.clone(); + rest.remove("operation"); + let record = record_id.map(|id| record::stored_record(reader, id)).transpose()?; + let profile = reader.athlete_profile()?; + let request = + ThresholdRequest { operation: &operation, record: record.as_ref(), parameters: &rest, max_gap_s: *max_gap_s }; + let run = reader.threshold(&request, &profile)?; + let (result, missing) = match run.outcome { + Ok(outcome) => (Some(OneRecordResult::Threshold(outcome)), Vec::new()), + Err(reason) => (None, vec![reason]), + }; + Ok(ApplyResult { + calculation: parsed.name.clone(), + operation: operation.clone(), + record_id: record_id.map(str::to_string), + fields_read: Vec::new(), + missing, + result, + inputs: (!run.evidence.is_empty()).then(|| range::ReceiptInput { + record_count: run.evidence.len(), + record_references: run.evidence.iter().take(MAX_RECEIPT_REFERENCES).cloned().collect(), + references_truncated: run.evidence.len() > MAX_RECEIPT_REFERENCES, + }), + exclusions: Vec::new(), + method_notice: None, + evidence: run.evidence, + }) +} + +/// `ath apply` on a coaching skill: it gives advice, it does not calculate. +fn coaching_refusal(text: &str) -> Option { + use crate::assets::{read_frontmatter, FrontmatterValue}; + let frontmatter = read_frontmatter(text); + let Some(FrontmatterValue::Map(metadata)) = frontmatter.get("metadata") else { + return None; + }; + if metadata.get("kind").map(String::as_str) != Some("coaching") { + return None; + } + let name = match frontmatter.get("name") { + Some(FrontmatterValue::Text(name)) => name.clone(), + _ => "this".to_string(), + }; + Some(Error::refused(format!( + "{name} is a coaching skill, not a calculation. An agent reads it to plan and review training; `ath apply` runs calculation skills." + ))) +} + +/// `ath apply` on a range calculation (D243): it needs a quantity and a +/// window, not one record, so name the command that runs it. +fn range_refusal(name: &str) -> Error { + let example = match name { + "compare-sources" => "ath calculate compare-sources --source --compare-source ".to_string(), + "correlation" => { + "ath calculate correlation --other-quantity --timezone ".to_string() + } + "workout-drift" => "ath calculate workout-drift heart_rate --session ".to_string(), + "provider-period-summary" => { + "ath calculate provider-period-summary --period-type ".to_string() + } + "coverage" => "ath calculate coverage --timezone ".to_string(), + other => format!("ath calculate {other} "), + }; + Error::refused(format!("{name} is a range calculation over many records, not one record. Run: {example}")) +} + +/// The human text `ath apply` printed. +pub fn render_apply_result(result: &ApplyResult) -> String { + let mut lines = vec![match &result.record_id { + Some(record_id) => format!("{} on {record_id}", result.calculation), + None => format!("{} ({})", result.calculation, result.operation), + }]; + for field in &result.fields_read { + lines.push(format!("read {}: {}", field.field, if field.present { "present" } else { "missing" })); + } + if !result.missing.is_empty() { + lines.push(format!("missing: {}", result.missing.join(", "))); + } + if let Some(inputs) = &result.inputs { + let plural = if inputs.record_count == 1 { "" } else { "s" }; + lines.push(format!("compared with: {} other record{plural}", inputs.record_count)); + } + for exclusion in &result.exclusions { + lines.push(format!("left out: {exclusion}")); + } + if let Some(notice) = &result.method_notice { + lines.push(format!("note: {notice}")); + } + lines.push(crate::json::encode(&result.result)); + lines.join("\n") +} diff --git a/src/calculate/range.rs b/core/src/calculate/range.rs similarity index 73% rename from src/calculate/range.rs rename to core/src/calculate/range.rs index d86f7d1f..f0b85146 100644 --- a/src/calculate/range.rs +++ b/core/src/calculate/range.rs @@ -17,17 +17,16 @@ use std::collections::{BTreeMap, BTreeSet}; use chrono::{DateTime, Datelike, TimeZone, Utc}; use chrono_tz::Tz; -use rusqlite::types::Value as Sql; -use rusqlite::{Connection, OptionalExtension}; use serde::Serialize; use super::definition::shipped_method; +use super::reader::{CalculationReader, InputRequest, PeriodRequest, RangeInput as Input}; use super::record::parse_millis; +use crate::calendar::{resolve_calendar_range_with, CalendarRangeRequest}; use crate::error::{Error, Result}; use crate::json::{self, Value}; use crate::model::{point_measurement_unit, series_quantity_unit, EvidenceReference, PointMeasurementType}; use crate::model::{ProviderReportingPeriodType, SeriesQuantity}; -use crate::view::calendar::{resolve_calendar_range_in, CalendarRangeRequest}; /// `ath-runtime-v2` adds daily means, trend precision, paired source days, /// a correlation minimum, and drift sample counts (D244). @@ -343,18 +342,6 @@ pub struct CalculationReceipt { pub provider_period_type: Option, } -/// One accepted input row. -#[derive(Debug, Clone)] -struct Input { - record_id: String, - revision: u64, - source_id: String, - recorded_at: String, - value: f64, - unit: String, - period: Option, -} - /// The fully resolved request the arithmetic runs on. struct Request<'a> { options: &'a CalculateOptions, @@ -397,42 +384,42 @@ pub fn known_measurement_unit(quantity: &str) -> Result<&'static str> { }) } -/// Run a named range calculation. Reading never writes athlete data. -/// Outside the library, use `calculate::calculate_range`. -pub(crate) fn calculate(connection: &Connection, options: &CalculateOptions) -> Result { +/// Run a named range calculation on what `reader` holds. Reading never +/// writes athlete data. Every input comes from the one reader. +pub fn calculate(reader: &R, options: &CalculateOptions) -> Result { let operation = options.operation; let kind = options.record_kind; let period_summary = operation == Operation::ProviderPeriodSummary; if !period_summary && kind == RecordKind::SessionSummary { - return Err(Error::other("session-summary records require the provider-period-summary operation")); + return Err(Error::other("session-summary records require the provider-period-summary operation").into()); } if period_summary && options.provider_period_type.is_none() { - return Err(Error::other("provider-period-summary needs --period-type ")); + return Err(Error::other("provider-period-summary needs --period-type ").into()); } if options.provider_period_type.is_some() && !period_summary { - return Err(Error::other("--period-type is used only with provider-period-summary")); + return Err(Error::other("--period-type is used only with provider-period-summary").into()); } if operation == Operation::WorkoutDrift && options.workout_session_id.is_none() { - return Err(Error::other("workout-drift needs --session ")); + return Err(Error::other("workout-drift needs --session ").into()); } if operation == Operation::CompareSources && (options.source_id.is_none() || options.compare_source_id.is_none()) { - return Err(Error::other("compare-sources needs --source and --compare-source")); + return Err(Error::other("compare-sources needs --source and --compare-source").into()); } if operation == Operation::Correlation && options.other_quantity.is_none() { - return Err(Error::other("correlation needs --other-quantity")); + return Err(Error::other("correlation needs --other-quantity").into()); } let needs_calendar = !period_summary && operation != Operation::WorkoutDrift && (options.group != Group::None || operation == Operation::Coverage || operation == Operation::Correlation); let (from, to, time_zone) = if needs_calendar { - let range = resolve_calendar_range_in( - connection, + let range = resolve_calendar_range_with( &CalendarRangeRequest { from: options.from.clone(), to: options.to.clone(), time_zone: options.time_zone.clone(), raw: false, }, + || reader.saved_time_zone(), )?; (range.from, range.to, range.time_zone.or_else(|| options.time_zone.clone())) } else { @@ -457,21 +444,22 @@ pub(crate) fn calculate(connection: &Connection, options: &CalculateOptions) -> expected_other_unit, method: shipped_method(operation.as_str()), }; - run(connection, &request) + run(reader, &request) } -fn run(connection: &Connection, request: &Request<'_>) -> Result { +fn run(reader: &R, request: &Request<'_>) -> Result { let options = request.options; let quantity = options.quantity.as_str(); let kind = options.record_kind; if let Some(period_type) = options.provider_period_type { - let inputs = read_period(connection, request, quantity, period_type)?; + let inputs = read_period(reader, request, quantity, period_type)?; if inputs.is_empty() { return Err(Error::other(format!( "No current {} {quantity} records matched {}", kind.as_str(), period_type.as_str() - ))); + )) + .into()); } let unit = one_unit(&inputs, None)?; let method = request.method_or( @@ -492,14 +480,14 @@ fn run(connection: &Connection, request: &Request<'_>) -> Result) -> Result { let mut result = Vec::new(); let daily_zone = if options.operation == Operation::Baseline && options.group == Group::None { - day_zone(connection, request)? + day_zone(reader, request)? } else { None }; @@ -559,43 +547,32 @@ fn run(connection: &Connection, request: &Request<'_>) -> Result coverage(request, unit, &inputs), - Operation::CompareSources => compare_sources(connection, request, unit, inputs), - Operation::Correlation => correlate(connection, request, unit, inputs), + Operation::Coverage => Ok(coverage(request, unit, &inputs)?), + Operation::CompareSources => compare_sources(reader, request, unit, inputs), + Operation::Correlation => correlate(reader, request, unit, inputs), Operation::WorkoutDrift | Operation::ProviderPeriodSummary => { - Err(Error::other(format!("Unsupported calculation operation: {}", options.operation.as_str()))) + Err(Error::other(format!("Unsupported calculation operation: {}", options.operation.as_str())).into()) } } } -fn workout_drift(connection: &Connection, request: &Request<'_>) -> Result { +fn workout_drift(reader: &R, request: &Request<'_>) -> Result { let options = request.options; let session_id = options.workout_session_id.clone().unwrap_or_default(); let not_a_session = || Error::other(format!("{session_id} is not a current workout session")); - let row: Option<(String, String, i64)> = connection - .query_row( - "SELECT records.record_type, record_revisions.record_json, records.is_deleted - FROM records - JOIN record_revisions ON record_revisions.record_id = records.record_id - AND record_revisions.revision = records.current_revision - WHERE records.record_id = ?1", - [&session_id], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), - ) - .optional()?; - let Some((record_type, record_json, deleted)) = row else { - return Err(not_a_session()); + let Some(session) = reader.current_record(&session_id)? else { + return Err(not_a_session().into()); }; - if deleted != 0 || record_type != "workout_session" { - return Err(not_a_session()); + if session.record_type != "workout_session" { + return Err(not_a_session().into()); } - let data = json::parse(&record_json)?; + let data = session.data; let start = data.get("start_at").and_then(Value::as_str).unwrap_or("").to_string(); let end = data.get("end_at").and_then(Value::as_str).unwrap_or("").to_string(); let window = (Some(start.clone()), Some(end.clone())); - let inputs = read_inputs(connection, request, &options.quantity, options.source_id.as_deref(), Some(window))?; + let inputs = read_inputs(reader, request, &options.quantity, options.source_id.as_deref(), Some(window))?; if inputs.len() < 2 { - return Err(Error::other("workout-drift needs at least two samples inside the session")); + return Err(Error::other("workout-drift needs at least two samples inside the session").into()); } let unit = one_unit(&inputs, request.expected_unit)?; let start_ms = parse_ms(&start); @@ -685,23 +662,23 @@ fn coverage(request: &Request<'_>, unit: String, inputs: &[Input]) -> Result( + reader: &R, request: &Request<'_>, unit: String, mut inputs: Vec, -) -> Result { +) -> Result { let options = request.options; let source_id = options.source_id.clone().unwrap_or_default(); let compare_id = options.compare_source_id.clone().unwrap_or_default(); - let other = read_inputs(connection, request, &options.quantity, Some(&compare_id), None)?; + let other = read_inputs(reader, request, &options.quantity, Some(&compare_id), None)?; if other.is_empty() { - return Err(Error::other(format!("No {} records matched --compare-source", options.quantity))); + return Err(Error::other(format!("No {} records matched --compare-source", options.quantity)).into()); } one_unit(&other, Some(&unit)).or_else(|_| one_unit(&other, request.expected_unit))?; let left = summarize(&inputs.iter().map(|input| input.value).collect::>()); let right = summarize(&other.iter().map(|input| input.value).collect::>()); - let paired = match day_zone(connection, request)? { + let paired = match day_zone(reader, request)? { Some(zone) => { let left_days = daily_means(&inputs, &zone)?; let right_days = daily_means(&other, &zone)?; @@ -734,17 +711,17 @@ fn compare_sources( )) } -fn correlate( - connection: &Connection, +fn correlate( + reader: &R, request: &Request<'_>, unit: String, mut inputs: Vec, -) -> Result { +) -> Result { let options = request.options; let other_quantity = options.other_quantity.clone().unwrap_or_default(); let zone = request.time_zone()?; let other_source = options.compare_source_id.as_deref().or(options.source_id.as_deref()); - let other = read_inputs(connection, request, &other_quantity, other_source, None)?; + let other = read_inputs(reader, request, &other_quantity, other_source, None)?; one_unit(&other, request.expected_other_unit)?; let left = daily_means(&inputs, zone)?; let right = daily_means(&other, zone)?; @@ -782,107 +759,30 @@ fn correlate( )) } -/// One branch of the union: a typed table's rows for a quantity, with the -/// source and window filters inside the branch so each uses its lookup index. -fn branch( - table: &str, - quantity_column: &str, - require_instant: bool, - source: Option<&str>, - window: (&Option, &Option), - args: &mut Vec, - quantity: &str, -) -> String { - let mut conditions = vec![format!("{table}.{quantity_column} = ?")]; - args.push(Sql::Text(quantity.to_string())); - if require_instant { - conditions.push(format!("{table}.recorded_at IS NOT NULL")); - } - if let Some(source) = source { - conditions.push(format!("{table}.source_id = ?")); - args.push(Sql::Text(source.to_string())); - } - if let Some(from) = window.0 { - conditions.push(format!("{table}.recorded_at >= ?")); - args.push(Sql::Text(from.clone())); - } - if let Some(to) = window.1 { - conditions.push(format!("{table}.recorded_at <= ?")); - args.push(Sql::Text(to.clone())); - } - format!( - "SELECT {table}.record_id, {table}.source_id, {table}.recorded_at, {table}.standard_value, {table}.standard_unit - FROM {table} WHERE {}", - conditions.join(" AND ") - ) -} - /// Current, non-manual rows with an instant, ordered by source, time, and ID. -fn read_inputs( - connection: &Connection, +fn read_inputs( + reader: &R, request: &Request<'_>, quantity: &str, source: Option<&str>, window: Option<(Option, Option)>, -) -> Result> { - let (sql, args) = inputs_sql(request, quantity, source, window); - let mut statement = connection.prepare(&sql)?; - let rows = statement - .query_map(rusqlite::params_from_iter(args), |row| { - Ok(Input { - record_id: row.get(0)?, - revision: row.get::<_, i64>(1)? as u64, - source_id: row.get(2)?, - recorded_at: row.get(3)?, - value: row.get(4)?, - unit: row.get(5)?, - period: None, - }) - })? - .collect::, _>>()?; +) -> Result, R::Error> { + let (from, to) = window.unwrap_or_else(|| (request.from.clone(), request.to.clone())); + let rows = reader.range_inputs(&InputRequest { + record_kind: request.options.record_kind, + quantity, + source_id: source, + from: from.as_deref(), + to: to.as_deref(), + limit: MAX_RUNTIME_INPUTS + 1, + })?; refuse_too_many(rows.len())?; - crate::package::failpoint!("calculate.after_inputs"); + reader.after_inputs_read()?; Ok(rows) } -/// The SQL and arguments that read instant inputs. Only typed columns are -/// read, and each union branch filters inside itself so it can use its -/// lookup index; no stored record JSON is scanned. -fn inputs_sql( - request: &Request<'_>, - quantity: &str, - source: Option<&str>, - window: Option<(Option, Option)>, -) -> (String, Vec) { - let (from, to) = window.unwrap_or_else(|| (request.from.clone(), request.to.clone())); - let bounds = (&from, &to); - let mut args = Vec::new(); - let values_sql = match request.options.record_kind { - RecordKind::ProviderScore => branch("provider_scores", "metric", true, source, bounds, &mut args, quantity), - RecordKind::ProviderSummary => { - branch("provider_summaries", "summary_type", true, source, bounds, &mut args, quantity) - } - _ => { - let points = branch("point_measurements", "quantity", true, source, bounds, &mut args, quantity); - let samples = branch("measurement_samples", "quantity", false, source, bounds, &mut args, quantity); - format!("{points} UNION ALL {samples}") - } - }; - args.push(Sql::Integer(MAX_RUNTIME_INPUTS as i64 + 1)); - let sql = format!( - "SELECT values_by_record.record_id, records.current_revision, values_by_record.source_id, - values_by_record.recorded_at, values_by_record.standard_value, values_by_record.standard_unit - FROM ({values_sql}) AS values_by_record - JOIN records ON records.record_id = values_by_record.record_id - JOIN sources ON sources.record_id = values_by_record.source_id - WHERE records.is_deleted = 0 AND sources.source_type <> 'manual' - ORDER BY values_by_record.source_id, values_by_record.recorded_at, values_by_record.record_id - LIMIT ?" - ); - (sql, args) -} - -fn refuse_too_many(count: usize) -> Result<()> { +/// The published refusal for more than `MAX_RUNTIME_INPUTS` inputs. +pub fn refuse_too_many(count: usize) -> Result<()> { if count > MAX_RUNTIME_INPUTS { return Err(Error::refused(format!( "Calculation matched more than {MAX_RUNTIME_INPUTS} records. Narrow --from and --to." @@ -892,108 +792,26 @@ fn refuse_too_many(count: usize) -> Result<()> { } /// Current, non-manual rows that carry the requested provider period type. -fn read_period( - connection: &Connection, +fn read_period( + reader: &R, request: &Request<'_>, quantity: &str, period_type: ProviderReportingPeriodType, -) -> Result> { - let (values_sql, mut args): (&str, Vec) = match request.options.record_kind { - RecordKind::ProviderScore => ( - "SELECT provider_scores.record_id, provider_scores.source_id, provider_scores.standard_value, provider_scores.standard_unit - FROM provider_scores WHERE provider_scores.metric = ?", - vec![Sql::Text(quantity.into())], - ), - RecordKind::ProviderSummary => ( - "SELECT provider_summaries.record_id, provider_summaries.source_id, provider_summaries.standard_value, provider_summaries.standard_unit - FROM provider_summaries WHERE provider_summaries.summary_type = ?", - vec![Sql::Text(quantity.into())], - ), - RecordKind::SessionSummary => ( - "SELECT sleep_sessions.record_id, sleep_sessions.source_id, - CAST(json_extract(summary.value, '$.standard_value') AS REAL) AS standard_value, - CAST(json_extract(summary.value, '$.standard_unit') AS TEXT) AS standard_unit - FROM sleep_sessions JOIN json_each(sleep_sessions.data_json, '$.source_reported_summaries') AS summary - WHERE json_extract(summary.value, '$.summary_type') = ? - UNION ALL - SELECT workout_sessions.record_id, workout_sessions.source_id, - CAST(json_extract(summary.value, '$.standard_value') AS REAL), - CAST(json_extract(summary.value, '$.standard_unit') AS TEXT) - FROM workout_sessions JOIN json_each(workout_sessions.data_json, '$.source_reported_summaries') AS summary - WHERE json_extract(summary.value, '$.summary_type') = ?", - vec![Sql::Text(quantity.into()), Sql::Text(quantity.into())], - ), - RecordKind::Measurement => ( - "SELECT point_measurements.record_id, point_measurements.source_id, point_measurements.standard_value, point_measurements.standard_unit - FROM point_measurements WHERE point_measurements.quantity = ? - UNION ALL - SELECT measurement_samples.record_id, measurement_samples.source_id, measurement_samples.standard_value, measurement_samples.standard_unit - FROM measurement_samples WHERE measurement_samples.quantity = ?", - vec![Sql::Text(quantity.into()), Sql::Text(quantity.into())], - ), - }; - let mut conditions = vec![ - "records.is_deleted = 0".to_string(), - "sources.source_type <> 'manual'".to_string(), - "provider_reporting_periods.period_type = ?".to_string(), - ]; - args.push(Sql::Text(period_type.as_str().into())); - if let Some(source) = &request.options.source_id { - conditions.push("values_by_record.source_id = ?".into()); - args.push(Sql::Text(source.clone())); - } - let period_key = "COALESCE(provider_reporting_periods.provider_date, provider_reporting_periods.start_at)"; - if let Some(from) = &request.from { - conditions.push(format!("{period_key} >= ?")); - args.push(Sql::Text(from.clone())); - } - if let Some(to) = &request.to { - conditions.push(format!("{period_key} <= ?")); - args.push(Sql::Text(to.clone())); - } - args.push(Sql::Integer(MAX_RUNTIME_INPUTS as i64 + 1)); - let sql = format!( - "WITH values_by_record AS ({values_sql}) - SELECT values_by_record.record_id, records.current_revision, values_by_record.source_id, - values_by_record.standard_value, values_by_record.standard_unit, provider_reporting_periods.period_json - FROM values_by_record - JOIN records ON records.record_id = values_by_record.record_id - JOIN sources ON sources.record_id = values_by_record.source_id - JOIN provider_reporting_periods ON provider_reporting_periods.owner_record_id = values_by_record.record_id - WHERE {} - ORDER BY values_by_record.source_id, {period_key}, values_by_record.record_id - LIMIT ?", - conditions.join(" AND ") - ); - let mut statement = connection.prepare(&sql)?; - let rows = statement - .query_map(rusqlite::params_from_iter(args), |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, i64>(1)?, - row.get::<_, String>(2)?, - row.get::<_, f64>(3)?, - row.get::<_, String>(4)?, - row.get::<_, String>(5)?, - )) - })? - .collect::, _>>()?; +) -> Result, R::Error> { + let mut rows = reader.period_inputs(&PeriodRequest { + record_kind: request.options.record_kind, + quantity, + period_type, + source_id: request.options.source_id.as_deref(), + from: request.from.as_deref(), + to: request.to.as_deref(), + limit: MAX_RUNTIME_INPUTS + 1, + })?; refuse_too_many(rows.len())?; - rows.into_iter() - .map(|(record_id, revision, source_id, value, unit, period_json)| { - let period = json::parse(&period_json)?; - let recorded_at = period_sort(&period); - Ok(Input { - record_id, - revision: revision as u64, - source_id, - recorded_at, - value, - unit, - period: Some(period), - }) - }) - .collect() + for row in &mut rows { + row.recorded_at = row.period.as_ref().map(period_sort).unwrap_or_default(); + } + Ok(rows) } fn summarize(values: &[f64]) -> NumericSummary { @@ -1114,10 +932,10 @@ fn grouped(inputs: &[&Input], group: Group, zone: &str) -> Result) -> Result> { +fn day_zone(reader: &R, request: &Request<'_>) -> Result, R::Error> { match &request.time_zone { Some(zone) => Ok(Some(zone.clone())), - None => crate::view::calendar::saved_time_zone(connection), + None => reader.saved_time_zone(), } } @@ -1226,7 +1044,7 @@ fn one_unit(inputs: &[Input], expected: Option<&str>) -> Result { /// The local date of an instant. The 2.1.0 range arithmetic read the /// timezone name exactly, so a name in another letter case is refused here. fn calendar_date(timestamp: &str, zone: &str) -> Result { - let tz: Tz = zone.parse().map_err(|_| crate::view::calendar::not_a_time_zone(zone))?; + let tz: Tz = zone.parse().map_err(|_| crate::calendar::not_a_time_zone(zone))?; let instant = DateTime::parse_from_rfc3339(timestamp).map_err(|error| Error::other(error.to_string()))?; Ok(instant.with_timezone(&tz).format("%Y-%m-%d").to_string()) } @@ -1254,7 +1072,9 @@ fn start_of_week(date: &str) -> String { (parsed - chrono::Duration::days(i64::from(day))).format("%Y-%m-%d").to_string() } -fn period_sort(period: &Value) -> String { +/// The sort key of a provider reporting period: its date, else its start, +/// else its provider ID. +pub fn period_sort(period: &Value) -> String { ["provider_date", "start_at", "provider_period_id"] .iter() .find_map(|key| period.get(*key).and_then(Value::as_str)) @@ -1311,62 +1131,3 @@ pub fn render_calculation_value(receipt: &Value) -> String { }); lines.join("\n") } - -#[cfg(test)] -mod tests { - use super::*; - use crate::store::{CreateOptions, Store}; - - fn query_plan(connection: &Connection, sql: &str, args: Vec) -> Vec { - let mut statement = connection.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap(); - statement - .query_map(rusqlite::params_from_iter(args), |row| row.get::<_, String>(3)) - .unwrap() - .map(std::result::Result::unwrap) - .collect() - } - - #[test] - fn bounded_inputs_use_lookup_indexes_and_never_read_stored_json() { - let directory = crate::files::make_temporary_directory("ath-plan-").unwrap(); - let store = Store::create(directory.join("plan.ath.sqlite"), CreateOptions::default()).unwrap(); - for (kind, quantity, tables) in [ - (RecordKind::Measurement, "hrv_rmssd", vec!["point_measurements", "measurement_samples"]), - (RecordKind::ProviderScore, "recovery", vec!["provider_scores"]), - (RecordKind::ProviderSummary, "sleep_need", vec!["provider_summaries"]), - ] { - for (source, from, to) in - [(None, None, None), (Some("s"), Some("2026-01-01T00:00:00.000Z"), Some("2026-02-01T00:00:00.000Z"))] - { - let mut options = CalculateOptions::new(Operation::Summary, quantity); - options.record_kind = kind; - let request = Request { - options: &options, - from: from.map(str::to_string), - to: to.map(str::to_string), - time_zone: None, - expected_unit: None, - expected_other_unit: None, - method: String::new(), - }; - let (sql, args) = inputs_sql(&request, quantity, source, None); - let plan = query_plan(store.connection(), &sql, args); - let text = plan.join("\n"); - for table in &tables { - assert!( - plan.iter() - .any(|step| step.starts_with(&format!("SEARCH {table} USING INDEX {table}_lookup_idx"))), - "{table} does not use its lookup index:\n{text}" - ); - assert!( - !plan.iter().any(|step| step.starts_with(&format!("SCAN {table}"))), - "{table} is scanned:\n{text}" - ); - } - assert!(!text.contains("record_revisions"), "stored JSON is read:\n{text}"); - } - } - drop(store); - std::fs::remove_dir_all(directory).unwrap(); - } -} diff --git a/core/src/calculate/reader.rs b/core/src/calculate/reader.rs new file mode 100644 index 00000000..b47e5fed --- /dev/null +++ b/core/src/calculate/reader.rs @@ -0,0 +1,172 @@ +//! What a calculation reads, and the interface its readers answer (D326). +//! +//! Each method names the data it needs as one of the requests below. Two +//! readers answer them: the desktop crate's SQLite reader runs the indexed +//! queries inside one read snapshot, and [`super::memory::RecordSnapshot`] +//! answers from records an app supplied. Both apply the same filters and +//! return rows in the same order, so the arithmetic and receipts, which live +//! in this crate, give the same results. + +use super::definition::OneRecordCalculation; +use super::methods::Profile; +use super::range::RecordKind; +use super::record::{RecordedInputs, StoredRecord}; +use super::window::{ThresholdRequest, ThresholdRun}; +use crate::json::Value; +use crate::model::ProviderReportingPeriodType; + +/// The table a session request reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionType { + Sleep, + Workout, +} + +/// The table a measurement request reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MeasurementType { + Point, + Sample, +} + +/// Other current records a one-record method compares with its target. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RelatedRequest<'a> { + /// Current point measurements of one source and quantity, ordered by + /// `recorded_at` (records without one first) and then record ID. + PointsOfQuantity { source_id: &'a str, quantity: &'a str }, + /// Current sessions of one source, ordered by creation time and then + /// record ID. + SessionsOfSource { session_type: SessionType, source_id: &'a str }, + /// Current point measurements or samples of one source and quantity + /// recorded from `from` to `to`, both included, ordered by `recorded_at` + /// and then record ID. + MeasurementsInWindow { + measurement_type: MeasurementType, + source_id: &'a str, + quantity: &'a str, + from: &'a str, + to: &'a str, + }, + /// Current sleep sessions of one source that start from `from` to `to`, + /// both included, ordered by start and then record ID. + SleepStartingInWindow { source_id: &'a str, from: &'a str, to: &'a str }, +} + +/// Current heart-rate samples of one source recorded from `start_at` to +/// `end_at`, both included, ordered by `recorded_at` and then record ID. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HeartRateRequest<'a> { + pub source_id: &'a str, + pub start_at: &'a str, + pub end_at: &'a str, +} + +/// One heart-rate sample row. The core reads its time; a row whose time does +/// not read as an instant is left out. +#[derive(Debug, Clone, PartialEq)] +pub struct SampleRow { + pub recorded_at: String, + pub value: f64, + pub record_id: String, + pub revision: u64, +} + +/// One accepted input row of a range calculation. +#[derive(Debug, Clone, PartialEq)] +pub struct RangeInput { + pub record_id: String, + pub revision: u64, + pub source_id: String, + /// The instant. For a provider-period input the core sets it to the + /// period's sort key, so a reader leaves it empty. + pub recorded_at: String, + pub value: f64, + pub unit: String, + /// The provider reporting period, for a provider-period input. + pub period: Option, +} + +/// The instant inputs of a range calculation: current rows of one quantity +/// whose source exists and is not manual, with an instant, inside the bounds +/// when they are given. Rows are ordered by source, instant, and record ID. +/// A reader returns at most `limit` rows; the caller refuses a full answer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InputRequest<'a> { + pub record_kind: RecordKind, + pub quantity: &'a str, + pub source_id: Option<&'a str>, + pub from: Option<&'a str>, + pub to: Option<&'a str>, + pub limit: usize, +} + +/// The provider-period inputs of a range calculation: current rows of one +/// quantity whose source exists and is not manual, one per reporting period +/// of `period_type`, with the period's date or start inside the bounds when +/// they are given. Rows are ordered by source, that date or start, and record +/// ID. A reader returns at most `limit` rows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PeriodRequest<'a> { + pub record_kind: RecordKind, + pub quantity: &'a str, + pub period_type: ProviderReportingPeriodType, + pub source_id: Option<&'a str>, + pub from: Option<&'a str>, + pub to: Option<&'a str>, + pub limit: usize, +} + +/// The data a calculation reads. One reader answers every request of one +/// calculation from the same state of the records. +pub trait CalculationReader { + /// The reader's error. The core's own errors convert into it. + type Error: From; + + /// A current record that is not deleted, or `None`. + fn current_record(&self, record_id: &str) -> Result, Self::Error>; + + fn related_records(&self, request: &RelatedRequest<'_>) -> Result, Self::Error>; + + fn heart_rate_samples(&self, request: &HeartRateRequest<'_>) -> Result, Self::Error>; + + /// The time zone and sex of the first current athlete profile, ordered by + /// creation time and then record ID. Empty without a profile. + fn athlete_profile(&self) -> Result; + + /// The default time zone of a current athlete profile, for calendar days. + fn saved_time_zone(&self) -> Result, Self::Error>; + + fn range_inputs(&self, request: &InputRequest<'_>) -> Result, Self::Error>; + + fn period_inputs(&self, request: &PeriodRequest<'_>) -> Result, Self::Error>; + + /// What a 3.0.0 workout operation reads besides its record (D302): the + /// workout's device recordings, the intensity references in effect on the + /// workout's day in `profile`'s time zone, the latest measured resting + /// heart rate, and for a planned session the workout that carried it out. + /// A reference or reading that cannot be found is a problem in the answer, + /// not an error. + fn recorded_inputs( + &self, + calculation: &OneRecordCalculation, + record: &StoredRecord, + profile: &Profile, + ) -> Result; + + /// Run one threshold method or maximum heart-rate estimate (D322): read + /// the window of workouts, the named workout, or the heart-rate recordings + /// it needs, and return what it found with every record read. + fn threshold(&self, request: &ThresholdRequest<'_>, profile: &Profile) -> Result; + + /// Called after a one-record calculation read its target. The SQLite + /// reader stops here in tests that write during a calculation. + fn after_target_read(&self) -> Result<(), Self::Error> { + Ok(()) + } + + /// Called after a range calculation read its inputs. + fn after_inputs_read(&self) -> Result<(), Self::Error> { + Ok(()) + } +} diff --git a/src/calculate/record.rs b/core/src/calculate/record.rs similarity index 81% rename from src/calculate/record.rs rename to core/src/calculate/record.rs index 163b8645..b938fe54 100644 --- a/src/calculate/record.rs +++ b/core/src/calculate/record.rs @@ -6,12 +6,12 @@ //! result is null; nothing is guessed. Some calculations also read other //! current records of the same source. Nothing is written. -use rusqlite::{params, Connection, OptionalExtension}; use serde::Serialize; use super::definition::{CalculationFile, OneRecordCalculation}; use super::methods::{self, Profile, SeriesSample}; use super::range::{ReceiptInput, MAX_RECEIPT_REFERENCES}; +use super::reader::{CalculationReader, HeartRateRequest, MeasurementType, RelatedRequest, SessionType}; use crate::error::{Error, Result}; use crate::json::{self, Map, Value}; use crate::model::{time, EvidenceReference}; @@ -143,69 +143,30 @@ pub struct RecordedInputs { pub resolved_targets: Vec>, } -/// A current, not deleted record's stored data. -pub(crate) fn stored_record(connection: &Connection, record_id: &str) -> Result { - let row: Option<(String, String, i64, String, Option)> = connection - .query_row( - "SELECT records.record_id, records.record_type, records.current_revision, record_revisions.record_json, - record_revisions.extensions_json - FROM records - JOIN record_revisions - ON record_revisions.record_id = records.record_id - AND record_revisions.revision = records.current_revision - WHERE records.record_id = ?1 AND records.is_deleted = 0", - [record_id], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)), - ) - .optional()?; - let Some((record_id, record_type, revision, record_json, extensions_json)) = row else { - return Err(Error::not_found(format!("record {record_id} was not found: Query returned no rows"))); - }; - let extensions = extensions_json.map(|text| json::parse(&text)).transpose()?; - Ok(StoredRecord { record_id, record_type, revision: revision as u64, data: json::parse(&record_json)?, extensions }) -} - -fn stored_records(connection: &Connection, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { - let mut statement = connection.prepare(sql)?; - let ids = statement.query_map(args, |row| row.get::<_, String>(0))?.collect::, _>>()?; - ids.iter().map(|id| stored_record(connection, id)).collect() +/// A current, not deleted record, or the published refusal. +pub fn stored_record(reader: &R, record_id: &str) -> Result { + match reader.current_record(record_id)? { + Some(record) => Ok(record), + None => Err(Error::not_found(format!("record {record_id} was not found: Query returned no rows")).into()), + } } /// The other current records a change or regularity calculation compares /// against: same-source point measurements of the same quantity, or /// same-source sessions of the same type. The record itself is included. -pub(crate) fn related_records(connection: &Connection, record: &StoredRecord) -> Result> { +pub fn related_records(reader: &R, record: &StoredRecord) -> Result, R::Error> { let Some(source_id) = record.data.get("source_id").and_then(Value::as_str) else { return Ok(Vec::new()); }; match record.record_type.as_str() { "point_measurement" => { let quantity = record.data.get("quantity").and_then(Value::as_str).unwrap_or(""); - stored_records( - connection, - "SELECT records.record_id - FROM point_measurements - JOIN records ON records.record_id = point_measurements.record_id - WHERE point_measurements.source_id = ?1 - AND point_measurements.quantity = ?2 - AND records.is_deleted = 0 - ORDER BY point_measurements.recorded_at, records.record_id", - params![source_id, quantity], - ) + reader.related_records(&RelatedRequest::PointsOfQuantity { source_id, quantity }) } "sleep_session" | "workout_session" => { - let table = if record.record_type == "sleep_session" { "sleep_sessions" } else { "workout_sessions" }; - stored_records( - connection, - &format!( - "SELECT records.record_id - FROM {table} - JOIN records ON records.record_id = {table}.record_id - WHERE {table}.source_id = ?1 AND records.is_deleted = 0 - ORDER BY records.created_at, records.record_id" - ), - params![source_id], - ) + let session_type = + if record.record_type == "sleep_session" { SessionType::Sleep } else { SessionType::Workout }; + reader.related_records(&RelatedRequest::SessionsOfSource { session_type, source_id }) } _ => Ok(Vec::new()), } @@ -213,7 +174,11 @@ pub(crate) fn related_records(connection: &Connection, record: &StoredRecord) -> /// Records of the same source, quantity, and record type for a change /// (D233), or same-source sleep sessions, inside the days a method can use. -fn window_related(connection: &Connection, record: &StoredRecord, days: u32) -> Result> { +fn window_related( + reader: &R, + record: &StoredRecord, + days: u32, +) -> Result, R::Error> { let Some(source_id) = record.data.get("source_id").and_then(Value::as_str) else { return Ok(Vec::new()); }; @@ -228,149 +193,103 @@ fn window_related(connection: &Connection, record: &StoredRecord, days: u32) -> }; match record.record_type.as_str() { "point_measurement" | "measurement_sample" => { - let table = - if record.record_type == "point_measurement" { "point_measurements" } else { "measurement_samples" }; + let measurement_type = if record.record_type == "point_measurement" { + MeasurementType::Point + } else { + MeasurementType::Sample + }; let quantity = record.data.get("quantity").and_then(Value::as_str).unwrap_or(""); let (Some(from), Some(to)) = (bound("recorded_at", -span), bound("recorded_at", 86_400_000)) else { return Ok(Vec::new()); }; - stored_records( - connection, - &format!( - "SELECT records.record_id - FROM {table} - JOIN records ON records.record_id = {table}.record_id - WHERE {table}.source_id = ?1 AND {table}.quantity = ?2 - AND {table}.recorded_at >= ?3 AND {table}.recorded_at <= ?4 - AND records.is_deleted = 0 - ORDER BY {table}.recorded_at, records.record_id" - ), - params![source_id, quantity, from, to], - ) + reader.related_records(&RelatedRequest::MeasurementsInWindow { + measurement_type, + source_id, + quantity, + from: &from, + to: &to, + }) } "sleep_session" => { let (Some(from), Some(to)) = (bound("start_at", -span), bound("end_at", 0)) else { return Ok(Vec::new()); }; - stored_records( - connection, - "SELECT records.record_id - FROM sleep_sessions - JOIN records ON records.record_id = sleep_sessions.record_id - WHERE sleep_sessions.source_id = ?1 - AND sleep_sessions.start_at >= ?2 AND sleep_sessions.start_at <= ?3 - AND records.is_deleted = 0 - ORDER BY sleep_sessions.start_at, records.record_id", - params![source_id, from, to], - ) + reader.related_records(&RelatedRequest::SleepStartingInWindow { source_id, from: &from, to: &to }) } _ => Ok(Vec::new()), } } -/// The current athlete profile's time zone and sex. -pub(crate) fn athlete_profile(connection: &Connection) -> Result { - let json: Option = connection - .query_row( - "SELECT record_revisions.record_json - FROM records - JOIN record_revisions - ON record_revisions.record_id = records.record_id - AND record_revisions.revision = records.current_revision - WHERE records.record_type = 'athlete_profile' AND records.is_deleted = 0 - ORDER BY records.created_at, records.record_id - LIMIT 1", - [], - |row| row.get(0), - ) - .optional()?; - let Some(json) = json else { - return Ok(Profile::default()); - }; - let data = json::parse(&json)?; - let text = |key: &str| data.get(key).and_then(Value::as_str).map(str::to_string); - Ok(Profile { - time_zone: text("default_time_zone"), - sex: text("sex"), - birth_year: data.get("birth_year").and_then(Value::as_i64).map(|year| year as i32), - }) -} - /// Heart-rate samples from the session's source inside the session. -fn session_heart_rate(connection: &Connection, record: &StoredRecord) -> Result> { +fn session_heart_rate(reader: &R, record: &StoredRecord) -> Result, R::Error> { let text = |key: &str| record.data.get(key).and_then(Value::as_str).map(str::to_string); let (Some(source_id), Some(start), Some(end)) = (text("source_id"), text("start_at"), text("end_at")) else { return Ok(Vec::new()); }; - let mut statement = connection.prepare( - "SELECT measurement_samples.recorded_at, measurement_samples.standard_value, - records.record_id, records.current_revision - FROM measurement_samples - JOIN records ON records.record_id = measurement_samples.record_id - WHERE measurement_samples.source_id = ?1 AND measurement_samples.quantity = 'heart_rate' - AND measurement_samples.recorded_at >= ?2 AND measurement_samples.recorded_at <= ?3 - AND records.is_deleted = 0 - ORDER BY measurement_samples.recorded_at, records.record_id", - )?; - let rows = statement - .query_map(params![source_id, start, end], |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, f64>(1)?, row.get::<_, String>(2)?, row.get::<_, i64>(3)?)) - })? - .collect::, _>>()?; + let rows = + reader.heart_rate_samples(&HeartRateRequest { source_id: &source_id, start_at: &start, end_at: &end })?; Ok(rows .into_iter() - .filter_map(|(at, bpm, record_id, revision)| { + .filter_map(|row| { Some(SeriesSample { - at_ms: parse_millis(&at)?, - bpm, - reference: EvidenceReference { record_id, revision: revision as u64 }, + at_ms: parse_millis(&row.recorded_at)?, + bpm: row.value, + reference: EvidenceReference { record_id: row.record_id, revision: row.revision }, }) }) .collect()) } /// Read what a method needs besides the target record. -fn method_inputs(connection: &Connection, file: &CalculationFile, record: &StoredRecord) -> Result { +fn method_inputs( + reader: &R, + file: &CalculationFile, + record: &StoredRecord, +) -> Result { use OneRecordCalculation::*; let mut inputs = MethodInputs::default(); match &file.calculation { NightAgreement { .. } | QuantityChange | SleepChange { .. } => { - inputs.related = related_records(connection, record)?; + inputs.related = related_records(reader, record)?; } EarlierWindowChange(settings) => { - inputs.related = window_related(connection, record, settings.window_days)?; - inputs.profile = athlete_profile(connection)?; + inputs.related = window_related(reader, record, settings.window_days)?; + inputs.profile = reader.athlete_profile()?; } SleepRegularityIndex { window_days, .. } if record.record_type == "sleep_session" => { - inputs.related = window_related(connection, record, *window_days)?; + inputs.related = window_related(reader, record, *window_days)?; } SessionEffortLoad { .. } => { if let Some(id) = record.data.get("workout_session_id").and_then(Value::as_str) { - inputs.linked_workout = stored_record(connection, id).ok(); + inputs.linked_workout = reader.current_record(id).ok().flatten(); } } - BanisterTrimp(_) | SleepClockTimes { .. } => inputs.profile = athlete_profile(connection)?, + BanisterTrimp(_) | SleepClockTimes { .. } => inputs.profile = reader.athlete_profile()?, BestMeanEfforts { .. } | TimeInPowerZones { .. } | TimeInZonesFromMaximumReference { .. } | BanisterTrimpFromReferences { .. } | WorkCapacityBalance { .. } | PlannedBlocksAgainstLaps => { - inputs.profile = athlete_profile(connection)?; - inputs.recorded = super::recorded_inputs::read(connection, &file.calculation, record, &inputs.profile)?; + inputs.profile = reader.athlete_profile()?; + inputs.recorded = reader.recorded_inputs(&file.calculation, record, &inputs.profile)?; } LowestRollingMean(_) if record.record_type == "sleep_session" => { - inputs.heart_rate = session_heart_rate(connection, record)?; + inputs.heart_rate = session_heart_rate(reader, record)?; } _ => {} } Ok(inputs) } -/// Run a calculation file on a record already read. Outside the library, -/// use `calculate::apply`. -pub(crate) fn apply_to(connection: &Connection, file: &CalculationFile, record: StoredRecord) -> Result { - let inputs = method_inputs(connection, file, &record)?; +/// Run a calculation file on a record already read, with what its method +/// reads besides the record. +pub fn apply_to( + reader: &R, + file: &CalculationFile, + record: StoredRecord, +) -> Result { + let inputs = method_inputs(reader, file, &record)?; Ok(run(file, &record, &inputs)) } diff --git a/core/src/calculate/recorded.rs b/core/src/calculate/recorded.rs new file mode 100644 index 00000000..d4407a83 --- /dev/null +++ b/core/src/calculate/recorded.rs @@ -0,0 +1,271 @@ +//! Calculations read device recordings (3.0.0 spec section 6; D302, D305, D306). +//! +//! A calculation reads every recording it needs and lists each recording and +//! revision it read. Readings are placed on a one-second grid counted from +//! the recording's start, under the gap rule below, so every method that +//! reads them treats a gap, a zero, and a timer stop the same way. +//! +//! **The gap rule.** A reading holds its value from its time until the next +//! reading, for at most `max_gap_s` seconds (default 5). An interval reading +//! holds its value for its own duration. A timer stop ends every hold until +//! the timer starts again. A second that no reading holds is uncovered. A +//! stored zero is a value, not a gap. An effort over a duration counts only +//! when every second of it is held. +//! +//! This module holds what a reading of recordings produces and the arithmetic +//! on it. The desktop crate's `calculate::recorded` reads the recordings from +//! SQLite. + +use serde::Serialize; + +use crate::json::Value; +use crate::model::{time, DeviceRecordingData, EvidenceReference, Reading, ReadingValue}; + +/// The default longest hold of one reading, in seconds. +pub const DEFAULT_MAX_GAP_S: u64 = 5; + +/// One recording read for a calculation. +#[derive(Debug, Clone)] +pub struct ReadRecording { + pub reference: EvidenceReference, + pub data: DeviceRecordingData, + pub start_ms: i64, + pub readings: Vec, +} + +impl ReadRecording { + /// The value held in each second from the recording's start, or none when + /// the second is uncovered (the gap rule above). + pub fn grid(&self, max_gap_s: u64) -> Grid { + let max_gap_ms = max_gap_s.max(1) * 1000; + let last_end = + self.readings.iter().map(|reading| reading.offset_ms + reading.duration_ms.unwrap_or(0)).max().unwrap_or(0); + let seconds = (last_end / 1000 + 1) as usize; + let mut values: Vec> = vec![None; seconds]; + let pauses: Vec<(u64, u64)> = + self.data.pauses.iter().flatten().map(|pause| (pause.start_offset_ms, pause.end_offset_ms)).collect(); + for (index, reading) in self.readings.iter().enumerate() { + let ReadingValue::Number(value) = reading.value else { continue }; + let start = reading.offset_ms; + let end = match reading.duration_ms { + Some(duration) if duration > 0 => start + duration, + _ => { + let next = self.readings[index + 1..] + .iter() + .map(|next| next.offset_ms) + .find(|offset| *offset > start) + .unwrap_or(start + 1000); + next.min(start + max_gap_ms) + } + }; + // A timer stop ends the hold. + let end = pauses + .iter() + .filter(|(pause_start, _)| *pause_start >= start && *pause_start < end) + .map(|(pause_start, _)| *pause_start) + .min() + .unwrap_or(end); + let first_second = start.div_ceil(1000); + let mut second = first_second; + while second * 1000 < end && (second as usize) < seconds { + values[second as usize] = Some(value); + second += 1; + } + } + for (pause_start, pause_end) in &pauses { + let from = pause_start.div_ceil(1000) as usize; + let to = (pause_end.div_ceil(1000) as usize).min(seconds); + for slot in values.iter_mut().take(to).skip(from) { + *slot = None; + } + } + Grid { start_ms: self.start_ms, values } + } +} + +/// The value held in each second of a recording. +#[derive(Debug, Clone, PartialEq)] +pub struct Grid { + pub start_ms: i64, + pub values: Vec>, +} + +/// The best mean over one duration. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Effort { + pub duration_s: u64, + pub mean: f64, + pub start_at: String, + pub end_at: String, +} + +impl Grid { + pub fn covered_seconds(&self) -> usize { + self.values.iter().filter(|value| value.is_some()).count() + } + + /// The highest mean over `duration_s` fully held seconds, with the + /// earliest window when two are equal. + pub fn best_mean(&self, duration_s: u64) -> Option { + let duration = duration_s as usize; + if duration == 0 || duration > self.values.len() { + return None; + } + let mut sum = 0.0; + let mut held = 0usize; + let mut best: Option<(f64, usize)> = None; + for end in 0..self.values.len() { + if let Some(value) = self.values[end] { + sum += value; + held += 1; + } + if end >= duration { + if let Some(value) = self.values[end - duration] { + sum -= value; + held -= 1; + } + } + if end + 1 >= duration && held == duration { + let start = end + 1 - duration; + let mean = sum / duration as f64; + if best.is_none_or(|(known, _)| mean > known + 1e-9) { + best = Some((mean, start)); + } + } + } + let (_, start) = best?; + // Recompute the winning window's sum exactly, so rounding drift in the + // running sum does not reach the reported mean. + let exact: f64 = self.values[start..start + duration].iter().map(|value| value.unwrap_or(0.0)).sum(); + Some(Effort { + duration_s, + mean: exact / duration as f64, + start_at: time::format_utc_millis(self.start_ms + start as i64 * 1000), + end_at: time::format_utc_millis(self.start_ms + (start + duration) as i64 * 1000), + }) + } +} + +/// A workout read for a calculation over a window. +#[derive(Debug, Clone)] +pub struct WindowWorkout { + pub reference: EvidenceReference, + pub start_at: String, + pub recordings: Vec, +} + +/// The best mean over each duration across recordings, with the recording +/// and workout each came from. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct WindowEffort { + #[serde(flatten)] + pub effort: Effort, + pub recording_id: String, + pub recording_revision: u64, + pub workout_id: String, + pub source_id: String, +} + +/// The best fully held effort over each duration in a set of workouts. +pub fn best_efforts_in(workouts: &[WindowWorkout], durations_s: &[u64], max_gap_s: u64) -> Vec> { + let mut best: Vec> = vec![None; durations_s.len()]; + for workout in workouts { + for recording in &workout.recordings { + let grid = recording.grid(max_gap_s); + for (index, duration) in durations_s.iter().enumerate() { + let Some(effort) = grid.best_mean(*duration) else { continue }; + if best[index].as_ref().is_none_or(|known| effort.mean > known.effort.mean + 1e-9) { + best[index] = Some(WindowEffort { + effort, + recording_id: recording.reference.record_id.clone(), + recording_revision: recording.reference.revision, + workout_id: workout.reference.record_id.clone(), + source_id: recording.data.source_id.clone(), + }); + } + } + } + } + best +} + +/// A workout's sport and machine from its stored data. +pub fn sport_and_machine(data: &Value) -> (Option, Option) { + ( + data.get("sport").and_then(Value::as_str).and_then(crate::model::Sport::parse), + data.get("machine").and_then(Value::as_str).and_then(crate::model::Machine::parse), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{RecordData, RecordType, RecordingPause}; + + fn recording(readings: Vec<(u64, f64)>, pauses: Vec<(u64, u64)>) -> ReadRecording { + let mut data: DeviceRecordingData = RecordData::decode( + RecordType::DeviceRecording, + &crate::json::parse( + r#"{"source_id":"01890f3e-e7d3-7cc0-88c8-000000000001","received_at":"2026-01-01T00:00:00.000Z", + "received_at_basis":"import_time","quantity":"power","unit":"W","reading_kind":"instant", + "start_at":"2026-01-01T00:00:00.000Z","end_at":"2026-01-01T00:00:00.000Z", + "input_start_timestamp":{"timestamp_text":"2026-01-01T00:00:00.000Z","utc_offset_text":"Z","utc_offset_meaning":"documented_recording_offset","timestamp_basis":"source_instant"},"window_ms":1000,"reading_count":0,"blocks":[]}"#, + ) + .unwrap(), + ) + .map(|data| match data { + RecordData::DeviceRecording(data) => data, + _ => unreachable!(), + }) + .unwrap(); + data.pauses = Some( + pauses + .into_iter() + .map(|(start, end)| RecordingPause { start_offset_ms: start, end_offset_ms: end }) + .collect(), + ); + ReadRecording { + reference: EvidenceReference { record_id: "r".into(), revision: 1 }, + data, + start_ms: 0, + readings: readings + .into_iter() + .map(|(offset, value)| Reading { + offset_ms: offset, + value: ReadingValue::Number(value), + duration_ms: None, + }) + .collect(), + } + } + + #[test] + fn a_reading_holds_until_the_next_for_at_most_the_gap() { + let grid = recording(vec![(0, 100.0), (1000, 200.0), (10_000, 300.0)], Vec::new()).grid(5); + let held: Vec> = grid.values.clone(); + assert_eq!(&held[..3], &[Some(100.0), Some(200.0), Some(200.0)]); + assert_eq!(held[6], None, "a hold stops 5 s after its reading"); + assert_eq!(held[10], Some(300.0)); + assert_eq!( + grid.best_mean(3), + Some(Effort { + duration_s: 3, + mean: 200.0, + start_at: "1970-01-01T00:00:01.000Z".into(), + end_at: "1970-01-01T00:00:04.000Z".into(), + }) + ); + assert!(grid.best_mean(8).is_none(), "an effort with an uncovered second does not count"); + } + + #[test] + fn a_timer_stop_ends_the_hold_and_a_zero_is_a_value() { + let readings: Vec<(u64, f64)> = + (0..10).map(|second| (second * 1000, if second == 2 { 0.0 } else { 100.0 })).collect(); + let grid = recording(readings, vec![(5000, 7000)]).grid(5); + assert_eq!(grid.values[2], Some(0.0)); + assert_eq!((grid.values[5], grid.values[6], grid.values[7]), (None, None, Some(100.0))); + assert_eq!(grid.best_mean(5).unwrap().mean, 80.0); + assert!(grid.best_mean(6).is_none()); + } +} diff --git a/core/src/calculate/recorded_inputs.rs b/core/src/calculate/recorded_inputs.rs new file mode 100644 index 00000000..5849093d --- /dev/null +++ b/core/src/calculate/recorded_inputs.rs @@ -0,0 +1,164 @@ +//! Run the 3.0.0 workout operations on what a reader read for them (D302). +//! +//! A reader answers one request for these operations: the workout's +//! recordings, the intensity references in effect, the resting heart rate, +//! and for a planned session the workout that carried it out. Each problem it +//! found means no result. Every record and revision read is listed. + +use super::definition::OneRecordCalculation; +use super::record::{Context, MethodInputs, OneRecordResult, StoredRecord}; +use super::recorded::ReadRecording; +use super::workout_ops::{self, ReferenceUsed}; +use crate::json::Value; +use crate::model::EvidenceReference; + +fn note_recordings(context: &mut Context<'_>, recordings: &[ReadRecording]) { + context.inputs.extend(recordings.iter().map(|recording| recording.reference.clone())); +} + +fn note_reference(context: &mut Context<'_>, reference: &Option) { + if let Some(reference) = reference { + context.inputs.push(EvidenceReference { record_id: reference.record_id.clone(), revision: reference.revision }); + } +} + +/// The recording with the most covered seconds, when a workout has two. +fn main_recording(recordings: &[ReadRecording], max_gap_s: u64) -> Option<&ReadRecording> { + recordings.iter().max_by_key(|recording| recording.grid(max_gap_s).covered_seconds()) +} + +/// Run an operation on inputs already read. +pub(crate) fn run( + context: &mut Context<'_>, + calculation: &OneRecordCalculation, + record: &StoredRecord, + extra: &MethodInputs, +) -> Option { + use OneRecordCalculation::*; + let inputs = &extra.recorded; + context.missing.extend(inputs.problems.iter().cloned()); + context.exclusions.extend(inputs.notes.iter().cloned()); + note_reference(context, &inputs.maximum); + note_reference(context, &inputs.threshold); + note_reference(context, &inputs.capacity); + if let Some(resting) = &inputs.resting { + context.inputs.push(EvidenceReference { record_id: resting.record_id.clone(), revision: resting.revision }); + } + if !inputs.problems.is_empty() { + return None; + } + // What each operation cannot run without, named when it was not read. + let needed: &[(&str, bool)] = match calculation { + TimeInPowerZones { .. } => &[("threshold_power", inputs.threshold.is_none())], + TimeInZonesFromMaximumReference { .. } => &[("maximum_heart_rate", inputs.maximum.is_none())], + BanisterTrimpFromReferences { .. } => { + &[("maximum_heart_rate", inputs.maximum.is_none()), ("resting_heart_rate", inputs.resting.is_none())] + } + WorkCapacityBalance { .. } => &[ + ("threshold_power", inputs.threshold.is_none()), + ("work_capacity_above_threshold", inputs.capacity.is_none()), + ], + PlannedBlocksAgainstLaps => &[("completed_workout_session_id", inputs.workout.is_none())], + _ => &[], + }; + let absent: Vec = needed.iter().filter(|(_, absent)| *absent).map(|(name, _)| name.to_string()).collect(); + if !absent.is_empty() { + context.missing.extend(absent); + return None; + } + match calculation { + BestMeanEfforts { durations_s, max_gap_s } => { + note_recordings(context, &inputs.power); + note_recordings(context, &inputs.speed); + let result = workout_ops::best_mean_efforts( + &[("power", "W", &inputs.power), ("speed", "m/s", &inputs.speed)], + durations_s, + *max_gap_s, + ); + Some(OneRecordResult::BestEfforts(result)) + } + TimeInPowerZones { cuts, max_gap_s } => { + note_recordings(context, &inputs.power); + let recording = main_recording(&inputs.power, *max_gap_s)?; + let threshold = inputs.threshold.clone()?; + Some(OneRecordResult::PowerZones(workout_ops::time_in_power_zones( + &recording.grid(*max_gap_s), + threshold, + cuts, + *max_gap_s, + ))) + } + TimeInZonesFromMaximumReference { cuts, max_gap_ms } => { + note_recordings(context, &inputs.heart_rate); + let (samples, from) = workout_ops::heart_rate_samples(&record.data, &inputs.heart_rate); + let maximum = inputs.maximum.clone()?; + Some(OneRecordResult::ReferenceZones(workout_ops::time_in_zones_from_reference( + &record.data, + &samples, + from, + maximum, + cuts, + *max_gap_ms, + ))) + } + BanisterTrimpFromReferences { max_gap_ms, male, female } => { + note_recordings(context, &inputs.heart_rate); + let weighting = match extra.profile.sex.as_deref() { + Some("male") => ("male", male.0, male.1), + Some("female") => ("female", female.0, female.1), + _ => { + context + .missing + .push("athlete_profile.sex, which chooses Banister's weighting; it is not guessed".into()); + return None; + } + }; + let (samples, from) = workout_ops::heart_rate_samples(&record.data, &inputs.heart_rate); + match workout_ops::banister_trimp( + &record.data, + &samples, + from, + inputs.maximum.clone()?, + inputs.resting.clone()?, + weighting, + *max_gap_ms, + ) { + Ok(result) => Some(OneRecordResult::ReferenceTrimp(result)), + Err(problem) => { + context.missing.push(problem); + None + } + } + } + WorkCapacityBalance { max_gap_s } => { + note_recordings(context, &inputs.power); + let recording = main_recording(&inputs.power, *max_gap_s)?; + Some(OneRecordResult::Balance(workout_ops::work_capacity_balance( + &recording.grid(*max_gap_s), + inputs.threshold.clone()?, + inputs.capacity.clone()?, + *max_gap_s, + ))) + } + PlannedBlocksAgainstLaps => { + let workout = inputs.workout.as_ref()?; + context.inputs.push(EvidenceReference { record_id: workout.record_id.clone(), revision: workout.revision }); + let steps = workout_ops::planned_steps( + record.data.get("blocks").and_then(Value::as_array).map_or(&[], Vec::as_slice), + ); + let laps = workout.data.get("segments").and_then(Value::as_array).cloned().unwrap_or_default(); + let mut resolved = inputs.resolved_targets.iter().cloned(); + for reference in inputs.resolved_targets.iter().flatten() { + context.inputs.push(EvidenceReference { + record_id: reference.3.record_id.clone(), + revision: reference.3.revision, + }); + } + let result = workout_ops::plan_against_laps(&workout.record_id, &steps, &laps, &mut |_, _| { + resolved.next().flatten() + }); + Some(OneRecordResult::Plan(result)) + } + _ => None, + } +} diff --git a/core/src/calculate/window.rs b/core/src/calculate/window.rs new file mode 100644 index 00000000..66373a04 --- /dev/null +++ b/core/src/calculate/window.rs @@ -0,0 +1,96 @@ +//! What a threshold method or maximum heart-rate estimate is asked, and what +//! it found (3.0.0 spec section 6; D302, D318, D320, D322). +//! +//! A reader answers a [`ThresholdRequest`]: the desktop crate's +//! `calculate::window` reads the window of workouts or the named workout from +//! SQLite and runs the arithmetic in `thresholds`. Nothing is saved. The +//! outcome lists the intensity references a person may save, each with its +//! basis and method, and what they must confirm first. + +use std::collections::BTreeMap; + +use serde::Serialize; + +use super::record::StoredRecord; +use super::recorded::WindowEffort; +use crate::json::Value; +use crate::model::EvidenceReference; +use crate::thresholds::{self as t, EffortLabels}; + +/// An intensity reference a person may save from the outcome. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ReferenceToSave { + pub quantity: String, + pub value: f64, + pub unit: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub sport: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub machine: Option, + pub effective_date: String, + pub basis: String, + pub method: String, + /// The records a saved reference cites; a `model` value cites the saved + /// calculation result instead. + pub evidence: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option, + /// Saved only when the person asks for it specifically (supplement 6). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub only_when_asked: bool, +} + +/// What a threshold method found. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct ThresholdOutcome { + pub operation: String, + pub parameters: BTreeMap, + #[serde(skip_serializing_if = "Option::is_none")] + pub period_start: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub period_end: Option, + /// The method's own result, with the names and units of its study. + pub result: Value, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub efforts: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub labels: Option, + /// What a person must confirm before a value becomes the one in effect. + pub confirm_before_saving: Vec, + pub references_to_save: Vec, +} + +/// What `ath apply` passed in. +pub struct ThresholdRequest<'a> { + pub operation: &'a str, + pub record: Option<&'a StoredRecord>, + pub parameters: &'a BTreeMap, + pub max_gap_s: u64, +} + +/// The outcome, or the plain reason the method refused, and every record read. +pub struct ThresholdRun { + pub outcome: std::result::Result, + pub evidence: Vec, +} + +/// The field tests, which read one workout a person names. +const TESTS: [&str; 5] = [ + t::THREE_MINUTE_ALL_OUT_CYCLING_TEST, + t::THREE_MINUTE_ALL_OUT_ROWING_TEST, + t::THREE_MINUTE_ALL_OUT_RUNNING_TEST, + t::CRITICAL_SWIM_SPEED_400_AND_200_M, + t::THIRTY_MINUTE_RUNNING_TIME_TRIAL, +]; + +/// Every operation a threshold skill may name. +pub fn is_threshold_operation(operation: &str) -> bool { + t::THRESHOLD_OPERATIONS.contains(&operation) + || operation == t::AGE_FORMULA_208_MINUS_0_7_AGE + || operation == t::HIGHEST_HEART_RATE_HELD_5_S +} + +/// True when the operation reads one workout a person names. +pub fn needs_record(operation: &str) -> bool { + TESTS.contains(&operation) +} diff --git a/src/calculate/workout_ops.rs b/core/src/calculate/workout_ops.rs similarity index 99% rename from src/calculate/workout_ops.rs rename to core/src/calculate/workout_ops.rs index 5b62104d..1cbf3c6e 100644 --- a/src/calculate/workout_ops.rs +++ b/core/src/calculate/workout_ops.rs @@ -13,8 +13,8 @@ //! - `planned_blocks_against_laps`: each planned block against the lap that //! carried it out. //! -//! Every function here is arithmetic on inputs already read; `record.rs` -//! reads them and lists every record and revision. +//! Every function here is arithmetic on inputs already read. A calculation +//! reader reads them, and `recorded_inputs` lists every record and revision. use serde::Serialize; diff --git a/core/src/calendar.rs b/core/src/calendar.rs new file mode 100644 index 00000000..c25573d4 --- /dev/null +++ b/core/src/calendar.rs @@ -0,0 +1,254 @@ +//! Calendar days, timezones, and the instants that bound them (D312). +//! +//! A calendar day starts at local midnight in a named timezone. The start is +//! found by asking what the wall clock reads at a candidate instant and moving +//! the candidate by the difference, as the 2.1.0 program did with +//! `Intl.DateTimeFormat`. The same search gives the same answer on days when a +//! clock change moves midnight, and the same refusal when it cannot settle. +//! +//! Timezones come from the bundled zone data, never from the device, so a +//! phone and a desktop give the same answer for the same request. + +use chrono::{FixedOffset, NaiveDateTime, TimeZone, Utc}; +use chrono_tz::Tz; + +use crate::error::{Error, Result}; +use crate::json::Value; +use crate::model::{time, utc_timestamp}; + +/// `UtcTimestamp.parse`: the stored UTC form, or a validation error. +pub fn parse_utc_timestamp(text: &str) -> Result { + utc_timestamp().validate(&Value::String(text.to_string()))?; + Ok(text.to_string()) +} + +/// A timezone accepted for calendar views: an IANA name in any letter case, +/// or a fixed UTC offset such as `+05:30`, which `Intl.DateTimeFormat` also +/// accepts. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Zone { + Named(Tz), + Fixed(FixedOffset), +} + +impl Zone { + /// Read a timezone name. `None` when the name is not a timezone. + pub fn parse(name: &str) -> Option { + if let Some(offset) = parse_offset(name) { + return Some(Zone::Fixed(offset)); + } + crate::model::resolve_time_zone(name).map(Zone::Named) + } + + /// Read a timezone name, or refuse with the published message. + pub fn require(name: &str) -> Result { + Zone::parse(name).ok_or_else(|| not_a_time_zone(name)) + } + + /// The wall-clock time at an instant, to the second. + pub fn wall_time(&self, millis: i64) -> NaiveDateTime { + let instant = Utc.timestamp_millis_opt(millis).single().unwrap_or_default(); + match self { + Zone::Named(zone) => instant.with_timezone(zone).naive_local(), + Zone::Fixed(offset) => instant.with_timezone(offset).naive_local(), + } + } +} + +/// The refusal for a name that is not a timezone. +pub fn not_a_time_zone(name: &str) -> Error { + Error::other(format!("'{name}' is not an IANA timezone such as America/Chicago")) +} + +/// `±HH:MM`, `±HHMM`, or `±HH`. +fn parse_offset(text: &str) -> Option { + let sign = match text.as_bytes().first()? { + b'+' => 1, + b'-' => -1, + _ => return None, + }; + let rest = &text[1..]; + let digits = |part: &str| { + (part.len() == 2 && part.bytes().all(|b| b.is_ascii_digit())).then(|| part.parse::().ok()).flatten() + }; + let (hours, minutes) = match rest.len() { + 2 => (digits(rest)?, 0), + 4 => (digits(&rest[0..2])?, digits(&rest[2..4])?), + 5 if rest.as_bytes()[2] == b':' => (digits(&rest[0..2])?, digits(&rest[3..5])?), + _ => return None, + }; + if hours > 23 || minutes > 59 { + return None; + } + FixedOffset::east_opt(sign * (hours * 3600 + minutes * 60)) +} + +/// True for `YYYY-MM-DD` with ASCII digits. The date may still be invalid. +pub fn looks_like_calendar_date(text: &str) -> bool { + let bytes = text.as_bytes(); + bytes.len() == 10 + && bytes[4] == b'-' + && bytes[7] == b'-' + && bytes.iter().enumerate().all(|(index, byte)| index == 4 || index == 7 || byte.is_ascii_digit()) +} + +/// The parts of a calendar date, or the published refusal. Years below 100 +/// are refused because `Date.UTC` reads them as 19xx. +pub fn calendar_date_parts(text: &str) -> Result<(u32, u32, u32)> { + if !looks_like_calendar_date(text) { + return Err(Error::other(format!("expected YYYY-MM-DD, not '{text}'"))); + } + match time::parse_calendar_date(text) { + Some((year, month, day)) if year >= 100 => Ok((year, month, day)), + _ => Err(Error::other(format!("invalid calendar date '{text}'"))), + } +} + +/// The day after a calendar date. +pub fn next_calendar_date(text: &str) -> Result { + let (year, month, day) = calendar_date_parts(text)?; + let days = time::days_from_civil(i64::from(year), month, day) + 1; + let (year, month, day) = time::civil_from_days(days); + Ok(time::format_date(year, month, day)) +} + +fn wall_millis(wall: NaiveDateTime) -> i64 { + wall.and_utc().timestamp_millis() +} + +/// The first instant of a calendar date in a timezone, in the stored UTC form. +pub fn start_of_date_in_zone(date: &str, zone_name: &str) -> Result { + let (year, month, day) = calendar_date_parts(date)?; + let zone = Zone::require(zone_name)?; + let target = time::days_from_civil(i64::from(year), month, day) * 86_400_000; + let mut candidate = target; + for _ in 0..6 { + let seen = wall_millis(zone.wall_time(candidate)); + let difference = target - seen; + if difference == 0 { + return Ok(time::format_utc_millis(candidate)); + } + candidate += difference; + } + Err(Error::other(format!("could not find the start of {date} in {zone_name}"))) +} + +/// The local calendar date of a timestamp in a timezone. +pub fn calendar_date_in_zone(timestamp: &str, zone_name: &str) -> Result { + let zone = Zone::require(zone_name)?; + let millis = crate::model::js_date_parse(timestamp) + .ok_or_else(|| Error::other(format!("Invalid time value: {timestamp}")))?; + Ok(zone.wall_time(millis).format("%Y-%m-%d").to_string()) +} + +/// A requested time window: calendar days or exact UTC instants. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CalendarRangeRequest { + pub from: Option, + pub to: Option, + pub time_zone: Option, + /// Raw sample reads need a timezone only for calendar-day bounds. + pub raw: bool, +} + +/// A resolved window in exact UTC instants, with the timezone used. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)] +pub struct InstantRange { + #[serde(skip_serializing_if = "Option::is_none")] + pub from: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub to: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub time_zone: Option, +} + +/// Turn calendar-day bounds into UTC instants. A calendar day uses the given +/// timezone, else the athlete profile's, which `saved_time_zone` reads only when +/// it is needed. Exact instants must use the stored UTC form. +pub fn resolve_calendar_range_with>( + request: &CalendarRangeRequest, + saved_time_zone: impl FnOnce() -> std::result::Result, E>, +) -> std::result::Result { + let is_date = |value: &Option| value.as_deref().is_some_and(looks_like_calendar_date); + let needs_time_zone = is_date(&request.from) || is_date(&request.to) || !request.raw; + let time_zone = match &request.time_zone { + Some(zone) => Some(zone.clone()), + None if needs_time_zone => saved_time_zone()?, + None => None, + }; + if needs_time_zone && time_zone.is_none() { + return Err(Error::other( + "a calendar-day series view needs --timezone or a default timezone in the athlete profile", + ) + .into()); + } + if let Some(zone) = &time_zone { + Zone::require(zone)?; + } + let from = match &request.from { + Some(from) if looks_like_calendar_date(from) => { + Some(start_of_date_in_zone(from, time_zone.as_deref().unwrap_or_default())?) + } + Some(from) => Some(parse_utc_timestamp(from)?), + None => None, + }; + let to = match &request.to { + Some(to) if looks_like_calendar_date(to) => { + let next = start_of_date_in_zone(&next_calendar_date(to)?, time_zone.as_deref().unwrap_or_default())?; + Some(time::format_utc_millis(time::parse_utc_timestamp(&next).unwrap_or_default() - 1)) + } + Some(to) => Some(parse_utc_timestamp(to)?), + None => None, + }; + if let (Some(from), Some(to)) = (&from, &to) { + if from > to { + return Err(Error::other("--from must not be after --to").into()); + } + } + Ok(InstantRange { from, to, time_zone }) +} + +/// The cut-off for a historical read. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct AsOfTime { + pub as_of: String, + /// The timezone used when the request named a calendar day. + #[serde(skip_serializing_if = "Option::is_none")] + pub time_zone: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn day_bounds_follow_clock_changes() { + assert_eq!(start_of_date_in_zone("2026-03-08", "America/Chicago").unwrap(), "2026-03-08T06:00:00.000Z"); + assert_eq!(start_of_date_in_zone("2026-03-09", "America/Chicago").unwrap(), "2026-03-09T05:00:00.000Z"); + assert_eq!(start_of_date_in_zone("2026-11-01", "America/Chicago").unwrap(), "2026-11-01T05:00:00.000Z"); + assert_eq!(start_of_date_in_zone("2026-11-02", "america/chicago").unwrap(), "2026-11-02T06:00:00.000Z"); + assert_eq!(start_of_date_in_zone("2026-01-01", "+05:30").unwrap(), "2025-12-31T18:30:00.000Z"); + assert_eq!(start_of_date_in_zone("2026-01-01", "Asia/Kolkata").unwrap(), "2025-12-31T18:30:00.000Z"); + } + + #[test] + fn midnight_that_does_not_exist_is_refused_like_the_old_search() { + // Santiago moves its clocks at midnight, so 2026-09-06 00:00 never occurs. + let error = start_of_date_in_zone("2026-09-06", "America/Santiago"); + assert_eq!( + error.map_err(|error| error.to_string()), + Err("could not find the start of 2026-09-06 in America/Santiago".to_string()) + ); + } + + #[test] + fn dates_are_checked_like_the_old_parser() { + assert_eq!(calendar_date_parts("2026-2-01").unwrap_err().to_string(), "expected YYYY-MM-DD, not '2026-2-01'"); + assert_eq!(calendar_date_parts("2026-02-30").unwrap_err().to_string(), "invalid calendar date '2026-02-30'"); + assert_eq!(calendar_date_parts("0050-01-01").unwrap_err().to_string(), "invalid calendar date '0050-01-01'"); + assert_eq!(next_calendar_date("2026-12-31").unwrap(), "2027-01-01"); + assert_eq!(calendar_date_in_zone("2026-10-02T03:00:00.000Z", "America/Chicago").unwrap(), "2026-10-01"); + assert!(Zone::parse("Z").is_none()); + assert!(Zone::parse("+24:00").is_none()); + } +} diff --git a/core/src/error.rs b/core/src/error.rs new file mode 100644 index 00000000..535fcfa2 --- /dev/null +++ b/core/src/error.rs @@ -0,0 +1,68 @@ +//! Errors the core's checks and calculations return (D312). +//! +//! The variants are the ones a calculation or check can produce. The desktop +//! error type converts from this one with the same codes and messages, and +//! adds the SQLite, file, and migration variants. + +use crate::model::ValidationError; + +#[derive(Debug, Clone, PartialEq)] +pub enum Error { + /// Input does not match the record format. + Invalid(ValidationError), + /// A named record, file, or setting does not exist. + NotFound(String), + /// The operation is refused to protect data. + Refused(String), + /// Any other failure, with its message. + Other(String), +} + +pub type Result = std::result::Result; + +impl Error { + pub fn other(message: impl Into) -> Self { + Error::Other(message.into()) + } + + pub fn refused(message: impl Into) -> Self { + Error::Refused(message.into()) + } + + pub fn not_found(message: impl Into) -> Self { + Error::NotFound(message.into()) + } + + /// The same short names the desktop error uses. + pub fn code(&self) -> &'static str { + match self { + Error::Invalid(_) => "invalid", + Error::NotFound(_) => "not_found", + Error::Refused(_) => "refused", + Error::Other(_) => "error", + } + } +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Invalid(error) => write!(f, "{error}"), + Error::NotFound(message) | Error::Refused(message) | Error::Other(message) => f.write_str(message), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(error: ValidationError) -> Self { + Error::Invalid(error) + } +} + +impl From for Error { + fn from(error: crate::json::JsonError) -> Self { + Error::Other(error.message) + } +} diff --git a/core/src/lib.rs b/core/src/lib.rs index 9d65455c..1baa41cd 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -1,19 +1,29 @@ //! Athletic Standard core (D312): the record model and its checks, the JSON //! rules, the arithmetic of the calculations, and the exact database changes //! a save needs. It has no file, database, or network access, so the native -//! program and the WebAssembly build run the same code. +//! program, the WebAssembly build, and the phone library run the same code. //! //! - `json`: parsing and writing JSON exactly as the format requires. //! - `model`: every record shape, its checks, and the package model. //! - `thresholds`: the arithmetic of the threshold methods and the maximum //! heart-rate estimates (D320, D322). +//! - `calculate`: calculation settings, methods, receipts, and the reader +//! interface they read their data through (D326). +//! - `calendar`: calendar days in a time zone. +//! - `assets`: the shipped skill and calculation text. //! - `engine`: one JSON request in, one answer out; the WebAssembly build's //! only entry point. //! - `save`: the typed rows and child rows a record's current state is //! stored as, and the statements that store them. +pub mod assets; +pub mod calculate; +pub mod calendar; pub mod engine; +mod error; pub mod json; pub mod model; pub mod save; pub mod thresholds; + +pub use error::{Error, Result}; diff --git a/docs/architecture.md b/docs/architecture.md index fecfdde1..b8cd323c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -24,13 +24,16 @@ Paths below are relative to the repository root. | SQLite connections, the one record encoder, writes, reads, migrations, backup, check, repair, stats | `src/store/` | model, files | | Provider imports: detection, readers, matching, staging, preview, apply | `src/import/` | model, store, files | | Complete JSON packages, conflicts, attachments, erasure | `src/package/` | model, store, files | -| Calculations and their receipts | `src/calculate/` | model, store | -| Series and record views, calendar ranges | `src/view/` | model, store | +| Calculation settings, methods, range arithmetic, receipts, threshold outcomes, and the memory reader | `core/src/calculate/` | model, calendar, thresholds | +| The SQLite calculation reader, the reads of recordings, intensity references, and threshold windows, and the database entry points (`ath apply`, `ath calculate`) | `src/calculate/` | core, store | +| Calendar days, timezones, and range bounds | `core/src/calendar.rs` | model | +| Series and record views, the saved profile timezone | `src/view/` | model, store | | Prediction evidence, grading, backtest | `src/prediction/` | model, store, calculate | | `ath log` planning | `src/log.rs` | model, store | | Optional network and system services: password store, model gateways, updates, the Garmin pull, and a local copy of a hosted record (browser sign-in and sync, D313) | `src/runtime/` | model, import, package | | Partial packages and the sync merge two copies of one record share | `src/package/sync.rs` | store | -| Shipped skills and mappings built into the program | `src/assets/` | files | +| Shipped skills, embedded on every platform | `core/src/assets.rs` | nothing | +| Installed skill copies and shipped mappings | `src/assets/` | core, files | | Limits on untrusted input | `src/input_policy.rs` | nothing | | Arguments, help, prompts, rendering | `src/cli/` | everything above | | The npm launcher, JavaScript client, and Zod compatibility facade | `packages/npm/` | the `ath` executable | @@ -57,6 +60,16 @@ Rules that keep this table true: (`src/package/zipped.rs`), and the protocol operations that use them. The phone storage binding builds the library without it, so the store, packages, calculations, and views must not depend on those modules (D327). `mobile/tests/dependencies.rs` checks the result. +- A calculation reads only through `CalculationReader` (D326). Its SQL lives + in `src/calculate/sqlite.rs`, with the 3.0.0 reads of recordings, intensity + references, and threshold windows in `src/calculate/recorded.rs`, + `recorded_inputs.rs`, and `window.rs`. `core/src/calculate/memory.rs` + answers the same requests from supplied records, and refuses the 3.0.0 + recording and threshold requests, which need a database. + `tests/calculate_readers.rs` runs every worked example and every case in + `tests/calculation_support/cases.rs` on both readers and compares the + complete results. A new filter in one reader needs the same filter in the + other and a case that exercises it. - `protocol::run_in_process` runs a protocol operation on a store the caller holds open. The phone binding uses it, so phone edits get the same handlers as the npm client. diff --git a/src/assets/mod.rs b/src/assets/mod.rs index 83d5f503..4f50fcfd 100644 --- a/src/assets/mod.rs +++ b/src/assets/mod.rs @@ -1,7 +1,7 @@ //! Shipped skills and mapping files. //! -//! The files under `skills/` and `mappings/` are compiled into the library by -//! `build.rs`. An executable copied into an empty directory can still install +//! The files under `skills/` are compiled into the core by `core/build.rs`, +//! and the files under `mappings/` into this library by `build.rs`. An executable copied into an empty directory can still install //! the agent skill and read its shipped mappings. Nothing here reads the //! repository at run time. //! @@ -19,21 +19,12 @@ use std::path::{Component, Path, PathBuf}; use crate::error::{Error, Result}; -/// One file compiled into the library. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct EmbeddedFile { - /// The path below `skills/` or `mappings/`, with `/` separators. - pub path: &'static str, - pub bytes: &'static [u8], -} +// The skills are embedded in the core, so every platform has them (D312). +pub(crate) use athleticstandard_core::assets::SKILL_FILES; +pub use athleticstandard_core::assets::{shipped_calculation, shipped_calculation_names, skill_files, EmbeddedFile}; include!(concat!(env!("OUT_DIR"), "/embedded_assets.rs")); -/// Every shipped file under `skills/`, sorted by path. -pub fn skill_files() -> &'static [EmbeddedFile] { - SKILL_FILES -} - /// Every shipped file under `mappings/`, sorted by path. pub fn mapping_files() -> &'static [EmbeddedFile] { MAPPING_FILES @@ -42,23 +33,7 @@ pub fn mapping_files() -> &'static [EmbeddedFile] { /// The shipped text of `mappings/.md`. Installed copies are not read. pub fn shipped_mapping(name: &str) -> Option<&'static str> { let wanted = format!("{name}.md"); - find_text(MAPPING_FILES, &wanted) -} - -/// The shipped text of `skills//SKILL.md`. Installed copies are not read. -pub fn shipped_calculation(name: &str) -> Option<&'static str> { - if name.is_empty() || name.contains('/') { - return None; - } - let wanted = format!("{name}/SKILL.md"); - find_text(SKILL_FILES, &wanted) -} - -fn find_text(files: &'static [EmbeddedFile], path: &str) -> Option<&'static str> { - files - .binary_search_by(|file| file.path.cmp(path)) - .ok() - .and_then(|index| std::str::from_utf8(files[index].bytes).ok()) + athleticstandard_core::assets::find_text(MAPPING_FILES, &wanted) } /// Where a mapping or calculation file came from. @@ -140,10 +115,7 @@ pub fn resolve_calculation(name: &str, cwd: &Path) -> Result { } /// `name.replace(/\.md$/, "").split(/[\\/]/).pop()`. -fn calculation_name(name: &str) -> &str { - let name = name.strip_suffix(".md").unwrap_or(name); - name.rsplit(['/', '\\']).next().unwrap_or(name) -} +use athleticstandard_core::assets::calculation_name; /// Node's `path.resolve(cwd, name)`: join, then remove `.` and `..` without /// reading the file system. diff --git a/src/assets/skill.rs b/src/assets/skill.rs index d208844f..91b92eea 100644 --- a/src/assets/skill.rs +++ b/src/assets/skill.rs @@ -15,7 +15,6 @@ //! Shipped mapping files are copied into `.agents/mappings/` only when that //! copy is missing. An installed mapping file is never replaced. -use std::collections::BTreeMap; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -25,6 +24,7 @@ use sha2::{Digest, Sha256}; use super::{EmbeddedFile, MAPPING_FILES, SKILL_FILES}; use crate::error::{Error, Result}; +pub use athleticstandard_core::assets::{read_frontmatter, FrontmatterValue}; /// The folder name the tool skill installs under, inside each skills directory. pub const SKILL_NAME: &str = "athletic-standard"; @@ -174,13 +174,6 @@ pub struct SkillInstallResult { pub mappings_installed: Vec, } -/// A frontmatter value: text, or one nested level of `key: value` pairs. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum FrontmatterValue { - Text(String), - Map(BTreeMap), -} - /// Shipped skill folder names that contain a `SKILL.md`, sorted. pub fn skill_names() -> Vec<&'static str> { let mut names: Vec<&'static str> = SKILL_FILES @@ -247,104 +240,6 @@ fn files_of(skill: &str) -> impl Iterator BTreeMap { - let mut out = BTreeMap::new(); - let Some(block) = frontmatter_block(text) else { - return out; - }; - let mut nested: Option = None; - for raw in split_lines(block) { - if raw.trim().is_empty() { - continue; - } - let indented = raw.starts_with(char::is_whitespace); - let Some((key, value)) = key_value(raw) else { - continue; - }; - match (&nested, indented) { - (Some(parent), true) => { - if let Some(FrontmatterValue::Map(map)) = out.get_mut(parent) { - map.insert(key.to_string(), unquote(value)); - } - } - _ if value.is_empty() => { - out.insert(key.to_string(), FrontmatterValue::Map(BTreeMap::new())); - nested = Some(key.to_string()); - } - _ => { - nested = None; - out.insert(key.to_string(), FrontmatterValue::Text(unquote(value))); - } - } - } - out -} - -/// `/^---\r?\n([\s\S]*?)\r?\n---/`: the text between the opening `---` line -/// and the first later line that starts with `---`. -fn frontmatter_block(text: &str) -> Option<&str> { - let start = if text.starts_with("---\r\n") { - 5 - } else if text.starts_with("---\n") { - 4 - } else { - return None; - }; - let rest = &text[start..]; - let mut index = 0; - while index <= rest.len() { - let tail = &rest[index..]; - if tail.starts_with("\r\n---") || tail.starts_with("\n---") { - return Some(&rest[..index]); - } - index += tail.chars().next().map_or(1, char::len_utf8); - } - None -} - -/// `text.split(/\r?\n/)`. -fn split_lines(text: &str) -> impl Iterator { - text.split('\n').map(|line| line.strip_suffix('\r').unwrap_or(line)) -} - -/// `/^\s*([A-Za-z_][\w-]*):\s*(.*)$/`. -fn key_value(line: &str) -> Option<(&str, &str)> { - let trimmed = line.trim_start(); - let mut chars = trimmed.char_indices(); - let (_, first) = chars.next()?; - if !(first.is_ascii_alphabetic() || first == '_') { - return None; - } - let mut end = first.len_utf8(); - for (index, character) in chars { - if character.is_ascii_alphanumeric() || character == '_' || character == '-' { - end = index + character.len_utf8(); - } else { - break; - } - } - let rest = trimmed[end..].strip_prefix(':')?; - let value = rest.trim_start(); - if value.contains('\r') || value.contains('\u{2028}') || value.contains('\u{2029}') { - return None; - } - Some((&trimmed[..end], value)) -} - -/// Trim, then remove one pair of matching surrounding quotes. -fn unquote(value: &str) -> String { - let value = value.trim(); - let quoted = value.len() >= 2 - && ((value.starts_with('"') && value.ends_with('"')) || (value.starts_with('\'') && value.ends_with('\''))); - if quoted { - value[1..value.len() - 1].to_string() - } else { - value.to_string() - } -} - fn version_in(text: &str) -> String { match read_frontmatter(text).get("metadata") { Some(FrontmatterValue::Map(map)) => match map.get("version") { diff --git a/src/calculate/mod.rs b/src/calculate/mod.rs index 8adbdcf4..2e90c3ca 100644 --- a/src/calculate/mod.rs +++ b/src/calculate/mod.rs @@ -1,40 +1,41 @@ -//! Calculations: typed calculation settings, arithmetic, and receipts. +//! Calculations on a database (D326). //! -//! `range` runs the eight named calculations over many records and returns a -//! receipt naming every input revision. `record` runs one editable calculation -//! file on one record. `definition` reads calculation files into typed -//! settings and chooses the installed or shipped copy. Reading a calculation -//! never writes an athlete record. +//! The settings, arithmetic, and receipts live in the core +//! (`athleticstandard_core::calculate`), which this module re-exports so the +//! paths stay the same. This module adds the SQLite reader, the 3.0.0 reads of +//! recordings, intensity references, and threshold windows (`recorded`, +//! `recorded_inputs`, `window`), and the database entry points. Every input of +//! one calculation comes from one read snapshot, so a write that commits +//! during the calculation is not seen. -pub mod definition; -pub mod hyrox; -pub mod methods; -pub mod range; -pub mod record; pub mod recorded; mod recorded_inputs; #[cfg(test)] mod snapshot_tests; -pub use athleticstandard_core::thresholds; +mod sqlite; pub mod window; -pub mod workout_ops; +use std::collections::BTreeMap; use std::path::Path; -pub use definition::{CalculationFile, OneRecordCalculation}; -pub use range::{ - render_calculation, CalculateOptions, CalculationReceipt, CalculationResult, Group, Operation, RecordKind, - MAX_RECEIPT_REFERENCES, MAX_RUNTIME_INPUTS, +pub use athleticstandard_core::calculate::{ + definition, hyrox, memory, methods, range, reader, record, render_apply_result, render_calculation, workout_ops, + ApplyResult, CalculateOptions, CalculationFile, CalculationReader, CalculationReceipt, CalculationResult, + FieldRead, Group, OneRecordCalculation, OneRecordResult, Operation, RecordKind, RecordSnapshot, SnapshotBuilder, + StoredRecord, MAX_RECEIPT_REFERENCES, MAX_RUNTIME_INPUTS, UNKNOWN_OPERATION_HINT, }; -pub use record::{ApplyResult, FieldRead, OneRecordResult, UNKNOWN_OPERATION_HINT}; +pub use athleticstandard_core::thresholds; +pub use sqlite::SqliteReader; use crate::error::Result; use crate::store::Store; /// `ath calculate`: run a named range calculation. Every input comes from one -/// read snapshot, so a write that commits during the calculation is not seen. +/// read snapshot. pub fn calculate_range(store: &Store, options: &CalculateOptions) -> Result { - store.read_snapshot(|| range::calculate(store.connection(), options)) + store.read_snapshot(|| { + athleticstandard_core::calculate::calculate_range(&SqliteReader::new(store.connection()), options) + }) } /// `ath apply`: run the calculation file named `calculation` on one current @@ -42,7 +43,7 @@ pub fn calculate_range(store: &Store, options: &CalculateOptions) -> Result Result { - apply_with(store, calculation, Some(record_id), &std::collections::BTreeMap::new(), working_directory) + apply_with(store, calculation, Some(record_id), &BTreeMap::new(), working_directory) } /// `ath apply` with its 3.0.0 options: a threshold calculation may read a @@ -52,131 +53,36 @@ pub fn apply_with( store: &Store, calculation: &str, record_id: Option<&str>, - parameters: &std::collections::BTreeMap, + parameters: &BTreeMap, working_directory: &Path, ) -> Result { - let connection = store.connection(); + // The 2.1.0 order: choose the file, find the record, then read the file. let file = crate::assets::resolve_calculation(calculation, working_directory)?; - // A file that is not a threshold file keeps the 2.1.0 order of checks: - // the record first, then the file. - let parsed = match CalculationFile::parse(&file.text) { - Ok(parsed) if matches!(parsed.calculation, OneRecordCalculation::Thresholds { .. }) => parsed, - other => { - if let (Some(record_id), true) = (record_id, parameters.is_empty()) { - return apply_one(store, &file, record_id); - } - let parsed = other.map_err(|error| coaching_refusal(&file.text).unwrap_or(error))?; - if !parameters.is_empty() { - return Err(crate::error::Error::refused(format!( - "{} takes no --set parameters; only threshold calculations do", - parsed.name - ))); - } - return Err(crate::error::Error::refused(format!( - "{} runs on one record: pass --record ", - parsed.name - ))); - } - }; - if let OneRecordCalculation::Thresholds { operations, max_gap_s } = &parsed.calculation { - let operation = - parameters.get("operation").cloned().or_else(|| operations.first().cloned()).unwrap_or_default(); - if !operations.contains(&operation) || !window::is_threshold_operation(&operation) { - return Err(crate::error::Error::refused(format!( - "{} runs one of: {}; {operation} is not one of them", - parsed.name, - operations.join(", ") - ))); - } - let mut rest = parameters.clone(); - rest.remove("operation"); - return store.read_snapshot(|| { - let record = record_id.map(|id| record::stored_record(connection, id)).transpose()?; - let profile = record::athlete_profile(connection)?; - let request = window::ThresholdRequest { - operation: &operation, - record: record.as_ref(), - parameters: &rest, - max_gap_s: *max_gap_s, - }; - let run = window::run(connection, &request, &profile)?; - let (result, missing) = match run.outcome { - Ok(outcome) => (Some(OneRecordResult::Threshold(outcome)), Vec::new()), - Err(reason) => (None, vec![reason]), - }; - Ok(ApplyResult { - calculation: parsed.name.clone(), - operation: operation.clone(), - record_id: record_id.map(str::to_string), - fields_read: Vec::new(), - missing, - result, - inputs: (!run.evidence.is_empty()).then(|| range::ReceiptInput { - record_count: run.evidence.len(), - record_references: run.evidence.iter().take(MAX_RECEIPT_REFERENCES).cloned().collect(), - references_truncated: run.evidence.len() > MAX_RECEIPT_REFERENCES, - }), - exclusions: Vec::new(), - method_notice: None, - evidence: run.evidence, - }) - }); - } - unreachable!("a threshold file returned above") + apply_text_with(store, &file.text, record_id, parameters) } -fn apply_one(store: &Store, file: &crate::assets::ResolvedAsset, record_id: &str) -> Result { - let connection = store.connection(); - // The 2.1.0 order: choose the file, find the record, then read the file. - store.read_snapshot(|| { - let record = record::stored_record(connection, record_id)?; - let parsed = - CalculationFile::parse(&file.text).map_err(|error| coaching_refusal(&file.text).unwrap_or(error))?; - if let OneRecordCalculation::Range(name) = &parsed.calculation { - return Err(range_refusal(name)); - } - crate::package::failpoint!("calculate.apply_after_target"); - record::apply_to(connection, &parsed, record) - }) +/// Run calculation skill text on one current record of a database, inside +/// one read snapshot. Phones pass a shipped skill's text or their own. +pub fn apply_text(store: &Store, text: &str, record_id: &str) -> Result { + apply_text_with(store, text, Some(record_id), &BTreeMap::new()) } -/// `ath apply` on a coaching skill: it gives advice, it does not calculate. -fn coaching_refusal(text: &str) -> Option { - use crate::assets::skill::{read_frontmatter, FrontmatterValue}; - let frontmatter = read_frontmatter(text); - let Some(FrontmatterValue::Map(metadata)) = frontmatter.get("metadata") else { - return None; - }; - if metadata.get("kind").map(String::as_str) != Some("coaching") { - return None; - } - let name = match frontmatter.get("name") { - Some(FrontmatterValue::Text(name)) => name.clone(), - _ => "this".to_string(), - }; - Some(crate::error::Error::refused(format!( - "{name} is a coaching skill, not a calculation. An agent reads it to plan and review training; `ath apply` runs calculation skills." - ))) -} - -/// `ath apply` on a range calculation (D243): it needs a quantity and a -/// window, not one record, so name the command that runs it. -fn range_refusal(name: &str) -> crate::error::Error { - let example = match name { - "compare-sources" => "ath calculate compare-sources --source --compare-source ".to_string(), - "correlation" => { - "ath calculate correlation --other-quantity --timezone ".to_string() - } - "workout-drift" => "ath calculate workout-drift heart_rate --session ".to_string(), - "provider-period-summary" => { - "ath calculate provider-period-summary --period-type ".to_string() - } - "coverage" => "ath calculate coverage --timezone ".to_string(), - other => format!("ath calculate {other} "), - }; - crate::error::Error::refused(format!( - "{name} is a range calculation over many records, not one record. Run: {example}" - )) +/// Run calculation skill text on a database with the options of +/// [`apply_with`], inside one read snapshot. +pub fn apply_text_with( + store: &Store, + text: &str, + record_id: Option<&str>, + parameters: &BTreeMap, +) -> Result { + store.read_snapshot(|| { + athleticstandard_core::calculate::apply_with( + &SqliteReader::new(store.connection()), + text, + record_id, + parameters, + ) + }) } /// The `calculation_result` a person may save from a result (D308): the @@ -343,29 +249,3 @@ fn unit_of(path: &str) -> &'static str { _ => "number", } } - -/// The human text `ath apply` printed. -pub fn render_apply_result(result: &ApplyResult) -> String { - let mut lines = vec![match &result.record_id { - Some(record_id) => format!("{} on {record_id}", result.calculation), - None => format!("{} ({})", result.calculation, result.operation), - }]; - for field in &result.fields_read { - lines.push(format!("read {}: {}", field.field, if field.present { "present" } else { "missing" })); - } - if !result.missing.is_empty() { - lines.push(format!("missing: {}", result.missing.join(", "))); - } - if let Some(inputs) = &result.inputs { - let plural = if inputs.record_count == 1 { "" } else { "s" }; - lines.push(format!("compared with: {} other record{plural}", inputs.record_count)); - } - for exclusion in &result.exclusions { - lines.push(format!("left out: {exclusion}")); - } - if let Some(notice) = &result.method_notice { - lines.push(format!("note: {notice}")); - } - lines.push(crate::json::encode(&result.result)); - lines.join("\n") -} diff --git a/src/calculate/recorded.rs b/src/calculate/recorded.rs index e3f5c007..211b6ec5 100644 --- a/src/calculate/recorded.rs +++ b/src/calculate/recorded.rs @@ -1,153 +1,20 @@ -//! Calculations read device recordings (3.0.0 spec section 6; D302, D305, D306). +//! Read device recordings and the intensity reference in effect from SQLite +//! for a calculation (3.0.0 spec section 6; D302, D305, D306). //! -//! A calculation reads every recording it needs and lists each recording and -//! revision it read. Readings are placed on a one-second grid counted from -//! the recording's start, under the gap rule below, so every method that -//! reads them treats a gap, a zero, and a timer stop the same way. -//! -//! **The gap rule.** A reading holds its value from its time until the next -//! reading, for at most `max_gap_s` seconds (default 5). An interval reading -//! holds its value for its own duration. A timer stop ends every hold until -//! the timer starts again. A second that no reading holds is uncovered. A -//! stored zero is a value, not a gap. An effort over a duration counts only -//! when every second of it is held. +//! The types and the gap rule live in the core +//! (`athleticstandard_core::calculate::recorded`), which this module +//! re-exports. A calculation reads every recording it needs and lists each +//! recording and revision it read. use rusqlite::{params, Connection}; -use serde::Serialize; - -use crate::error::Result; -use crate::json::Value; -use crate::model::{ - time, DeviceRecordingData, EvidenceReference, Reading, ReadingValue, RecordData, RecordType, RecordingQuantity, -}; - -/// The default longest hold of one reading, in seconds. -pub const DEFAULT_MAX_GAP_S: u64 = 5; - -/// One recording read for a calculation. -#[derive(Debug, Clone)] -pub struct ReadRecording { - pub reference: EvidenceReference, - pub data: DeviceRecordingData, - pub start_ms: i64, - pub readings: Vec, -} - -impl ReadRecording { - /// The value held in each second from the recording's start, or none when - /// the second is uncovered (the gap rule above). - pub fn grid(&self, max_gap_s: u64) -> Grid { - let max_gap_ms = max_gap_s.max(1) * 1000; - let last_end = - self.readings.iter().map(|reading| reading.offset_ms + reading.duration_ms.unwrap_or(0)).max().unwrap_or(0); - let seconds = (last_end / 1000 + 1) as usize; - let mut values: Vec> = vec![None; seconds]; - let pauses: Vec<(u64, u64)> = - self.data.pauses.iter().flatten().map(|pause| (pause.start_offset_ms, pause.end_offset_ms)).collect(); - for (index, reading) in self.readings.iter().enumerate() { - let ReadingValue::Number(value) = reading.value else { continue }; - let start = reading.offset_ms; - let end = match reading.duration_ms { - Some(duration) if duration > 0 => start + duration, - _ => { - let next = self.readings[index + 1..] - .iter() - .map(|next| next.offset_ms) - .find(|offset| *offset > start) - .unwrap_or(start + 1000); - next.min(start + max_gap_ms) - } - }; - // A timer stop ends the hold. - let end = pauses - .iter() - .filter(|(pause_start, _)| *pause_start >= start && *pause_start < end) - .map(|(pause_start, _)| *pause_start) - .min() - .unwrap_or(end); - let first_second = start.div_ceil(1000); - let mut second = first_second; - while second * 1000 < end && (second as usize) < seconds { - values[second as usize] = Some(value); - second += 1; - } - } - for (pause_start, pause_end) in &pauses { - let from = pause_start.div_ceil(1000) as usize; - let to = (pause_end.div_ceil(1000) as usize).min(seconds); - for slot in values.iter_mut().take(to).skip(from) { - *slot = None; - } - } - Grid { start_ms: self.start_ms, values } - } -} -/// The value held in each second of a recording. -#[derive(Debug, Clone, PartialEq)] -pub struct Grid { - pub start_ms: i64, - pub values: Vec>, -} - -/// The best mean over one duration. -#[derive(Debug, Clone, PartialEq, Serialize)] -pub struct Effort { - pub duration_s: u64, - pub mean: f64, - pub start_at: String, - pub end_at: String, -} - -impl Grid { - pub fn covered_seconds(&self) -> usize { - self.values.iter().filter(|value| value.is_some()).count() - } +pub use athleticstandard_core::calculate::recorded::*; - /// The highest mean over `duration_s` fully held seconds, with the - /// earliest window when two are equal. - pub fn best_mean(&self, duration_s: u64) -> Option { - let duration = duration_s as usize; - if duration == 0 || duration > self.values.len() { - return None; - } - let mut sum = 0.0; - let mut held = 0usize; - let mut best: Option<(f64, usize)> = None; - for end in 0..self.values.len() { - if let Some(value) = self.values[end] { - sum += value; - held += 1; - } - if end >= duration { - if let Some(value) = self.values[end - duration] { - sum -= value; - held -= 1; - } - } - if end + 1 >= duration && held == duration { - let start = end + 1 - duration; - let mean = sum / duration as f64; - if best.is_none_or(|(known, _)| mean > known + 1e-9) { - best = Some((mean, start)); - } - } - } - let (_, start) = best?; - // Recompute the winning window's sum exactly, so rounding drift in the - // running sum does not reach the reported mean. - let exact: f64 = self.values[start..start + duration].iter().map(|value| value.unwrap_or(0.0)).sum(); - Some(Effort { - duration_s, - mean: exact / duration as f64, - start_at: time::format_utc_millis(self.start_ms + start as i64 * 1000), - end_at: time::format_utc_millis(self.start_ms + (start + duration) as i64 * 1000), - }) - } -} +use crate::error::Result; +use crate::model::{time, EvidenceReference, RecordData, RecordType, RecordingQuantity}; fn recording_from_row(connection: &Connection, record_id: &str) -> Result> { - let record = super::record::stored_record(connection, record_id)?; + let record = super::sqlite::stored_record(connection, record_id)?; let RecordData::DeviceRecording(data) = RecordData::decode(RecordType::DeviceRecording, &record.data)? else { return Ok(None); }; @@ -184,14 +51,6 @@ pub fn workout_recordings( Ok(out) } -/// A workout read for a calculation over a window. -#[derive(Debug, Clone)] -pub struct WindowWorkout { - pub reference: EvidenceReference, - pub start_at: String, - pub recordings: Vec, -} - /// The current workouts with this sport and machine that start inside /// `[from_ms, to_ms]`, each with its recordings of one quantity. `machine: /// unknown` never matches (D295), so it is refused before this is called. @@ -227,41 +86,6 @@ pub fn window_workouts( Ok(out) } -/// The best mean over each duration across recordings, with the recording -/// and workout each came from. -#[derive(Debug, Clone, PartialEq, Serialize)] -pub struct WindowEffort { - #[serde(flatten)] - pub effort: Effort, - pub recording_id: String, - pub recording_revision: u64, - pub workout_id: String, - pub source_id: String, -} - -/// The best fully held effort over each duration in a set of workouts. -pub fn best_efforts_in(workouts: &[WindowWorkout], durations_s: &[u64], max_gap_s: u64) -> Vec> { - let mut best: Vec> = vec![None; durations_s.len()]; - for workout in workouts { - for recording in &workout.recordings { - let grid = recording.grid(max_gap_s); - for (index, duration) in durations_s.iter().enumerate() { - let Some(effort) = grid.best_mean(*duration) else { continue }; - if best[index].as_ref().is_none_or(|known| effort.mean > known.effort.mean + 1e-9) { - best[index] = Some(WindowEffort { - effort, - recording_id: recording.reference.record_id.clone(), - recording_revision: recording.reference.revision, - workout_id: workout.reference.record_id.clone(), - source_id: recording.data.source_id.clone(), - }); - } - } - } - } - best -} - /// The value in effect for a quantity on a date, read for a calculation. pub fn reference_in_effect( connection: &Connection, @@ -282,84 +106,3 @@ pub fn reference_in_effect( }, ) } - -/// A workout's sport and machine from its stored data. -pub fn sport_and_machine(data: &Value) -> (Option, Option) { - ( - data.get("sport").and_then(Value::as_str).and_then(crate::model::Sport::parse), - data.get("machine").and_then(Value::as_str).and_then(crate::model::Machine::parse), - ) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::model::RecordingPause; - - fn recording(readings: Vec<(u64, f64)>, pauses: Vec<(u64, u64)>) -> ReadRecording { - let mut data: DeviceRecordingData = RecordData::decode( - RecordType::DeviceRecording, - &crate::json::parse( - r#"{"source_id":"01890f3e-e7d3-7cc0-88c8-000000000001","received_at":"2026-01-01T00:00:00.000Z", - "received_at_basis":"import_time","quantity":"power","unit":"W","reading_kind":"instant", - "start_at":"2026-01-01T00:00:00.000Z","end_at":"2026-01-01T00:00:00.000Z", - "input_start_timestamp":{"timestamp_text":"2026-01-01T00:00:00.000Z","utc_offset_text":"Z","utc_offset_meaning":"documented_recording_offset","timestamp_basis":"source_instant"},"window_ms":1000,"reading_count":0,"blocks":[]}"#, - ) - .unwrap(), - ) - .map(|data| match data { - RecordData::DeviceRecording(data) => data, - _ => unreachable!(), - }) - .unwrap(); - data.pauses = Some( - pauses - .into_iter() - .map(|(start, end)| RecordingPause { start_offset_ms: start, end_offset_ms: end }) - .collect(), - ); - ReadRecording { - reference: EvidenceReference { record_id: "r".into(), revision: 1 }, - data, - start_ms: 0, - readings: readings - .into_iter() - .map(|(offset, value)| Reading { - offset_ms: offset, - value: ReadingValue::Number(value), - duration_ms: None, - }) - .collect(), - } - } - - #[test] - fn a_reading_holds_until_the_next_for_at_most_the_gap() { - let grid = recording(vec![(0, 100.0), (1000, 200.0), (10_000, 300.0)], Vec::new()).grid(5); - let held: Vec> = grid.values.clone(); - assert_eq!(&held[..3], &[Some(100.0), Some(200.0), Some(200.0)]); - assert_eq!(held[6], None, "a hold stops 5 s after its reading"); - assert_eq!(held[10], Some(300.0)); - assert_eq!( - grid.best_mean(3), - Some(Effort { - duration_s: 3, - mean: 200.0, - start_at: "1970-01-01T00:00:01.000Z".into(), - end_at: "1970-01-01T00:00:04.000Z".into(), - }) - ); - assert!(grid.best_mean(8).is_none(), "an effort with an uncovered second does not count"); - } - - #[test] - fn a_timer_stop_ends_the_hold_and_a_zero_is_a_value() { - let readings: Vec<(u64, f64)> = - (0..10).map(|second| (second * 1000, if second == 2 { 0.0 } else { 100.0 })).collect(); - let grid = recording(readings, vec![(5000, 7000)]).grid(5); - assert_eq!(grid.values[2], Some(0.0)); - assert_eq!((grid.values[5], grid.values[6], grid.values[7]), (None, None, Some(100.0))); - assert_eq!(grid.best_mean(5).unwrap().mean, 80.0); - assert!(grid.best_mean(6).is_none()); - } -} diff --git a/src/calculate/recorded_inputs.rs b/src/calculate/recorded_inputs.rs index 16e7593d..4ef78b69 100644 --- a/src/calculate/recorded_inputs.rs +++ b/src/calculate/recorded_inputs.rs @@ -1,4 +1,5 @@ -//! Read what the 3.0.0 workout operations need, then run them (D302). +//! Read what the 3.0.0 workout operations need from SQLite (D302). The core's +//! `calculate::recorded_inputs` runs them on what this reads. //! //! The intensity reference in effect is the one for the workout's sport and //! machine on the workout's day in the athlete's time zone (D294). A maximum @@ -11,8 +12,9 @@ use rusqlite::{params, Connection, OptionalExtension}; use super::definition::OneRecordCalculation; use super::methods::Profile; -use super::record::{stored_record, Context, MethodInputs, OneRecordResult, RecordedInputs, StoredRecord}; -use super::recorded::{workout_recordings, ReadRecording}; +use super::record::{RecordedInputs, StoredRecord}; +use super::recorded::workout_recordings; +use super::sqlite::stored_record; use super::workout_ops::{self, ReferenceUsed, RestingUsed}; use crate::error::Result; use crate::json::Value; @@ -117,7 +119,7 @@ fn resting(connection: &Connection, date: &str, profile: &Profile) -> Result Result, recordings: &[ReadRecording]) { - context.inputs.extend(recordings.iter().map(|recording| recording.reference.clone())); -} - -fn note_reference(context: &mut Context<'_>, reference: &Option) { - if let Some(reference) = reference { - context.inputs.push(EvidenceReference { record_id: reference.record_id.clone(), revision: reference.revision }); - } -} - -/// The recording with the most covered seconds, when a workout has two. -fn main_recording(recordings: &[ReadRecording], max_gap_s: u64) -> Option<&ReadRecording> { - recordings.iter().max_by_key(|recording| recording.grid(max_gap_s).covered_seconds()) -} - -/// Run an operation on inputs already read. -pub(super) fn run( - context: &mut Context<'_>, - calculation: &OneRecordCalculation, - record: &StoredRecord, - extra: &MethodInputs, -) -> Option { - use OneRecordCalculation::*; - let inputs = &extra.recorded; - context.missing.extend(inputs.problems.iter().cloned()); - context.exclusions.extend(inputs.notes.iter().cloned()); - note_reference(context, &inputs.maximum); - note_reference(context, &inputs.threshold); - note_reference(context, &inputs.capacity); - if let Some(resting) = &inputs.resting { - context.inputs.push(EvidenceReference { record_id: resting.record_id.clone(), revision: resting.revision }); - } - if !inputs.problems.is_empty() { - return None; - } - // What each operation cannot run without, named when it was not read. - let needed: &[(&str, bool)] = match calculation { - TimeInPowerZones { .. } => &[("threshold_power", inputs.threshold.is_none())], - TimeInZonesFromMaximumReference { .. } => &[("maximum_heart_rate", inputs.maximum.is_none())], - BanisterTrimpFromReferences { .. } => { - &[("maximum_heart_rate", inputs.maximum.is_none()), ("resting_heart_rate", inputs.resting.is_none())] - } - WorkCapacityBalance { .. } => &[ - ("threshold_power", inputs.threshold.is_none()), - ("work_capacity_above_threshold", inputs.capacity.is_none()), - ], - PlannedBlocksAgainstLaps => &[("completed_workout_session_id", inputs.workout.is_none())], - _ => &[], - }; - let absent: Vec = needed.iter().filter(|(_, absent)| *absent).map(|(name, _)| name.to_string()).collect(); - if !absent.is_empty() { - context.missing.extend(absent); - return None; - } - match calculation { - BestMeanEfforts { durations_s, max_gap_s } => { - note_recordings(context, &inputs.power); - note_recordings(context, &inputs.speed); - let result = workout_ops::best_mean_efforts( - &[("power", "W", &inputs.power), ("speed", "m/s", &inputs.speed)], - durations_s, - *max_gap_s, - ); - Some(OneRecordResult::BestEfforts(result)) - } - TimeInPowerZones { cuts, max_gap_s } => { - note_recordings(context, &inputs.power); - let recording = main_recording(&inputs.power, *max_gap_s)?; - let threshold = inputs.threshold.clone()?; - Some(OneRecordResult::PowerZones(workout_ops::time_in_power_zones( - &recording.grid(*max_gap_s), - threshold, - cuts, - *max_gap_s, - ))) - } - TimeInZonesFromMaximumReference { cuts, max_gap_ms } => { - note_recordings(context, &inputs.heart_rate); - let (samples, from) = workout_ops::heart_rate_samples(&record.data, &inputs.heart_rate); - let maximum = inputs.maximum.clone()?; - Some(OneRecordResult::ReferenceZones(workout_ops::time_in_zones_from_reference( - &record.data, - &samples, - from, - maximum, - cuts, - *max_gap_ms, - ))) - } - BanisterTrimpFromReferences { max_gap_ms, male, female } => { - note_recordings(context, &inputs.heart_rate); - let weighting = match extra.profile.sex.as_deref() { - Some("male") => ("male", male.0, male.1), - Some("female") => ("female", female.0, female.1), - _ => { - context - .missing - .push("athlete_profile.sex, which chooses Banister's weighting; it is not guessed".into()); - return None; - } - }; - let (samples, from) = workout_ops::heart_rate_samples(&record.data, &inputs.heart_rate); - match workout_ops::banister_trimp( - &record.data, - &samples, - from, - inputs.maximum.clone()?, - inputs.resting.clone()?, - weighting, - *max_gap_ms, - ) { - Ok(result) => Some(OneRecordResult::ReferenceTrimp(result)), - Err(problem) => { - context.missing.push(problem); - None - } - } - } - WorkCapacityBalance { max_gap_s } => { - note_recordings(context, &inputs.power); - let recording = main_recording(&inputs.power, *max_gap_s)?; - Some(OneRecordResult::Balance(workout_ops::work_capacity_balance( - &recording.grid(*max_gap_s), - inputs.threshold.clone()?, - inputs.capacity.clone()?, - *max_gap_s, - ))) - } - PlannedBlocksAgainstLaps => { - let workout = inputs.workout.as_ref()?; - context.inputs.push(EvidenceReference { record_id: workout.record_id.clone(), revision: workout.revision }); - let steps = workout_ops::planned_steps( - record.data.get("blocks").and_then(Value::as_array).map_or(&[], Vec::as_slice), - ); - let laps = workout.data.get("segments").and_then(Value::as_array).cloned().unwrap_or_default(); - let mut resolved = inputs.resolved_targets.iter().cloned(); - for reference in inputs.resolved_targets.iter().flatten() { - context.inputs.push(EvidenceReference { - record_id: reference.3.record_id.clone(), - revision: reference.3.revision, - }); - } - let result = workout_ops::plan_against_laps(&workout.record_id, &steps, &laps, &mut |_, _| { - resolved.next().flatten() - }); - Some(OneRecordResult::Plan(result)) - } - _ => None, - } -} diff --git a/src/calculate/sqlite.rs b/src/calculate/sqlite.rs new file mode 100644 index 00000000..c814ba3e --- /dev/null +++ b/src/calculate/sqlite.rs @@ -0,0 +1,455 @@ +//! The SQLite reader for calculations (D326). +//! +//! Each request runs the indexed query the desktop has always run: typed +//! columns only, with the source and window filters inside each union branch +//! so each branch uses its lookup index. The caller holds one read snapshot +//! around a calculation, so every request sees the same database state. The +//! arithmetic and receipts live in the core. + +use rusqlite::types::Value as Sql; +use rusqlite::{params, Connection, OptionalExtension}; + +use athleticstandard_core::calculate::methods::Profile; +use athleticstandard_core::calculate::reader::{ + CalculationReader, HeartRateRequest, InputRequest, MeasurementType, PeriodRequest, RangeInput, RelatedRequest, + SampleRow, SessionType, +}; +use athleticstandard_core::calculate::record::RecordedInputs; +use athleticstandard_core::calculate::window::{ThresholdRequest, ThresholdRun}; +use athleticstandard_core::calculate::{OneRecordCalculation, RecordKind, StoredRecord}; + +use crate::error::{Error, Result}; +use crate::json::{self, Value}; + +/// A current, not deleted record, or the published refusal. The desktop's +/// own 3.0.0 reads (recordings, plans, threshold windows) use it. +pub(crate) fn stored_record(connection: &Connection, record_id: &str) -> Result { + athleticstandard_core::calculate::record::stored_record(&SqliteReader::new(connection), record_id) +} + +/// Calculation requests answered from one open database connection. +pub struct SqliteReader<'c> { + connection: &'c Connection, +} + +impl<'c> SqliteReader<'c> { + pub fn new(connection: &'c Connection) -> Self { + SqliteReader { connection } + } + + /// A current, not deleted record's stored data. + fn stored_record(&self, record_id: &str) -> Result> { + let row: Option<(String, String, i64, String, Option)> = self + .connection + .query_row( + "SELECT records.record_id, records.record_type, records.current_revision, record_revisions.record_json, + record_revisions.extensions_json + FROM records + JOIN record_revisions + ON record_revisions.record_id = records.record_id + AND record_revisions.revision = records.current_revision + WHERE records.record_id = ?1 AND records.is_deleted = 0", + [record_id], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)), + ) + .optional()?; + let Some((record_id, record_type, revision, record_json, extensions_json)) = row else { + return Ok(None); + }; + let extensions = extensions_json.map(|text| json::parse(&text)).transpose()?; + Ok(Some(StoredRecord { + record_id, + record_type, + revision: revision as u64, + data: json::parse(&record_json)?, + extensions, + })) + } + + fn stored_records(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { + let mut statement = self.connection.prepare(sql)?; + let ids = + statement.query_map(args, |row| row.get::<_, String>(0))?.collect::, _>>()?; + Ok(ids.iter().map(|id| self.stored_record(id)).collect::>>()?.into_iter().flatten().collect()) + } +} + +impl CalculationReader for SqliteReader<'_> { + type Error = Error; + + fn current_record(&self, record_id: &str) -> Result> { + self.stored_record(record_id) + } + + fn related_records(&self, request: &RelatedRequest<'_>) -> Result> { + match *request { + RelatedRequest::PointsOfQuantity { source_id, quantity } => self.stored_records( + "SELECT records.record_id + FROM point_measurements + JOIN records ON records.record_id = point_measurements.record_id + WHERE point_measurements.source_id = ?1 + AND point_measurements.quantity = ?2 + AND records.is_deleted = 0 + ORDER BY point_measurements.recorded_at, records.record_id", + params![source_id, quantity], + ), + RelatedRequest::SessionsOfSource { session_type, source_id } => { + let table = match session_type { + SessionType::Sleep => "sleep_sessions", + SessionType::Workout => "workout_sessions", + }; + self.stored_records( + &format!( + "SELECT records.record_id + FROM {table} + JOIN records ON records.record_id = {table}.record_id + WHERE {table}.source_id = ?1 AND records.is_deleted = 0 + ORDER BY records.created_at, records.record_id" + ), + params![source_id], + ) + } + RelatedRequest::MeasurementsInWindow { measurement_type, source_id, quantity, from, to } => { + let table = match measurement_type { + MeasurementType::Point => "point_measurements", + MeasurementType::Sample => "measurement_samples", + }; + self.stored_records( + &format!( + "SELECT records.record_id + FROM {table} + JOIN records ON records.record_id = {table}.record_id + WHERE {table}.source_id = ?1 AND {table}.quantity = ?2 + AND {table}.recorded_at >= ?3 AND {table}.recorded_at <= ?4 + AND records.is_deleted = 0 + ORDER BY {table}.recorded_at, records.record_id" + ), + params![source_id, quantity, from, to], + ) + } + RelatedRequest::SleepStartingInWindow { source_id, from, to } => self.stored_records( + "SELECT records.record_id + FROM sleep_sessions + JOIN records ON records.record_id = sleep_sessions.record_id + WHERE sleep_sessions.source_id = ?1 + AND sleep_sessions.start_at >= ?2 AND sleep_sessions.start_at <= ?3 + AND records.is_deleted = 0 + ORDER BY sleep_sessions.start_at, records.record_id", + params![source_id, from, to], + ), + } + } + + fn heart_rate_samples(&self, request: &HeartRateRequest<'_>) -> Result> { + let mut statement = self.connection.prepare( + "SELECT measurement_samples.recorded_at, measurement_samples.standard_value, + records.record_id, records.current_revision + FROM measurement_samples + JOIN records ON records.record_id = measurement_samples.record_id + WHERE measurement_samples.source_id = ?1 AND measurement_samples.quantity = 'heart_rate' + AND measurement_samples.recorded_at >= ?2 AND measurement_samples.recorded_at <= ?3 + AND records.is_deleted = 0 + ORDER BY measurement_samples.recorded_at, records.record_id", + )?; + let rows = statement + .query_map(params![request.source_id, request.start_at, request.end_at], |row| { + Ok(SampleRow { + recorded_at: row.get(0)?, + value: row.get(1)?, + record_id: row.get(2)?, + revision: row.get::<_, i64>(3)? as u64, + }) + })? + .collect::, _>>()?; + Ok(rows) + } + + fn athlete_profile(&self) -> Result { + let json: Option = self + .connection + .query_row( + "SELECT record_revisions.record_json + FROM records + JOIN record_revisions + ON record_revisions.record_id = records.record_id + AND record_revisions.revision = records.current_revision + WHERE records.record_type = 'athlete_profile' AND records.is_deleted = 0 + ORDER BY records.created_at, records.record_id + LIMIT 1", + [], + |row| row.get(0), + ) + .optional()?; + let Some(json) = json else { + return Ok(Profile::default()); + }; + let data = json::parse(&json)?; + let text = |key: &str| data.get(key).and_then(Value::as_str).map(str::to_string); + Ok(Profile { + time_zone: text("default_time_zone"), + sex: text("sex"), + birth_year: data.get("birth_year").and_then(Value::as_i64).map(|year| year as i32), + }) + } + + fn saved_time_zone(&self) -> Result> { + crate::view::calendar::saved_time_zone(self.connection) + } + + fn range_inputs(&self, request: &InputRequest<'_>) -> Result> { + let (sql, args) = inputs_sql(request); + let mut statement = self.connection.prepare(&sql)?; + let rows = statement + .query_map(rusqlite::params_from_iter(args), |row| { + Ok(RangeInput { + record_id: row.get(0)?, + revision: row.get::<_, i64>(1)? as u64, + source_id: row.get(2)?, + recorded_at: row.get(3)?, + value: row.get(4)?, + unit: row.get(5)?, + period: None, + }) + })? + .collect::, _>>()?; + Ok(rows) + } + + fn period_inputs(&self, request: &PeriodRequest<'_>) -> Result> { + let quantity = request.quantity; + let (values_sql, mut args): (&str, Vec) = match request.record_kind { + RecordKind::ProviderScore => ( + "SELECT provider_scores.record_id, provider_scores.source_id, provider_scores.standard_value, provider_scores.standard_unit + FROM provider_scores WHERE provider_scores.metric = ?", + vec![Sql::Text(quantity.into())], + ), + RecordKind::ProviderSummary => ( + "SELECT provider_summaries.record_id, provider_summaries.source_id, provider_summaries.standard_value, provider_summaries.standard_unit + FROM provider_summaries WHERE provider_summaries.summary_type = ?", + vec![Sql::Text(quantity.into())], + ), + RecordKind::SessionSummary => ( + "SELECT sleep_sessions.record_id, sleep_sessions.source_id, + CAST(json_extract(summary.value, '$.standard_value') AS REAL) AS standard_value, + CAST(json_extract(summary.value, '$.standard_unit') AS TEXT) AS standard_unit + FROM sleep_sessions JOIN json_each(sleep_sessions.data_json, '$.source_reported_summaries') AS summary + WHERE json_extract(summary.value, '$.summary_type') = ? + UNION ALL + SELECT workout_sessions.record_id, workout_sessions.source_id, + CAST(json_extract(summary.value, '$.standard_value') AS REAL), + CAST(json_extract(summary.value, '$.standard_unit') AS TEXT) + FROM workout_sessions JOIN json_each(workout_sessions.data_json, '$.source_reported_summaries') AS summary + WHERE json_extract(summary.value, '$.summary_type') = ?", + vec![Sql::Text(quantity.into()), Sql::Text(quantity.into())], + ), + RecordKind::Measurement => ( + "SELECT point_measurements.record_id, point_measurements.source_id, point_measurements.standard_value, point_measurements.standard_unit + FROM point_measurements WHERE point_measurements.quantity = ? + UNION ALL + SELECT measurement_samples.record_id, measurement_samples.source_id, measurement_samples.standard_value, measurement_samples.standard_unit + FROM measurement_samples WHERE measurement_samples.quantity = ?", + vec![Sql::Text(quantity.into()), Sql::Text(quantity.into())], + ), + }; + let mut conditions = vec![ + "records.is_deleted = 0".to_string(), + "sources.source_type <> 'manual'".to_string(), + "provider_reporting_periods.period_type = ?".to_string(), + ]; + args.push(Sql::Text(request.period_type.as_str().into())); + if let Some(source) = request.source_id { + conditions.push("values_by_record.source_id = ?".into()); + args.push(Sql::Text(source.to_string())); + } + let period_key = "COALESCE(provider_reporting_periods.provider_date, provider_reporting_periods.start_at)"; + if let Some(from) = request.from { + conditions.push(format!("{period_key} >= ?")); + args.push(Sql::Text(from.to_string())); + } + if let Some(to) = request.to { + conditions.push(format!("{period_key} <= ?")); + args.push(Sql::Text(to.to_string())); + } + args.push(Sql::Integer(request.limit as i64)); + let sql = format!( + "WITH values_by_record AS ({values_sql}) + SELECT values_by_record.record_id, records.current_revision, values_by_record.source_id, + values_by_record.standard_value, values_by_record.standard_unit, provider_reporting_periods.period_json + FROM values_by_record + JOIN records ON records.record_id = values_by_record.record_id + JOIN sources ON sources.record_id = values_by_record.source_id + JOIN provider_reporting_periods ON provider_reporting_periods.owner_record_id = values_by_record.record_id + WHERE {} + ORDER BY values_by_record.source_id, {period_key}, values_by_record.record_id + LIMIT ?", + conditions.join(" AND ") + ); + let mut statement = self.connection.prepare(&sql)?; + let rows = statement + .query_map(rusqlite::params_from_iter(args), |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, i64>(1)?, + row.get::<_, String>(2)?, + row.get::<_, f64>(3)?, + row.get::<_, String>(4)?, + row.get::<_, String>(5)?, + )) + })? + .collect::, _>>()?; + rows.into_iter() + .map(|(record_id, revision, source_id, value, unit, period_json)| { + Ok(RangeInput { + record_id, + revision: revision as u64, + source_id, + recorded_at: String::new(), + value, + unit, + period: Some(json::parse(&period_json)?), + }) + }) + .collect() + } + + fn recorded_inputs( + &self, + calculation: &OneRecordCalculation, + record: &StoredRecord, + profile: &Profile, + ) -> Result { + super::recorded_inputs::read(self.connection, calculation, record, profile) + } + + fn threshold(&self, request: &ThresholdRequest<'_>, profile: &Profile) -> Result { + super::window::run(self.connection, request, profile) + } + + fn after_target_read(&self) -> Result<()> { + crate::package::failpoint!("calculate.apply_after_target"); + Ok(()) + } + + fn after_inputs_read(&self) -> Result<()> { + crate::package::failpoint!("calculate.after_inputs"); + Ok(()) + } +} + +/// One branch of the union: a typed table's rows for a quantity, with the +/// source and window filters inside the branch so each uses its lookup index. +fn branch( + table: &str, + quantity_column: &str, + require_instant: bool, + request: &InputRequest<'_>, + args: &mut Vec, +) -> String { + let mut conditions = vec![format!("{table}.{quantity_column} = ?")]; + args.push(Sql::Text(request.quantity.to_string())); + if require_instant { + conditions.push(format!("{table}.recorded_at IS NOT NULL")); + } + if let Some(source) = request.source_id { + conditions.push(format!("{table}.source_id = ?")); + args.push(Sql::Text(source.to_string())); + } + if let Some(from) = request.from { + conditions.push(format!("{table}.recorded_at >= ?")); + args.push(Sql::Text(from.to_string())); + } + if let Some(to) = request.to { + conditions.push(format!("{table}.recorded_at <= ?")); + args.push(Sql::Text(to.to_string())); + } + format!( + "SELECT {table}.record_id, {table}.source_id, {table}.recorded_at, {table}.standard_value, {table}.standard_unit + FROM {table} WHERE {}", + conditions.join(" AND ") + ) +} + +/// The SQL and arguments that read instant inputs. Only typed columns are +/// read, and each union branch filters inside itself so it can use its +/// lookup index; no stored record JSON is scanned. +fn inputs_sql(request: &InputRequest<'_>) -> (String, Vec) { + let mut args = Vec::new(); + let values_sql = match request.record_kind { + RecordKind::ProviderScore => branch("provider_scores", "metric", true, request, &mut args), + RecordKind::ProviderSummary => branch("provider_summaries", "summary_type", true, request, &mut args), + _ => { + let points = branch("point_measurements", "quantity", true, request, &mut args); + let samples = branch("measurement_samples", "quantity", false, request, &mut args); + format!("{points} UNION ALL {samples}") + } + }; + args.push(Sql::Integer(request.limit as i64)); + let sql = format!( + "SELECT values_by_record.record_id, records.current_revision, values_by_record.source_id, + values_by_record.recorded_at, values_by_record.standard_value, values_by_record.standard_unit + FROM ({values_sql}) AS values_by_record + JOIN records ON records.record_id = values_by_record.record_id + JOIN sources ON sources.record_id = values_by_record.source_id + WHERE records.is_deleted = 0 AND sources.source_type <> 'manual' + ORDER BY values_by_record.source_id, values_by_record.recorded_at, values_by_record.record_id + LIMIT ?" + ); + (sql, args) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::calculate::MAX_RUNTIME_INPUTS; + use crate::store::{CreateOptions, Store}; + + fn query_plan(connection: &Connection, sql: &str, args: Vec) -> Vec { + let mut statement = connection.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap(); + statement + .query_map(rusqlite::params_from_iter(args), |row| row.get::<_, String>(3)) + .unwrap() + .map(std::result::Result::unwrap) + .collect() + } + + #[test] + fn bounded_inputs_use_lookup_indexes_and_never_read_stored_json() { + let directory = crate::files::make_temporary_directory("ath-plan-").unwrap(); + let store = Store::create(directory.join("plan.ath.sqlite"), CreateOptions::default()).unwrap(); + for (kind, quantity, tables) in [ + (RecordKind::Measurement, "hrv_rmssd", vec!["point_measurements", "measurement_samples"]), + (RecordKind::ProviderScore, "recovery", vec!["provider_scores"]), + (RecordKind::ProviderSummary, "sleep_need", vec!["provider_summaries"]), + ] { + for (source, from, to) in + [(None, None, None), (Some("s"), Some("2026-01-01T00:00:00.000Z"), Some("2026-02-01T00:00:00.000Z"))] + { + let request = InputRequest { + record_kind: kind, + quantity, + source_id: source, + from, + to, + limit: MAX_RUNTIME_INPUTS + 1, + }; + let (sql, args) = inputs_sql(&request); + let plan = query_plan(store.connection(), &sql, args); + let text = plan.join("\n"); + for table in &tables { + assert!( + plan.iter() + .any(|step| step.starts_with(&format!("SEARCH {table} USING INDEX {table}_lookup_idx"))), + "{table} does not use its lookup index:\n{text}" + ); + assert!( + !plan.iter().any(|step| step.starts_with(&format!("SCAN {table}"))), + "{table} is scanned:\n{text}" + ); + } + assert!(!text.contains("record_revisions"), "stored JSON is read:\n{text}"); + } + } + drop(store); + std::fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/src/calculate/window.rs b/src/calculate/window.rs index 0a1c3592..31307fe6 100644 --- a/src/calculate/window.rs +++ b/src/calculate/window.rs @@ -22,68 +22,15 @@ use serde::Serialize; use super::methods::Profile; use super::record::StoredRecord; use super::recorded::{self, ReadRecording, WindowEffort, WindowWorkout}; -use super::thresholds::{self as t, BestEffort, EffortLabels, EffortOrigin}; +use super::thresholds::{self as t, BestEffort, EffortOrigin}; use crate::error::Result; use crate::json::Value; use crate::model::{time, EvidenceReference, ReadingValue, RecordingQuantity}; use rusqlite::Connection; -/// An intensity reference a person may save from the outcome. -#[derive(Debug, Clone, PartialEq, Serialize)] -pub struct ReferenceToSave { - pub quantity: String, - pub value: f64, - pub unit: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub sport: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub machine: Option, - pub effective_date: String, - pub basis: String, - pub method: String, - /// The records a saved reference cites; a `model` value cites the saved - /// calculation result instead. - pub evidence: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub note: Option, - /// Saved only when the person asks for it specifically (supplement 6). - #[serde(skip_serializing_if = "std::ops::Not::not")] - pub only_when_asked: bool, -} - -/// What a threshold method found. -#[derive(Debug, Clone, PartialEq, Serialize)] -pub struct ThresholdOutcome { - pub operation: String, - pub parameters: BTreeMap, - #[serde(skip_serializing_if = "Option::is_none")] - pub period_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub period_end: Option, - /// The method's own result, with the names and units of its study. - pub result: Value, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub efforts: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub labels: Option, - /// What a person must confirm before a value becomes the one in effect. - pub confirm_before_saving: Vec, - pub references_to_save: Vec, -} - -/// What `ath apply` passed in. -pub struct ThresholdRequest<'a> { - pub operation: &'a str, - pub record: Option<&'a StoredRecord>, - pub parameters: &'a BTreeMap, - pub max_gap_s: u64, -} - -/// The outcome, or the plain reason the method refused, and every record read. -pub struct ThresholdRun { - pub outcome: std::result::Result, - pub evidence: Vec, -} +pub use athleticstandard_core::calculate::window::{ + is_threshold_operation, needs_record, ReferenceToSave, ThresholdOutcome, ThresholdRequest, ThresholdRun, +}; fn serialized(value: &T) -> Value { crate::json::to_value(value) @@ -190,26 +137,6 @@ const FITS_SPEED: [&str; 4] = [ t::CRITICAL_SPEED_HYPERBOLIC, t::CRITICAL_SPEED_THREE_PARAMETER, ]; -const TESTS: [&str; 5] = [ - t::THREE_MINUTE_ALL_OUT_CYCLING_TEST, - t::THREE_MINUTE_ALL_OUT_ROWING_TEST, - t::THREE_MINUTE_ALL_OUT_RUNNING_TEST, - t::CRITICAL_SWIM_SPEED_400_AND_200_M, - t::THIRTY_MINUTE_RUNNING_TIME_TRIAL, -]; - -/// Every operation a threshold skill may name. -pub fn is_threshold_operation(operation: &str) -> bool { - t::THRESHOLD_OPERATIONS.contains(&operation) - || operation == t::AGE_FORMULA_208_MINUS_0_7_AGE - || operation == t::HIGHEST_HEART_RATE_HELD_5_S -} - -/// True when the operation reads one workout a person names. -pub fn needs_record(operation: &str) -> bool { - TESTS.contains(&operation) -} - /// Run one threshold method. pub fn run(connection: &Connection, request: &ThresholdRequest<'_>, profile: &Profile) -> Result { let mut evidence = Vec::new(); @@ -678,7 +605,7 @@ fn run_test( let label_200 = refuse!(params.text("lap_200").ok_or("needs --set lap_200=")); let second = match params.text("workout_200") { Some(id) => { - let workout = super::record::stored_record(connection, &id)?; + let workout = super::sqlite::stored_record(connection, &id)?; evidence .push(EvidenceReference { record_id: workout.record_id.clone(), revision: workout.revision }); workout @@ -736,7 +663,7 @@ fn held_heart_rate( .collect::>()?; let mut recordings = Vec::new(); for (workout_id, revision, start_at, workout_sport) in rows { - let workout = super::record::stored_record(connection, &workout_id)?; + let workout = super::sqlite::stored_record(connection, &workout_id)?; evidence.push(EvidenceReference { record_id: workout_id.clone(), revision: revision as u64 }); let start_ms = time::parse_utc_timestamp(&start_at).unwrap_or_default(); let local = profile diff --git a/src/error.rs b/src/error.rs index e4f51bef..6e60fcac 100644 --- a/src/error.rs +++ b/src/error.rs @@ -97,6 +97,18 @@ impl From for Error { } } +/// The core's errors keep their code and message (D312). +impl From for Error { + fn from(error: athleticstandard_core::Error) -> Self { + match error { + athleticstandard_core::Error::Invalid(validation) => Error::Invalid(validation), + athleticstandard_core::Error::NotFound(message) => Error::NotFound(message), + athleticstandard_core::Error::Refused(message) => Error::Refused(message), + athleticstandard_core::Error::Other(message) => Error::Other(message), + } + } +} + impl From for Error { fn from(error: crate::json::JsonError) -> Self { Error::Other(error.message) diff --git a/src/protocol/worker.rs b/src/protocol/worker.rs index 9d51772e..acf573a3 100644 --- a/src/protocol/worker.rs +++ b/src/protocol/worker.rs @@ -34,6 +34,12 @@ impl From for Failure { } } +impl From for Failure { + fn from(error: athleticstandard_core::Error) -> Self { + Failure::Error(error.into()) + } +} + impl From for Failure { fn from(error: crate::model::ValidationError) -> Self { Failure::Error(Error::Invalid(error)) diff --git a/src/store/query.rs b/src/store/query.rs index aa07d4c2..1a5d2cae 100644 --- a/src/store/query.rs +++ b/src/store/query.rs @@ -15,8 +15,7 @@ use rusqlite::Connection; use super::read::current_from_row; use crate::error::{Error, Result}; -use crate::json::Value; -use crate::model::{utc_timestamp, CurrentRecord, PointMeasurementType, RecordData, RecordType, SeriesQuantity}; +use crate::model::{CurrentRecord, PointMeasurementType, RecordData, RecordType, SeriesQuantity}; pub const DEFAULT_QUERY_LIMIT: u32 = 10_000; pub const MAX_QUERY_LIMIT: u32 = 100_000; @@ -125,8 +124,7 @@ impl AsOfQuery { /// `UtcTimestamp.parse`: the stored UTC form, or a validation error. pub fn parse_utc_timestamp(text: &str) -> Result { - utc_timestamp().validate(&Value::String(text.to_string()))?; - Ok(text.to_string()) + Ok(athleticstandard_core::calendar::parse_utc_timestamp(text)?) } /// Check a query limit. The default is 10,000 and the maximum 100,000. diff --git a/src/view/calendar.rs b/src/view/calendar.rs index 032fee9b..f08c4960 100644 --- a/src/view/calendar.rs +++ b/src/view/calendar.rs @@ -1,139 +1,17 @@ -//! Calendar days, timezones, and the instants that bound them. +//! Calendar views on a database: the profile's saved timezone, and the +//! ranges and cut-offs that need it. //! -//! A calendar day starts at local midnight in a named timezone. The start is -//! found by asking what the wall clock reads at a candidate instant and moving -//! the candidate by the difference, as the 2.1.0 program did with -//! `Intl.DateTimeFormat`. The same search gives the same answer on days when a -//! clock change moves midnight, and the same refusal when it cannot settle. +//! The calendar rules themselves live in the core, so phones use the same +//! ones (D312). This module re-exports them. -use chrono::{FixedOffset, NaiveDateTime, TimeZone, Utc}; -use chrono_tz::Tz; use rusqlite::{Connection, OptionalExtension}; +pub use athleticstandard_core::calendar::*; + use crate::error::{Error, Result}; use crate::model::time; -pub use crate::store::query::parse_utc_timestamp; use crate::store::Store; -/// A timezone accepted for calendar views: an IANA name in any letter case, -/// or a fixed UTC offset such as `+05:30`, which `Intl.DateTimeFormat` also -/// accepts. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Zone { - Named(Tz), - Fixed(FixedOffset), -} - -impl Zone { - /// Read a timezone name. `None` when the name is not a timezone. - pub fn parse(name: &str) -> Option { - if let Some(offset) = parse_offset(name) { - return Some(Zone::Fixed(offset)); - } - crate::model::resolve_time_zone(name).map(Zone::Named) - } - - /// Read a timezone name, or refuse with the published message. - pub fn require(name: &str) -> Result { - Zone::parse(name).ok_or_else(|| not_a_time_zone(name)) - } - - /// The wall-clock time at an instant, to the second. - pub fn wall_time(&self, millis: i64) -> NaiveDateTime { - let instant = Utc.timestamp_millis_opt(millis).single().unwrap_or_default(); - match self { - Zone::Named(zone) => instant.with_timezone(zone).naive_local(), - Zone::Fixed(offset) => instant.with_timezone(offset).naive_local(), - } - } -} - -/// The refusal for a name that is not a timezone. -pub fn not_a_time_zone(name: &str) -> Error { - Error::other(format!("'{name}' is not an IANA timezone such as America/Chicago")) -} - -/// `±HH:MM`, `±HHMM`, or `±HH`. -fn parse_offset(text: &str) -> Option { - let sign = match text.as_bytes().first()? { - b'+' => 1, - b'-' => -1, - _ => return None, - }; - let rest = &text[1..]; - let digits = |part: &str| { - (part.len() == 2 && part.bytes().all(|b| b.is_ascii_digit())).then(|| part.parse::().ok()).flatten() - }; - let (hours, minutes) = match rest.len() { - 2 => (digits(rest)?, 0), - 4 => (digits(&rest[0..2])?, digits(&rest[2..4])?), - 5 if rest.as_bytes()[2] == b':' => (digits(&rest[0..2])?, digits(&rest[3..5])?), - _ => return None, - }; - if hours > 23 || minutes > 59 { - return None; - } - FixedOffset::east_opt(sign * (hours * 3600 + minutes * 60)) -} - -/// True for `YYYY-MM-DD` with ASCII digits. The date may still be invalid. -pub fn looks_like_calendar_date(text: &str) -> bool { - let bytes = text.as_bytes(); - bytes.len() == 10 - && bytes[4] == b'-' - && bytes[7] == b'-' - && bytes.iter().enumerate().all(|(index, byte)| index == 4 || index == 7 || byte.is_ascii_digit()) -} - -/// The parts of a calendar date, or the published refusal. Years below 100 -/// are refused because `Date.UTC` reads them as 19xx. -pub fn calendar_date_parts(text: &str) -> Result<(u32, u32, u32)> { - if !looks_like_calendar_date(text) { - return Err(Error::other(format!("expected YYYY-MM-DD, not '{text}'"))); - } - match time::parse_calendar_date(text) { - Some((year, month, day)) if year >= 100 => Ok((year, month, day)), - _ => Err(Error::other(format!("invalid calendar date '{text}'"))), - } -} - -/// The day after a calendar date. -pub fn next_calendar_date(text: &str) -> Result { - let (year, month, day) = calendar_date_parts(text)?; - let days = time::days_from_civil(i64::from(year), month, day) + 1; - let (year, month, day) = time::civil_from_days(days); - Ok(time::format_date(year, month, day)) -} - -fn wall_millis(wall: NaiveDateTime) -> i64 { - wall.and_utc().timestamp_millis() -} - -/// The first instant of a calendar date in a timezone, in the stored UTC form. -pub fn start_of_date_in_zone(date: &str, zone_name: &str) -> Result { - let (year, month, day) = calendar_date_parts(date)?; - let zone = Zone::require(zone_name)?; - let target = time::days_from_civil(i64::from(year), month, day) * 86_400_000; - let mut candidate = target; - for _ in 0..6 { - let seen = wall_millis(zone.wall_time(candidate)); - let difference = target - seen; - if difference == 0 { - return Ok(time::format_utc_millis(candidate)); - } - candidate += difference; - } - Err(Error::other(format!("could not find the start of {date} in {zone_name}"))) -} - -/// The local calendar date of a timestamp in a timezone. -pub fn calendar_date_in_zone(timestamp: &str, zone_name: &str) -> Result { - let zone = Zone::require(zone_name)?; - let millis = crate::model::js_date_parse(timestamp) - .ok_or_else(|| Error::other(format!("Invalid time value: {timestamp}")))?; - Ok(zone.wall_time(millis).format("%Y-%m-%d").to_string()) -} - /// The athlete profile's default timezone, when one is saved. pub(crate) fn saved_time_zone(connection: &Connection) -> Result> { let value: Option> = connection @@ -149,27 +27,6 @@ pub(crate) fn saved_time_zone(connection: &Connection) -> Result> Ok(value.flatten()) } -/// A requested time window: calendar days or exact UTC instants. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct CalendarRangeRequest { - pub from: Option, - pub to: Option, - pub time_zone: Option, - /// Raw sample reads need a timezone only for calendar-day bounds. - pub raw: bool, -} - -/// A resolved window in exact UTC instants, with the timezone used. -#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)] -pub struct InstantRange { - #[serde(skip_serializing_if = "Option::is_none")] - pub from: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub to: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub time_zone: Option, -} - /// Turn calendar-day bounds into UTC instants. A calendar day uses the given /// timezone, else the profile's. Exact instants must use the stored UTC form. pub fn resolve_calendar_range(store: &Store, request: &CalendarRangeRequest) -> Result { @@ -181,51 +38,7 @@ pub(crate) fn resolve_calendar_range_in( connection: &Connection, request: &CalendarRangeRequest, ) -> Result { - let is_date = |value: &Option| value.as_deref().is_some_and(looks_like_calendar_date); - let needs_time_zone = is_date(&request.from) || is_date(&request.to) || !request.raw; - let time_zone = match &request.time_zone { - Some(zone) => Some(zone.clone()), - None if needs_time_zone => saved_time_zone(connection)?, - None => None, - }; - if needs_time_zone && time_zone.is_none() { - return Err(Error::other( - "a calendar-day series view needs --timezone or a default timezone in the athlete profile", - )); - } - if let Some(zone) = &time_zone { - Zone::require(zone)?; - } - let from = match &request.from { - Some(from) if looks_like_calendar_date(from) => { - Some(start_of_date_in_zone(from, time_zone.as_deref().unwrap_or_default())?) - } - Some(from) => Some(parse_utc_timestamp(from)?), - None => None, - }; - let to = match &request.to { - Some(to) if looks_like_calendar_date(to) => { - let next = start_of_date_in_zone(&next_calendar_date(to)?, time_zone.as_deref().unwrap_or_default())?; - Some(time::format_utc_millis(time::parse_utc_timestamp(&next).unwrap_or_default() - 1)) - } - Some(to) => Some(parse_utc_timestamp(to)?), - None => None, - }; - if let (Some(from), Some(to)) = (&from, &to) { - if from > to { - return Err(Error::other("--from must not be after --to")); - } - } - Ok(InstantRange { from, to, time_zone }) -} - -/// The cut-off for a historical read. -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] -pub struct AsOfTime { - pub as_of: String, - /// The timezone used when the request named a calendar day. - #[serde(skip_serializing_if = "Option::is_none")] - pub time_zone: Option, + resolve_calendar_range_with(request, || saved_time_zone(connection)) } /// Resolve `--as-of`: now, an exact UTC instant, or the last millisecond of a @@ -255,39 +68,3 @@ pub fn resolve_as_of_time( let as_of = time::format_utc_millis(time::parse_utc_timestamp(&next).unwrap_or_default() - 1); Ok(AsOfTime { as_of, time_zone: Some(time_zone) }) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn day_bounds_follow_clock_changes() { - assert_eq!(start_of_date_in_zone("2026-03-08", "America/Chicago").unwrap(), "2026-03-08T06:00:00.000Z"); - assert_eq!(start_of_date_in_zone("2026-03-09", "America/Chicago").unwrap(), "2026-03-09T05:00:00.000Z"); - assert_eq!(start_of_date_in_zone("2026-11-01", "America/Chicago").unwrap(), "2026-11-01T05:00:00.000Z"); - assert_eq!(start_of_date_in_zone("2026-11-02", "america/chicago").unwrap(), "2026-11-02T06:00:00.000Z"); - assert_eq!(start_of_date_in_zone("2026-01-01", "+05:30").unwrap(), "2025-12-31T18:30:00.000Z"); - assert_eq!(start_of_date_in_zone("2026-01-01", "Asia/Kolkata").unwrap(), "2025-12-31T18:30:00.000Z"); - } - - #[test] - fn midnight_that_does_not_exist_is_refused_like_the_old_search() { - // Santiago moves its clocks at midnight, so 2026-09-06 00:00 never occurs. - let error = start_of_date_in_zone("2026-09-06", "America/Santiago"); - assert_eq!( - error.map_err(|error| error.to_string()), - Err("could not find the start of 2026-09-06 in America/Santiago".to_string()) - ); - } - - #[test] - fn dates_are_checked_like_the_old_parser() { - assert_eq!(calendar_date_parts("2026-2-01").unwrap_err().to_string(), "expected YYYY-MM-DD, not '2026-2-01'"); - assert_eq!(calendar_date_parts("2026-02-30").unwrap_err().to_string(), "invalid calendar date '2026-02-30'"); - assert_eq!(calendar_date_parts("0050-01-01").unwrap_err().to_string(), "invalid calendar date '0050-01-01'"); - assert_eq!(next_calendar_date("2026-12-31").unwrap(), "2027-01-01"); - assert_eq!(calendar_date_in_zone("2026-10-02T03:00:00.000Z", "America/Chicago").unwrap(), "2026-10-01"); - assert!(Zone::parse("Z").is_none()); - assert!(Zone::parse("+24:00").is_none()); - } -} diff --git a/tests/calculate_readers.rs b/tests/calculate_readers.rs new file mode 100644 index 00000000..a22835dd --- /dev/null +++ b/tests/calculate_readers.rs @@ -0,0 +1,322 @@ +//! The SQLite reader and a memory snapshot give the same calculations (D326). +//! +//! Every worked example in the shipped skills and every case in +//! `calculation_support::cases` runs twice: on the database through the +//! desktop entry points, and on a memory snapshot of the same records through +//! the core. The complete outputs must match byte for byte, and failures must +//! have the same code and message. +//! +//! A memory snapshot does not hold device recordings yet. A calculation that +//! reads recordings or intensity references must get exactly the refusal +//! that says to run it on a database (D326); those runs are counted apart. + +mod calculation_support; + +use std::collections::BTreeMap; + +use athleticstandard::calculate::{self, CalculationFile, OneRecordCalculation, SnapshotBuilder}; +use athleticstandard::json; +use athleticstandard_core::assets::resolve_shipped_calculation; +use calculation_support::{cases, Lab}; + +/// `ok ` or `error `. +fn outcome(result: Result) -> String { + match result { + Ok(value) => format!("ok {}", json::encode(&value)), + Err((code, message)) => format!("error {code} {message}"), + } +} + +fn desktop(result: athleticstandard::Result) -> Result { + result.map_err(|error| (error.code().to_string(), error.to_string())) +} + +fn core(result: athleticstandard_core::Result) -> Result { + result.map_err(|error| (error.code().to_string(), error.to_string())) +} + +/// The two outcomes of one request. +struct Outcomes { + sqlite: String, + memory: String, + /// The memory snapshot's refusal, when the calculation reads recordings. + refusal: Option, +} + +impl Outcomes { + /// `None` when the readers agree, `Some(true)` for the documented + /// refusal, and `Some(false)` for a difference. + fn refused(&self) -> Option { + if self.sqlite == self.memory { + return None; + } + Some(self.refusal.as_deref() == Some(self.memory.as_str())) + } +} + +/// What the memory snapshot answers when a calculation reads recordings. +fn refusal_for(text: &str, parameters: &BTreeMap) -> Option { + let parsed = CalculationFile::parse(text).ok()?; + if !parsed.calculation.reads_recordings() { + return None; + } + let operation = match &parsed.calculation { + OneRecordCalculation::Thresholds { operations, .. } => { + parameters.get("operation").cloned().or_else(|| operations.first().cloned()).unwrap_or_default() + } + other => other.operation().to_string(), + }; + Some(format!( + "error refused {operation} reads device recordings and intensity references, which a record snapshot does not hold; run it on a database" + )) +} + +/// Run one request through both readers and return both outcomes. +fn both(lab: &mut Lab, snapshot: &calculate::RecordSnapshot, request: &serde_json::Value) -> Outcomes { + let working = lab.directory.join("empty-work"); + std::fs::create_dir_all(&working).unwrap(); + if let Some(request) = request.get("calculate") { + let options = lab.options(request); + let sqlite = outcome(desktop(calculate::calculate_range(&lab.store, &options))); + let memory = outcome(core(athleticstandard_core::calculate::calculate_range(snapshot, &options))); + return Outcomes { sqlite, memory, refusal: None }; + } + let target = request.get("target").and_then(|value| value.as_str()).map(|short| lab.id(short)); + let parameters: BTreeMap = request + .get("set") + .and_then(|value| value.as_object()) + .into_iter() + .flatten() + .map(|(key, value)| (key.clone(), value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string()))) + .collect(); + let (sqlite, text) = match request.get("apply").and_then(|value| value.as_str()) { + Some(name) => ( + outcome(desktop(calculate::apply_with(&lab.store, name, target.as_deref(), ¶meters, &working))), + resolve_shipped_calculation(name), + ), + None => { + let text = request["apply_text"].as_str().unwrap(); + (outcome(desktop(calculate::apply_text_with(&lab.store, text, target.as_deref(), ¶meters))), Ok(text)) + } + }; + let refusal = text.as_ref().ok().and_then(|text| refusal_for(text, ¶meters)); + let memory = outcome(core(text.and_then(|text| { + athleticstandard_core::calculate::apply_with(snapshot, text, target.as_deref(), ¶meters) + }))); + Outcomes { sqlite, memory, refusal } +} + +fn snapshot_of(lab: &Lab) -> calculate::RecordSnapshot { + let mut builder = SnapshotBuilder::new(); + builder.add_batch(&lab.current_records()).unwrap(); + builder.finish() +} + +/// The fenced `json ath-example` blocks of every shipped skill. +fn worked_examples() -> Vec<(String, serde_json::Value)> { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("skills"); + let mut dirs: Vec<_> = std::fs::read_dir(root).unwrap().map(|entry| entry.unwrap().path()).collect(); + dirs.sort(); + let mut out = Vec::new(); + for dir in dirs { + let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { + continue; + }; + let name = dir.file_name().unwrap().to_string_lossy().to_string(); + let marker = "```json ath-example\n"; + let mut rest = text.as_str(); + while let Some(start) = rest.find(marker) { + let body = &rest[start + marker.len()..]; + let end = body.find("\n```").unwrap(); + out.push((name.clone(), serde_json::from_str(&body[..end]).unwrap())); + rest = &body[end..]; + } + } + out +} + +#[test] +fn every_worked_example_agrees_on_both_readers() { + let examples = worked_examples(); + assert!(examples.len() >= 32, "found {} worked examples", examples.len()); + let mut differences = Vec::new(); + let mut refused = 0; + for (skill, example) in &examples { + let mut lab = Lab::new(); + lab.write(example["records"].as_array().unwrap()); + let snapshot = snapshot_of(&lab); + let request = if example.get("set").is_some() || example.get("apply").is_some() { + serde_json::json!({ "apply": skill, "target": example.get("apply"), "set": example.get("set") }) + } else { + serde_json::json!({ "calculate": example["calculate"] }) + }; + let outcomes = both(&mut lab, &snapshot, &request); + match outcomes.refused() { + None => {} + Some(true) => refused += 1, + Some(false) => { + differences.push(format!("{skill}:\n sqlite {}\n memory {}", outcomes.sqlite, outcomes.memory)) + } + } + } + assert!(differences.is_empty(), "{} examples differ:\n{}", differences.len(), differences.join("\n")); + eprintln!("worked examples: {} agree, {refused} need a database", examples.len() - refused); + assert!(examples.len() - refused >= 30, "{} examples agree", examples.len() - refused); +} + +#[test] +fn every_reader_case_agrees_on_both_readers() { + let mut differences = Vec::new(); + let mut ran = 0; + let mut refused = 0; + for case in cases::all() { + let mut lab = Lab::new(); + lab.write(&case.records); + let snapshot = snapshot_of(&lab); + for request in &case.requests { + ran += 1; + let outcomes = both(&mut lab, &snapshot, request); + if std::env::var_os("ATH_SHOW_OUTCOMES").is_some() { + eprintln!("{} | {}", case.name, outcomes.sqlite.chars().take(150).collect::()); + } + match outcomes.refused() { + None => {} + Some(true) => refused += 1, + Some(false) => differences.push(format!( + "{} / {request}:\n sqlite {}\n memory {}", + case.name, outcomes.sqlite, outcomes.memory + )), + } + } + } + assert!(differences.is_empty(), "{} of {ran} requests differ:\n{}", differences.len(), differences.join("\n")); + eprintln!("reader cases: {} agree, {refused} need a database", ran - refused); + assert!(ran - refused >= 60, "{} requests agree", ran - refused); +} + +#[test] +fn a_refused_batch_leaves_the_builder_as_it_was() { + let mut lab = Lab::new(); + lab.write(&[serde_json::json!({ "id": "p1", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-01T06:00:00.000Z", "value": 50 })]); + let records = lab.current_records(); + let mut builder = SnapshotBuilder::new(); + assert_eq!(builder.add_batch(&records).unwrap(), 2); + // The same records again: a duplicate ID refuses the whole batch. + let error = builder.add_batch(&records).unwrap_err(); + assert_eq!(error.code(), "refused"); + assert!(error.to_string().contains("is already in this snapshot"), "{error}"); + assert_eq!(builder.len(), 2); + // An invalid record names its place in the batch. + let mut invalid = records + .as_array() + .unwrap() + .iter() + .find(|record| record["record_type"].as_str() == Some("point_measurement")) + .unwrap() + .clone(); + invalid["record_id"] = json::Value::from("01890f3e-e7d3-7cc0-88c8-0000000fffff"); + invalid["data"].as_object_mut().unwrap().remove("source_id"); + let error = builder.add_batch(&json::Value::Array(vec![invalid])).unwrap_err(); + let athleticstandard_core::Error::Invalid(validation) = error else { panic!("expected an invalid record") }; + assert_eq!(validation.issues[0].path_text(), "0.data.source_id"); + assert_eq!(builder.len(), 2); + assert_eq!(builder.add_batch(&json::Value::from("not an array")).unwrap_err().code(), "error"); +} + +#[test] +fn a_record_whose_source_was_not_supplied_is_not_an_input() { + // A database always holds a measurement's source. A memory snapshot holds + // what the app supplied, and an input whose source is missing is left + // out, as the SQL join leaves it out. + let mut lab = Lab::new(); + lab.write(&[ + serde_json::json!({ "id": "p1", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-01T06:00:00.000Z", "value": 50 }), + serde_json::json!({ "id": "p2", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-02T06:00:00.000Z", "value": 52, "source": "b" }), + ]); + let source_b = lab.source_id("b"); + let records: Vec = lab + .current_records() + .as_array() + .unwrap() + .iter() + .filter(|record| record["record_id"].as_str() != Some(source_b.as_str())) + .cloned() + .collect(); + let mut builder = SnapshotBuilder::new(); + builder.add_batch(&json::Value::Array(records)).unwrap(); + let snapshot = builder.finish(); + let options = lab.options(&serde_json::json!({ "operation": "summary", "quantity": "hrv_rmssd" })); + let receipt = athleticstandard_core::calculate::calculate_range(&snapshot, &options).unwrap(); + assert_eq!(receipt.input.record_count, 1); + assert_eq!(receipt.sources, vec![lab.source_id("a")]); +} + +/// 100,000 inputs are accepted and 100,001 are refused, on both readers. +#[test] +fn the_input_limit_holds_at_the_boundary_and_one_beyond() { + use athleticstandard::model::{CurrentRecord, RecordActor}; + use athleticstandard::store::{Changes, CreateOptions, NewRecord, Store}; + let folder = athleticstandard::files::make_temporary_directory("ath-limit-").unwrap(); + let mut store = Store::create(folder.join("limit.ath.sqlite"), CreateOptions::default()).unwrap(); + let source_id = "01890f3e-e7d3-7cc0-88c8-0000000000a0"; + let record = |id: &str, record_type: &str, data: String| { + format!( + r#"{{"record_id":"{id}","record_type":"{record_type}","created_at":"2026-01-01T00:00:00.000Z","current_revision":1,"is_deleted":false,"data":{data}}}"# + ) + }; + let mut texts = vec![record( + source_id, + "source", + r#"{"source_type":"wearable","data_writer":"Band","data_route":"test"}"#.to_string(), + )]; + for index in 0..=athleticstandard::calculate::MAX_RUNTIME_INPUTS { + let at = athleticstandard::model::time::format_utc_millis(1_790_000_000_000 + index as i64 * 1000); + texts.push(record( + &format!("01890f3e-e7d3-7cc0-88c8-{:012x}", 0x1000 + index), + "measurement_sample", + format!( + r#"{{"source_id":"{source_id}","received_at":"{at}","received_at_basis":"import_time","quantity":"heart_rate","recorded_at":"{at}","input_timestamp":{{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"}},"value":{{"standard_value":{},"standard_unit":"bpm","input_value_missing_reason":"not_provided_by_source","input_unit_missing_reason":"not_provided_by_source"}}}}"#, + 60 + index % 30 + ), + )); + } + let actor: RecordActor = serde_json::from_str(r#"{"author_type":"athlete"}"#).unwrap(); + let records: Vec = + texts.iter().map(|text| CurrentRecord::from_value(&json::parse(text).unwrap()).unwrap()).collect(); + let creates = records + .iter() + .map(|record| NewRecord { + record_id: Some(record.record_id.clone()), + created_at: Some(record.created_at.clone()), + ..NewRecord::new(record.data.clone(), actor.clone()) + }) + .collect(); + store.apply(Changes { creates, ..Changes::default() }).unwrap(); + let mut builder = SnapshotBuilder::new(); + builder.add_batch(&json::Value::Array(records.iter().map(|record| record.to_value()).collect())).unwrap(); + let snapshot = builder.finish(); + + let last = athleticstandard::model::time::format_utc_millis( + 1_790_000_000_000 + (athleticstandard::calculate::MAX_RUNTIME_INPUTS as i64 - 1) * 1000, + ); + let mut at_limit = athleticstandard::calculate::CalculateOptions::new(calculate::Operation::Summary, "heart_rate"); + at_limit.to = Some(last); + let beyond = athleticstandard::calculate::CalculateOptions::new(calculate::Operation::Summary, "heart_rate"); + for (options, expected) in + [(&at_limit, None), (&beyond, Some("Calculation matched more than 100000 records. Narrow --from and --to."))] + { + let sqlite = outcome(desktop(calculate::calculate_range(&store, options))); + let memory = outcome(core(athleticstandard_core::calculate::calculate_range(&snapshot, options))); + assert_eq!(sqlite, memory); + match expected { + Some(message) => assert_eq!(sqlite, format!("error refused {message}")), + None => assert!( + sqlite.contains(r#""record_count":100000,"#) && sqlite.contains(r#""references_truncated":true"#), + "{}", + &sqlite[..300] + ), + } + } + drop(store); + std::fs::remove_dir_all(folder).unwrap(); +} diff --git a/tests/calculation_support/cases.rs b/tests/calculation_support/cases.rs new file mode 100644 index 00000000..ff9af7c6 --- /dev/null +++ b/tests/calculation_support/cases.rs @@ -0,0 +1,338 @@ +//! Synthetic cases that exercise every filter the calculation readers apply +//! (D326, D333). `tests/calculate_readers.rs` runs each case through the +//! SQLite reader and a memory snapshot of the same records and compares the +//! complete results. The phone fixture exporter runs the same cases through +//! the phone bindings. +//! +//! Each case has short-form records (see the parent module) and requests: +//! `{"apply": , "target": }`, `{"apply_text": , +//! "target": }`, or `{"calculate": }`. + +use serde_json::{json, Value}; + +pub struct Case { + pub name: &'static str, + pub records: Vec, + pub requests: Vec, +} + +fn sample(id: &str, quantity: &str, at: &str, value: f64) -> Value { + json!({ "id": id, "record_type": "measurement_sample", "quantity": quantity, "at": at, "value": value }) +} + +fn point(id: &str, quantity: &str, at: &str, value: f64) -> Value { + json!({ "id": id, "record_type": "point_measurement", "quantity": quantity, "at": at, "value": value }) +} + +fn calculate(request: Value) -> Value { + json!({ "calculate": request }) +} + +/// Every reader case. +pub fn all() -> Vec { + vec![ + ties_deletions_and_sources(), + clock_changes(), + provider_periods(), + session_summaries(), + workouts(), + one_record_lookups(), + receipt_cap(), + ] +} + +/// Equal times, deleted records, a deleted source, a manual source, and a +/// corrected record. +fn ties_deletions_and_sources() -> Case { + let mut records = vec![ + point("p1", "hrv_rmssd", "2026-10-01T06:00:00.000Z", 50.0), + point("p2", "hrv_rmssd", "2026-10-01T06:00:00.000Z", 54.0), + json!({ "id": "p3", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-02T06:00:00.000Z", "value": 60, "deleted": true }), + json!({ "id": "p4", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-02T06:00:00.000Z", "value": 40, "source": "manual" }), + json!({ "id": "p5", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-03T06:00:00.000Z", "value": 58, "source": "b" }), + json!({ "id": "p6", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-04T06:00:00.000Z", "value": 62, "source": "b" }), + json!({ "id": "p7", "record_type": "point_measurement", "quantity": "hrv_sdnn", "at": "2026-10-01T06:00:00.000Z", "value": 70 }), + point("r1", "resting_heart_rate", "2026-10-01T06:00:00.000Z", 52.0), + point("r2", "resting_heart_rate", "2026-10-02T06:00:00.000Z", 50.0), + point("r3", "resting_heart_rate", "2026-10-03T06:00:00.000Z", 49.0), + point("p8", "hrv_rmssd", "2026-10-02T07:00:00.000Z", 56.0), + point("p9", "hrv_rmssd", "2026-10-03T07:00:00.000Z", 59.0), + json!({ "correct": "p8", "data": { "value": { "standard_value": 57, "standard_unit": "ms", "input_value": 57, "input_unit": "ms" } } }), + json!({ "delete": "source:b" }), + ]; + records.push(json!({ "id": "profile", "record_type": "athlete_profile", "default_time_zone": "America/Chicago" })); + let requests = vec![ + calculate(json!({ "operation": "summary", "quantity": "hrv_rmssd" })), + calculate(json!({ "operation": "summary", "quantity": "hrv_sdnn" })), + calculate(json!({ "operation": "summary", "quantity": "hrv_rmssd", "source": "a" })), + calculate( + json!({ "operation": "summary", "quantity": "hrv_rmssd", "from": "2026-10-01T06:00:00.000Z", "to": "2026-10-01T06:00:00.000Z" }), + ), + calculate( + json!({ "operation": "summary", "quantity": "hrv_rmssd", "group": "day", "time_zone": "America/Chicago" }), + ), + calculate(json!({ "operation": "summary", "quantity": "hrv_rmssd", "group": "week" })), + calculate(json!({ "operation": "baseline", "quantity": "hrv_rmssd" })), + calculate(json!({ "operation": "trend", "quantity": "hrv_rmssd" })), + calculate( + json!({ "operation": "coverage", "quantity": "hrv_rmssd", "time_zone": "UTC", "from": "2026-09-30", "to": "2026-10-05" }), + ), + calculate( + json!({ "operation": "compare-sources", "quantity": "hrv_rmssd", "source": "a", "compare_source": "b" }), + ), + calculate( + json!({ "operation": "compare-sources", "quantity": "hrv_rmssd", "source": "a", "compare_source": "b", "time_zone": "UTC" }), + ), + calculate( + json!({ "operation": "correlation", "quantity": "hrv_rmssd", "other_quantity": "resting_heart_rate", "time_zone": "UTC" }), + ), + calculate(json!({ "operation": "summary", "quantity": "hrv_rmssd", "source": "manual" })), + calculate(json!({ "operation": "summary", "quantity": "body_weight" })), + calculate(json!({ "operation": "summary", "quantity": "not_a_quantity" })), + calculate( + json!({ "operation": "summary", "quantity": "hrv_rmssd", "from": "2026-10-04", "to": "2026-10-01", "time_zone": "UTC", "group": "day" }), + ), + json!({ "apply": "hrv-change", "target": "p9" }), + json!({ "apply": "hrv-change", "target": "p8" }), + json!({ "apply": "hrv-change", "target": "p3" }), + ]; + Case { name: "ties, deletions, and sources", records, requests } +} + +/// Calendar days across both clock changes in Chicago, with and without a +/// saved profile timezone. +fn clock_changes() -> Case { + let mut records = Vec::new(); + for (index, at) in [ + "2026-03-08T05:30:00.000Z", + "2026-03-08T06:30:00.000Z", + "2026-03-08T07:30:00.000Z", + "2026-03-09T04:59:59.999Z", + "2026-03-09T05:00:00.000Z", + "2026-11-01T04:30:00.000Z", + "2026-11-01T05:30:00.000Z", + "2026-11-01T06:30:00.000Z", + "2026-11-02T05:59:59.999Z", + "2026-11-02T06:00:00.000Z", + ] + .iter() + .enumerate() + { + records.push(sample(&format!("h{index}"), "heart_rate", at, 60.0 + index as f64)); + } + let requests = vec![ + calculate( + json!({ "operation": "summary", "quantity": "heart_rate", "group": "day", "time_zone": "America/Chicago" }), + ), + calculate( + json!({ "operation": "summary", "quantity": "heart_rate", "group": "month", "time_zone": "America/Chicago" }), + ), + calculate( + json!({ "operation": "coverage", "quantity": "heart_rate", "time_zone": "America/Chicago", "from": "2026-03-07", "to": "2026-03-10" }), + ), + calculate( + json!({ "operation": "summary", "quantity": "heart_rate", "from": "2026-11-01", "to": "2026-11-01", "time_zone": "America/Chicago" }), + ), + // No timezone and no profile: the daily-mean summary is left out. + calculate(json!({ "operation": "baseline", "quantity": "heart_rate" })), + calculate(json!({ "operation": "coverage", "quantity": "heart_rate" })), + calculate(json!({ "operation": "baseline", "quantity": "heart_rate", "time_zone": "+05:30" })), + calculate(json!({ "operation": "baseline", "quantity": "heart_rate", "time_zone": "Not/AZone" })), + ]; + Case { name: "clock changes", records, requests } +} + +/// Provider scores and summaries with reporting periods: ties inside one +/// record, periods that start before local midnight, bounds, mixed units. +fn provider_periods() -> Case { + let day = |date: &str| json!({ "period_type": "oura_sleep_day", "provider_date": date }); + let cycle = |start: &str, end: &str| json!({ "period_type": "whoop_physiological_cycle", "start_at": start, "end_at": end }); + let records = vec![ + json!({ "id": "s1", "record_type": "provider_score", "metric": "readiness", "value": 80, "unit": "score", "at": "2026-10-03T07:00:00.000Z", "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "s2", "record_type": "provider_score", "metric": "readiness", "value": 70, "unit": "score", "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "s3", "record_type": "provider_score", "metric": "readiness", "value": 90, "unit": "score", "at": "2026-10-04T07:00:00.000Z", "provider_reporting_periods": [day("2026-10-04"), day("2026-10-05")] }), + json!({ "id": "s4", "record_type": "provider_score", "metric": "readiness", "value": 60, "unit": "score", "source": "b", "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "s5", "record_type": "provider_score", "metric": "readiness", "value": 65, "unit": "score", "source": "manual", "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "s6", "record_type": "provider_score", "metric": "strain", "value": 12, "unit": "strain", "provider_reporting_periods": [cycle("2026-10-03T03:30:00.000Z", "2026-10-04T03:00:00.000Z")] }), + json!({ "id": "s7", "record_type": "provider_score", "metric": "strain", "value": 14, "unit": "strain", "provider_reporting_periods": [cycle("2026-10-04T04:30:00.000Z", "2026-10-05T03:30:00.000Z")] }), + json!({ "id": "s8", "record_type": "provider_score", "metric": "mixed", "value": 1, "unit": "a", "at": "2026-10-03T07:00:00.000Z" }), + json!({ "id": "s9", "record_type": "provider_score", "metric": "mixed", "value": 2, "unit": "b", "at": "2026-10-04T07:00:00.000Z" }), + json!({ "id": "m1", "record_type": "provider_summary", "summary_type": "sleep_need", "value": 480, "unit": "min", "at": "2026-10-03T07:00:00.000Z", "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "m2", "record_type": "provider_summary", "summary_type": "sleep_need", "value": 450, "unit": "min", "deleted": true, "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "p1", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-03T06:00:00.000Z", "value": 48, "provider_reporting_periods": [day("2026-10-03")] }), + ]; + let requests = vec![ + calculate( + json!({ "operation": "provider-period-summary", "quantity": "readiness", "record_kind": "provider-score", "period_type": "oura_sleep_day" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "readiness", "record_kind": "provider-score", "period_type": "oura_sleep_day", "source": "a" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "readiness", "record_kind": "provider-score", "period_type": "oura_sleep_day", "from": "2026-10-04", "to": "2026-10-05" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "strain", "record_kind": "provider-score", "period_type": "whoop_physiological_cycle" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "strain", "record_kind": "provider-score", "period_type": "whoop_physiological_cycle", "from": "2026-10-04T00:00:00.000Z" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "readiness", "record_kind": "provider-score", "period_type": "whoop_physiological_cycle" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "sleep_need", "record_kind": "provider-summary", "period_type": "oura_sleep_day" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "hrv_rmssd", "period_type": "oura_sleep_day" }), + ), + calculate(json!({ "operation": "summary", "quantity": "readiness", "record_kind": "provider-score" })), + calculate(json!({ "operation": "summary", "quantity": "mixed", "record_kind": "provider-score" })), + calculate(json!({ "operation": "summary", "quantity": "sleep_need", "record_kind": "provider-summary" })), + calculate(json!({ "operation": "summary", "quantity": "readiness", "record_kind": "session-summary" })), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "readiness", "record_kind": "provider-score" }), + ), + ]; + Case { name: "provider periods", records, requests } +} + +/// Summaries a session reported, two of one type in one session. +fn session_summaries() -> Case { + let summary = |kind: &str, value: f64, unit: &str| json!({ "summary_type": kind, "standard_value": value, "standard_unit": unit, "input_value": value, "input_unit": unit }); + let day = |date: &str| json!({ "period_type": "oura_activity_day", "provider_date": date }); + let records = vec![ + json!({ "id": "w1", "record_type": "workout_session", "start": "2026-10-03T17:00:00.000Z", "end": "2026-10-03T18:00:00.000Z", + "source_reported_summaries": [summary("total_distance", 5000.0, "m"), summary("total_distance", 5100.0, "m"), summary("calories", 400.0, "kcal")], + "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "n1", "record_type": "sleep_session", "start": "2026-10-02T23:00:00.000Z", "end": "2026-10-03T06:00:00.000Z", + "source_reported_summaries": [summary("total_distance", 10.0, "m")], + "provider_reporting_periods": [day("2026-10-03")] }), + json!({ "id": "w2", "record_type": "workout_session", "start": "2026-10-04T17:00:00.000Z", "end": "2026-10-04T18:00:00.000Z", "source": "b", + "source_reported_summaries": [summary("total_distance", 3000.0, "m")], + "provider_reporting_periods": [day("2026-10-04")] }), + ]; + let requests = vec![ + calculate( + json!({ "operation": "provider-period-summary", "quantity": "total_distance", "record_kind": "session-summary", "period_type": "oura_activity_day" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "calories", "record_kind": "session-summary", "period_type": "oura_activity_day" }), + ), + calculate( + json!({ "operation": "provider-period-summary", "quantity": "steps", "record_kind": "session-summary", "period_type": "oura_activity_day" }), + ), + ]; + Case { name: "session summaries", records, requests } +} + +/// Workout drift on a current, a deleted, and a sparse session. +fn workouts() -> Case { + let mut records = vec![ + json!({ "id": "w1", "record_type": "workout_session", "start": "2026-10-05T17:00:00.000Z", "end": "2026-10-05T17:40:00.000Z" }), + json!({ "id": "w2", "record_type": "workout_session", "start": "2026-10-06T17:00:00.000Z", "end": "2026-10-06T17:40:00.000Z", "deleted": true }), + json!({ "id": "w3", "record_type": "workout_session", "start": "2026-10-07T17:00:00.000Z", "end": "2026-10-07T17:40:00.000Z" }), + sample("x1", "heart_rate", "2026-10-07T17:10:00.000Z", 140.0), + ]; + for minute in 0..=40 { + records.push(sample( + &format!("hr{minute}"), + "heart_rate", + &format!("2026-10-05T17:{minute:02}:00.000Z"), + 120.0 + minute as f64, + )); + if minute % 10 == 0 { + records.push(json!({ "id": format!("hb{minute}"), "record_type": "measurement_sample", "quantity": "heart_rate", + "at": format!("2026-10-05T17:{minute:02}:00.000Z"), "value": 100.0 + minute as f64, "source": "b" })); + } + } + let requests = vec![ + calculate(json!({ "operation": "workout-drift", "quantity": "heart_rate", "session": "w1" })), + calculate(json!({ "operation": "workout-drift", "quantity": "heart_rate", "session": "w1", "source": "a" })), + calculate(json!({ "operation": "workout-drift", "quantity": "heart_rate", "session": "w2" })), + calculate(json!({ "operation": "workout-drift", "quantity": "heart_rate", "session": "w3" })), + calculate(json!({ "operation": "workout-drift", "quantity": "heart_rate", "session": "hr1" })), + calculate(json!({ "operation": "workout-drift", "quantity": "heart_rate" })), + ]; + Case { name: "workouts", records, requests } +} + +/// One-record methods that read more than the target: a linked workout, a +/// removed one, earlier windows, same-source sessions, the profile, and +/// heart-rate samples inside a session. Edited, malformed, coaching, and +/// range skill text. +fn one_record_lookups() -> Case { + let mut records = vec![ + json!({ "id": "profile", "record_type": "athlete_profile", "default_time_zone": "America/Chicago", "sex": "female" }), + json!({ "id": "w", "record_type": "workout_session", "start": "2026-10-02T17:00:00.000Z", "end": "2026-10-02T17:45:00.000Z" }), + json!({ "id": "gone", "record_type": "workout_session", "start": "2026-10-03T17:00:00.000Z", "end": "2026-10-03T17:30:00.000Z", "deleted": true }), + json!({ "id": "rpe", "record_type": "athlete_report", "report_type": "session_effort", "at": "2026-10-02T18:15:00.000Z", "rating": 15, "rating_scale": "6-20", "workout": "w" }), + json!({ "id": "rpe-gone", "record_type": "athlete_report", "report_type": "session_effort", "at": "2026-10-03T18:15:00.000Z", "rating": 7, "rating_scale": "0-10", "workout": "gone" }), + json!({ "id": "night", "record_type": "sleep_session", "start": "2026-10-01T23:00:00.000Z", "end": "2026-10-02T07:00:00.000Z", "asleep_seconds": 25200, "in_bed_seconds": 28800 }), + json!({ "id": "night2", "record_type": "sleep_session", "start": "2026-10-02T23:10:00.000Z", "end": "2026-10-03T07:05:00.000Z", "asleep_seconds": 25000, "in_bed_seconds": 28500 }), + json!({ "id": "night-b", "record_type": "sleep_session", "start": "2026-10-02T22:00:00.000Z", "end": "2026-10-03T06:00:00.000Z", "source": "b" }), + ]; + for minute in 0..12 { + records.push(sample( + &format!("h{minute}"), + "heart_rate", + &format!("2026-10-02T02:{minute:02}:00.000Z"), + 58.0 - (minute.min(6)) as f64, + )); + } + for day in 1..=9 { + records.push(point( + &format!("v{day}"), + "hrv_rmssd", + &format!("2026-09-{:02}T06:00:00.000Z", day + 20), + 50.0 + day as f64, + )); + } + let edited = + "```ath-calculation\nname: hrv-change\nuse: earlier_window_change\nwindow_days: 5\nminimum_days: 3\n```\n"; + // The 2.1.2 zone and load blocks read the workout's own fields and the + // profile. Their operations keep their arithmetic (D230); the shipped + // 3.0.0 files read intensity references, which need a database (D326). + let zones_2_1_2 = "```ath-calculation\nname: heart-rate-zones\nuse: time_in_zones\nsample_field: heart_rate_samples\nmaximum_field: maximum_heart_rate_bpm\nmax_gap_ms: 60000\nzone: 0.60\nzone: 0.70\nzone: 0.80\nzone: 0.90\n```\n"; + let load_2_1_2 = "```ath-calculation\nname: training-load-heart-rate\nuse: banister_trimp\nsample_field: heart_rate_samples\nrest_field: resting_heart_rate_bpm\nmaximum_field: maximum_heart_rate_bpm\nmax_gap_ms: 60000\nmale_coefficient: 0.64\nmale_exponent: 1.92\nfemale_coefficient: 0.86\nfemale_exponent: 1.67\n```\n"; + let requests = vec![ + json!({ "apply": "training-load-effort", "target": "rpe" }), + json!({ "apply": "training-load-effort", "target": "rpe-gone" }), + json!({ "apply": "hrv-change", "target": "v9" }), + json!({ "apply_text": edited, "target": "v9" }), + json!({ "apply": "sleep-regularity", "target": "night2" }), + json!({ "apply": "sleep-timing", "target": "night2" }), + json!({ "apply": "sleep-efficiency", "target": "night" }), + json!({ "apply": "resting-heart-rate", "target": "night" }), + json!({ "apply": "heart-rate-zones", "target": "w" }), + json!({ "apply": "training-load-heart-rate", "target": "w" }), + json!({ "apply_text": zones_2_1_2, "target": "w" }), + json!({ "apply_text": load_2_1_2, "target": "w" }), + json!({ "apply": "sleep-change", "target": "night2" }), + json!({ "apply": "summary", "target": "v9" }), + json!({ "apply": "crossfit", "target": "w" }), + json!({ "apply": "no-such-skill", "target": "w" }), + json!({ "apply": "hrv-change", "target": "not-written" }), + json!({ "apply_text": "no block here", "target": "v9" }), + json!({ "apply_text": "```ath-calculation\nname: later\nuse: a_newer_operation\n```\n", "target": "v9" }), + json!({ "apply_text": "```ath-calculation\nname: broken\nuse: field\n", "target": "v9" }), + ]; + Case { name: "one-record lookups", records, requests } +} + +/// The receipt lists at most 1,000 input references: 1,000 inputs list all, +/// 1,001 inputs list 1,000 and say so. +fn receipt_cap() -> Case { + let mut records = Vec::new(); + for index in 0..1_001 { + let source = if index < 1_000 { "a" } else { "b" }; + records.push(json!({ "id": format!("c{index}"), "record_type": "measurement_sample", "quantity": "heart_rate", + "at": format!("2026-10-10T{:02}:{:02}:{:02}.000Z", index / 3600, (index / 60) % 60, index % 60), + "value": 60 + index % 7, "source": source })); + } + let requests = vec![ + calculate(json!({ "operation": "summary", "quantity": "heart_rate", "source": "a" })), + calculate(json!({ "operation": "summary", "quantity": "heart_rate" })), + ]; + Case { name: "receipt cap", records, requests } +} diff --git a/tests/calculation_support/mod.rs b/tests/calculation_support/mod.rs index 2559ebbb..55c9403c 100644 --- a/tests/calculation_support/mod.rs +++ b/tests/calculation_support/mod.rs @@ -27,12 +27,19 @@ //! unless `authorship` is given. //! - `planned_session`: data fields as written, with optional //! `completed_workout` (the `id` of a workout); the athlete authors it. +//! - `provider_score`: `metric`, `value`, `unit`, optional `at`, `scale`, and +//! any other data fields. `provider_summary`: the same with `summary_type`. //! //! Any record may name a second `source` (`"source": "b"`); it gets its own -//! wearable source. +//! wearable source. A source whose name starts with `manual` is a manual +//! source. `"deleted": true` deletes the record after it is written, and +//! `{"delete": ""}` deletes an earlier record, such as `source:b`, and +//! `{"correct": "", "data": {...}}` replaces some of its data fields. #![allow(dead_code)] +pub mod cases; + use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -120,7 +127,8 @@ impl Lab { return id.clone(); } let id = self.id(&format!("source:{name}")); - let data = json!({ "source_type": "wearable", "data_writer": format!("Device {name}"), "data_route": "test" }); + let source_type = if name.starts_with("manual") { "manual" } else { "wearable" }; + let data = json!({ "source_type": source_type, "data_writer": format!("Device {name}"), "data_route": "test" }); self.create(RecordType::Source, &id, data, None, tool()); self.sources.insert(name.to_string(), id.clone()); id @@ -177,6 +185,69 @@ impl Lab { } pub fn write_one(&mut self, record: &serde_json::Value) { + if let Some(short) = record.get("delete").and_then(|value| value.as_str()) { + let id = self.id(short); + self.delete(&id); + return; + } + if let Some(short) = record.get("correct").and_then(|value| value.as_str()) { + let id = self.id(short); + self.correct(&id, &record["data"]); + return; + } + self.write_record(record); + if record.get("deleted").and_then(|value| value.as_bool()) == Some(true) { + let id = self.id(record["id"].as_str().unwrap()); + self.delete(&id); + } + } + + /// Delete a current record, keeping its history. + fn delete(&mut self, id: &str) { + let revision = self.store.get_record(id).unwrap().expect("a record to delete").current_revision; + let deletion = athleticstandard::store::Deletion { + record_id: id.to_string(), + expected_revision: revision, + deleted_by: tool(), + deleted_at: Some("2026-01-02T00:00:00.000Z".to_string()), + }; + self.store.apply(Changes { deletions: vec![deletion], ..Changes::default() }).unwrap(); + } + + /// Replace some data fields of a current record with a correction, so its + /// revision advances. + fn correct(&mut self, id: &str, fields: &serde_json::Value) { + let current = self.store.get_record(id).unwrap().expect("a record to correct"); + let mut data: serde_json::Value = serde_json::from_str(¤t.data.to_json()).unwrap(); + for (key, value) in fields.as_object().expect("fields to replace") { + data[key] = value.clone(); + } + let value: Value = json::parse(&data.to_string()).unwrap(); + let correction = athleticstandard::store::Correction { + record_id: id.to_string(), + expected_revision: current.current_revision, + data: RecordData::decode(current.record_type(), &value).unwrap(), + extensions: athleticstandard::store::ExtensionsUpdate::Keep, + changed_by: tool(), + became_known_at: Some("2026-01-03T00:00:00.000Z".to_string()), + became_known_at_basis: athleticstandard::model::BecameKnownAtBasis::LocalWrite, + stale_style: athleticstandard::store::write::StaleStyle::Revision, + }; + self.store.apply(Changes { corrections: vec![correction], ..Changes::default() }).unwrap(); + } + + /// Every record as current-record JSON, deleted ones included, in creation + /// order: what an app supplies to a memory snapshot. + pub fn current_records(&self) -> Value { + let options = athleticstandard::store::read::ListOptions { + record_type: None, + include_deleted: true, + limit: athleticstandard::store::read::MAX_LIST_LIMIT, + }; + Value::Array(self.store.list_records(&options).unwrap().iter().map(|record| record.to_value()).collect()) + } + + fn write_record(&mut self, record: &serde_json::Value) { let kind = record["record_type"].as_str().unwrap(); let id = self.id(record["id"].as_str().unwrap()); let source_name = record.get("source").and_then(|value| value.as_str()).unwrap_or("a").to_string(); @@ -197,7 +268,9 @@ impl Lab { "input_timestamp": receipt(&when), "value": { "standard_value": value, "standard_unit": unit, "input_value": value, "input_unit": unit } }); - for (key, extra) in rest(record, &["id", "record_type", "quantity", "at", "value", "basis", "source"]) { + for (key, extra) in + rest(record, &["id", "record_type", "quantity", "at", "value", "basis", "source", "deleted"]) + { data[key] = extra; } if let Some(basis) = record.get("basis") { @@ -213,7 +286,7 @@ impl Lab { "sleep_session" | "workout_session" => { let source = self.source(&source_name); let (start, end) = (at("start").unwrap(), at("end").unwrap()); - let mut data = rest(record, &["id", "record_type", "start", "end", "source"]); + let mut data = rest(record, &["id", "record_type", "start", "end", "source", "deleted"]); data.insert("source_id".into(), json!(source)); data.insert("received_at".into(), json!(end)); data.insert("received_at_basis".into(), json!("import_time")); @@ -228,7 +301,7 @@ impl Lab { } "athlete_report" => { let when = at("at").unwrap(); - let mut data = rest(record, &["id", "record_type", "at", "workout"]); + let mut data = rest(record, &["id", "record_type", "at", "workout", "deleted"]); data.insert("reported_at".into(), json!(when)); data.insert("input_reported_at".into(), receipt(&when)); data.entry("reported_via").or_insert(json!("text")); @@ -238,7 +311,7 @@ impl Lab { self.create(RecordType::AthleteReport, &id, serde_json::Value::Object(data), None, athlete()); } "athlete_profile" => { - let data = rest(record, &["id", "record_type"]); + let data = rest(record, &["id", "record_type", "deleted"]); self.create(RecordType::AthleteProfile, &id, serde_json::Value::Object(data), None, athlete()); } "benchmark_result" => { @@ -369,6 +442,39 @@ impl Lab { }; self.create(record_type, &id, serde_json::Value::Object(data), None, athlete()); } + "provider_score" | "provider_summary" => { + let source = self.source(&source_name); + let key = if kind == "provider_score" { "metric" } else { "summary_type" }; + let value = &record["value"]; + let unit = record["unit"].as_str().unwrap(); + let mut data = rest(record, &["id", "record_type", "at", "value", "unit", "source", "deleted"]); + data.insert("source_id".into(), json!(source)); + data.insert("received_at".into(), json!("2026-01-01T00:00:00.000Z")); + data.insert("received_at_basis".into(), json!("import_time")); + data.insert( + "value".into(), + json!({ "standard_value": value, "standard_unit": unit, "input_value": value, "input_unit": unit }), + ); + match at("at") { + Some(when) => { + data.insert("recorded_at".into(), json!(when)); + data.insert("input_timestamp".into(), receipt(&when)); + } + None => { + data.insert( + "input_timestamp".into(), + json!({ "timestamp_missing_reason": "not_provided_by_source", "utc_offset_missing_reason": "not_provided_by_source" }), + ); + } + } + if kind == "provider_score" { + data.entry("scale").or_insert(json!("0-100")); + } + assert!(data.contains_key(key), "a {kind} needs {key}"); + let record_type = + if kind == "provider_score" { RecordType::ProviderScore } else { RecordType::ProviderSummary }; + self.create(record_type, &id, serde_json::Value::Object(data), None, tool()); + } other => panic!("the lab does not write {other}"), } } @@ -446,6 +552,15 @@ impl Lab { /// (names), `other_quantity`, `session` (a short ID), `from`, `to`, /// `time_zone`, `group`, and `period_type`. pub fn calculate(&mut self, request: &serde_json::Value) -> serde_json::Value { + let options = self.options(request); + match calculate::calculate_range(&self.store, &options) { + Ok(receipt) => serde_json::from_str(&json::encode(&receipt)).unwrap(), + Err(error) => json!({ "error": error.to_string() }), + } + } + + /// The range options for a short request, with full IDs. + pub fn options(&mut self, request: &serde_json::Value) -> athleticstandard::calculate::CalculateOptions { use athleticstandard::calculate::{CalculateOptions, Group, Operation, RecordKind}; let text = |key: &str| request.get(key).and_then(|value| value.as_str()).map(str::to_string); let mut options = CalculateOptions::new( @@ -467,10 +582,7 @@ impl Lab { } options.provider_period_type = text("period_type").map(|kind| athleticstandard::model::ProviderReportingPeriodType::parse(&kind).unwrap()); - match calculate::calculate_range(&self.store, &options) { - Ok(receipt) => serde_json::from_str(&json::encode(&receipt)).unwrap(), - Err(error) => json!({ "error": error.to_string() }), - } + options } /// Save a verified copy of the database to `destination`. From 76bb3495b8ac54b86248877f085e371819ce2e15 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 18:22:06 -0600 Subject: [PATCH 06/30] Turn on the ureq and uuid features the sign-in runtime uses. `src/runtime/sign_in.rs` and `src/runtime/host_sync.rs` send and read JSON with `ureq` and make random `uuid` values, but the root manifest did not turn on `ureq/json` or `uuid/v4`. A workspace build got them from `host/`, so `cargo check -p athleticstandard --bin ath` failed only when the program was built alone. The `cli` feature now turns both on, so the phone build without it still has neither. Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 553585b1..1eb0f327 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,9 @@ required-features = ["changesets"] # log planning, and the network runtime. Phone builds turn it off, so they hold # the store and calculations without any network code (D327). default = ["cli"] -cli = ["dep:clap", "dep:flate2", "dep:quick-xml", "dep:terminal_size", "dep:ureq", "dep:zip"] +# The sign-in and sync runtime sends and reads JSON with `ureq` and makes +# random `uuid` values, so the feature turns those on. +cli = ["dep:clap", "dep:flate2", "dep:quick-xml", "dep:terminal_size", "dep:ureq", "dep:zip", "ureq/json", "uuid/v4"] # Record the rows a write changes and replay them on another copy (D268). # Only the host program turns this on. changesets = [] From 9090e11596596b4516df8c2a1ab6719447fff911 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 18:24:14 -0600 Subject: [PATCH 07/30] Run single-record and range calculations from the phone packages. The phone binding gains `RecordSnapshotBuilder` and `RecordSnapshot`, which calculate on records an app supplies, and `apply`, `applyWith`, and `calculate` on an open `Database`. Both give the desktop JSON. A skill is either a shipped name or the text of an edited copy, `applyWith` takes the options of `ath apply --set` for the threshold methods, and `RangeRequest` carries the options of `ath calculate`. The phone test bundle gains a calculation suite, with the 42 worked examples and the reader edge cases, each with its records, a SQLite file, and the desktop outcome, and a coaching suite for the 20 record-example blocks. All 113 calculation requests match the desktop through the database. Through the memory snapshot, 99 match and 14, which read device recordings or intensity references, get the documented refusal, which the bundle carries as `expected_memory`. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 + build-history/v3.0.0/progress.md | 37 +- mobile/Cargo.toml | 10 + mobile/README.md | 34 ++ .../ai/athleticstandard/CalculationTest.kt | 182 ++++++++ .../ai/athleticstandard/ModelVectorTest.kt | 11 +- mobile/scripts/test-apple.sh | 9 +- mobile/src/calculate.rs | 273 ++++++++++++ mobile/src/lib.rs | 5 + mobile/src/store.rs | 47 ++ .../CalculationTests.swift | 159 +++++++ .../ModelVectorTests.swift | 27 +- mobile/tests/fixtures.rs | 417 +++++++++++++++++- 13 files changed, 1200 insertions(+), 14 deletions(-) create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt create mode 100644 mobile/src/calculate.rs create mode 100644 mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift diff --git a/Cargo.lock b/Cargo.lock index f7111811..1440aa8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -240,6 +240,9 @@ version = "3.0.0" dependencies = [ "athleticstandard", "athleticstandard-core", + "rusqlite", + "serde", + "serde_json", "sha2", "tempfile", "uniffi", diff --git a/build-history/v3.0.0/progress.md b/build-history/v3.0.0/progress.md index 92f88eb9..33379dec 100644 --- a/build-history/v3.0.0/progress.md +++ b/build-history/v3.0.0/progress.md @@ -18,7 +18,7 @@ Status: **being built; not released.** The plan is [spec.md](spec.md). | 12 | Phone library plan, decisions D325–D333 ([plan](appendix/mobile-library-plan.md)) | done | | 13 | UniFFI crate, validation from the Swift package and the Android library | Mac and Android emulator pass; iPhone simulator not run | | 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | Mac and two Android emulators pass; iPhone simulator and iCloud not run | -| 15 | Calculations from memory and SQLite through one reader interface | not started | +| 15 | Calculations from memory and SQLite through one reader interface | Mac and two Android emulators pass; iPhone simulator not run | | 16 | Host client for Swift and Kotlin with browser sign-in | not started | | 17 | Release packaging, phone test runs, release gate | not started | @@ -731,3 +731,38 @@ These follow the guide and the decisions. Each is open to review. - Not run: the iPhone simulator (it needs Xcode's license accepted on this machine), and the iCloud Drive picker on a signed-in device. +## Step 15: calculations from memory and from a file + +- The calculation settings, methods, range arithmetic, receipts, calendar rules, and + shipped skills moved into the core, with the 3.0.0 workout operations, their + results, and the threshold outcomes. The desktop keeps the SQL in + `src/calculate/sqlite.rs`, `recorded.rs`, `recorded_inputs.rs`, and `window.rs`, + unchanged, and every existing calculation, golden, and query-plan test passed + without a change to an expected value. +- `tests/calculate_readers.rs` runs the 42 worked examples and 71 requests over seven + synthetic cases on both readers and compares the complete results. The cases cover + equal times, deleted records and a deleted source, a manual source, a corrected + record, both Chicago clock changes, a missing profile timezone, provider periods with + several periods in one record and periods that start before local midnight, two + summaries of one type in one session, mixed units, workout drift on a deleted + session, linked and removed workouts, edited, malformed, coaching, and range skill + text, and the receipt cap at 1,000 and 1,001 inputs. +- A memory snapshot does not hold device recordings, so the methods that read + recordings or intensity references are refused from memory with a message that says + to run them on a database (D326). 12 worked examples and 2 case requests get that + refusal; the test checks its exact text. The other 30 examples and 69 requests match. +- The input limit holds on both readers at 100,000 inputs and refuses 100,001. +- The phone bundle's calculation suite has 49 cases and 113 requests. Through the + database, all of them match the desktop. Through the memory snapshot, 99 match and + 14 give the documented refusal. Both hold in Rust, in the Swift package on a Mac, + and in the Android library on both emulators. The coaching suite checks the 20 + record-example blocks as 53 shape checks. +- `applyWith` on a snapshot and on a `Database` takes the options of + `ath apply --set`, so a phone runs the threshold methods on a file. +- Building `ath` alone (`cargo check -p athleticstandard --bin ath`) failed, because + the root manifest did not turn on the `ureq` JSON and `uuid` v4 features the sign-in + runtime uses; a workspace build got them from `host/`. The `cli` feature now turns + them on. +- One clock fallback remains in range arithmetic: a calendar date that does not read + falls back to today. The calendar range check refuses such a date first, so no + request reaches it. diff --git a/mobile/Cargo.toml b/mobile/Cargo.toml index 8b6fa281..777cf07a 100644 --- a/mobile/Cargo.toml +++ b/mobile/Cargo.toml @@ -30,8 +30,18 @@ sha2 = { version = "0.11.0", optional = true } uniffi = "=0.33.0" [dev-dependencies] +# The desktop library with every feature, and SQLite, for the test helpers +# it shares with the desktop tests. +athleticstandard = { path = ".." } +rusqlite = { version = "0.42", features = ["bundled"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = { version = "1.0.154", features = ["preserve_order", "float_roundtrip"] } tempfile = "3.27.0" [[test]] name = "store" required-features = ["sqlite"] + +[[test]] +name = "fixtures" +required-features = ["sqlite"] diff --git a/mobile/README.md b/mobile/README.md index 63889425..19166b55 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -58,6 +58,40 @@ thread, so call them away from the main thread. The binding resolves the system in front of app folders (`/var` on iOS, `/data/user/0` on Android) before it opens a file. The desktop store refuses a path through a symbolic link. +## Calculations + +Calculations run the desktop methods on records from memory or from a file +([D326](../build-history/v3.0.0/decisions.md#d326-calculations-ask-for-their-data-through-one-reader-interface)). +Both entry points give the desktop JSON: the `ath apply --json` object and the +`ath calculate --json` receipt. + +- **From memory.** `RecordSnapshotBuilder` takes batches of current records as a JSON + array, the shape `listRecords` returns. Supply the sources, the athlete profile, and + the samples the calculation reads; deleted records may be included. A batch with an + invalid record or a repeated ID is refused and leaves the builder as it was. + `finish()` gives a `RecordSnapshot`, which cannot change and can be shared between + threads. The records supplied are all the data a calculation sees: a range input + whose source is missing is left out, and a missing profile means no saved timezone. +- **From a file.** `Database.apply` and `Database.calculate` read the file inside one + read snapshot. +- `apply(recordId, skill)` runs one calculation skill on one record. `skill` is + `CalculationSkill.Shipped(name)` for a skill shipped with the library, or + `CalculationSkill.Text(text)` for an edited copy. A coaching skill or a range + calculation is refused with the command that runs it. +- `applyWith(recordId, skill, parameters)` takes the options of `ath apply --set`. A + threshold method may run without a record and takes `name=value` parameters, such + as `operation` and `end_date`. Every other skill needs a record and takes none. +- A `RecordSnapshot` does not hold device recordings yet. The 3.0.0 methods that read + recordings or the intensity reference in effect, such as `heart-rate-zones`, + `training-load-heart-rate`, and the threshold methods, are refused from memory with a + message that says to run them on a database. Run them on a `Database`. +- `calculate(request)` runs one of the eight range calculations. `RangeRequest` has the + options `ath calculate` takes; `RangeGroup.Ungrouped` is the desktop's `none`. +- `shippedCalculationNames()` and `shippedSkillText(name)` read the shipped skills. + +Calendar days use the bundled timezone data, never the phone's own timezone, so the +same request gives the same answer on every device. + ### Where to keep the file Recommend local storage, and keep iCloud Drive and other locations selectable diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt new file mode 100644 index 00000000..8147cc2f --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt @@ -0,0 +1,182 @@ +package ai.athleticstandard + +import android.util.Log +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** + * Every worked calculation example and every reader case, through the Android + * library's memory snapshot and its database, compared with the desktop result in + * the fixture bundle (D326, D333). A request with `expected_memory` reads device + * recordings, so the snapshot must give exactly that refusal. + */ +@RunWith(AndroidJUnit4::class) +class CalculationTest { + private fun operation(name: String) = when (name) { + "summary" -> RangeOperation.SUMMARY + "baseline" -> RangeOperation.BASELINE + "trend" -> RangeOperation.TREND + "coverage" -> RangeOperation.COVERAGE + "compare-sources" -> RangeOperation.COMPARE_SOURCES + "correlation" -> RangeOperation.CORRELATION + "workout-drift" -> RangeOperation.WORKOUT_DRIFT + else -> RangeOperation.PROVIDER_PERIOD_SUMMARY + } + + private fun recordKind(name: String) = when (name) { + "measurement" -> RangeRecordKind.MEASUREMENT + "provider-score" -> RangeRecordKind.PROVIDER_SCORE + "provider-summary" -> RangeRecordKind.PROVIDER_SUMMARY + else -> RangeRecordKind.SESSION_SUMMARY + } + + private fun group(name: String) = when (name) { + "none" -> RangeGroup.UNGROUPED + "day" -> RangeGroup.DAY + "week" -> RangeGroup.WEEK + else -> RangeGroup.MONTH + } + + private fun JSONObject.text(key: String): String? = if (isNull(key)) null else getString(key) + + private fun rangeRequest(fields: JSONObject) = RangeRequest( + operation = operation(fields.getString("operation")), + quantity = fields.getString("quantity"), + recordKind = recordKind(fields.getString("record_kind")), + group = group(fields.getString("group")), + from = fields.text("from"), + to = fields.text("to"), + timeZone = fields.text("time_zone"), + sourceId = fields.text("source_id"), + compareSourceId = fields.text("compare_source_id"), + otherQuantity = fields.text("other_quantity"), + workoutSessionId = fields.text("workout_session_id"), + providerPeriodType = fields.text("provider_period_type"), + ) + + /** `ok ` or `error ` from a bundle's expected outcome. */ + private fun wanted(expected: JSONObject): String = if (expected.has("output")) { + "ok " + expected.getString("output") + } else { + val error = expected.getJSONObject("error") + "error ${error.getString("code")} ${error.getString("detail")}" + } + + /** `ok ` or `error `, the same for both entry points. */ + private fun outcome(body: () -> ByteArray): String = try { + "ok " + body().decodeToString() + } catch (error: AthleticStandardException) { + "error ${error.code} ${error.detail}" + } + + @Test + fun everyCalculationMatchesTheDesktop() { + val suite = FixtureBundle.suite("calculations") + val cases = suite.getJSONArray("cases") + val counts = suite.getJSONObject("counts") + val folder = StoreTest.folder() + var requests = 0 + var memoryRefusals = 0 + val failures = mutableListOf() + for (number in 0 until cases.length()) { + val item = cases.getJSONObject(number) + val name = item.getString("name") + val builder = RecordSnapshotBuilder() + val batches = item.getJSONArray("record_batches") + for (index in 0 until batches.length()) { + builder.addRecords(batches.getString(index).toByteArray(Charsets.UTF_8)) + } + assertEquals(item.getLong("record_count").toULong(), builder.recordCount()) + val snapshot = builder.finish() + val copy = StoreTest.fixture(item.getString("database"), folder) + val database = Database.open(copy.path, OpenDatabaseOptions(readOnly = true)) + val list = item.getJSONArray("requests") + for (index in 0 until list.length()) { + requests += 1 + val request = list.getJSONObject(index) + val wanted = wanted(request.getJSONObject("expected")) + val wantedMemory = if (request.has("expected_memory")) { + memoryRefusals += 1 + wanted(request.getJSONObject("expected_memory")) + } else { + wanted + } + val memory: String + val file: String + if (request.getString("kind") == "apply") { + val recordId = request.text("record_id") + val fields = request.getJSONObject("skill") + val skill = if (fields.has("shipped")) { + CalculationSkill.Shipped(fields.getString("shipped")) + } else { + CalculationSkill.Text(fields.getString("text")) + } + val given = request.getJSONObject("parameters") + val parameters = given.keys().asSequence().associateWith { given.getString(it) } + if (recordId != null && parameters.isEmpty()) { + memory = outcome { snapshot.apply(recordId, skill) } + file = outcome { database.apply(recordId, skill) } + } else { + memory = outcome { snapshot.applyWith(recordId, skill, parameters) } + file = outcome { database.applyWith(recordId, skill, parameters) } + } + } else { + val range = rangeRequest(request.getJSONObject("request")) + memory = outcome { snapshot.calculate(range) } + file = outcome { database.calculate(range) } + } + if (memory != wantedMemory || file != wanted) { + failures += "$name: expected ${wanted.take(200)}\n memory ${memory.take(200)}\n file ${file.take(200)}" + } + } + database.closeDatabase() + database.close() + snapshot.close() + builder.close() + File(copy.path).delete() + } + Log.i( + "AthleticStandard", + "calculations: ${cases.length()} cases, $requests requests, $memoryRefusals need a database, ${failures.size} failed", + ) + assertEquals(counts.getInt("cases"), cases.length()) + assertEquals(counts.getInt("requests"), requests) + assertEquals(counts.getInt("memory_refusals"), memoryRefusals) + assertTrue(failures.take(10).joinToString("\n"), failures.isEmpty()) + } + + @Test + fun shippedSkillsAreListed() { + val names = shippedCalculationNames() + assertTrue("hrv-change" in names) + assertTrue("summary" in names) + assertFalse("crossfit" in names) + assertTrue(shippedSkillText("crossfit")!!.contains("kind: coaching")) + } + + @Test + fun aRefusedBatchLeavesTheBuilderAsItWas() { + val builder = RecordSnapshotBuilder() + try { + builder.addRecords("""[{"record_id":"x"}]""".toByteArray()) + fail("an invalid batch was accepted") + } catch (error: AthleticStandardException) { + assertEquals("invalid", error.code) + } + assertEquals(0uL, builder.recordCount()) + builder.finish() + try { + builder.finish() + fail("a finished builder finished again") + } catch (error: AthleticStandardException) { + assertEquals("closed", error.code) + } + } +} diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt index 059d6714..cb42299b 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ModelVectorTest.kt @@ -14,8 +14,13 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ModelVectorTest { @Test - fun everyModelVectorMatchesTheDesktop() { - val suite = FixtureBundle.suite("model-vectors") + fun everyModelVectorMatchesTheDesktop() = run("model-vectors") + + @Test + fun everyCoachingRecordExampleMatchesTheDesktop() = run("coaching-records") + + private fun run(name: String) { + val suite = FixtureBundle.suite(name) val cases = suite.getJSONArray("cases") val counts = suite.getJSONObject("counts") var run = 0 @@ -47,7 +52,7 @@ class ModelVectorTest { } } } - Log.i("AthleticStandard", "model-vectors: $run run, $skipped skipped, ${failures.size} failed") + Log.i("AthleticStandard", "$name: $run run, $skipped skipped, ${failures.size} failed") assertEquals(counts.getInt("run"), run) assertEquals(counts.getInt("skipped"), skipped) assertEquals(counts.getInt("cases"), cases.length()) diff --git a/mobile/scripts/test-apple.sh b/mobile/scripts/test-apple.sh index 223b33eb..b828a06d 100755 --- a/mobile/scripts/test-apple.sh +++ b/mobile/scripts/test-apple.sh @@ -35,7 +35,14 @@ rm -rf "$ROUNDTRIP_OUT" mkdir -p "$ROUNDTRIP_OUT" cd "$ROOT/mobile/swift" -ATH_MOBILE_FIXTURES="$FIXTURES" ATH_MOBILE_ROUNDTRIP_OUT="$ROUNDTRIP_OUT/mac" swift test +# Some Command Line Tools releases leave the Swift Testing macro plugin out of +# the search path; naming its folder is harmless when it is already found. +SWIFT_TEST_FLAGS=() +PLUGINS="$(xcode-select -p)/usr/lib/swift/host/plugins/testing" +if [ -d "$PLUGINS" ]; then + SWIFT_TEST_FLAGS=(-Xswiftc -plugin-path -Xswiftc "$PLUGINS") +fi +ATH_MOBILE_FIXTURES="$FIXTURES" ATH_MOBILE_ROUNDTRIP_OUT="$ROUNDTRIP_OUT/mac" swift test "${SWIFT_TEST_FLAGS[@]}" # The desktop `ath` checks the file the phone library saved. "$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$ROUNDTRIP_OUT/mac/phone-edited.ath.sqlite" diff --git a/mobile/src/calculate.rs b/mobile/src/calculate.rs new file mode 100644 index 00000000..eaea58c9 --- /dev/null +++ b/mobile/src/calculate.rs @@ -0,0 +1,273 @@ +//! Calculations on a phone (D326). +//! +//! A `RecordSnapshotBuilder` takes batches of current records as UTF-8 JSON +//! and gives an immutable `RecordSnapshot`. `apply`, `apply_with`, and +//! `calculate` on the snapshot run the desktop calculations on those records. +//! `Database` runs the same calls on an open file. Results are the desktop +//! JSON: the `ath apply --json` object and the `ath calculate --json` receipt. +//! +//! A snapshot does not hold device recordings yet, so it refuses the 3.0.0 +//! methods that read recordings or the intensity references in effect, with a +//! message that says to run them on a database (D326). + +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Arc, Mutex}; + +use athleticstandard_core::calculate::{self, CalculateOptions, Group, Operation, RecordKind}; +use athleticstandard_core::json; +use athleticstandard_core::model::ProviderReportingPeriodType; + +use crate::error::AthleticStandardError; +use crate::validate::parse_json; + +impl From for AthleticStandardError { + fn from(error: athleticstandard_core::Error) -> Self { + let detail = error.to_string(); + match error { + athleticstandard_core::Error::Invalid(validation) => validation.into(), + athleticstandard_core::Error::NotFound(_) => AthleticStandardError::NotFound { detail }, + athleticstandard_core::Error::Refused(_) => AthleticStandardError::Refused { detail }, + athleticstandard_core::Error::Other(_) => AthleticStandardError::Failed { detail }, + } + } +} + +/// Which calculation skill to run on one record. +#[derive(Debug, Clone, PartialEq, uniffi::Enum)] +pub enum CalculationSkill { + /// A skill shipped with this library, such as `hrv-change`, named as + /// `ath apply` names it. + Shipped { name: String }, + /// The complete text of a skill file, such as an edited copy. + Text { text: String }, +} + +/// The `--set name=value` parameters of `ath apply`, in a fixed order. +pub(crate) fn parameters(parameters: HashMap) -> BTreeMap { + parameters.into_iter().collect() +} + +impl CalculationSkill { + pub(crate) fn text(&self) -> Result { + match self { + CalculationSkill::Shipped { name } => { + Ok(athleticstandard_core::assets::resolve_shipped_calculation(name)?.to_string()) + } + CalculationSkill::Text { text } => Ok(text.clone()), + } + } +} + +/// A named range calculation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum RangeOperation { + Summary, + Baseline, + Trend, + Coverage, + CompareSources, + Correlation, + WorkoutDrift, + ProviderPeriodSummary, +} + +/// Which typed rows a range calculation reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum RangeRecordKind { + Measurement, + ProviderScore, + ProviderSummary, + SessionSummary, +} + +/// Calendar grouping for summary and baseline. `Ungrouped` is the desktop's +/// `none`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum RangeGroup { + Ungrouped, + Day, + Week, + Month, +} + +/// A range calculation request, with the options `ath calculate` takes. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct RangeRequest { + pub operation: RangeOperation, + /// A measurement quantity, provider metric, or summary type. + pub quantity: String, + pub record_kind: RangeRecordKind, + pub group: RangeGroup, + /// A calendar day (`YYYY-MM-DD`) or an exact UTC instant. + #[uniffi(default = None)] + pub from: Option, + #[uniffi(default = None)] + pub to: Option, + #[uniffi(default = None)] + pub time_zone: Option, + #[uniffi(default = None)] + pub source_id: Option, + #[uniffi(default = None)] + pub compare_source_id: Option, + #[uniffi(default = None)] + pub other_quantity: Option, + #[uniffi(default = None)] + pub workout_session_id: Option, + /// A provider reporting period type, such as `oura_sleep_day`. + #[uniffi(default = None)] + pub provider_period_type: Option, +} + +impl RangeRequest { + pub(crate) fn options(&self) -> Result { + let operation = match self.operation { + RangeOperation::Summary => Operation::Summary, + RangeOperation::Baseline => Operation::Baseline, + RangeOperation::Trend => Operation::Trend, + RangeOperation::Coverage => Operation::Coverage, + RangeOperation::CompareSources => Operation::CompareSources, + RangeOperation::Correlation => Operation::Correlation, + RangeOperation::WorkoutDrift => Operation::WorkoutDrift, + RangeOperation::ProviderPeriodSummary => Operation::ProviderPeriodSummary, + }; + let mut options = CalculateOptions::new(operation, self.quantity.clone()); + options.record_kind = match self.record_kind { + RangeRecordKind::Measurement => RecordKind::Measurement, + RangeRecordKind::ProviderScore => RecordKind::ProviderScore, + RangeRecordKind::ProviderSummary => RecordKind::ProviderSummary, + RangeRecordKind::SessionSummary => RecordKind::SessionSummary, + }; + options.group = match self.group { + RangeGroup::Ungrouped => Group::None, + RangeGroup::Day => Group::Day, + RangeGroup::Week => Group::Week, + RangeGroup::Month => Group::Month, + }; + options.from = self.from.clone(); + options.to = self.to.clone(); + options.time_zone = self.time_zone.clone(); + options.source_id = self.source_id.clone(); + options.compare_source_id = self.compare_source_id.clone(); + options.other_quantity = self.other_quantity.clone(); + options.workout_session_id = self.workout_session_id.clone(); + options.provider_period_type = match &self.provider_period_type { + None => None, + Some(name) => { + Some(ProviderReportingPeriodType::parse(name).ok_or_else(|| AthleticStandardError::Failed { + detail: format!( + "Unknown provider period type '{name}'. Known types: {}", + ProviderReportingPeriodType::NAMES.join(", ") + ), + })?) + } + }; + Ok(options) + } +} + +/// Collects batches of current records for a `RecordSnapshot`. A refused +/// batch leaves the builder as it was. After `finish`, the builder is spent. +#[derive(uniffi::Object)] +pub struct RecordSnapshotBuilder { + builder: Mutex>, +} + +#[uniffi::export] +impl RecordSnapshotBuilder { + #[uniffi::constructor] + pub fn new() -> Arc { + Arc::new(RecordSnapshotBuilder { builder: Mutex::new(Some(calculate::SnapshotBuilder::new())) }) + } + + /// Add a batch: a UTF-8 JSON array of current records, the shape + /// `listRecords` returns. Include sources, the athlete profile, and the + /// samples a calculation reads. Deleted records may be included. Returns + /// the number of records held after the batch. + pub fn add_records(&self, records: Vec) -> Result { + let batch = parse_json(&records)?; + let mut guard = self.builder.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let builder = guard + .as_mut() + .ok_or_else(|| AthleticStandardError::Closed { detail: "this snapshot builder already finished".into() })?; + Ok(builder.add_batch(&batch)? as u64) + } + + /// The number of records added so far. + pub fn record_count(&self) -> u64 { + let guard = self.builder.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + guard.as_ref().map_or(0, |builder| builder.len() as u64) + } + + /// The finished, immutable snapshot. + pub fn finish(&self) -> Result, AthleticStandardError> { + let builder = + self.builder.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take().ok_or_else(|| { + AthleticStandardError::Closed { detail: "this snapshot builder already finished".into() } + })?; + Ok(Arc::new(RecordSnapshot { snapshot: builder.finish() })) + } +} + +/// Records an app supplied, ready for calculations. It cannot change, and +/// several threads may calculate on it at once. +#[derive(uniffi::Object)] +pub struct RecordSnapshot { + snapshot: calculate::RecordSnapshot, +} + +#[uniffi::export] +impl RecordSnapshot { + /// The number of records supplied, deleted ones included. + pub fn record_count(&self) -> u64 { + self.snapshot.len() as u64 + } + + /// Run a calculation skill on one current record: the `ath apply --json` + /// object as UTF-8 JSON. + pub fn apply(&self, record_id: String, skill: CalculationSkill) -> Result, AthleticStandardError> { + let text = skill.text()?; + let result = calculate::apply_text(&self.snapshot, &text, &record_id)?; + Ok(json::encode(&result).into_bytes()) + } + + /// Run a calculation skill with the options of `ath apply --set`: a + /// threshold method may run without a record, and takes `name=value` + /// parameters such as `operation` and `end_date`. Every other skill needs + /// a record and takes none. A snapshot refuses the methods that read + /// device recordings or intensity references; run those on a `Database`. + pub fn apply_with( + &self, + record_id: Option, + skill: CalculationSkill, + parameters: HashMap, + ) -> Result, AthleticStandardError> { + let text = skill.text()?; + let result = calculate::apply_with( + &self.snapshot, + &text, + record_id.as_deref(), + &crate::calculate::parameters(parameters), + )?; + Ok(json::encode(&result).into_bytes()) + } + + /// Run a named range calculation: the `ath calculate --json` receipt as + /// UTF-8 JSON. + pub fn calculate(&self, request: RangeRequest) -> Result, AthleticStandardError> { + let receipt = calculate::calculate_range(&self.snapshot, &request.options()?)?; + Ok(json::encode(&receipt).into_bytes()) + } +} + +/// The names of the calculation skills shipped with this library, sorted. +#[uniffi::export] +pub fn shipped_calculation_names() -> Vec { + athleticstandard_core::assets::shipped_calculation_names().into_iter().map(str::to_string).collect() +} + +/// The shipped text of `skills//SKILL.md`, for any shipped skill, +/// including coaching skills. +#[uniffi::export] +pub fn shipped_skill_text(name: String) -> Option { + athleticstandard_core::assets::shipped_calculation(&name).map(str::to_string) +} diff --git a/mobile/src/lib.rs b/mobile/src/lib.rs index c1b306cd..0ff6a5c1 100644 --- a/mobile/src/lib.rs +++ b/mobile/src/lib.rs @@ -11,11 +11,16 @@ uniffi::setup_scaffolding!(); +mod calculate; mod error; #[cfg(feature = "sqlite")] mod store; mod validate; +pub use calculate::{ + shipped_calculation_names, shipped_skill_text, CalculationSkill, RangeGroup, RangeOperation, RangeRecordKind, + RangeRequest, RecordSnapshot, RecordSnapshotBuilder, +}; pub use error::{AthleticStandardError, PathSegment, ValidationIssue}; #[cfg(feature = "sqlite")] pub use store::{ diff --git a/mobile/src/store.rs b/mobile/src/store.rs index b3bbdde8..a9f96685 100644 --- a/mobile/src/store.rs +++ b/mobile/src/store.rs @@ -14,6 +14,7 @@ //! symbolic link, so the binding resolves the folder's real path first. A //! database file that is itself a link is still refused. +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard}; @@ -23,6 +24,7 @@ use athleticstandard::store::{CreateOptions, OpenOptions, Store}; use athleticstandard::Error; use sha2::{Digest, Sha256}; +use crate::calculate::{CalculationSkill, RangeRequest}; use crate::error::AthleticStandardError; use crate::validate::parse_json; @@ -336,6 +338,51 @@ impl Database { self.json_operation("records.delete", &request) } + /// Run a calculation skill on one current record of this file, inside one + /// read snapshot: the `ath apply --json` object as UTF-8 JSON. + pub fn apply(&self, record_id: String, skill: CalculationSkill) -> Result, AthleticStandardError> { + let text = skill.text()?; + self.with_store(|store| { + let result = + athleticstandard::calculate::apply_text(store.as_ref().expect("checked open"), &text, &record_id)?; + Ok(json::encode(&result).into_bytes()) + }) + } + + /// Run a calculation skill on this file with the options of `ath apply + /// --set`, inside one read snapshot: a threshold method may run without a + /// record, and takes `name=value` parameters. Every other skill needs a + /// record and takes none. + pub fn apply_with( + &self, + record_id: Option, + skill: CalculationSkill, + parameters: HashMap, + ) -> Result, AthleticStandardError> { + let text = skill.text()?; + let parameters = crate::calculate::parameters(parameters); + self.with_store(|store| { + let result = athleticstandard::calculate::apply_text_with( + store.as_ref().expect("checked open"), + &text, + record_id.as_deref(), + ¶meters, + )?; + Ok(json::encode(&result).into_bytes()) + }) + } + + /// Run a named range calculation on this file, inside one read snapshot: + /// the `ath calculate --json` receipt as UTF-8 JSON. + pub fn calculate(&self, request: RangeRequest) -> Result, AthleticStandardError> { + let options = request.options()?; + self.with_store(|store| { + let receipt = + athleticstandard::calculate::calculate_range(store.as_ref().expect("checked open"), &options)?; + Ok(json::encode(&receipt).into_bytes()) + }) + } + /// Run one of the protocol operations a phone may run on this database, /// with the npm client's input and output shapes as UTF-8 JSON. pub fn run_operation(&self, name: String, input: Vec) -> Result { diff --git a/mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift b/mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift new file mode 100644 index 00000000..286471e2 --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift @@ -0,0 +1,159 @@ +import AthleticStandard +import Foundation +import Testing + +/// Every worked calculation example and every reader case, through the Swift +/// package's memory snapshot and its database, compared with the desktop result +/// in the fixture bundle (D326, D333). A request with `expected_memory` reads +/// device recordings, so the snapshot must give exactly that refusal. +@Suite(.serialized) +struct CalculationTests { + static func operation(_ name: String) -> RangeOperation { + switch name { + case "summary": .summary + case "baseline": .baseline + case "trend": .trend + case "coverage": .coverage + case "compare-sources": .compareSources + case "correlation": .correlation + case "workout-drift": .workoutDrift + default: .providerPeriodSummary + } + } + + static func recordKind(_ name: String) -> RangeRecordKind { + switch name { + case "measurement": .measurement + case "provider-score": .providerScore + case "provider-summary": .providerSummary + default: .sessionSummary + } + } + + static func group(_ name: String) -> RangeGroup { + switch name { + case "none": .ungrouped + case "day": .day + case "week": .week + default: .month + } + } + + static func rangeRequest(_ fields: [String: Any]) -> RangeRequest { + RangeRequest( + operation: operation(fields["operation"] as! String), quantity: fields["quantity"] as! String, + recordKind: recordKind(fields["record_kind"] as! String), group: group(fields["group"] as! String), + from: fields["from"] as? String, to: fields["to"] as? String, timeZone: fields["time_zone"] as? String, + sourceId: fields["source_id"] as? String, compareSourceId: fields["compare_source_id"] as? String, + otherQuantity: fields["other_quantity"] as? String, + workoutSessionId: fields["workout_session_id"] as? String, + providerPeriodType: fields["provider_period_type"] as? String) + } + + /// `ok ` or `error ` from a bundle's expected outcome. + static func wanted(_ expected: [String: Any]) -> String { + if let output = expected["output"] as? String { + return "ok " + output + } + let error = expected["error"] as! [String: String] + return "error \(error["code"]!) \(error["detail"]!)" + } + + /// `ok ` or `error `, the same for both entry points. + static func outcome(_ body: () throws -> Data) -> String { + do { + return "ok " + String(decoding: try body(), as: UTF8.self) + } catch let error as AthleticStandardError { + return "error \(error.code) \(error.detail)" + } catch { + return "unexpected \(error)" + } + } + + @Test func everyCalculationMatchesTheDesktop() throws { + let suite = try FixtureBundle.suite("calculations") + let cases = try #require(suite["cases"] as? [[String: Any]]) + let counts = try #require(suite["counts"] as? [String: Int]) + let folder = try StoreTests.folder() + var requests = 0 + var memoryRefusals = 0 + var failures: [String] = [] + for (number, item) in cases.enumerated() { + let name = item["name"] as! String + let builder = RecordSnapshotBuilder() + for batch in item["record_batches"] as! [String] { + _ = try builder.addRecords(records: Data(batch.utf8)) + } + #expect(builder.recordCount() == UInt64(item["record_count"] as! Int)) + let snapshot = try builder.finish() + let copy = folder.appendingPathComponent("case-\(number).ath.sqlite") + try FileManager.default.copyItem(at: try FixtureBundle.file(item["database"] as! String), to: copy) + let database = try Database.open(path: copy.path, options: OpenDatabaseOptions(readOnly: true)) + for request in item["requests"] as! [[String: Any]] { + requests += 1 + let wanted = Self.wanted(request["expected"] as! [String: Any]) + var wantedMemory = wanted + if let refusal = request["expected_memory"] as? [String: Any] { + memoryRefusals += 1 + wantedMemory = Self.wanted(refusal) + } + let memory: String + let file: String + if request["kind"] as! String == "apply" { + let recordID = request["record_id"] as? String + let parameters = request["parameters"] as! [String: String] + let skillFields = request["skill"] as! [String: String] + let skill: CalculationSkill = + if let shipped = skillFields["shipped"] { .shipped(name: shipped) } else { + .text(text: skillFields["text"]!) + } + if let recordID, parameters.isEmpty { + memory = Self.outcome { try snapshot.apply(recordId: recordID, skill: skill) } + file = Self.outcome { try database.apply(recordId: recordID, skill: skill) } + } else { + memory = Self.outcome { + try snapshot.applyWith(recordId: recordID, skill: skill, parameters: parameters) + } + file = Self.outcome { + try database.applyWith(recordId: recordID, skill: skill, parameters: parameters) + } + } + } else { + let range = Self.rangeRequest(request["request"] as! [String: Any]) + memory = Self.outcome { try snapshot.calculate(request: range) } + file = Self.outcome { try database.calculate(request: range) } + } + if memory != wantedMemory || file != wanted { + failures.append("\(name): expected \(wanted.prefix(200))\n memory \(memory.prefix(200))\n file \(file.prefix(200))") + } + } + try database.close() + } + print("calculations: \(cases.count) cases, \(requests) requests, \(memoryRefusals) need a database, \(failures.count) failed") + #expect(cases.count == counts["cases"]) + #expect(requests == counts["requests"]) + #expect(memoryRefusals == counts["memory_refusals"]) + #expect(failures.isEmpty, "\(failures.prefix(10).joined(separator: "\n"))") + } + + @Test func shippedSkillsAreListed() { + let names = shippedCalculationNames() + #expect(names.contains("hrv-change")) + #expect(names.contains("summary")) + #expect(!names.contains("crossfit")) + #expect(shippedSkillText(name: "crossfit")?.contains("kind: coaching") == true) + } + + @Test func aRefusedBatchLeavesTheBuilderAsItWas() throws { + let builder = RecordSnapshotBuilder() + do { + _ = try builder.addRecords(records: Data(#"[{"record_id":"x"}]"#.utf8)) + Issue.record("an invalid batch was accepted") + } catch let error as AthleticStandardError { + #expect(error.code == "invalid") + } + #expect(builder.recordCount() == 0) + _ = try builder.finish() + #expect(throws: AthleticStandardError.self) { try builder.finish() } + } +} diff --git a/mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift b/mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift index 6e22c2b4..1d26cce1 100644 --- a/mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift +++ b/mobile/swift/Tests/AthleticStandardTests/ModelVectorTests.swift @@ -2,11 +2,12 @@ import AthleticStandard import Foundation import Testing -/// Every recorded model vector, through the Swift package, compared with the -/// desktop outcome in the fixture bundle (D333). +/// Every recorded model vector and every coaching record example, through the +/// Swift package, compared with the desktop outcome in the fixture bundle (D333). struct ModelVectorTests { - @Test func everyModelVectorMatchesTheDesktop() throws { - let suite = try FixtureBundle.suite("model-vectors") + /// Run one validation suite and return its failures. + static func run(_ name: String) throws -> [String] { + let suite = try FixtureBundle.suite(name) let cases = try #require(suite["cases"] as? [[String: Any]]) let counts = try #require(suite["counts"] as? [String: Int]) var run = 0 @@ -19,26 +20,36 @@ struct ModelVectorTests { } run += 1 let schema = item["schema"] as! String - let name = item["name"] as! String + let caseName = item["name"] as! String let input = Data((item["input_text"] as! String).utf8) let expectedIssues = item["issues"] as! [String] let expectedOutput = (item["output_text"] as? String).map { Data($0.utf8) } do { let output = try validate(shape: schema, json: input) if !expectedIssues.isEmpty || output != expectedOutput { - failures.append("\(schema) / \(name): accepted, expected \(expectedIssues)") + failures.append("\(schema) / \(caseName): accepted, expected \(expectedIssues)") } } catch let error as AthleticStandardError { let issues = error.issues.map(FixtureBundle.text) if error.code != "invalid" || issues != expectedIssues { - failures.append("\(schema) / \(name): \(error.code) \(issues), expected \(expectedIssues)") + failures.append("\(schema) / \(caseName): \(error.code) \(issues), expected \(expectedIssues)") } } } - print("model-vectors: \(run) run, \(skipped) skipped, \(failures.count) failed") + print("\(name): \(run) run, \(skipped) skipped, \(failures.count) failed") #expect(run == counts["run"]) #expect(skipped == counts["skipped"]) #expect(cases.count == counts["cases"]) + return failures + } + + @Test func everyModelVectorMatchesTheDesktop() throws { + let failures = try Self.run("model-vectors") + #expect(failures.isEmpty, "\(failures.prefix(20).joined(separator: "\n"))") + } + + @Test func everyCoachingRecordExampleMatchesTheDesktop() throws { + let failures = try Self.run("coaching-records") #expect(failures.isEmpty, "\(failures.prefix(20).joined(separator: "\n"))") } } diff --git a/mobile/tests/fixtures.rs b/mobile/tests/fixtures.rs index b098fc5a..621d292c 100644 --- a/mobile/tests/fixtures.rs +++ b/mobile/tests/fixtures.rs @@ -9,7 +9,7 @@ //! skipped with their documented reason, and the counts. A phone run must skip //! exactly the listed cases and match every other one. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use athleticstandard_core::json::{self, Map, Value}; @@ -18,6 +18,9 @@ use athleticstandard_mobile::{validate, AthleticStandardError, PathSegment}; #[path = "../../tests/vector_rules/mod.rs"] mod vector_rules; +#[path = "../../tests/calculation_support/mod.rs"] +mod calculation_support; + fn repository() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..") } @@ -151,3 +154,415 @@ fn storage_files_are_exported() { std::fs::copy(&outdated, folder.join("outdated-2-1-0.ath.sqlite")).unwrap(); } } + +/// A request as the phone tests read it: full record IDs and the binding's +/// names, with the desktop outcome. +fn phone_request( + lab: &mut calculation_support::Lab, + request: &serde_json::Value, +) -> (Value, Result) { + use athleticstandard::calculate; + let working = lab.directory.join("empty-work"); + std::fs::create_dir_all(&working).unwrap(); + let desktop = |result: athleticstandard::Result| { + result.map_err(|error| (error.code().to_string(), error.to_string())) + }; + if let Some(short) = request.get("calculate") { + let options = lab.options(short); + let outcome = desktop(calculate::calculate_range(&lab.store, &options).map(|receipt| json::encode(&receipt))); + let text = |value: &Option| value.clone().map(Value::String).unwrap_or(Value::Null); + let mut fields = Map::new(); + fields.insert("operation".into(), Value::String(options.operation.as_str().into())); + fields.insert("quantity".into(), Value::String(options.quantity.clone())); + fields.insert("record_kind".into(), Value::String(options.record_kind.as_str().into())); + fields.insert("group".into(), Value::String(options.group.as_str().into())); + fields.insert("from".into(), text(&options.from)); + fields.insert("to".into(), text(&options.to)); + fields.insert("time_zone".into(), text(&options.time_zone)); + fields.insert("source_id".into(), text(&options.source_id)); + fields.insert("compare_source_id".into(), text(&options.compare_source_id)); + fields.insert("other_quantity".into(), text(&options.other_quantity)); + fields.insert("workout_session_id".into(), text(&options.workout_session_id)); + fields.insert( + "provider_period_type".into(), + options.provider_period_type.map(|kind| Value::String(kind.as_str().into())).unwrap_or(Value::Null), + ); + let mut out = Map::new(); + out.insert("kind".into(), Value::String("calculate".into())); + out.insert("request".into(), Value::Object(fields)); + return (Value::Object(out), outcome); + } + let target = request.get("target").and_then(|value| value.as_str()).map(|short| lab.id(short)); + let parameters: BTreeMap = request + .get("set") + .and_then(|value| value.as_object()) + .into_iter() + .flatten() + .map(|(key, value)| (key.clone(), value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string()))) + .collect(); + let mut skill = Map::new(); + let outcome = if let Some(name) = request.get("apply").and_then(|value| value.as_str()) { + skill.insert("shipped".into(), Value::String(name.into())); + desktop( + calculate::apply_with(&lab.store, name, target.as_deref(), ¶meters, &working) + .map(|result| json::encode(&result)), + ) + } else { + let text = request["apply_text"].as_str().unwrap(); + skill.insert("text".into(), Value::String(text.into())); + desktop( + calculate::apply_text_with(&lab.store, text, target.as_deref(), ¶meters) + .map(|result| json::encode(&result)), + ) + }; + let mut out = Map::new(); + out.insert("kind".into(), Value::String("apply".into())); + out.insert("record_id".into(), target.map(Value::String).unwrap_or(Value::Null)); + out.insert("skill".into(), Value::Object(skill)); + out.insert( + "parameters".into(), + Value::Object(parameters.into_iter().map(|(key, value)| (key, Value::String(value))).collect()), + ); + (Value::Object(out), outcome) +} + +/// What a memory snapshot answers for a calculation that reads device +/// recordings or intensity references, which it does not hold (D326). The +/// phones must get exactly this refusal from the snapshot. +fn memory_refusal(request: &Value) -> Option<(String, String)> { + use athleticstandard_core::calculate::{CalculationFile, OneRecordCalculation}; + if request["kind"].as_str() != Some("apply") { + return None; + } + let text = match request["skill"].get("shipped").and_then(Value::as_str) { + Some(name) => athleticstandard_core::assets::resolve_shipped_calculation(name).ok()?.to_string(), + None => request["skill"]["text"].as_str()?.to_string(), + }; + let parsed = CalculationFile::parse(&text).ok()?; + if !parsed.calculation.reads_recordings() { + return None; + } + let operation = match &parsed.calculation { + OneRecordCalculation::Thresholds { operations, .. } => request["parameters"] + .get("operation") + .and_then(Value::as_str) + .map(str::to_string) + .or_else(|| operations.first().cloned()) + .unwrap_or_default(), + other => other.operation().to_string(), + }; + Some(( + "refused".into(), + format!( + "{operation} reads device recordings and intensity references, which a record snapshot does not hold; run it on a database" + ), + )) +} + +/// Run a phone request through a binding entry point. +/// A request without parameters on one record runs through `apply`; any +/// other runs through `apply_with`. +fn calculation_outcome( + request: &Value, + apply: impl Fn(String, athleticstandard_mobile::CalculationSkill) -> Result, AthleticStandardError>, + apply_with: impl Fn( + Option, + athleticstandard_mobile::CalculationSkill, + HashMap, + ) -> Result, AthleticStandardError>, + calculate: impl Fn(athleticstandard_mobile::RangeRequest) -> Result, AthleticStandardError>, +) -> Result { + use athleticstandard_mobile::{CalculationSkill, RangeGroup, RangeOperation, RangeRecordKind, RangeRequest}; + let result = if request["kind"].as_str() == Some("apply") { + let skill = match request["skill"].get("shipped").and_then(Value::as_str) { + Some(name) => CalculationSkill::Shipped { name: name.into() }, + None => CalculationSkill::Text { text: request["skill"]["text"].as_str().unwrap().into() }, + }; + let record_id = request["record_id"].as_str().map(str::to_string); + let parameters: HashMap = request["parameters"] + .as_object() + .unwrap() + .iter() + .map(|(key, value)| (key.clone(), value.as_str().unwrap().to_string())) + .collect(); + match record_id { + Some(record_id) if parameters.is_empty() => apply(record_id, skill), + record_id => apply_with(record_id, skill, parameters), + } + } else { + let fields = &request["request"]; + let text = |key: &str| fields[key].as_str().map(str::to_string); + let operation = match fields["operation"].as_str().unwrap() { + "summary" => RangeOperation::Summary, + "baseline" => RangeOperation::Baseline, + "trend" => RangeOperation::Trend, + "coverage" => RangeOperation::Coverage, + "compare-sources" => RangeOperation::CompareSources, + "correlation" => RangeOperation::Correlation, + "workout-drift" => RangeOperation::WorkoutDrift, + _ => RangeOperation::ProviderPeriodSummary, + }; + let record_kind = match fields["record_kind"].as_str().unwrap() { + "measurement" => RangeRecordKind::Measurement, + "provider-score" => RangeRecordKind::ProviderScore, + "provider-summary" => RangeRecordKind::ProviderSummary, + _ => RangeRecordKind::SessionSummary, + }; + let group = match fields["group"].as_str().unwrap() { + "none" => RangeGroup::Ungrouped, + "day" => RangeGroup::Day, + "week" => RangeGroup::Week, + _ => RangeGroup::Month, + }; + calculate(RangeRequest { + operation, + quantity: text("quantity").unwrap(), + record_kind, + group, + from: text("from"), + to: text("to"), + time_zone: text("time_zone"), + source_id: text("source_id"), + compare_source_id: text("compare_source_id"), + other_quantity: text("other_quantity"), + workout_session_id: text("workout_session_id"), + provider_period_type: text("provider_period_type"), + }) + }; + result + .map(|bytes| String::from_utf8(bytes).unwrap()) + .map_err(|error| (error.code().to_string(), error.detail().to_string())) +} + +/// `{"output": }` or `{"error": {"code", "detail"}}`. +fn expected_outcome(outcome: Result) -> Value { + let mut expected = Map::new(); + match outcome { + Ok(output) => { + expected.insert("output".into(), Value::String(output)); + } + Err((code, detail)) => { + let mut error = Map::new(); + error.insert("code".into(), Value::String(code)); + error.insert("detail".into(), Value::String(detail)); + expected.insert("error".into(), Value::Object(error)); + } + } + Value::Object(expected) +} + +/// Every worked calculation example and every reader case, through the +/// binding's memory snapshot and its database, compared with the desktop. A +/// request whose snapshot answer is the documented refusal carries it as +/// `expected_memory`. +#[test] +fn every_calculation_case_runs_through_the_binding() { + use athleticstandard_mobile::{Database, OpenDatabaseOptions, RecordSnapshotBuilder}; + let mut groups: Vec<(String, Vec, Vec)> = Vec::new(); + let skills = repository().join("skills"); + let mut dirs: Vec = std::fs::read_dir(&skills).unwrap().map(|entry| entry.unwrap().path()).collect(); + dirs.sort(); + for dir in dirs { + let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue }; + let skill = dir.file_name().unwrap().to_string_lossy().to_string(); + let marker = "```json ath-example\n"; + let mut rest = text.as_str(); + let mut index = 0; + while let Some(start) = rest.find(marker) { + let body = &rest[start + marker.len()..]; + let end = body.find("\n```").unwrap(); + let example: serde_json::Value = serde_json::from_str(&body[..end]).unwrap(); + let request = if example.get("set").is_some() || example.get("apply").is_some() { + serde_json::json!({ "apply": skill, "target": example.get("apply"), "set": example.get("set") }) + } else { + serde_json::json!({ "calculate": example["calculate"] }) + }; + groups.push(( + format!("{skill} example {index}"), + example["records"].as_array().unwrap().clone(), + vec![request], + )); + rest = &body[end..]; + index += 1; + } + } + let examples = groups.len(); + assert!(examples >= 32, "found {examples} worked examples"); + for case in calculation_support::cases::all() { + groups.push((case.name.to_string(), case.records, case.requests)); + } + let export_folder = std::env::var_os("ATH_MOBILE_FIXTURES").map(PathBuf::from); + if let Some(folder) = &export_folder { + std::fs::create_dir_all(folder.join("calculations")).unwrap(); + } + let mut suite_cases = Vec::new(); + let mut failures = Vec::new(); + let mut requests_run = 0; + let mut memory_refusals = 0; + for (number, (name, records, requests)) in groups.into_iter().enumerate() { + let mut lab = calculation_support::Lab::new(); + lab.write(&records); + let current = lab.current_records(); + let database_file = lab.directory.join(format!("case-{number}.ath.sqlite")); + lab.save_copy(&database_file); + let builder = RecordSnapshotBuilder::new(); + // Two batches, as an app supplies large data in parts. The phones get + // the exact JSON text, so numbers are not written again. + let items = current.as_array().unwrap(); + let half = items.len() / 2; + let batches = [ + json::to_string(&Value::Array(items[..half].to_vec())), + json::to_string(&Value::Array(items[half..].to_vec())), + ]; + for batch in &batches { + builder.add_records(batch.clone().into_bytes()).unwrap(); + } + let snapshot = builder.finish().unwrap(); + let database = Database::open( + database_file.display().to_string(), + OpenDatabaseOptions { read_only: true, allow_outdated_schema: false, expected_database_id: None }, + ) + .unwrap(); + let mut phone_requests = Vec::new(); + for request in &requests { + requests_run += 1; + let (phone, desktop) = phone_request(&mut lab, request); + let memory = calculation_outcome( + &phone, + |id, skill| snapshot.apply(id, skill), + |id, skill, parameters| snapshot.apply_with(id, skill, parameters), + |range| snapshot.calculate(range), + ); + let file = calculation_outcome( + &phone, + |id, skill| database.apply(id, skill), + |id, skill, parameters| database.apply_with(id, skill, parameters), + |range| database.calculate(range), + ); + // The snapshot gives the desktop outcome, or, for a calculation + // that reads recordings, exactly the documented refusal. + let refusal = memory_refusal(&phone); + let expected_memory = match &memory { + outcome if *outcome == desktop => None, + Err(error) if refusal.as_ref() == Some(error) => refusal.clone(), + _ => { + failures.push(format!("{name} / {request}:\n desktop {desktop:?}\n memory {memory:?}")); + None + } + }; + if file != desktop { + failures.push(format!("{name} / {request}:\n desktop {desktop:?}\n file {file:?}")); + } + let mut item = match phone { + Value::Object(map) => map, + _ => unreachable!(), + }; + item.insert("expected".into(), expected_outcome(desktop)); + if let Some(refusal) = expected_memory { + memory_refusals += 1; + item.insert("expected_memory".into(), expected_outcome(Err(refusal))); + } + phone_requests.push(Value::Object(item)); + } + database.close().unwrap(); + let database_name = format!("calculations/case-{number}.ath.sqlite"); + if let Some(folder) = &export_folder { + std::fs::copy(&database_file, folder.join(&database_name)).unwrap(); + } + let mut case = Map::new(); + case.insert("name".into(), Value::String(name)); + case.insert("record_count".into(), Value::from(items.len() as u64)); + case.insert("record_batches".into(), Value::Array(batches.iter().cloned().map(Value::String).collect())); + case.insert("database".into(), Value::String(database_name)); + case.insert("requests".into(), Value::Array(phone_requests)); + suite_cases.push(Value::Object(case)); + } + assert!(failures.is_empty(), "{} requests differ:\n{}", failures.len(), failures.join("\n")); + eprintln!( + "calculations: {} cases ({examples} worked examples), {requests_run} requests, {memory_refusals} need a database", + suite_cases.len() + ); + let mut counts = Map::new(); + counts.insert("cases".into(), Value::from(suite_cases.len() as u64)); + counts.insert("worked_examples".into(), Value::from(examples as u64)); + counts.insert("requests".into(), Value::from(requests_run as u64)); + counts.insert("memory_refusals".into(), Value::from(memory_refusals as u64)); + let mut suite = Map::new(); + suite.insert("suite".into(), Value::String("calculations".into())); + suite.insert("counts".into(), Value::Object(counts)); + suite.insert("cases".into(), Value::Array(suite_cases)); + export("calculations", Value::Object(suite)); +} + +/// Every `ath-record-example` block in a coaching skill: each record's data +/// checked against its record type's published data shape, and its +/// extensions against `RecordExtensions`. Written in the model-vector format, +/// so the phones run it with the same code. +#[test] +fn every_coaching_record_example_runs_through_the_binding() { + use athleticstandard_core::model::RecordType; + let skills = repository().join("skills"); + let mut files = Vec::new(); + let mut dirs: Vec = std::fs::read_dir(&skills).unwrap().map(|entry| entry.unwrap().path()).collect(); + dirs.sort(); + for dir in dirs { + let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue }; + if !text.contains("kind: coaching") { + continue; + } + files.push(dir.join("SKILL.md")); + if let Ok(entries) = std::fs::read_dir(dir.join("references")) { + let mut references: Vec = entries.map(|entry| entry.unwrap().path()).collect(); + references.sort(); + files.extend(references.into_iter().filter(|file| file.extension().is_some_and(|ext| ext == "md"))); + } + } + let mut cases = Vec::new(); + let mut blocks = 0; + for file in files { + let text = std::fs::read_to_string(&file).unwrap(); + let shown = file.strip_prefix(&skills).unwrap().display().to_string(); + let marker = "```json ath-record-example\n"; + let mut rest = text.as_str(); + while let Some(start) = rest.find(marker) { + let body = &rest[start + marker.len()..]; + let end = body.find("\n```").unwrap(); + let items = json::parse(&body[..end]).unwrap(); + for (position, item) in items.as_array().unwrap().iter().enumerate() { + let kind = RecordType::parse(item["record_type"].as_str().unwrap()).unwrap(); + let pascal: String = + kind.as_str().split('_').map(|part| part[..1].to_uppercase() + &part[1..]).collect(); + let mut checks = vec![(format!("{pascal}Data"), item["data"].clone())]; + if let Some(extensions) = item.get("extensions") { + checks.push(("RecordExtensions".to_string(), extensions.clone())); + } + for (schema, value) in checks { + let input_text = json::to_string(&value); + let output = validate(schema.clone(), input_text.clone().into_bytes()) + .unwrap_or_else(|error| panic!("{shown} block {blocks} item {position}: {error:?}")); + let mut case = Map::new(); + case.insert("schema".into(), Value::String(schema)); + case.insert("name".into(), Value::String(format!("{shown} block {blocks} item {position}"))); + case.insert("input_text".into(), Value::String(input_text)); + case.insert("issues".into(), Value::Array(Vec::new())); + case.insert("output_text".into(), Value::String(String::from_utf8(output).unwrap())); + cases.push(Value::Object(case)); + } + } + blocks += 1; + rest = &body[end..]; + } + } + assert!(blocks >= 20, "found {blocks} coaching record-example blocks"); + eprintln!("coaching records: {blocks} blocks, {} checks", cases.len()); + let mut counts = Map::new(); + counts.insert("blocks".into(), Value::from(blocks as u64)); + counts.insert("cases".into(), Value::from(cases.len() as u64)); + counts.insert("run".into(), Value::from(cases.len() as u64)); + counts.insert("skipped".into(), Value::from(0u64)); + let mut suite = Map::new(); + suite.insert("suite".into(), Value::String("coaching-records".into())); + suite.insert("counts".into(), Value::Object(counts)); + suite.insert("cases".into(), Value::Array(cases)); + export("coaching-records", Value::Object(suite)); +} From d689dd33949e72c5825d7bc76de68ee62bb3a0b1 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 10:11:25 -0600 Subject: [PATCH 08/30] Add a test-only sign-in provider for the phone host client tests. `host/examples/test-sign-in-provider.rs` answers like the WorkOS AuthKit recipe: OpenID Connect discovery, a browser authorization endpoint that requires S256 PKCE, a token endpoint that exchanges the code and rotates refresh tokens, and the signing keys. Tokens carry `client_id` and the requested `resource` as their audience, and are signed with the fixed test key. `mobile/scripts/host-test-env.sh` starts it with a real `ath-host` that trusts it. Co-Authored-By: Claude Opus 5.5 --- host/examples/test-sign-in-provider.rs | 235 +++++++++++++++++++++++++ mobile/scripts/host-test-env.sh | 89 ++++++++++ 2 files changed, 324 insertions(+) create mode 100644 host/examples/test-sign-in-provider.rs create mode 100755 mobile/scripts/host-test-env.sh diff --git a/host/examples/test-sign-in-provider.rs b/host/examples/test-sign-in-provider.rs new file mode 100644 index 00000000..591c8680 --- /dev/null +++ b/host/examples/test-sign-in-provider.rs @@ -0,0 +1,235 @@ +//! A test-only sign-in provider for the phone host clients (D330). +//! +//! It answers like the WorkOS AuthKit recipe in `docs/hosting.md`: OpenID +//! Connect discovery, a browser authorization endpoint that requires S256 +//! PKCE, a token endpoint that exchanges the code and rotates refresh tokens, +//! and the signing keys. Access tokens name the app in `client_id`, as WorkOS +//! tokens do, and their audience is the `resource` the app asked for. +//! +//! Tokens are signed with the fixed, test-only Ed25519 key from +//! `host/tests/support/mod.rs`. Nothing here is for real accounts. +//! +//! The authorization endpoint approves at once and redirects to the app's +//! callback. `login_hint` names the person; `login_hint=cancel` answers with +//! `access_denied`, as a person who closes the sign-in page does. +//! +//! Usage: `cargo run -p athleticstandard-host --example test-sign-in-provider -- +//! [--listen 127.0.0.1:0] [--token-seconds 3600]`. The first line printed is +//! `issuer `. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use axum::extract::{Form, Query, State}; +use axum::http::{header, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +const SEED: &str = "4828f8020207fb11233d01b011c5937bede2b268a8603620b80bf97e050503d0"; +const PUBLIC_X: &str = "itrbr0O5BuqdMUzuGWjVxNLAdQjldIGhKq8Rxhhr3_A"; + +struct Pending { + client_id: String, + redirect_uri: String, + challenge: String, + resource: Option, + subject: String, +} + +struct Grant { + client_id: String, + resource: Option, + subject: String, +} + +struct Provider { + issuer: String, + token_seconds: u64, + codes: Mutex>, + refresh_tokens: Mutex>, +} + +fn base64url(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let mut out = String::new(); + for chunk in bytes.chunks(3) { + let n = chunk.iter().enumerate().fold(0u32, |n, (index, byte)| n | (u32::from(*byte) << (16 - 8 * index))); + for index in 0..=chunk.len() { + out.push(ALPHABET[((n >> (18 - 6 * index)) & 63) as usize] as char); + } + } + out +} + +fn hex_bytes(text: &str) -> Vec { + (0..text.len()).step_by(2).map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap()).collect() +} + +fn now() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() +} + +fn oauth_error(code: &str, description: &str) -> Response { + (StatusCode::BAD_REQUEST, Json(json!({ "error": code, "error_description": description }))).into_response() +} + +impl Provider { + fn access_token(&self, grant: &Grant) -> String { + let mut der = hex_bytes("302e020100300506032b657004220420"); + der.extend(hex_bytes(SEED)); + let mut header = Header::new(Algorithm::EdDSA); + header.kid = Some("test-key".into()); + let issued = now(); + let claims = json!({ + "iss": self.issuer, + "sub": grant.subject, + "aud": grant.resource.clone().unwrap_or_default(), + "client_id": grant.client_id, + "name": grant.subject, + "iat": issued, + "exp": issued + self.token_seconds, + }); + encode(&header, &claims, &EncodingKey::from_ed_der(&der)).unwrap() + } + + fn tokens(&self, grant: Grant) -> Response { + let access = self.access_token(&grant); + let refresh = uuid::Uuid::new_v4().simple().to_string(); + self.refresh_tokens.lock().unwrap().insert(refresh.clone(), grant); + Json(json!({ + "access_token": access, + "token_type": "Bearer", + "expires_in": self.token_seconds, + "refresh_token": refresh, + })) + .into_response() + } +} + +async fn discovery(State(provider): State>) -> Json { + let issuer = &provider.issuer; + Json(json!({ + "issuer": issuer, + "authorization_endpoint": format!("{issuer}/oauth2/authorize"), + "token_endpoint": format!("{issuer}/oauth2/token"), + "jwks_uri": format!("{issuer}/oauth2/jwks"), + "response_types_supported": ["code"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": ["none"], + })) +} + +async fn jwks() -> Json { + Json( + json!({ "keys": [{ "kty": "OKP", "crv": "Ed25519", "x": PUBLIC_X, "kid": "test-key", "alg": "EdDSA", "use": "sig" }] }), + ) +} + +async fn authorize(State(provider): State>, Query(query): Query>) -> Response { + let field = |key: &str| query.get(key).filter(|value| !value.is_empty()).cloned(); + let (Some(redirect_uri), Some(client_id)) = (field("redirect_uri"), field("client_id")) else { + return oauth_error("invalid_request", "client_id and redirect_uri are required"); + }; + let state = field("state").unwrap_or_default(); + let separator = if redirect_uri.contains('?') { '&' } else { '?' }; + let redirect = |parameters: String| { + (StatusCode::FOUND, [(header::LOCATION, format!("{redirect_uri}{separator}{parameters}"))]).into_response() + }; + if field("response_type").as_deref() != Some("code") + || field("code_challenge_method").as_deref() != Some("S256") + || field("code_challenge").is_none() + || state.is_empty() + { + return redirect(format!("error=invalid_request&state={state}")); + } + let subject = field("login_hint").unwrap_or_else(|| "person-1".into()); + if subject == "cancel" { + return redirect(format!("error=access_denied&state={state}")); + } + let code = uuid::Uuid::new_v4().simple().to_string(); + provider.codes.lock().unwrap().insert( + code.clone(), + Pending { + client_id, + redirect_uri: redirect_uri.clone(), + challenge: field("code_challenge").unwrap(), + resource: field("resource"), + subject, + }, + ); + redirect(format!("code={code}&state={state}")) +} + +async fn token(State(provider): State>, Form(form): Form>) -> Response { + let field = |key: &str| form.get(key).cloned().unwrap_or_default(); + match field("grant_type").as_str() { + "authorization_code" => { + let Some(pending) = provider.codes.lock().unwrap().remove(&field("code")) else { + return oauth_error("invalid_grant", "the code is unknown or used"); + }; + let challenge = base64url(&Sha256::digest(field("code_verifier").as_bytes())); + if pending.client_id != field("client_id") + || pending.redirect_uri != field("redirect_uri") + || pending.challenge != challenge + { + return oauth_error("invalid_grant", "the code does not match this client, callback, or verifier"); + } + let resource = form.get("resource").cloned().or(pending.resource); + provider.tokens(Grant { client_id: pending.client_id, resource, subject: pending.subject }) + } + "refresh_token" => { + let Some(grant) = provider.refresh_tokens.lock().unwrap().remove(&field("refresh_token")) else { + return oauth_error("invalid_grant", "the refresh token is unknown, used, or revoked"); + }; + if grant.client_id != field("client_id") { + return oauth_error("invalid_grant", "the refresh token belongs to another client"); + } + provider.tokens(grant) + } + _ => oauth_error("unsupported_grant_type", "use authorization_code or refresh_token"), + } +} + +/// Test control: forget every refresh token, as a provider does when a +/// person's sessions are ended. +async fn revoke_all(State(provider): State>) -> StatusCode { + provider.refresh_tokens.lock().unwrap().clear(); + StatusCode::NO_CONTENT +} + +#[tokio::main] +async fn main() { + let mut listen = "127.0.0.1:0".to_string(); + let mut token_seconds = 3600u64; + let mut arguments = std::env::args().skip(1); + while let Some(argument) = arguments.next() { + match argument.as_str() { + "--listen" => listen = arguments.next().expect("--listen

"), + "--token-seconds" => token_seconds = arguments.next().and_then(|n| n.parse().ok()).expect("seconds"), + other => panic!("unknown argument {other}"), + } + } + let listener = tokio::net::TcpListener::bind(&listen).await.expect("bind"); + let issuer = format!("http://{}", listener.local_addr().unwrap()); + println!("issuer {issuer}"); + let provider = Arc::new(Provider { + issuer, + token_seconds, + codes: Mutex::new(HashMap::new()), + refresh_tokens: Mutex::new(HashMap::new()), + }); + let router = Router::new() + .route("/.well-known/openid-configuration", get(discovery)) + .route("/.well-known/oauth-authorization-server", get(discovery)) + .route("/oauth2/jwks", get(jwks)) + .route("/oauth2/authorize", get(authorize)) + .route("/oauth2/token", post(token)) + .route("/test/revoke-refresh-tokens", post(revoke_all)) + .with_state(provider); + axum::serve(listener, router).await.unwrap(); +} diff --git a/mobile/scripts/host-test-env.sh b/mobile/scripts/host-test-env.sh new file mode 100755 index 00000000..a681074b --- /dev/null +++ b/mobile/scripts/host-test-env.sh @@ -0,0 +1,89 @@ +#!/bin/bash +# Start a real `ath-host` and the test sign-in provider for the phone host +# client tests (D330). +# +# mobile/scripts/host-test-env.sh start +# Builds both programs, starts the provider and a host in native directory +# mode that trusts it, and writes /env with ATH_TEST_HOST_URL and +# ATH_TEST_ISSUER. Both listen on 127.0.0.1 only. +# mobile/scripts/host-test-env.sh stop +# +# The provider signs with a fixed, test-only key. No real account is used. + +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +COMMAND="${1:-}" +FOLDER="${2:-}" +if [ -z "$FOLDER" ]; then + echo "usage: $0 start|stop " >&2 + exit 2 +fi +if ! command -v cargo > /dev/null && [ -x "$HOME/.cargo/bin/cargo" ]; then + export PATH="$HOME/.cargo/bin:$PATH" +fi + +stop() { + for name in host provider; do + if [ -f "$FOLDER/$name.pid" ]; then + kill "$(cat "$FOLDER/$name.pid")" 2> /dev/null || true + rm -f "$FOLDER/$name.pid" + fi + done +} + +free_port() { + python3 -I -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()' +} + +case "$COMMAND" in + start) + mkdir -p "$FOLDER" + FOLDER="$(cd "$FOLDER" && pwd -P)" + stop + rm -rf "$FOLDER/data" + cargo build --locked -p athleticstandard-host --bin ath-host --example test-sign-in-provider \ + --manifest-path "$ROOT/Cargo.toml" + provider_port="$(free_port)" + "$ROOT/target/debug/examples/test-sign-in-provider" --listen "127.0.0.1:$provider_port" \ + > "$FOLDER/provider.log" 2>&1 & + echo $! > "$FOLDER/provider.pid" + issuer="http://127.0.0.1:$provider_port" + host_port="$(free_port)" + host_url="http://127.0.0.1:$host_port" + cat > "$FOLDER/host-config.json" < "$FOLDER/host.log" 2>&1 & + echo $! > "$FOLDER/host.pid" + for _ in $(seq 1 100); do + if curl -fsS "$host_url/v1/capabilities" > /dev/null 2>&1 && + curl -fsS "$issuer/.well-known/openid-configuration" > /dev/null 2>&1; then + printf 'ATH_TEST_HOST_URL=%s\nATH_TEST_ISSUER=%s\nATH_TEST_HOST_PORT=%s\nATH_TEST_ISSUER_PORT=%s\n' \ + "$host_url" "$issuer" "$host_port" "$provider_port" > "$FOLDER/env" + echo "host $host_url, sign-in provider $issuer" + exit 0 + fi + sleep 0.2 + done + echo "the host or the provider did not start; see $FOLDER/host.log and $FOLDER/provider.log" >&2 + stop + exit 1 + ;; + stop) + FOLDER="$(cd "$FOLDER" && pwd -P)" + stop + ;; + *) + echo "usage: $0 start|stop " >&2 + exit 2 + ;; +esac From 37d8d8c73276e966f8372d1bdd3916c7b52546a0 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 10:11:25 -0600 Subject: [PATCH 09/30] Add the host client with browser sign-in to the Swift and Android packages. `AthleticStandardHost` in Swift and `ai.athleticstandard.host` in Kotlin connect to `ath-host` (D330). Sign-in reads the host's protected-resource metadata and the provider's discovery document, runs the authorization code flow with S256 PKCE in the system browser, checks the callback's address and `state`, asks for a token for the host's resource, and refreshes it. Tokens stay in the Keychain or in a file encrypted with an Android Keystore key. An app with its own session can supply the token. Owner writes are prepared as exact request bytes with an idempotency key, so a retry after a lost reply sends the same request. The tests run both clients against a real host and the test provider: retries, a stale correction, a reused key, refresh and a refused refresh, cancelled and foreign callbacks, a revoked coach, and a disconnected app. The record snapshot builder also accepts the host's record list and the `ath records list --json` output, which hold the array under `records`. Co-Authored-By: Claude Opus 5.5 --- build-history/v3.0.0/progress.md | 24 +- docs/hosting.md | 4 +- mobile/README.md | 84 ++++ .../android/athleticstandard/build.gradle.kts | 4 +- .../kotlin/ai/athleticstandard/HostTest.kt | 182 ++++++++ .../ai/athleticstandard/host/HostClient.kt | 358 +++++++++++++++ .../ai/athleticstandard/host/HostSignIn.kt | 385 ++++++++++++++++ mobile/scripts/test-android.sh | 16 +- mobile/scripts/test-apple.sh | 10 + mobile/src/calculate.rs | 17 +- mobile/swift/Package.swift | 5 + .../AthleticStandardHost/HostClient.swift | 386 ++++++++++++++++ .../AthleticStandardHost/HostError.swift | 73 +++ .../AthleticStandardHost/HostSignIn.swift | 434 ++++++++++++++++++ .../Sources/AthleticStandardHost/Models.swift | 357 ++++++++++++++ .../AthleticStandardHostTests/HostTests.swift | 203 ++++++++ 16 files changed, 2534 insertions(+), 8 deletions(-) create mode 100644 mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt create mode 100644 mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt create mode 100644 mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostSignIn.kt create mode 100644 mobile/swift/Sources/AthleticStandardHost/HostClient.swift create mode 100644 mobile/swift/Sources/AthleticStandardHost/HostError.swift create mode 100644 mobile/swift/Sources/AthleticStandardHost/HostSignIn.swift create mode 100644 mobile/swift/Sources/AthleticStandardHost/Models.swift create mode 100644 mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift diff --git a/build-history/v3.0.0/progress.md b/build-history/v3.0.0/progress.md index 33379dec..97b26d73 100644 --- a/build-history/v3.0.0/progress.md +++ b/build-history/v3.0.0/progress.md @@ -19,7 +19,7 @@ Status: **being built; not released.** The plan is [spec.md](spec.md). | 13 | UniFFI crate, validation from the Swift package and the Android library | Mac and Android emulator pass; iPhone simulator not run | | 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | Mac and two Android emulators pass; iPhone simulator and iCloud not run | | 15 | Calculations from memory and SQLite through one reader interface | Mac and two Android emulators pass; iPhone simulator not run | -| 16 | Host client for Swift and Kotlin with browser sign-in | not started | +| 16 | Host client for Swift and Kotlin with browser sign-in | Mac and two Android emulators pass against a real host; live WorkOS not run | | 17 | Release packaging, phone test runs, release gate | not started | ## Step 2: what was built @@ -766,3 +766,25 @@ These follow the guide and the decisions. Each is open to review. - One clock fallback remains in range arithmetic: a calendar date that does not read falls back to today. The calendar range check refuses such a date first, so no request reaches it. + +## Step 16: the host client with browser sign-in + +- The Swift package gains the `AthleticStandardHost` module, built from the example + client with the owner record routes, changes, export, app connections, and prepared + writes. The Android library gains `ai.athleticstandard.host` with the same calls. +- Sign-in is the library's own code on the platform browser APIs: discovery, S256 + PKCE, a `state` check, the code exchange with `resource`, refresh with rotation, and + sign-out. Tokens are kept in the Keychain on iOS and in a file encrypted with an + Android Keystore key. +- `host/examples/test-sign-in-provider.rs` is a test-only provider that answers like + the WorkOS recipe: `client_id` in the token, the audience from `resource`, and + rotated refresh tokens. It signs with the fixed test key. +- Against a real `ath-host`, the Swift tests on a Mac and the Kotlin tests on both + Android emulators each pass five cases: sign-in and owner writes with a retried + write, a stale correction, and a key reused for another request; refresh and a + refused refresh; a cancelled sign-in and callbacks with another `state` or address; + a revoked coach and a disconnected app; and a token supplied by the app. +- Not run: the system browser sheets (`ASWebAuthenticationSession`, Custom Tabs) with a + person, and a live WorkOS environment with expired, wrong-audience, wrong-issuer, + and wrong-app tokens. Both belong with issue 57 and need a WorkOS test environment + and registered public apps. diff --git a/docs/hosting.md b/docs/hosting.md index f55c579d..20867987 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -780,7 +780,9 @@ JavaScript and TypeScript programs can call these routes through `connectHost` i npm package `athleticstandard`. [`examples/host-starter/`](../examples/host-starter/) runs a coach's steps with it, and [`examples/host-mcp/`](../examples/host-mcp/) is an MCP server built on it. [`examples/host-swift/`](../examples/host-swift/) is a Swift -client for macOS and iOS apps that runs the same coach steps. +client for macOS and iOS apps that runs the same coach steps. The iPhone and Android +packages in [`mobile/`](../mobile/README.md#connect-to-a-host) include a client with +browser sign-in for owners and coaches (D330). ### 7.1 Conventions diff --git a/mobile/README.md b/mobile/README.md index 19166b55..e4cc742f 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -115,6 +115,90 @@ through iCloud Drive can cause sync conflicts." On Android, take a persistable permission for the document's URI. - A single-file save does not carry attachment files. Use a package export for them. +## Connect to a host + +Local files need no account and no network. Connecting to an `ath-host` is optional +([D330](../build-history/v3.0.0/decisions.md#d330-the-packages-include-a-host-client-with-browser-sign-in)). +The Swift module `AthleticStandardHost` and the Kotlin package `ai.athleticstandard.host` +hold the same client. It needs no native library. + +Give it the host's address, the app's registered public client ID, and its registered +callback address, then sign in. The client reads the host's protected-resource +metadata and the sign-in provider's discovery document, opens the provider in the +system browser with the authorization code flow and S256 PKCE, checks that the +callback carries this sign-in's `state`, and asks for a token for the host's resource. +It refreshes the token before it expires. + +```swift +import AthleticStandardHost + +let configuration = HostSignInConfiguration( + hostURL: URL(string: "https://records.example.org")!, clientID: "client_01EXAMPLE", + redirectURI: URL(string: "org.example.athlete:/oauth/callback")!) +let signIn = HostSignIn(configuration: configuration, store: KeychainTokenStore(configuration: configuration)) +try await signIn.signIn(browser: SystemBrowser { window }) // ASWebAuthenticationSession +let host = signIn.client() +let me = try await host.me() // the records this person owns +``` + +```kotlin +val configuration = HostSignInConfiguration( + hostUrl = "https://records.example.org", clientId = "client_01EXAMPLE", + redirectUri = "org.example.athlete:/oauth/callback", +) +val signIn = HostSignIn(configuration, KeystoreTokenStore(context)) +signIn.signIn(CustomTabsBrowser(activity)) // away from the main thread +val host = signIn.client() +``` + +On Android, add the `INTERNET` permission, and route the callback address to the +library's redirect activity in the app's manifest. The library declares neither, so +an app that only uses local files gets neither: + +```xml + + + + + + + + + +``` + +Call `CustomTabsBrowser.cancelPendingSignIn()` from the activity's `onResume` when the +person comes back without signing in. + +Tokens stay in the iOS Keychain (`KeychainTokenStore`) or in a private file encrypted +with an Android Keystore key (`KeystoreTokenStore`), never in an athlete file or +export. `signOut()` forgets them. An app that already has a session for this host and +app can skip `HostSignIn` and give `HostClient` a function that returns a current +access token. + +**Writes.** `prepareRecordCreation`, `prepareCorrection`, and `prepareDeletion` build a +`PreparedWrite`: the exact request bytes and a new `Idempotency-Key`. Keep it with the +unsent edit, and send the same `PreparedWrite` again after a lost reply; the host +returns the first answer and writes nothing new. A correction carries the revision the +person edited. If the record changed since, the host answers `stale`; keep the +person's edit for review. Connecting never links a local file or uploads it. Keeping a +local copy in step with a host is [issue 58](https://github.com/mwhitham/ath/issues/58). + +**Setting up WorkOS.** Follow [docs/hosting.md section 6.5](../docs/hosting.md#65-recipe-workos-authkit). +Register each app as a public OAuth application under Connect, and register its +callback address exactly. iOS and Android apps with different client IDs are different +apps to the host: a coach grant names one client ID, so each needs its own grant. Set +the host's public address as the Resource Indicator and the host's `audience`. + +**Tests.** `mobile/scripts/host-test-env.sh` starts a real `ath-host` and +`host/examples/test-sign-in-provider.rs`, a test-only provider that answers like the +WorkOS recipe and signs with the fixed test key. The tests sign in through a stand-in +browser, write with retries, refresh and rotate tokens, and check a stale correction, a +key reused for another request, a cancelled and a foreign callback, a revoked coach, +and a disconnected app. They do not run the system browser or a real WorkOS account; +that check belongs with [issue 57](https://github.com/mwhitham/ath/issues/57). + ## Build You need the Rust toolchain from `rust-toolchain.toml` with these targets: diff --git a/mobile/android/athleticstandard/build.gradle.kts b/mobile/android/athleticstandard/build.gradle.kts index cce4cf36..723f6e3f 100644 --- a/mobile/android/athleticstandard/build.gradle.kts +++ b/mobile/android/athleticstandard/build.gradle.kts @@ -53,7 +53,7 @@ android { // Build the native library and generate the Kotlin bindings before anything // reads them. The script checks 16 KB page alignment for each ABI. -val buildRust by tasks.registering(Exec::class) { +val buildRust = tasks.register("buildRust") { group = "build" description = "Builds libathleticstandard_mobile.so for each ABI and generates the Kotlin bindings." val output = rustOutput.get().asFile @@ -76,6 +76,8 @@ dependencies { // app resolves it with this library. api("net.java.dev.jna:jna:5.19.1@aar") implementation("androidx.annotation:annotation:1.9.1") + // Custom Tabs for browser sign-in to a host (D330). Local use never opens it. + implementation("androidx.browser:browser:1.9.0") androidTestImplementation("androidx.test:runner:1.7.0") androidTestImplementation("androidx.test.ext:junit:1.3.0") diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt new file mode 100644 index 00000000..d4e3da38 --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt @@ -0,0 +1,182 @@ +package ai.athleticstandard + +import ai.athleticstandard.host.AuthorizationBrowser +import ai.athleticstandard.host.HostClient +import ai.athleticstandard.host.HostException +import ai.athleticstandard.host.HostSignIn +import ai.athleticstandard.host.HostSignInConfiguration +import ai.athleticstandard.host.HostSignInException +import ai.athleticstandard.host.HostTokenStore +import ai.athleticstandard.host.KeystoreTokenStore +import ai.athleticstandard.host.MemoryTokenStore +import ai.athleticstandard.host.PreparedWrite +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import org.junit.runner.RunWith +import java.net.HttpURLConnection +import java.net.URL +import java.util.UUID + +/** + * The host client and browser sign-in against a real `ath-host` and the test sign-in + * provider that `mobile/scripts/host-test-env.sh` starts on the computer (D330). The + * test script forwards both ports with `adb reverse` and passes their addresses as + * the `hostUrl` and `issuer` arguments. The browser is a stand-in that loads the + * sign-in page without following its redirect; the Custom Tab itself needs a person, + * so it runs in the live provider check. + */ +@RunWith(AndroidJUnit4::class) +class HostTest { + private val arguments = InstrumentationRegistry.getArguments() + private val hostUrl: String = arguments.getString("hostUrl") + ?: error("pass -Pandroid.testInstrumentationRunnerArguments.hostUrl (mobile/scripts/test-android.sh does)") + private val issuer: String = arguments.getString("issuer") ?: error("pass the issuer argument") + private val redirect = "ai.athleticstandard.test:/callback" + private val source = """{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"}""" + + private class TestBrowser(private val rewrite: (String) -> String = { it }) : AuthorizationBrowser { + override fun authorize(url: String, redirectUri: String): String { + val connection = URL(url).openConnection() as HttpURLConnection + connection.instanceFollowRedirects = false + try { + assertEquals(302, connection.responseCode) + return rewrite(connection.getHeaderField("Location")) + } finally { + connection.disconnect() + } + } + } + + private fun signIn(client: String, person: String, store: HostTokenStore = MemoryTokenStore()): HostSignIn { + val signIn = HostSignIn(HostSignInConfiguration(hostUrl, client, redirect, loginHint = person), store) + signIn.signIn(TestBrowser()) + return signIn + } + + private fun code(body: () -> Unit): String? = try { + body() + null + } catch (error: HostException) { + error.code + } + + @Test + fun signInWriteRetryAndStaleCorrection() { + val client = signIn("athlete-app", "owner-${UUID.randomUUID()}").client() + assertEquals("athlete-app", client.me().clientId) + val athlete = client.createAthlete("Synthetic athlete") + assertTrue(client.athletes().any { it.athleteId == athlete.athleteId }) + + val write = client.prepareRecordCreation(athlete.athleteId, "source", source.toByteArray()) + val first = client.send(write) + // Sent again after a lost reply, from the stored form: written once. + assertEquals(first, client.send(PreparedWrite.fromJson(write.toJson()))) + val sourceId = first.records.first().recordId + + val corrected = source.replace("Example Band", "Example Band 2").toByteArray() + assertEquals(2L, client.send(client.prepareCorrection(athlete.athleteId, sourceId, 1, corrected)).records.first().revision) + assertEquals("stale", code { client.send(client.prepareCorrection(athlete.athleteId, sourceId, 1, corrected)) }) + assertEquals("request_conflict", code { client.send(write.copy(body = corrected)) }) + + val records = JSONObject(client.recordsJson(athlete.athleteId).decodeToString()).getJSONArray("records") + assertEquals(1, records.length()) + // The host's list feeds a memory snapshot directly. + val builder = RecordSnapshotBuilder() + builder.addRecords(records.toString().toByteArray()) + assertEquals(1uL, builder.finish().recordCount()) + assertEquals(2, client.changes(athlete.athleteId, 0).changes.size) + val zip = client.export(athlete.athleteId) + assertEquals(0x50, zip[0].toInt()) + assertEquals(0x4b, zip[1].toInt()) + } + + @Test + fun anExpiredTokenIsRefreshedAndARefusedRefreshAsksForSignIn() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val store = KeystoreTokenStore(context, "test-${UUID.randomUUID()}") + val signIn = signIn("athlete-app", "refresh-${UUID.randomUUID()}", store) + val tokens = store.load()!! + store.save(tokens.copy(expiresAtMillis = System.currentTimeMillis() - 10_000)) + signIn.client().me() + val refreshed = store.load()!! + assertNotNull(refreshed.refreshToken) + assertNotEquals(tokens.refreshToken, refreshed.refreshToken) + assertTrue(refreshed.expiresAtMillis > System.currentTimeMillis()) + + // The provider ends the person's sessions: the next refresh is refused. + val revoke = URL("$issuer/test/revoke-refresh-tokens").openConnection() as HttpURLConnection + revoke.requestMethod = "POST" + assertEquals(204, revoke.responseCode) + store.save(refreshed.copy(expiresAtMillis = System.currentTimeMillis() - 10_000)) + try { + signIn.accessToken() + fail("a refused refresh gave a token") + } catch (expected: HostSignInException.SignInRequired) { + } + assertFalse(signIn.isSignedIn()) + } + + @Test + fun aCancelledOrForeignCallbackIsRefused() { + val configuration = { hint: String -> HostSignInConfiguration(hostUrl, "athlete-app", redirect, loginHint = hint) } + try { + HostSignIn(configuration("cancel"), MemoryTokenStore()).signIn(TestBrowser()) + fail("a cancelled sign-in finished") + } catch (expected: HostSignInException.Cancelled) { + } + val foreign = HostSignIn(configuration("person-1"), MemoryTokenStore()) + try { + foreign.signIn(TestBrowser { it.replace("state=", "state=x") }) + fail("a callback with another state was accepted") + } catch (expected: HostSignInException.StateMismatch) { + } + try { + foreign.signIn(TestBrowser { it.replace("/callback", "/elsewhere") }) + fail("a callback to another address was accepted") + } catch (expected: HostSignInException.CallbackMismatch) { + } + try { + foreign.accessToken() + fail("a token without sign-in") + } catch (expected: HostSignInException.SignInRequired) { + } + } + + @Test + fun aRevokedCoachAndADisconnectedAppAreRefused() { + val ownerName = "owner-${UUID.randomUUID()}" + val owner = signIn("athlete-app", ownerName).client() + val athlete = owner.createAthlete("Synthetic athlete") + val offer = owner.createGrantOffer(athlete.athleteId, listOf("read_workout_summaries"), "coach-app") + val coach = signIn("coach-app", "coach-${UUID.randomUUID()}").client() + val grant = coach.acceptGrantOffer(offer.code) + assertEquals(listOf(athlete.athleteId), coach.roster().map { it.athleteId }) + assertTrue(coach.workoutSummaries(athlete.athleteId).workouts.isEmpty()) + owner.revokeGrant(athlete.athleteId, grant.grantId) + assertEquals("not_found", code { coach.workoutSummaries(athlete.athleteId) }) + + val second = signIn("athlete-app-2", ownerName).client() + assertEquals("owner", second.athlete(athlete.athleteId).role) + assertEquals("disconnected", owner.disconnectApp(athlete.athleteId, "athlete-app-2").state) + assertEquals("app_disconnected", code { second.athlete(athlete.athleteId) }) + owner.connectApp(athlete.athleteId, "athlete-app-2") + assertEquals("owner", second.athlete(athlete.athleteId).role) + } + + @Test + fun anAppWithItsOwnSessionSuppliesTheToken() { + val store = MemoryTokenStore() + signIn("athlete-app", "own-${UUID.randomUUID()}", store) + val token = store.load()!!.accessToken + assertEquals("athlete-app", HostClient(hostUrl) { token }.me().clientId) + assertEquals("sign_in_required", code { HostClient(hostUrl) { "not-a-token" }.me() }) + } +} diff --git a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt new file mode 100644 index 00000000..2eb9f588 --- /dev/null +++ b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt @@ -0,0 +1,358 @@ +package ai.athleticstandard.host + +import android.net.Uri +import org.json.JSONArray +import org.json.JSONObject +import java.io.ByteArrayOutputStream +import java.net.HttpURLConnection +import java.net.URL +import java.util.UUID + +/** + * An error reply from the host: the HTTP status, its stable code, and its message. + * The host sends `{"error": {"code", "message"}}`. A failure to reach the host stays + * an `IOException`. [code] is null when the reply had no error body. + */ +class HostException(val status: Int, val code: String?, message: String) : + Exception("${code ?: "http_error"} ($status): $message") + +/** + * A write the client built but the host has not answered yet: its method, path, exact + * body bytes, and `Idempotency-Key` (D261). Keep it with an unsent edit, across a + * restart if needed, and send it again unchanged after a lost reply. + */ +data class PreparedWrite( + val method: String, + val path: List, + val body: ByteArray, + val idempotencyKey: String, + val contentType: String = "application/json", +) { + override fun equals(other: Any?): Boolean = other is PreparedWrite && method == other.method && + path == other.path && body.contentEquals(other.body) && idempotencyKey == other.idempotencyKey && + contentType == other.contentType + + override fun hashCode(): Int = listOf(method, path, body.contentHashCode(), idempotencyKey, contentType).hashCode() + + /** The write as JSON text, to store with the app's unsent edits. */ + fun toJson(): String = JSONObject() + .put("method", method) + .put("path", JSONArray(path)) + .put("body", android.util.Base64.encodeToString(body, android.util.Base64.NO_WRAP)) + .put("idempotency_key", idempotencyKey) + .put("content_type", contentType) + .toString() + + companion object { + fun fromJson(text: String): PreparedWrite { + val json = JSONObject(text) + val path = json.getJSONArray("path") + return PreparedWrite( + json.getString("method"), + List(path.length()) { path.getString(it) }, + android.util.Base64.decode(json.getString("body"), android.util.Base64.NO_WRAP), + json.getString("idempotency_key"), + json.getString("content_type"), + ) + } + } +} + +data class WriteResult(val databaseRevision: Long, val records: List) +data class WrittenRecord(val recordId: String, val revision: Long) +data class ProtectedResource(val resource: String, val authorizationServers: List) +data class Me(val principalId: String, val clientId: String, val coachId: String, val athletes: List) +data class CreatedAthlete(val athleteId: String, val databaseRevision: Long, val operatorDisclosure: String) +data class OwnedAthlete(val athleteId: String, val displayName: String?, val state: String) +data class AthleteInfo( + val athleteId: String, + val role: String, + val state: String, + val operatorDisclosure: String, + val databaseRevision: Long?, +) +data class Change(val databaseRevision: Long, val recordId: String, val recordRevision: Long, val kind: String) +data class ChangesPage(val from: Long, val to: Long, val complete: Boolean, val changes: List) +data class ConnectedApp(val clientId: String, val state: String, val thisApp: Boolean) +data class GrantOffer(val code: String, val expiresAt: String, val permissions: List, val clientId: String) +data class Grant(val grantId: String, val resourceId: String, val clientId: String, val permissions: List) +data class RosterEntry(val athleteId: String, val displayName: String?, val permissions: List, val grantId: String) +data class WorkoutSummary( + val recordId: String, + val revision: Long, + val startAt: String, + val endAt: String, + val activityType: String?, +) +data class WorkoutPage(val workouts: List, val next: String?) + +/** + * A client for version 1 of the `ath-host` API (D330). It sends an OAuth access token + * with each request; the host checks it and applies the athlete's grants. The client + * never holds database credentials (D266). + * + * Every call does network work on the calling thread: call it away from the main + * thread. [accessToken] returns a current token; [HostSignIn.client] passes one that + * refreshes. An app that already has a session for this host passes its own. + * Connecting does not link a local file or upload it. + */ +class HostClient( + val baseUrl: String, + private val accessToken: () -> String, +) { + /** The host's resource identifier and its sign-in provider (RFC 9728). No token. */ + fun protectedResource(): ProtectedResource { + val json = JSONObject(send("GET", listOf(".well-known", "oauth-protected-resource"), signedIn = false).text()) + return ProtectedResource(json.getString("resource"), json.getJSONArray("authorization_servers").strings()) + } + + fun me(): Me { + val json = JSONObject(send("GET", listOf("v1", "me")).text()) + return Me(json.getString("principal_id"), json.getString("client_id"), json.getString("coach_id"), + json.getJSONArray("athletes").strings()) + } + + fun createAthlete(displayName: String? = null, invitation: String? = null): CreatedAthlete { + val body = JSONObject() + displayName?.let { body.put("display_name", it) } + invitation?.let { body.put("invitation", it) } + val json = JSONObject(send("POST", listOf("v1", "athletes"), body = body.toString().toByteArray()).text()) + return CreatedAthlete(json.getString("athlete_id"), json.getLong("database_revision"), + json.getString("operator_disclosure")) + } + + fun athletes(): List { + val list = JSONObject(send("GET", listOf("v1", "athletes")).text()).getJSONArray("athletes") + return List(list.length()) { + val item = list.getJSONObject(it) + OwnedAthlete(item.getString("athlete_id"), item.optStringOrNull("display_name"), item.getString("state")) + } + } + + fun athlete(athleteId: String): AthleteInfo { + val json = JSONObject(send("GET", listOf("v1", "athletes", athleteId)).text()) + return AthleteInfo(json.getString("athlete_id"), json.getString("role"), json.getString("state"), + json.getString("operator_disclosure"), + if (json.isNull("database_revision")) null else json.optLong("database_revision")) + } + + /** + * Current records, oldest first, as the host's UTF-8 JSON reply + * `{"records": [...]}`. Pass it to `RecordSnapshotBuilder.addRecords` to calculate + * on the phone. + */ + fun recordsJson(athleteId: String, recordType: String? = null, limit: Int? = null): ByteArray { + val query = mutableListOf>() + recordType?.let { query += "record_type" to it } + limit?.let { query += "limit" to it.toString() } + return send("GET", listOf("v1", "athletes", athleteId, "records"), query = query) + } + + /** One record and its complete history, as `{"record": {...}, "revisions": [...]}`. */ + fun recordJson(athleteId: String, recordId: String): ByteArray = + send("GET", listOf("v1", "athletes", athleteId, "records", recordId)) + + /** The changes since a database revision (D263). */ + fun changes(athleteId: String, since: Long): ChangesPage { + val json = JSONObject( + send("GET", listOf("v1", "athletes", athleteId, "changes"), query = listOf("since" to since.toString())) + .text(), + ) + val list = json.getJSONArray("changes") + return ChangesPage(json.getLong("from"), json.getLong("to"), json.getBoolean("complete"), List(list.length()) { + val item = list.getJSONObject(it) + Change(item.getLong("database_revision"), item.getString("record_id"), item.getLong("record_revision"), + item.getString("kind")) + }) + } + + /** The complete package as a zip. */ + fun export(athleteId: String): ByteArray = + send("GET", listOf("v1", "athletes", athleteId, "export"), accept = "application/zip") + + fun apps(athleteId: String): List { + val list = JSONObject(send("GET", listOf("v1", "athletes", athleteId, "apps")).text()).getJSONArray("apps") + return List(list.length()) { app(list.getJSONObject(it)) } + } + + /** Disconnect an app from a record (D270). Its next request gets `app_disconnected`. */ + fun disconnectApp(athleteId: String, clientId: String): ConnectedApp = + app(JSONObject(send("DELETE", listOf("v1", "athletes", athleteId, "apps", clientId)).text()).getJSONObject("app")) + + fun connectApp(athleteId: String, clientId: String): ConnectedApp = + app(JSONObject(send("PUT", listOf("v1", "athletes", athleteId, "apps", clientId)).text()).getJSONObject("app")) + + /** A new record. `data` is the record's data as UTF-8 JSON, kept byte for byte. */ + fun prepareRecordCreation( + athleteId: String, + recordType: String, + data: ByteArray, + recordId: String? = null, + idempotencyKey: String = UUID.randomUUID().toString(), + ): PreparedWrite { + val fields = mutableListOf("data" to jsonObject(data), "record_type" to JSONObject.quote(recordType)) + recordId?.let { fields += "record_id" to JSONObject.quote(it) } + return PreparedWrite("POST", listOf("v1", "athletes", athleteId, "records"), joined(fields), idempotencyKey) + } + + /** + * A correction: the complete new data, and the revision the person edited. If the + * record changed since, the host answers `stale`; keep the person's edit for review. + */ + fun prepareCorrection( + athleteId: String, + recordId: String, + expectedRevision: Long, + data: ByteArray, + idempotencyKey: String = UUID.randomUUID().toString(), + ): PreparedWrite = PreparedWrite( + "POST", + listOf("v1", "athletes", athleteId, "records", recordId, "corrections"), + joined(listOf("data" to jsonObject(data), "expected_revision" to expectedRevision.toString())), + idempotencyKey, + ) + + fun prepareDeletion( + athleteId: String, + recordId: String, + expectedRevision: Long, + idempotencyKey: String = UUID.randomUUID().toString(), + ): PreparedWrite = PreparedWrite( + "POST", + listOf("v1", "athletes", athleteId, "records", recordId, "deletion"), + joined(listOf("expected_revision" to expectedRevision.toString())), + idempotencyKey, + ) + + /** Send a prepared write. The same write sent again is answered with the first result. */ + fun send(write: PreparedWrite): WriteResult { + val json = JSONObject( + send(write.method, write.path, body = write.body, contentType = write.contentType, + idempotencyKey = write.idempotencyKey).text(), + ) + val list = json.getJSONArray("records") + return WriteResult(json.getLong("database_revision"), List(list.length()) { + val item = list.getJSONObject(it) + WrittenRecord(item.getString("record_id"), item.getLong("revision")) + }) + } + + /** Offer a coach access, through the coach app named by `coachClientId`. */ + fun createGrantOffer(athleteId: String, permissions: List, coachClientId: String): GrantOffer { + val body = JSONObject().put("permissions", JSONArray(permissions)).put("client_id", coachClientId) + val json = JSONObject( + send("POST", listOf("v1", "athletes", athleteId, "grant-offers"), body = body.toString().toByteArray()).text(), + ) + return GrantOffer(json.getString("code"), json.getString("expires_at"), json.getJSONArray("permissions").strings(), + json.getString("client_id")) + } + + fun revokeGrant(athleteId: String, grantId: String) { + send("DELETE", listOf("v1", "athletes", athleteId, "grants", grantId)) + } + + fun acceptGrantOffer(code: String): Grant { + val body = JSONObject().put("code", code).toString().toByteArray() + val grant = JSONObject(send("POST", listOf("v1", "grant-offers", "accept"), body = body).text()) + .getJSONObject("grant") + return Grant(grant.getString("grant_id"), grant.getString("resource_id"), grant.getString("client_id"), + grant.getJSONArray("permissions").strings()) + } + + fun roster(): List { + val list = JSONObject(send("GET", listOf("v1", "roster")).text()).getJSONArray("athletes") + return List(list.length()) { + val item = list.getJSONObject(it) + RosterEntry(item.getString("athlete_id"), item.optStringOrNull("display_name"), + item.getJSONArray("permissions").strings(), item.getString("grant_id")) + } + } + + fun workoutSummaries(athleteId: String, limit: Int? = null, after: String? = null): WorkoutPage { + val query = mutableListOf>() + limit?.let { query += "limit" to it.toString() } + after?.let { query += "after" to it } + val json = JSONObject(send("GET", listOf("v1", "athletes", athleteId, "workouts"), query = query).text()) + val list = json.getJSONArray("workouts") + return WorkoutPage(List(list.length()) { + val item = list.getJSONObject(it) + WorkoutSummary(item.getString("record_id"), item.getLong("revision"), item.getString("start_at"), + item.getString("end_at"), item.optStringOrNull("activity_type")) + }, json.optStringOrNull("next")) + } + + private fun app(json: JSONObject) = + ConnectedApp(json.getString("client_id"), json.getString("state"), json.getBoolean("this_app")) + + private fun jsonObject(data: ByteArray): String { + val text = data.decodeToString() + JSONObject(text) // must be a JSON object + return text + } + + /** `{"key": value, ...}` from encoded values, keys sorted, so a write built twice has the same bytes. */ + private fun joined(fields: List>): ByteArray = + fields.sortedBy { it.first }.joinToString(",", "{", "}") { "${JSONObject.quote(it.first)}:${it.second}" } + .toByteArray(Charsets.UTF_8) + + private fun url(path: List, query: List>): URL { + val base = baseUrl.trimEnd('/') + val encoded = path.joinToString("/") { segment -> + if (segment == "." || segment == "..") segment.replace(".", "%2E") else Uri.encode(segment) + } + val search = if (query.isEmpty()) "" else query.joinToString("&", "?") { "${Uri.encode(it.first)}=${Uri.encode(it.second)}" } + return URL("$base/$encoded$search") + } + + private fun send( + method: String, + path: List, + query: List> = emptyList(), + body: ByteArray? = null, + contentType: String = "application/json", + idempotencyKey: String? = null, + signedIn: Boolean = true, + accept: String = "application/json", + ): ByteArray { + val connection = url(path, query).openConnection() as HttpURLConnection + try { + connection.requestMethod = method + // A cached reply could show data after the athlete revoked a grant. + connection.useCaches = false + connection.instanceFollowRedirects = false + connection.setRequestProperty("Accept", accept) + if (signedIn) connection.setRequestProperty("Authorization", "Bearer ${accessToken()}") + idempotencyKey?.let { connection.setRequestProperty("Idempotency-Key", it) } + if (body != null) { + connection.doOutput = true + connection.setRequestProperty("Content-Type", contentType) + connection.setFixedLengthStreamingMode(body.size) + connection.outputStream.use { it.write(body) } + } + val status = connection.responseCode + val stream = if (status in 200..299) connection.inputStream else connection.errorStream + val bytes = stream?.use { input -> ByteArrayOutputStream().also { input.copyTo(it) }.toByteArray() } + ?: ByteArray(0) + if (status !in 200..299) throw error(status, bytes) + return bytes + } finally { + connection.disconnect() + } + } + + private fun error(status: Int, body: ByteArray): HostException { + val text = body.decodeToString() + return try { + val detail = JSONObject(text).getJSONObject("error") + HostException(status, detail.getString("code"), detail.getString("message")) + } catch (notJson: org.json.JSONException) { + HostException(status, null, text.trim().ifEmpty { "HTTP $status" }) + } + } +} + +internal fun ByteArray.text(): String = decodeToString() + +internal fun JSONArray.strings(): List = List(length()) { getString(it) } + +internal fun JSONObject.optStringOrNull(key: String): String? = if (isNull(key)) null else optString(key) diff --git a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostSignIn.kt b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostSignIn.kt new file mode 100644 index 00000000..2d65f38f --- /dev/null +++ b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostSignIn.kt @@ -0,0 +1,385 @@ +package ai.athleticstandard.host + +import android.app.Activity +import android.content.Context +import android.net.Uri +import android.os.Bundle +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import androidx.browser.customtabs.CustomTabsIntent +import org.json.JSONObject +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.security.KeyStore +import java.security.MessageDigest +import java.security.SecureRandom +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** + * What an app registers with its sign-in provider, such as a WorkOS public OAuth + * application (D330, docs/hosting.md section 6.5). + * + * [redirectUri] must be registered exactly, and the app's manifest must route it to + * [SignInRedirectActivity]; see the mobile README. + */ +data class HostSignInConfiguration( + val hostUrl: String, + val clientId: String, + val redirectUri: String, + val scopes: List = listOf("openid", "profile", "email", "offline_access"), + val loginHint: String? = null, +) + +/** The tokens of one signed-in person for one host and app. Never put them in an athlete file. */ +data class HostTokens( + val accessToken: String, + val refreshToken: String?, + val expiresAtMillis: Long, + val tokenEndpoint: String, + val resource: String, + val clientId: String, +) { + fun toJson(): String = JSONObject() + .put("access_token", accessToken) + .put("refresh_token", refreshToken ?: JSONObject.NULL) + .put("expires_at_millis", expiresAtMillis) + .put("token_endpoint", tokenEndpoint) + .put("resource", resource) + .put("client_id", clientId) + .toString() + + companion object { + fun fromJson(text: String): HostTokens { + val json = JSONObject(text) + return HostTokens(json.getString("access_token"), json.optStringOrNull("refresh_token"), + json.getLong("expires_at_millis"), json.getString("token_endpoint"), json.getString("resource"), + json.getString("client_id")) + } + } +} + +/** Where [HostSignIn] keeps tokens. */ +interface HostTokenStore { + fun load(): HostTokens? + fun save(tokens: HostTokens) + fun clear() +} + +/** Tokens in memory only, for tests and for apps that sign in each time. */ +class MemoryTokenStore(@Volatile private var tokens: HostTokens? = null) : HostTokenStore { + override fun load() = tokens + override fun save(tokens: HostTokens) { this.tokens = tokens } + override fun clear() { tokens = null } +} + +/** + * Tokens in a private file of the app, encrypted with an AES key that the Android + * Keystore holds and never releases. The file is in `noBackupFilesDir`, so backups do + * not carry it. + */ +class KeystoreTokenStore(context: Context, private val name: String = "athleticstandard-host") : HostTokenStore { + private val file = File(context.noBackupFilesDir, "$name.tokens") + private val alias = "ai.athleticstandard.host.$name" + + private fun key(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey(alias, null) as? SecretKey)?.let { return it } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + generator.init( + KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build(), + ) + return generator.generateKey() + } + + @Synchronized + override fun load(): HostTokens? { + if (!file.exists()) return null + val bytes = file.readBytes() + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes, 0, 12)) + return HostTokens.fromJson(cipher.doFinal(bytes, 12, bytes.size - 12).decodeToString()) + } + + @Synchronized + override fun save(tokens: HostTokens) { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, key()) + val sealed = cipher.iv + cipher.doFinal(tokens.toJson().toByteArray()) + val temporary = File(file.parentFile, "$name.tokens.new") + temporary.writeBytes(sealed) + if (!temporary.renameTo(file)) throw java.io.IOException("cannot replace ${file.path}") + } + + @Synchronized + override fun clear() { + file.delete() + } +} + +/** Opens the provider's sign-in page and returns the callback the provider redirected to. */ +interface AuthorizationBrowser { + /** Blocks until the callback arrives. Call it away from the main thread. */ + fun authorize(url: String, redirectUri: String): String +} + +/** Why sign-in did not finish. */ +sealed class HostSignInException(message: String) : Exception(message) { + /** The person closed the sign-in page, or the provider answered `access_denied`. */ + class Cancelled : HostSignInException("sign-in was cancelled") + class DiscoveryFailed(detail: String) : HostSignInException(detail) + /** The callback is not the registered callback address. */ + class CallbackMismatch : HostSignInException("the callback is not the registered address") + /** The callback belongs to another sign-in: its `state` is not the one sent. */ + class StateMismatch : HostSignInException("the callback belongs to another sign-in") + class ProviderError(val code: String, val description: String?) : + HostSignInException("$code${description?.let { ": $it" } ?: ""}") + /** Nobody is signed in, or the provider no longer accepts the refresh token. */ + class SignInRequired : HostSignInException("sign in again") +} + +/** + * The system browser in a Custom Tab (RFC 8252). The callback reaches + * [SignInRedirectActivity], which the app routes its redirect address to. The app + * never sees the password. If the person closes the tab, call [cancelPendingSignIn] + * from the activity's `onResume`, or the wait ends after [timeoutMillis]. + */ +class CustomTabsBrowser( + private val activity: Activity, + private val timeoutMillis: Long = 10 * 60 * 1000, +) : AuthorizationBrowser { + override fun authorize(url: String, redirectUri: String): String { + val pending = SignInRedirects.expect() + activity.runOnUiThread { CustomTabsIntent.Builder().build().launchUrl(activity, Uri.parse(url)) } + return pending.await(timeoutMillis) ?: throw HostSignInException.Cancelled() + } + + companion object { + /** End a sign-in whose tab the person closed. */ + @JvmStatic + fun cancelPendingSignIn() = SignInRedirects.cancel() + } +} + +internal object SignInRedirects { + class Pending { + val latch = CountDownLatch(1) + val callback = AtomicReference() + + fun await(timeoutMillis: Long): String? { + latch.await(timeoutMillis, TimeUnit.MILLISECONDS) + return callback.get() + } + } + + private val current = AtomicReference() + + fun expect(): Pending = Pending().also { current.getAndSet(it)?.latch?.countDown() } + + fun deliver(callback: String) { + current.getAndSet(null)?.let { + it.callback.set(callback) + it.latch.countDown() + } + } + + fun cancel() { + current.getAndSet(null)?.latch?.countDown() + } +} + +/** + * Receives the sign-in callback and hands it to the waiting [CustomTabsBrowser]. Declare + * it in the app's manifest with an intent filter for the app's redirect address. + */ +class SignInRedirectActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + intent?.data?.let { SignInRedirects.deliver(it.toString()) } + finish() + } +} + +/** + * Browser sign-in for `ath-host` with the authorization code flow and S256 PKCE (RFC + * 8252, RFC 7636), and a token for the host's resource (RFC 8707) (D330). + * + * [signIn] reads the host's protected-resource metadata and the provider's discovery + * document, opens the provider in the browser, checks that the callback carries this + * sign-in's `state`, and exchanges the code. [accessToken] refreshes the token when it + * is about to expire. [client] makes a [HostClient] that uses it. Every call does + * network work on the calling thread. Local files need none of this. + */ +class HostSignIn( + val configuration: HostSignInConfiguration, + private val store: HostTokenStore, + private val refreshMarginMillis: Long = 60_000, +) { + private val lock = Any() + + fun isSignedIn(): Boolean = store.load() != null + + fun client(): HostClient = HostClient(configuration.hostUrl) { accessToken() } + + /** Sign in through [browser]. Replaces any stored tokens. */ + fun signIn(browser: AuthorizationBrowser) { + val resource = HostClient(configuration.hostUrl) { "" }.protectedResource() + val issuer = resource.authorizationServers.firstOrNull() + ?: throw HostSignInException.DiscoveryFailed("the host names no sign-in provider") + val provider = discover(issuer) + if (provider.getString("issuer") != issuer) { + throw HostSignInException.DiscoveryFailed("the provider's issuer is not $issuer") + } + val verifier = random(32) + val state = random(16) + val authorization = Uri.parse(provider.getString("authorization_endpoint")).buildUpon() + .appendQueryParameter("response_type", "code") + .appendQueryParameter("client_id", configuration.clientId) + .appendQueryParameter("redirect_uri", configuration.redirectUri) + .appendQueryParameter("scope", configuration.scopes.joinToString(" ")) + .appendQueryParameter("state", state) + .appendQueryParameter("code_challenge", challenge(verifier)) + .appendQueryParameter("code_challenge_method", "S256") + .appendQueryParameter("resource", resource.resource) + .apply { configuration.loginHint?.let { appendQueryParameter("login_hint", it) } } + .build() + val callback = browser.authorize(authorization.toString(), configuration.redirectUri) + val code = code(callback, configuration.redirectUri, state) + store.save( + tokenRequest( + provider.getString("token_endpoint"), + resource.resource, + mapOf( + "grant_type" to "authorization_code", + "code" to code, + "redirect_uri" to configuration.redirectUri, + "client_id" to configuration.clientId, + "code_verifier" to verifier, + "resource" to resource.resource, + ), + null, + ), + ) + } + + /** A current access token, refreshed when it is about to expire. */ + fun accessToken(): String = synchronized(lock) { + val tokens = store.load() ?: throw HostSignInException.SignInRequired() + if (tokens.expiresAtMillis - System.currentTimeMillis() > refreshMarginMillis) return tokens.accessToken + val refreshToken = tokens.refreshToken ?: run { + store.clear() + throw HostSignInException.SignInRequired() + } + val fresh = try { + tokenRequest( + tokens.tokenEndpoint, + tokens.resource, + mapOf( + "grant_type" to "refresh_token", + "refresh_token" to refreshToken, + "client_id" to tokens.clientId, + "resource" to tokens.resource, + ), + refreshToken, + ) + } catch (refused: HostSignInException.ProviderError) { + if (refused.code != "invalid_grant") throw refused + store.clear() + throw HostSignInException.SignInRequired() + } + store.save(fresh) + fresh.accessToken + } + + /** Forget the stored tokens. Local files are not touched. */ + fun signOut() = store.clear() + + private fun discover(issuer: String): JSONObject { + for (document in listOf("openid-configuration", "oauth-authorization-server")) { + val connection = URL("${issuer.trimEnd('/')}/.well-known/$document").openConnection() as HttpURLConnection + try { + connection.useCaches = false + if (connection.responseCode == 200) { + return JSONObject(connection.inputStream.use { it.readBytes() }.decodeToString()) + } + } catch (unreadable: Exception) { + continue + } finally { + connection.disconnect() + } + } + throw HostSignInException.DiscoveryFailed("no discovery document at $issuer") + } + + private fun tokenRequest( + endpoint: String, + resource: String, + fields: Map, + previousRefreshToken: String?, + ): HostTokens { + val body = fields.toSortedMap().entries.joinToString("&") { "${Uri.encode(it.key)}=${Uri.encode(it.value)}" } + .toByteArray() + val connection = URL(endpoint).openConnection() as HttpURLConnection + val reply = try { + connection.requestMethod = "POST" + connection.useCaches = false + connection.doOutput = true + connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") + connection.setRequestProperty("Accept", "application/json") + connection.outputStream.use { it.write(body) } + val stream = if (connection.responseCode in 200..299) connection.inputStream else connection.errorStream + JSONObject(stream.use { it.readBytes() }.decodeToString()) + } finally { + connection.disconnect() + } + reply.optStringOrNull("error")?.let { + throw HostSignInException.ProviderError(it, reply.optStringOrNull("error_description")) + } + val access = reply.optStringOrNull("access_token") + ?: throw HostSignInException.ProviderError("invalid_response", "no access_token") + val expiresIn = if (reply.has("expires_in")) reply.getLong("expires_in") else 300L + return HostTokens(access, reply.optStringOrNull("refresh_token") ?: previousRefreshToken, + System.currentTimeMillis() + expiresIn * 1000, endpoint, resource, configuration.clientId) + } + + companion object { + /** The code from a callback, after checking its address and `state`. */ + internal fun code(callback: String, redirectUri: String, state: String): String { + val received = Uri.parse(callback) + val expected = Uri.parse(redirectUri) + val trim = { path: String? -> (path ?: "").trimEnd('/') } + if (!received.scheme.equals(expected.scheme, ignoreCase = true) || + (received.host ?: "") != (expected.host ?: "") || trim(received.path) != trim(expected.path) + ) { + throw HostSignInException.CallbackMismatch() + } + if (received.getQueryParameter("state") != state) throw HostSignInException.StateMismatch() + received.getQueryParameter("error")?.let { + if (it == "access_denied") throw HostSignInException.Cancelled() + throw HostSignInException.ProviderError(it, received.getQueryParameter("error_description")) + } + return received.getQueryParameter("code")?.takeIf { it.isNotEmpty() } + ?: throw HostSignInException.ProviderError("invalid_response", "the callback has no code") + } + + internal fun challenge(verifier: String): String = base64Url( + MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(Charsets.US_ASCII)), + ) + + private fun random(bytes: Int): String = base64Url(ByteArray(bytes).also { SecureRandom().nextBytes(it) }) + + private fun base64Url(bytes: ByteArray): String = + Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP) + } +} diff --git a/mobile/scripts/test-android.sh b/mobile/scripts/test-android.sh index 25627e65..186ac960 100755 --- a/mobile/scripts/test-android.sh +++ b/mobile/scripts/test-android.sh @@ -24,10 +24,24 @@ ATH_MOBILE_FIXTURES="$FIXTURES" cargo test --locked -p athleticstandard-mobile - cargo build --locked --bin ath --manifest-path "$ROOT/Cargo.toml" "$ROOT/mobile/scripts/roundtrip.sh" create "$FIXTURES/roundtrip" +# A real ath-host and the test sign-in provider on this computer, forwarded to +# each device's own 127.0.0.1 so the same addresses work on both sides. +HOST_ENV="$ROOT/target/host-test" +"$ROOT/mobile/scripts/host-test-env.sh" start "$HOST_ENV" +trap '"$ROOT/mobile/scripts/host-test-env.sh" stop "$HOST_ENV"' EXIT +# shellcheck disable=SC1091 +source "$HOST_ENV/env" +for device in $(adb devices | awk 'NR > 1 && $2 == "device" { print $1 }'); do + adb -s "$device" reverse "tcp:$ATH_TEST_HOST_PORT" "tcp:$ATH_TEST_HOST_PORT" > /dev/null + adb -s "$device" reverse "tcp:$ATH_TEST_ISSUER_PORT" "tcp:$ATH_TEST_ISSUER_PORT" > /dev/null +done + cd "$ROOT/mobile/android" rm -rf athleticstandard/build/outputs/connected_android_test_additional_output ./gradlew --no-daemon :athleticstandard:connectedDebugAndroidTest \ - -Pathleticstandard.rustProfile="$PROFILE" -Pathleticstandard.fixtures="$FIXTURES" + -Pathleticstandard.rustProfile="$PROFILE" -Pathleticstandard.fixtures="$FIXTURES" \ + -Pandroid.testInstrumentationRunnerArguments.hostUrl="$ATH_TEST_HOST_URL" \ + -Pandroid.testInstrumentationRunnerArguments.issuer="$ATH_TEST_ISSUER" for report in athleticstandard/build/outputs/androidTest-results/connected/debug/TEST-*.xml; do grep -o ']*>' "$report" done diff --git a/mobile/scripts/test-apple.sh b/mobile/scripts/test-apple.sh index b828a06d..62fbe36e 100755 --- a/mobile/scripts/test-apple.sh +++ b/mobile/scripts/test-apple.sh @@ -34,6 +34,15 @@ ROUNDTRIP_OUT="$ROOT/target/mobile-roundtrip" rm -rf "$ROUNDTRIP_OUT" mkdir -p "$ROUNDTRIP_OUT" +# A real ath-host and the test sign-in provider for the host client tests. +HOST_ENV="$ROOT/target/host-test" +"$ROOT/mobile/scripts/host-test-env.sh" start "$HOST_ENV" +trap '"$ROOT/mobile/scripts/host-test-env.sh" stop "$HOST_ENV"' EXIT +set -a +# shellcheck disable=SC1091 +source "$HOST_ENV/env" +set +a + cd "$ROOT/mobile/swift" # Some Command Line Tools releases leave the Swift Testing macro plugin out of # the search path; naming its folder is harmless when it is already found. @@ -63,6 +72,7 @@ if [ -z "$SIMULATOR" ]; then fi # xcodebuild passes TEST_RUNNER_ variables to the test process without the prefix. TEST_RUNNER_ATH_MOBILE_FIXTURES="$FIXTURES" TEST_RUNNER_ATH_MOBILE_ROUNDTRIP_OUT="$ROUNDTRIP_OUT/simulator" \ + TEST_RUNNER_ATH_TEST_HOST_URL="$ATH_TEST_HOST_URL" TEST_RUNNER_ATH_TEST_ISSUER="$ATH_TEST_ISSUER" \ xcodebuild test -scheme AthleticStandard \ -destination "platform=iOS Simulator,id=$SIMULATOR" -derivedDataPath "$ROOT/mobile/swift/.build/xcode" \ | tail -n 40 diff --git a/mobile/src/calculate.rs b/mobile/src/calculate.rs index eaea58c9..8c6c2a6b 100644 --- a/mobile/src/calculate.rs +++ b/mobile/src/calculate.rs @@ -180,11 +180,20 @@ impl RecordSnapshotBuilder { } /// Add a batch: a UTF-8 JSON array of current records, the shape - /// `listRecords` returns. Include sources, the athlete profile, and the - /// samples a calculation reads. Deleted records may be included. Returns - /// the number of records held after the batch. + /// `listRecords` returns, or an object that holds that array under + /// `records`, as the host's record list and `ath records list --json` do. + /// Include sources, the athlete profile, and the samples a calculation + /// reads. Deleted records may be included. Returns the number of records + /// held after the batch. pub fn add_records(&self, records: Vec) -> Result { - let batch = parse_json(&records)?; + let mut batch = parse_json(&records)?; + // The host's record list and `ath records list --json` hold the array + // under `records`. + if let json::Value::Object(map) = &mut batch { + if let Some(list @ json::Value::Array(_)) = map.remove("records") { + batch = list; + } + } let mut guard = self.builder.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let builder = guard .as_mut() diff --git a/mobile/swift/Package.swift b/mobile/swift/Package.swift index acbc14d4..f7674106 100644 --- a/mobile/swift/Package.swift +++ b/mobile/swift/Package.swift @@ -12,6 +12,7 @@ let package = Package( platforms: [.iOS(.v17), .macOS(.v14)], products: [ .library(name: "AthleticStandard", targets: ["AthleticStandard"]), + .library(name: "AthleticStandardHost", targets: ["AthleticStandardHost"]), ], targets: [ .binaryTarget(name: "AthleticStandardFFI", path: "build/AthleticStandardFFI.xcframework"), @@ -20,6 +21,10 @@ let package = Package( dependencies: ["AthleticStandardFFI"], linkerSettings: [.linkedFramework("CoreFoundation"), .linkedLibrary("iconv")] ), + // The optional client for ath-host, with browser sign-in (D330). It needs no + // native library, and local files never need it. + .target(name: "AthleticStandardHost"), .testTarget(name: "AthleticStandardTests", dependencies: ["AthleticStandard"]), + .testTarget(name: "AthleticStandardHostTests", dependencies: ["AthleticStandardHost"]), ] ) diff --git a/mobile/swift/Sources/AthleticStandardHost/HostClient.swift b/mobile/swift/Sources/AthleticStandardHost/HostClient.swift new file mode 100644 index 00000000..96144d2d --- /dev/null +++ b/mobile/swift/Sources/AthleticStandardHost/HostClient.swift @@ -0,0 +1,386 @@ +import Foundation + +/// A client for version 1 of the `ath-host` API (spec 2.1.3 section 6.5, D330). +/// +/// The client sends an OAuth access token with each request. The host checks the +/// token, then applies the athlete's grants. The client never holds database +/// credentials (D266). `HostSignIn` signs a person in through the system browser +/// and makes a client; an app that already has a session for this host can pass +/// its own token function instead. +/// +/// Connecting does not link a local file or upload it. Keeping a local copy in step +/// with a host is not part of this client. +/// +/// Every method throws `HostError` when the host answers with an error, and +/// `URLError` when the request does not reach the host. +public struct HostClient: Sendable { + /// The host's address, such as `https://records.example.org`. + public let baseURL: URL + private let session: URLSession + private let accessToken: @Sendable () async throws -> String + + /// A client that asks `accessToken` for a current token before each request. An + /// app passes a function that refreshes the token when it has expired. + public init( + baseURL: URL, session: URLSession = .shared, + accessToken: @escaping @Sendable () async throws -> String + ) { + self.baseURL = baseURL + self.session = session + self.accessToken = accessToken + } + + /// A client with one fixed access token. + public init(baseURL: URL, token: String, session: URLSession = .shared) { + self.init(baseURL: baseURL, session: session, accessToken: { token }) + } + + // MARK: - Discovery + + /// The host's resource identifier and its sign-in provider (RFC 9728). An app + /// reads this before sign-in. It needs no token. + public func protectedResource() async throws -> ProtectedResource { + try await send("GET", [".well-known", "oauth-protected-resource"], signedIn: false) + } + + /// The API version, the storage kind, and who runs the host. It needs no token. + public func capabilities() async throws -> Capabilities { + try await send("GET", ["v1", "capabilities"], signedIn: false) + } + + /// The signed-in person and the records they own. + public func me() async throws -> Me { + try await send("GET", ["v1", "me"]) + } + + // MARK: - Owner + + /// Create an empty record owned by the signed-in person. The host refuses this + /// without an invitation unless it allows open enrollment. + public func createAthlete(displayName: String? = nil, invitation: String? = nil) async throws + -> CreatedAthlete + { + struct Body: Encodable { + let displayName: String? + let invitation: String? + enum CodingKeys: String, CodingKey { + case displayName = "display_name" + case invitation + } + } + return try await send( + "POST", ["v1", "athletes"], body: Self.json(Body(displayName: displayName, invitation: invitation))) + } + + /// Restore a complete package, as a zip of the package folder, into the owner's + /// empty record. Returns the record's database revision. + public func restorePackage(athleteID: String, zip: Data) async throws -> Int { + struct Reply: Decodable { + let databaseRevision: Int + enum CodingKeys: String, CodingKey { case databaseRevision = "database_revision" } + } + let reply: Reply = try await send( + "PUT", ["v1", "athletes", athleteID, "package"], body: zip, contentType: "application/zip") + return reply.databaseRevision + } + + /// Offer a coach access. The athlete gives the returned code to the coach, who + /// accepts it with the app named by `coachClientID`. Nothing is granted until then. + public func createGrantOffer( + athleteID: String, permissions: [Permission], coachClientID: String, coachLabel: String? = nil, + validSeconds: Int? = nil + ) async throws -> GrantOffer { + struct Body: Encodable { + let permissions: [Permission] + let clientID: String + let coachLabel: String? + let validSeconds: Int? + enum CodingKeys: String, CodingKey { + case permissions + case clientID = "client_id" + case coachLabel = "coach_label" + case validSeconds = "valid_seconds" + } + } + let body = Body( + permissions: permissions, clientID: coachClientID, coachLabel: coachLabel, validSeconds: validSeconds) + return try await send("POST", ["v1", "athletes", athleteID, "grant-offers"], body: Self.json(body)) + } + + /// Every grant on the owner's record, revoked ones included. + public func grants(athleteID: String) async throws -> [Grant] { + struct Reply: Decodable { let grants: [Grant] } + let reply: Reply = try await send("GET", ["v1", "athletes", athleteID, "grants"]) + return reply.grants + } + + /// Revoke a grant. The coach's next request about this athlete gets `notFound`, + /// and a coach write that was waiting fails. + public func revokeGrant(athleteID: String, grantID: String) async throws -> Revocation { + try await send("DELETE", ["v1", "athletes", athleteID, "grants", grantID]) + } + + /// The records the signed-in person owns, through this app. + public func athletes() async throws -> [OwnedAthlete] { + struct Reply: Decodable { let athletes: [OwnedAthlete] } + let reply: Reply = try await send("GET", ["v1", "athletes"]) + return reply.athletes + } + + /// One record's state and the caller's role in it. + public func athlete(_ athleteID: String) async throws -> AthleteInfo { + try await send("GET", ["v1", "athletes", athleteID]) + } + + /// Current records, oldest first, as the host's UTF-8 JSON reply: + /// `{"records": [...]}`. Pass it to `RecordSnapshotBuilder.addRecords` to + /// calculate on the phone. The host caps `limit` at its page size. + public func recordsJSON(athleteID: String, recordType: String? = nil, limit: Int? = nil) async throws -> Data { + var query: [URLQueryItem] = [] + if let recordType { query.append(URLQueryItem(name: "record_type", value: recordType)) } + if let limit { query.append(URLQueryItem(name: "limit", value: String(limit))) } + return try await sendRaw("GET", ["v1", "athletes", athleteID, "records"], query: query) + } + + /// One record and its complete history, as the host's UTF-8 JSON reply: + /// `{"record": {...}, "revisions": [...]}`. + public func recordJSON(athleteID: String, recordID: String) async throws -> Data { + try await sendRaw("GET", ["v1", "athletes", athleteID, "records", recordID]) + } + + /// The changes since a database revision (D263). When `complete` is false the + /// log does not reach back that far; download the export instead. + public func changes(athleteID: String, since: Int) async throws -> ChangesPage { + try await send( + "GET", ["v1", "athletes", athleteID, "changes"], query: [URLQueryItem(name: "since", value: String(since))]) + } + + /// The complete package as a zip, and the SHA-256 of its manifest. + public func export(athleteID: String) async throws -> (zip: Data, manifestDigest: String?) { + let (data, http) = try await exchange("GET", ["v1", "athletes", athleteID, "export"], accept: "application/zip") + return (data, http.value(forHTTPHeaderField: "x-manifest-digest")) + } + + /// The apps the owner has used with a record. + public func apps(athleteID: String) async throws -> [ConnectedApp] { + struct Reply: Decodable { let apps: [ConnectedApp] } + let reply: Reply = try await send("GET", ["v1", "athletes", athleteID, "apps"]) + return reply.apps + } + + /// Disconnect an app from a record (D270). Its next request for the record gets + /// `appDisconnected`. The last connected app cannot be disconnected. + public func disconnectApp(athleteID: String, clientID: String) async throws -> ConnectedApp { + struct Reply: Decodable { let app: ConnectedApp } + let reply: Reply = try await send("DELETE", ["v1", "athletes", athleteID, "apps", clientID]) + return reply.app + } + + /// Connect a disconnected app again, from an app that is still connected. + public func connectApp(athleteID: String, clientID: String) async throws -> ConnectedApp { + struct Reply: Decodable { let app: ConnectedApp } + let reply: Reply = try await send("PUT", ["v1", "athletes", athleteID, "apps", clientID]) + return reply.app + } + + // MARK: - Owner writes + + /// A new record. `data` is the record's data as UTF-8 JSON, kept byte for byte. + /// Keep the returned write until the host answers, and send it again unchanged + /// after a lost reply (D261). + public func prepareRecordCreation( + athleteID: String, recordType: String, data: Data, recordID: String? = nil, attachments: [String] = [], + idempotencyKey: String = UUID().uuidString + ) throws -> PreparedWrite { + var fields = [("record_type", try Self.json(recordType)), ("data", try Self.jsonObject(data))] + if let recordID { fields.append(("record_id", try Self.json(recordID))) } + if !attachments.isEmpty { fields.append(("attachments", try Self.json(attachments))) } + return PreparedWrite( + method: "POST", path: ["v1", "athletes", athleteID, "records"], body: Self.object(fields), + idempotencyKey: idempotencyKey) + } + + /// A correction: the complete new data, and the revision the person edited. If + /// the record changed since, the host answers `stale` and writes nothing; keep the + /// person's edit for review. + public func prepareCorrection( + athleteID: String, recordID: String, expectedRevision: Int, data: Data, + idempotencyKey: String = UUID().uuidString + ) throws -> PreparedWrite { + let fields = [("data", try Self.jsonObject(data)), ("expected_revision", try Self.json(expectedRevision))] + return PreparedWrite( + method: "POST", path: ["v1", "athletes", athleteID, "records", recordID, "corrections"], + body: Self.object(fields), idempotencyKey: idempotencyKey) + } + + /// A normal deletion that keeps the record's history. + public func prepareDeletion( + athleteID: String, recordID: String, expectedRevision: Int, idempotencyKey: String = UUID().uuidString + ) throws -> PreparedWrite { + PreparedWrite( + method: "POST", path: ["v1", "athletes", athleteID, "records", recordID, "deletion"], + body: Self.object([("expected_revision", try Self.json(expectedRevision))]), + idempotencyKey: idempotencyKey) + } + + /// Send a prepared write. Sending the same write again, as after a lost reply, + /// sends the same bytes and key: the host returns the first answer and writes + /// nothing new. + public func send(_ write: PreparedWrite) async throws -> WriteResult { + try await send( + write.method, write.path, body: write.body, contentType: write.contentType, + idempotencyKey: write.idempotencyKey) + } + + // MARK: - Coach + + /// Accept an athlete's offer with the app this token was issued to. A code works + /// once. An unknown, used, or expired code, or a code for another app, gives + /// `notFound`. + public func acceptGrantOffer(code: String) async throws -> Grant { + struct Body: Encodable { let code: String } + struct Reply: Decodable { let grant: Grant } + let reply: Reply = try await send("POST", ["v1", "grant-offers", "accept"], body: Self.json(Body(code: code))) + return reply.grant + } + + /// The athletes who granted the signed-in coach access through this app. + public func roster() async throws -> [RosterEntry] { + struct Reply: Decodable { let athletes: [RosterEntry] } + let reply: Reply = try await send("GET", ["v1", "roster"]) + return reply.athletes + } + + /// One page of an athlete's workout summaries, newest first. Pass the previous + /// page's `next` as `after` for the following page. The host caps `limit` at its + /// page size. + public func workoutSummaries(athleteID: String, limit: Int? = nil, after: String? = nil) async throws + -> WorkoutPage + { + var query: [URLQueryItem] = [] + if let limit { query.append(URLQueryItem(name: "limit", value: String(limit))) } + if let after { query.append(URLQueryItem(name: "after", value: after)) } + return try await send("GET", ["v1", "athletes", athleteID, "workouts"], query: query) + } + + /// Add a coaching note. + /// + /// Make `idempotencyKey` once, when the coach saves the note, for example with + /// `UUID().uuidString`. Keep it with the note until the host answers. To retry + /// after a lost reply, send the same note with the same key: the host returns + /// the first result and writes nothing new. The same key with a different note + /// is `requestConflict`. + public func addCoachingNote(_ note: CoachingNote, athleteID: String, idempotencyKey: String) async throws + -> WriteResult + { + try await send( + "POST", ["v1", "athletes", athleteID, "notes"], body: Self.json(note), idempotencyKey: idempotencyKey) + } + + // MARK: - Requests + + /// JSON with sorted keys. The host compares the bytes of a retried write with the + /// first request, so the same note must encode to the same bytes every time. + static func json(_ value: some Encodable) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return try encoder.encode(value) + } + + /// A JSON value, from a JSON object the app supplied, checked and kept byte for + /// byte. + static func jsonObject(_ data: Data) throws -> Data { + guard (try? JSONSerialization.jsonObject(with: data)) is [String: Any] else { + throw HostClientError.notAJSONObject + } + return data + } + + /// `{"key": value, ...}` from already encoded values, keys sorted, so a write + /// built twice has the same bytes. + static func object(_ fields: [(String, Data)]) -> Data { + var out = Data("{".utf8) + for (index, (key, value)) in fields.sorted(by: { $0.0 < $1.0 }).enumerated() { + if index > 0 { out.append(Data(",".utf8)) } + out.append((try? json(key)) ?? Data()) + out.append(Data(":".utf8)) + out.append(value) + } + out.append(Data("}".utf8)) + return out + } + + private func send( + _ method: String, _ path: [String], query: [URLQueryItem] = [], body: Data? = nil, + contentType: String = "application/json", idempotencyKey: String? = nil, signedIn: Bool = true + ) async throws -> Reply { + let data = try await sendRaw( + method, path, query: query, body: body, contentType: contentType, idempotencyKey: idempotencyKey, + signedIn: signedIn) + return try JSONDecoder().decode(Reply.self, from: data) + } + + private func sendRaw( + _ method: String, _ path: [String], query: [URLQueryItem] = [], body: Data? = nil, + contentType: String = "application/json", idempotencyKey: String? = nil, signedIn: Bool = true + ) async throws -> Data { + try await exchange( + method, path, query: query, body: body, contentType: contentType, idempotencyKey: idempotencyKey, + signedIn: signedIn + ).0 + } + + private func exchange( + _ method: String, _ path: [String], query: [URLQueryItem] = [], body: Data? = nil, + contentType: String = "application/json", idempotencyKey: String? = nil, signedIn: Bool = true, + accept: String = "application/json" + ) async throws -> (Data, HTTPURLResponse) { + var request = URLRequest(url: try url(path, query: query)) + request.httpMethod = method + // A cached reply could show data after the athlete revoked a grant. + request.cachePolicy = .reloadIgnoringLocalCacheData + request.setValue(accept, forHTTPHeaderField: "Accept") + if signedIn { + request.setValue("Bearer \(try await accessToken())", forHTTPHeaderField: "Authorization") + } + if let idempotencyKey { + request.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") + } + if let body { + request.httpBody = body + request.setValue(contentType, forHTTPHeaderField: "Content-Type") + } + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse else { + throw URLError(.badServerResponse) + } + guard (200..<300).contains(http.statusCode) else { + throw HostError(status: http.statusCode, body: data) + } + return (data, http) + } + + /// The base URL's path, then each segment percent-encoded on its own, so an ID + /// can never add or remove a path segment. + private func url(_ segments: [String], query: [URLQueryItem]) throws -> URL { + guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { + throw URLError(.badURL) + } + var allowed = CharacterSet.urlPathAllowed + allowed.remove("/") + let encoded = segments.map { segment in + if segment == "." || segment == ".." { + return segment.replacingOccurrences(of: ".", with: "%2E") + } + return segment.addingPercentEncoding(withAllowedCharacters: allowed) ?? segment + } + var base = components.percentEncodedPath + while base.hasSuffix("/") { base.removeLast() } + components.percentEncodedPath = base + "/" + encoded.joined(separator: "/") + components.queryItems = query.isEmpty ? nil : query + guard let url = components.url else { + throw URLError(.badURL) + } + return url + } +} diff --git a/mobile/swift/Sources/AthleticStandardHost/HostError.swift b/mobile/swift/Sources/AthleticStandardHost/HostError.swift new file mode 100644 index 00000000..038d136b --- /dev/null +++ b/mobile/swift/Sources/AthleticStandardHost/HostError.swift @@ -0,0 +1,73 @@ +import Foundation + +/// An error reply from the host. The host sends `{"error": {"code", "message"}}` +/// with a stable code (spec 2.1.3 section 6.5). Network failures stay `URLError`. +public struct HostError: Error, Sendable, CustomStringConvertible { + /// The host's stable error codes. It is a string wrapper, so a code added by a + /// newer host still decodes. + public struct Code: RawRepresentable, Hashable, Sendable, CustomStringConvertible { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public var description: String { rawValue } + + /// The token is missing, expired, for another audience, or from an app the + /// host does not accept. Sign in again. + public static let signInRequired = Code(rawValue: "sign_in_required") + /// The caller can see the athlete but the grant does not cover this. + public static let permissionDenied = Code(rawValue: "permission_denied") + /// The athlete disconnected this app from the record. Connect it again from + /// another app the athlete uses. + public static let appDisconnected = Code(rawValue: "app_disconnected") + /// No such athlete or record, or it is not shared with the caller. The host + /// gives the same answer for both, so a caller cannot learn that it exists. + public static let notFound = Code(rawValue: "not_found") + /// The record changed since the caller read it, or access changed while the + /// write waited: a grant was revoked or an app disconnected. + public static let stale = Code(rawValue: "stale") + /// This `Idempotency-Key` was already used for a different request. + public static let requestConflict = Code(rawValue: "request_conflict") + /// The record is moving to another host and accepts no changes. + public static let hostMoving = Code(rawValue: "host_moving") + public static let limitReached = Code(rawValue: "limit_reached") + /// The request is malformed. + public static let invalid = Code(rawValue: "invalid") + /// The request is well formed, but the record rules refuse it. + public static let refused = Code(rawValue: "refused") + /// The host failed. Its own log has the details. + public static let internalError = Code(rawValue: "internal") + } + + /// The HTTP status. + public let status: Int + /// The host's code, or nil when the reply had no error body. The host's web + /// framework answers an unknown path or an unreadable query without one. + public let code: Code? + public let message: String + + public var description: String { + "\(code?.rawValue ?? "http_error") (\(status)): \(message)" + } + + init(status: Int, body: Data) { + struct Envelope: Decodable { + struct Detail: Decodable { + let code: String + let message: String + } + let error: Detail + } + self.status = status + if let envelope = try? JSONDecoder().decode(Envelope.self, from: body) { + code = Code(rawValue: envelope.error.code) + message = envelope.error.message + } else { + code = nil + let text = String(decoding: body, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) + message = text.isEmpty ? HTTPURLResponse.localizedString(forStatusCode: status) : text + } + } +} diff --git a/mobile/swift/Sources/AthleticStandardHost/HostSignIn.swift b/mobile/swift/Sources/AthleticStandardHost/HostSignIn.swift new file mode 100644 index 00000000..4dce2e15 --- /dev/null +++ b/mobile/swift/Sources/AthleticStandardHost/HostSignIn.swift @@ -0,0 +1,434 @@ +import CryptoKit +import Foundation +import Security + +#if canImport(AuthenticationServices) + import AuthenticationServices +#endif + +/// What an app registers with its sign-in provider, such as a WorkOS public OAuth +/// application (D330, docs/hosting.md section 6.5). +public struct HostSignInConfiguration: Sendable, Equatable { + /// The host's address, such as `https://records.example.org`. + public var hostURL: URL + /// The app's registered public client ID. + public var clientID: String + /// The callback address registered for the app, such as + /// `org.example.athlete:/oauth/callback`. It must match exactly. + public var redirectURI: URL + public var scopes: [String] + /// Passed to the provider as `login_hint`, when the app knows the account. + public var loginHint: String? + + public init( + hostURL: URL, clientID: String, redirectURI: URL, + scopes: [String] = ["openid", "profile", "email", "offline_access"], loginHint: String? = nil + ) { + self.hostURL = hostURL + self.clientID = clientID + self.redirectURI = redirectURI + self.scopes = scopes + self.loginHint = loginHint + } +} + +/// The tokens of one signed-in person for one host and app. Keep them in the +/// Keychain, never in an athlete file or export. +public struct HostTokens: Codable, Sendable, Equatable { + public var accessToken: String + public var refreshToken: String? + public var expiresAt: Date + public var tokenEndpoint: URL + /// The host's resource identifier the tokens were issued for. + public var resource: String + public var clientID: String +} + +/// Where `HostSignIn` keeps tokens. +public protocol HostTokenStore: Sendable { + func load() throws -> HostTokens? + func save(_ tokens: HostTokens) throws + func clear() throws +} + +/// Tokens in memory only, for tests and for apps that sign in each time. +public final class MemoryTokenStore: HostTokenStore, @unchecked Sendable { + private var tokens: HostTokens? + private let lock = NSLock() + + public init(_ tokens: HostTokens? = nil) { + self.tokens = tokens + } + + public func load() throws -> HostTokens? { + lock.lock() + defer { lock.unlock() } + return tokens + } + + public func save(_ tokens: HostTokens) throws { + lock.lock() + defer { lock.unlock() } + self.tokens = tokens + } + + public func clear() throws { + lock.lock() + defer { lock.unlock() } + tokens = nil + } +} + +/// Tokens in the iOS or macOS Keychain, readable only on this device after it was +/// first unlocked. +public struct KeychainTokenStore: HostTokenStore { + public let service: String + public let account: String + + /// One entry per host and app. + public init(configuration: HostSignInConfiguration, service: String = "ai.athleticstandard.host") { + self.service = service + account = configuration.hostURL.absoluteString + " " + configuration.clientID + } + + private var query: [String: Any] { + [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, + kSecAttrAccount as String: account] + } + + public func load() throws -> HostTokens? { + var item: CFTypeRef? + var search = query + search[kSecReturnData as String] = true + search[kSecMatchLimit as String] = kSecMatchLimitOne + let status = SecItemCopyMatching(search as CFDictionary, &item) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess, let data = item as? Data else { throw HostSignInError.keychain(status) } + return try JSONDecoder().decode(HostTokens.self, from: data) + } + + public func save(_ tokens: HostTokens) throws { + let data = try JSONEncoder().encode(tokens) + let update = [kSecValueData as String: data] + var status = SecItemUpdate(query as CFDictionary, update as CFDictionary) + if status == errSecItemNotFound { + var add = query + add[kSecValueData as String] = data + add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + status = SecItemAdd(add as CFDictionary, nil) + } + guard status == errSecSuccess else { throw HostSignInError.keychain(status) } + } + + public func clear() throws { + let status = SecItemDelete(query as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { throw HostSignInError.keychain(status) } + } +} + +/// Opens the provider's sign-in page in the system browser and returns the +/// callback address the provider redirected to. +public protocol AuthorizationBrowser: Sendable { + func authorize(url: URL, callbackScheme: String) async throws -> URL +} + +#if canImport(AuthenticationServices) + /// The system browser through `ASWebAuthenticationSession` (RFC 8252). The app + /// never sees the password. + @MainActor + public final class SystemBrowser: NSObject, AuthorizationBrowser, ASWebAuthenticationPresentationContextProviding + { + private let anchor: () -> ASPresentationAnchor + private let ephemeral: Bool + + /// `anchor` returns the window that presents the sign-in sheet. + /// `ephemeral` signs in without the browser's saved sessions. + public init(ephemeral: Bool = false, anchor: @escaping () -> ASPresentationAnchor) { + self.anchor = anchor + self.ephemeral = ephemeral + } + + public func authorize(url: URL, callbackScheme: String) async throws -> URL { + try await withCheckedThrowingContinuation { continuation in + let session = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme) { url, error in + if let url { + continuation.resume(returning: url) + } else if let error = error as? ASWebAuthenticationSessionError, error.code == .canceledLogin { + continuation.resume(throwing: HostSignInError.cancelled) + } else { + continuation.resume(throwing: error ?? HostSignInError.cancelled) + } + } + session.presentationContextProvider = self + session.prefersEphemeralWebBrowserSession = ephemeral + if !session.start() { + continuation.resume(throwing: HostSignInError.cancelled) + } + } + } + + public nonisolated func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + MainActor.assumeIsolated { anchor() } + } + } +#endif + +/// Why sign-in did not finish. +public enum HostSignInError: Error, Sendable, Equatable { + /// The person closed the sign-in page, or the provider answered `access_denied`. + case cancelled + /// The host names no sign-in provider, or its discovery document is unusable. + case discoveryFailed(String) + /// The callback is not the registered callback address. + case callbackMismatch + /// The callback belongs to another sign-in: its `state` is not the one sent. + case stateMismatch + /// The provider answered with an OAuth error. + case providerError(code: String, description: String?) + /// Nobody is signed in, or the provider no longer accepts the refresh token. + case signInRequired + case keychain(OSStatus) +} + +/// Browser sign-in for `ath-host` with the authorization code flow and S256 PKCE +/// (RFC 8252, RFC 7636), and a token for the host's resource (RFC 8707) (D330). +/// +/// `signIn(browser:)` reads the host's protected-resource metadata and the +/// provider's discovery document, opens the provider in the browser, checks that +/// the callback carries this sign-in's `state`, and exchanges the code. +/// `accessToken()` refreshes the token when it is about to expire. `client()` +/// makes a `HostClient` that uses it. Local files need none of this. +public actor HostSignIn { + public let configuration: HostSignInConfiguration + private let store: HostTokenStore + private let session: URLSession + /// A token this close to expiry is refreshed before it is sent. + private let refreshMargin: TimeInterval + private var refreshing: Task? + + public init( + configuration: HostSignInConfiguration, store: HostTokenStore, session: URLSession = .shared, + refreshMargin: TimeInterval = 60 + ) { + self.configuration = configuration + self.store = store + self.session = session + self.refreshMargin = refreshMargin + } + + /// True when tokens are stored. + public func isSignedIn() throws -> Bool { + try store.load() != nil + } + + /// A client for the host that signs each request with a current token. + public nonisolated func client() -> HostClient { + HostClient(baseURL: configuration.hostURL, accessToken: { try await self.accessToken() }) + } + + /// Sign in through `browser`. Replaces any stored tokens. + public func signIn(browser: AuthorizationBrowser) async throws { + let host = HostClient(baseURL: configuration.hostURL, token: "", session: session) + let resource = try await host.protectedResource() + guard let issuer = resource.authorizationServers.first, let issuerURL = URL(string: issuer) else { + throw HostSignInError.discoveryFailed("the host names no sign-in provider") + } + let provider = try await discover(issuerURL) + guard provider.issuer == issuer else { + throw HostSignInError.discoveryFailed("the provider's issuer \(provider.issuer) is not \(issuer)") + } + let verifier = Self.randomURLSafe(bytes: 32) + let state = Self.randomURLSafe(bytes: 16) + guard var components = URLComponents(url: provider.authorizationEndpoint, resolvingAgainstBaseURL: false) + else { + throw HostSignInError.discoveryFailed("the authorization endpoint is not an address") + } + var items = components.queryItems ?? [] + items += [ + URLQueryItem(name: "response_type", value: "code"), + URLQueryItem(name: "client_id", value: configuration.clientID), + URLQueryItem(name: "redirect_uri", value: configuration.redirectURI.absoluteString), + URLQueryItem(name: "scope", value: configuration.scopes.joined(separator: " ")), + URLQueryItem(name: "state", value: state), + URLQueryItem(name: "code_challenge", value: Self.challenge(for: verifier)), + URLQueryItem(name: "code_challenge_method", value: "S256"), + URLQueryItem(name: "resource", value: resource.resource), + ] + if let hint = configuration.loginHint { items.append(URLQueryItem(name: "login_hint", value: hint)) } + components.queryItems = items + guard let authorizationURL = components.url, let scheme = configuration.redirectURI.scheme else { + throw HostSignInError.discoveryFailed("cannot build the sign-in address") + } + let callback = try await browser.authorize(url: authorizationURL, callbackScheme: scheme) + let code = try Self.code(from: callback, redirectURI: configuration.redirectURI, state: state) + let tokens = try await tokenRequest( + provider.tokenEndpoint, resource: resource.resource, + fields: [ + "grant_type": "authorization_code", "code": code, + "redirect_uri": configuration.redirectURI.absoluteString, "client_id": configuration.clientID, + "code_verifier": verifier, "resource": resource.resource, + ], previousRefreshToken: nil) + try store.save(tokens) + } + + /// A current access token for the host, refreshed when it is about to expire. + /// Throws `signInRequired` when nobody is signed in or the refresh is refused. + public func accessToken() async throws -> String { + guard let tokens = try store.load() else { throw HostSignInError.signInRequired } + if tokens.expiresAt.timeIntervalSinceNow > refreshMargin { + return tokens.accessToken + } + if let refreshing { + return try await refreshing.value.accessToken + } + let task = Task { try await self.refresh(tokens) } + refreshing = task + defer { refreshing = nil } + return try await task.value.accessToken + } + + /// Forget the stored tokens. Local files are not touched. + public func signOut() throws { + try store.clear() + } + + private func refresh(_ tokens: HostTokens) async throws -> HostTokens { + guard let refreshToken = tokens.refreshToken else { + try store.clear() + throw HostSignInError.signInRequired + } + do { + let fresh = try await tokenRequest( + tokens.tokenEndpoint, resource: tokens.resource, + fields: [ + "grant_type": "refresh_token", "refresh_token": refreshToken, "client_id": tokens.clientID, + "resource": tokens.resource, + ], previousRefreshToken: refreshToken) + try store.save(fresh) + return fresh + } catch HostSignInError.providerError(code: "invalid_grant", _) { + try store.clear() + throw HostSignInError.signInRequired + } + } + + struct Provider: Decodable { + let issuer: String + let authorizationEndpoint: URL + let tokenEndpoint: URL + + enum CodingKeys: String, CodingKey { + case issuer + case authorizationEndpoint = "authorization_endpoint" + case tokenEndpoint = "token_endpoint" + } + } + + /// OpenID Connect discovery, then OAuth authorization server metadata. + private func discover(_ issuer: URL) async throws -> Provider { + for document in ["openid-configuration", "oauth-authorization-server"] { + let url = issuer.appending(path: ".well-known").appending(path: document) + var request = URLRequest(url: url) + request.cachePolicy = .reloadIgnoringLocalCacheData + guard let (data, response) = try? await session.data(for: request), + (response as? HTTPURLResponse)?.statusCode == 200, + let provider = try? JSONDecoder().decode(Provider.self, from: data) + else { continue } + return provider + } + throw HostSignInError.discoveryFailed("no discovery document at \(issuer.absoluteString)") + } + + private func tokenRequest( + _ endpoint: URL, resource: String, fields: [String: String], previousRefreshToken: String? + ) async throws -> HostTokens { + struct Reply: Decodable { + let accessToken: String? + let refreshToken: String? + let expiresIn: Double? + let error: String? + let errorDescription: String? + + enum CodingKeys: String, CodingKey { + case accessToken = "access_token" + case refreshToken = "refresh_token" + case expiresIn = "expires_in" + case error + case errorDescription = "error_description" + } + } + var request = URLRequest(url: endpoint) + request.httpMethod = "POST" + request.cachePolicy = .reloadIgnoringLocalCacheData + request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + request.setValue("application/json", forHTTPHeaderField: "Accept") + request.httpBody = Data(Self.form(fields).utf8) + let (data, _) = try await session.data(for: request) + let reply = try JSONDecoder().decode(Reply.self, from: data) + if let error = reply.error { + throw HostSignInError.providerError(code: error, description: reply.errorDescription) + } + guard let access = reply.accessToken else { + throw HostSignInError.providerError(code: "invalid_response", description: "no access_token") + } + return HostTokens( + accessToken: access, refreshToken: reply.refreshToken ?? previousRefreshToken, + expiresAt: Date().addingTimeInterval(reply.expiresIn ?? 300), tokenEndpoint: endpoint, + resource: resource, clientID: configuration.clientID) + } + + /// The authorization code from a callback, after checking that the callback is + /// the registered address and carries this sign-in's `state`. + static func code(from callback: URL, redirectURI: URL, state: String) throws -> String { + guard let received = URLComponents(url: callback, resolvingAgainstBaseURL: false), + let expected = URLComponents(url: redirectURI, resolvingAgainstBaseURL: false), + received.scheme?.lowercased() == expected.scheme?.lowercased(), + (received.host ?? "") == (expected.host ?? ""), Self.samePath(received.path, expected.path) + else { throw HostSignInError.callbackMismatch } + let items = received.queryItems ?? [] + let value = { (name: String) in items.first(where: { $0.name == name })?.value } + guard value("state") == state else { throw HostSignInError.stateMismatch } + if let error = value("error") { + if error == "access_denied" { throw HostSignInError.cancelled } + throw HostSignInError.providerError(code: error, description: value("error_description")) + } + guard let code = value("code"), !code.isEmpty else { + throw HostSignInError.providerError(code: "invalid_response", description: "the callback has no code") + } + return code + } + + /// `/callback` and `/callback/` are one address; a provider may add the slash. + private static func samePath(_ left: String, _ right: String) -> Bool { + let trim = { (path: String) in path.hasSuffix("/") ? String(path.dropLast()) : path } + return trim(left) == trim(right) + } + + static func challenge(for verifier: String) -> String { + base64URL(Data(SHA256.hash(data: Data(verifier.utf8)))) + } + + static func randomURLSafe(bytes count: Int) -> String { + var bytes = [UInt8](repeating: 0, count: count) + let status = SecRandomCopyBytes(kSecRandomDefault, count, &bytes) + precondition(status == errSecSuccess, "the system random generator failed") + return base64URL(Data(bytes)) + } + + static func base64URL(_ data: Data) -> String { + data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } + + static func form(_ fields: [String: String]) -> String { + var allowed = CharacterSet.alphanumerics + allowed.insert(charactersIn: "-._~") + return fields.keys.sorted().map { key in + let value = fields[key] ?? "" + return + "\(key.addingPercentEncoding(withAllowedCharacters: allowed) ?? key)=\(value.addingPercentEncoding(withAllowedCharacters: allowed) ?? value)" + }.joined(separator: "&") + } +} diff --git a/mobile/swift/Sources/AthleticStandardHost/Models.swift b/mobile/swift/Sources/AthleticStandardHost/Models.swift new file mode 100644 index 00000000..a526624a --- /dev/null +++ b/mobile/swift/Sources/AthleticStandardHost/Models.swift @@ -0,0 +1,357 @@ +// The JSON shapes of host API version 1, as `host/src/api.rs` writes them. +// Every type names its wire fields in `CodingKeys`, so a reader can match them to the +// host without knowing a key strategy. + +import Foundation + +/// One of the three things an athlete can grant a coach (D262). It is a string +/// wrapper, not an enum, so a newer host's permission does not break decoding. +public struct Permission: RawRepresentable, Codable, Hashable, Sendable, CustomStringConvertible { + public let rawValue: String + + public init(rawValue: String) { + self.rawValue = rawValue + } + + public init(from decoder: any Decoder) throws { + rawValue = try decoder.singleValueContainer().decode(String.self) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(rawValue) + } + + public var description: String { rawValue } + + /// List workouts: record ID, revision, start, end, and activity type. Nothing else. + public static let readWorkoutSummaries = Permission(rawValue: "read_workout_summaries") + /// Add a coaching note. Evidence can name only workouts the coach can read. + public static let addCoachNotes = Permission(rawValue: "add_coach_notes") + /// Add a training plan and its planned sessions. + public static let addProgramming = Permission(rawValue: "add_programming") +} + +/// `GET /v1/capabilities`: what this host offers. +public struct Capabilities: Decodable, Sendable { + public let apiVersion: Int + public let athleticStandardVersion: String + /// `directory` or `libsql`. + public let storage: String + public let permissions: [Permission] + /// Who runs the host and its storage. Show it to an athlete before they connect. + public let operatorDisclosure: String + public let openEnrollment: Bool + + enum CodingKeys: String, CodingKey { + case apiVersion = "api_version" + case athleticStandardVersion = "athleticstandard_version" + case storage + case permissions + case operatorDisclosure = "operator_disclosure" + case openEnrollment = "open_enrollment" + } +} + +/// `GET /.well-known/oauth-protected-resource` (RFC 9728): the host's resource +/// identifier and the sign-in provider that issues tokens for it. +public struct ProtectedResource: Decodable, Sendable { + /// Ask the provider for a token with this audience. + public let resource: String + public let authorizationServers: [String] + + enum CodingKeys: String, CodingKey { + case resource + case authorizationServers = "authorization_servers" + } +} + +/// `GET /v1/me`: the signed-in person as the host knows them. +public struct Me: Decodable, Sendable { + public let principalID: String + /// The app the token was issued to. + public let clientID: String + /// The opaque ID the host writes into coach authorship (D255). + public let coachID: String + /// Records this person owns. + public let athletes: [String] + + enum CodingKeys: String, CodingKey { + case principalID = "principal_id" + case clientID = "client_id" + case coachID = "coach_id" + case athletes + } +} + +/// `POST /v1/athletes`: a new, empty record owned by the caller. +public struct CreatedAthlete: Decodable, Sendable { + public let athleteID: String + public let databaseRevision: Int + public let operatorDisclosure: String + + enum CodingKeys: String, CodingKey { + case athleteID = "athlete_id" + case databaseRevision = "database_revision" + case operatorDisclosure = "operator_disclosure" + } +} + +/// `POST /v1/athletes/{id}/grant-offers`: a one-time code the athlete gives a coach. +public struct GrantOffer: Decodable, Sendable { + public let code: String + public let expiresAt: String + public let permissions: [Permission] + /// The coach app that can accept the offer. + public let clientID: String + + enum CodingKeys: String, CodingKey { + case code + case expiresAt = "expires_at" + case permissions + case clientID = "client_id" + } +} + +/// A grant: one coach, through one app, for one athlete. +public struct Grant: Decodable, Sendable { + public let grantID: String + public let athleteID: String + public let coachPrincipalID: String + public let clientID: String + public let permissions: [Permission] + public let coachLabel: String? + public let createdAt: String + public let revokedAt: String? + + enum CodingKeys: String, CodingKey { + case grantID = "grant_id" + case athleteID = "resource_id" + case coachPrincipalID = "coach_principal_id" + case clientID = "client_id" + case permissions + case coachLabel = "coach_label" + case createdAt = "created_at" + case revokedAt = "revoked_at" + } +} + +/// `DELETE /v1/athletes/{id}/grants/{grant_id}`. +public struct Revocation: Decodable, Sendable { + public let grantID: String + /// The athlete's new access epoch. A coach write that checked an older epoch fails. + public let accessEpoch: Int + + enum CodingKeys: String, CodingKey { + case grantID = "revoked" + case accessEpoch = "access_epoch" + } +} + +/// One athlete on a coach's roster, through the app that asked. +public struct RosterEntry: Decodable, Sendable { + public let athleteID: String + public let displayName: String? + public let permissions: [Permission] + public let grantID: String + + enum CodingKeys: String, CodingKey { + case athleteID = "athlete_id" + case displayName = "display_name" + case permissions + case grantID = "grant_id" + } +} + +/// A workout as the read grant shows it. Times are UTC timestamps as the record +/// stores them. +public struct WorkoutSummary: Decodable, Sendable, Hashable { + public let recordID: String + public let revision: Int + public let startAt: String + public let endAt: String + public let activityType: String? + + enum CodingKeys: String, CodingKey { + case recordID = "record_id" + case revision + case startAt = "start_at" + case endAt = "end_at" + case activityType = "activity_type" + } +} + +/// One page of workout summaries, newest first. Pass `next` as `after` to get the +/// following page. `next` is nil on the last page. +public struct WorkoutPage: Decodable, Sendable { + public let workouts: [WorkoutSummary] + public let next: String? +} + +/// A workout revision a coaching note points to. +public struct Evidence: Codable, Sendable, Hashable { + public var recordID: String + public var revision: Int + + public init(recordID: String, revision: Int) { + self.recordID = recordID + self.revision = revision + } + + /// The current revision of a workout from the summary list. + public init(_ workout: WorkoutSummary) { + self.init(recordID: workout.recordID, revision: workout.revision) + } + + enum CodingKeys: String, CodingKey { + case recordID = "record_id" + case revision + } +} + +/// A coaching note to add. The host writes the author and the time. +public struct CoachingNote: Encodable, Sendable, Hashable { + public var note: String + public var title: String? + /// A local date, such as `2026-12-01`, from which the note applies. + public var appliesFrom: String? + public var appliesTo: String? + public var evidence: [Evidence] + + public init( + note: String, title: String? = nil, appliesFrom: String? = nil, appliesTo: String? = nil, + evidence: [Evidence] = [] + ) { + self.note = note + self.title = title + self.appliesFrom = appliesFrom + self.appliesTo = appliesTo + self.evidence = evidence + } + + enum CodingKeys: String, CodingKey { + case note + case title + case appliesFrom = "applies_from" + case appliesTo = "applies_to" + case evidence + } +} + +/// The result of a write: the record's new database revision and each record written. +public struct WriteResult: Decodable, Sendable, Equatable { + public struct Record: Decodable, Sendable, Equatable { + public let recordID: String + public let revision: Int + + enum CodingKeys: String, CodingKey { + case recordID = "record_id" + case revision + } + } + + public let databaseRevision: Int + public let records: [Record] + + enum CodingKeys: String, CodingKey { + case databaseRevision = "database_revision" + case records + } +} + +/// A write the client built but the host has not answered yet: its method, path, +/// exact body bytes, and `Idempotency-Key` (D261). It is `Codable`, so an app can +/// keep it with an unsent edit across a restart and send it again unchanged. +public struct PreparedWrite: Codable, Sendable, Equatable { + public let method: String + public let path: [String] + public let body: Data + public let contentType: String + public let idempotencyKey: String + + public init( + method: String, path: [String], body: Data, contentType: String = "application/json", idempotencyKey: String + ) { + self.method = method + self.path = path + self.body = body + self.contentType = contentType + self.idempotencyKey = idempotencyKey + } +} + +/// A failure the client finds before it sends anything. +public enum HostClientError: Error, Sendable { + /// Record data must be a JSON object. + case notAJSONObject +} + +/// `GET /v1/athletes`: a record the caller owns. +public struct OwnedAthlete: Decodable, Sendable, Equatable { + public let athleteID: String + public let displayName: String? + /// `active`, `frozen`, or `staged`. + public let state: String + + enum CodingKeys: String, CodingKey { + case athleteID = "athlete_id" + case displayName = "display_name" + case state + } +} + +/// `GET /v1/athletes/{id}`. +public struct AthleteInfo: Decodable, Sendable { + public let athleteID: String + /// `owner` or `coach`. + public let role: String + public let state: String + public let operatorDisclosure: String + /// For the owner only. + public let databaseRevision: Int? + + enum CodingKeys: String, CodingKey { + case athleteID = "athlete_id" + case role + case state + case operatorDisclosure = "operator_disclosure" + case databaseRevision = "database_revision" + } +} + +/// `GET /v1/athletes/{id}/changes`. +public struct ChangesPage: Decodable, Sendable { + public struct Change: Decodable, Sendable, Equatable { + public let databaseRevision: Int + public let recordID: String + public let recordRevision: Int + /// `revision`, `deletion`, or `erasure`. + public let kind: String + + enum CodingKeys: String, CodingKey { + case databaseRevision = "database_revision" + case recordID = "record_id" + case recordRevision = "record_revision" + case kind + } + } + + public let from: Int + public let to: Int + public let complete: Bool + public let changes: [Change] +} + +/// An app the owner used with a record (D270). +public struct ConnectedApp: Decodable, Sendable, Equatable { + public let clientID: String + /// `connected` or `disconnected`. + public let state: String + public let thisApp: Bool + + enum CodingKeys: String, CodingKey { + case clientID = "client_id" + case state + case thisApp = "this_app" + } +} diff --git a/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift b/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift new file mode 100644 index 00000000..f62be70b --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift @@ -0,0 +1,203 @@ +import AthleticStandardHost +import Foundation +import Testing + +/// The host client and browser sign-in against a real `ath-host` and the test +/// sign-in provider that `mobile/scripts/host-test-env.sh` starts (D330). The +/// browser is a stand-in that loads the sign-in page without following its +/// redirect; the system browser itself needs a person, so it runs in the live +/// provider check. +struct TestEnvironment { + let hostURL: URL + let issuer: URL + + static func load() throws -> TestEnvironment { + let environment = ProcessInfo.processInfo.environment + guard let host = environment["ATH_TEST_HOST_URL"].flatMap(URL.init(string:)), + let issuer = environment["ATH_TEST_ISSUER"].flatMap(URL.init(string:)) + else { + throw SetupError(description: "run mobile/scripts/host-test-env.sh start and set ATH_TEST_HOST_URL and ATH_TEST_ISSUER") + } + return TestEnvironment(hostURL: host, issuer: issuer) + } +} + +struct SetupError: Error, CustomStringConvertible { + let description: String +} + +/// Loads the sign-in page and returns the address the provider redirects to. +final class TestBrowser: NSObject, AuthorizationBrowser, URLSessionTaskDelegate, @unchecked Sendable { + var rewrite: (@Sendable (URL) -> URL)? + + init(rewrite: (@Sendable (URL) -> URL)? = nil) { + self.rewrite = rewrite + } + + func authorize(url: URL, callbackScheme: String) async throws -> URL { + let session = URLSession(configuration: .ephemeral, delegate: self, delegateQueue: nil) + let (_, response) = try await session.data(from: url) + guard let location = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Location"), + let callback = URL(string: location) + else { throw SetupError(description: "the provider did not redirect") } + #expect(callback.scheme == callbackScheme) + return rewrite?(callback) ?? callback + } + + func urlSession( + _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest + ) async -> URLRequest? { + nil + } +} + +func signIn(_ environment: TestEnvironment, client: String, person: String, store: HostTokenStore = MemoryTokenStore()) + async throws -> HostSignIn +{ + let configuration = HostSignInConfiguration( + hostURL: environment.hostURL, clientID: client, redirectURI: URL(string: "ai.athleticstandard.test:/callback")!, + loginHint: person) + let signIn = HostSignIn(configuration: configuration, store: store) + try await signIn.signIn(browser: TestBrowser()) + return signIn +} + +func code(_ body: () async throws -> some Any) async -> String? { + do { + _ = try await body() + return nil + } catch let error as HostError { + return error.code?.rawValue + } catch { + return "\(error)" + } +} + +let sourceData = Data(#"{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"}"#.utf8) + +@Suite(.serialized) +struct HostTests { + @Test func signInWriteRetryAndStaleCorrection() async throws { + let environment = try TestEnvironment.load() + let store = MemoryTokenStore() + let signIn = try await AthleticStandardHostTests.signIn(environment, client: "athlete-app", person: "owner-\(UUID().uuidString)", store: store) + #expect(try await signIn.isSignedIn()) + let client = signIn.client() + let me = try await client.me() + #expect(me.clientID == "athlete-app") + let created = try await client.createAthlete(displayName: "Synthetic athlete") + #expect(try await client.athletes().map(\.athleteID).contains(created.athleteID)) + + // A write sent twice, as after a lost reply, is written once. + let write = try client.prepareRecordCreation(athleteID: created.athleteID, recordType: "source", data: sourceData) + let first = try await client.send(write) + let again = try await client.send(write) + #expect(first == again) + let sourceID = try #require(first.records.first?.recordID) + + let corrected = Data(#"{"source_type":"wearable","data_writer":"Example Band 2","data_route":"provider_export"}"#.utf8) + let correction = try client.prepareCorrection( + athleteID: created.athleteID, recordID: sourceID, expectedRevision: 1, data: corrected) + let result = try await client.send(correction) + #expect(result.records.first?.revision == 2) + // The same edit with a new key is stale now; the app keeps the edit. + let stale = try client.prepareCorrection( + athleteID: created.athleteID, recordID: sourceID, expectedRevision: 1, data: corrected) + #expect(await code { try await client.send(stale) } == "stale") + // The same key with a different body is a conflict. + let conflicting = PreparedWrite( + method: write.method, path: write.path, body: corrected, idempotencyKey: write.idempotencyKey) + #expect(await code { try await client.send(conflicting) } == "request_conflict") + + let records = try JSONSerialization.jsonObject(with: try await client.recordsJSON(athleteID: created.athleteID)) + #expect(((records as? [String: Any])?["records"] as? [Any])?.count == 1) + let changes = try await client.changes(athleteID: created.athleteID, since: 0) + #expect(changes.changes.count == 2) + let export = try await client.export(athleteID: created.athleteID) + #expect(export.zip.starts(with: [0x50, 0x4b])) + } + + @Test func anExpiredTokenIsRefreshedAndARefusedRefreshAsksForSignIn() async throws { + let environment = try TestEnvironment.load() + let store = MemoryTokenStore() + let signIn = try await AthleticStandardHostTests.signIn(environment, client: "athlete-app", person: "refresh-\(UUID().uuidString)", store: store) + var tokens = try #require(try store.load()) + let firstRefresh = tokens.refreshToken + tokens.expiresAt = Date().addingTimeInterval(-10) + try store.save(tokens) + _ = try await signIn.client().me() + // The provider rotates refresh tokens, so a used one is replaced. + let refreshed = try #require(try store.load()) + #expect(refreshed.refreshToken != nil) + #expect(refreshed.refreshToken != firstRefresh) + #expect(refreshed.expiresAt > Date()) + + // The provider ends the person's sessions: the next refresh is refused. + var request = URLRequest(url: environment.issuer.appending(path: "test/revoke-refresh-tokens")) + request.httpMethod = "POST" + _ = try await URLSession.shared.data(for: request) + var expired = refreshed + expired.expiresAt = Date().addingTimeInterval(-10) + try store.save(expired) + await #expect(throws: HostSignInError.signInRequired) { try await signIn.accessToken() } + #expect(try await !signIn.isSignedIn()) + } + + @Test func aCancelledOrForeignCallbackIsRefused() async throws { + let environment = try TestEnvironment.load() + let configuration = { (hint: String) in + HostSignInConfiguration( + hostURL: environment.hostURL, clientID: "athlete-app", + redirectURI: URL(string: "ai.athleticstandard.test:/callback")!, loginHint: hint) + } + let cancelled = HostSignIn(configuration: configuration("cancel"), store: MemoryTokenStore()) + await #expect(throws: HostSignInError.cancelled) { try await cancelled.signIn(browser: TestBrowser()) } + + let foreign = HostSignIn(configuration: configuration("person-1"), store: MemoryTokenStore()) + let otherState = TestBrowser { url in + URL(string: url.absoluteString.replacingOccurrences(of: "state=", with: "state=x"))! + } + await #expect(throws: HostSignInError.stateMismatch) { try await foreign.signIn(browser: otherState) } + let otherAddress = TestBrowser { url in + URL(string: url.absoluteString.replacingOccurrences(of: "/callback", with: "/elsewhere"))! + } + await #expect(throws: HostSignInError.callbackMismatch) { try await foreign.signIn(browser: otherAddress) } + await #expect(throws: HostSignInError.signInRequired) { try await foreign.accessToken() } + } + + @Test func aRevokedCoachAndADisconnectedAppAreRefused() async throws { + let environment = try TestEnvironment.load() + let ownerName = "owner-\(UUID().uuidString)" + let owner = try await AthleticStandardHostTests.signIn(environment, client: "athlete-app", person: ownerName).client() + let athlete = try await owner.createAthlete(displayName: "Synthetic athlete") + let offer = try await owner.createGrantOffer( + athleteID: athlete.athleteID, permissions: [.readWorkoutSummaries], coachClientID: "coach-app") + let coach = try await AthleticStandardHostTests.signIn(environment, client: "coach-app", person: "coach-\(UUID().uuidString)").client() + let grant = try await coach.acceptGrantOffer(code: offer.code) + #expect(try await coach.roster().map(\.athleteID) == [athlete.athleteID]) + #expect(try await coach.workoutSummaries(athleteID: athlete.athleteID).workouts.isEmpty) + _ = try await owner.revokeGrant(athleteID: athlete.athleteID, grantID: grant.grantID) + #expect(await code { try await coach.workoutSummaries(athleteID: athlete.athleteID) } == "not_found") + + // The owner uses a second app, then disconnects it from the first app. + let second = try await AthleticStandardHostTests.signIn(environment, client: "athlete-app-2", person: ownerName).client() + #expect(try await second.athlete(athlete.athleteID).role == "owner") + let disconnected = try await owner.disconnectApp(athleteID: athlete.athleteID, clientID: "athlete-app-2") + #expect(disconnected.state == "disconnected") + #expect(await code { try await second.athlete(athlete.athleteID) } == "app_disconnected") + _ = try await owner.connectApp(athleteID: athlete.athleteID, clientID: "athlete-app-2") + #expect(try await second.athlete(athlete.athleteID).role == "owner") + } + + @Test func anAppWithItsOwnSessionSuppliesTheToken() async throws { + let environment = try TestEnvironment.load() + let store = MemoryTokenStore() + _ = try await AthleticStandardHostTests.signIn(environment, client: "athlete-app", person: "own-\(UUID().uuidString)", store: store) + let token = try #require(try store.load()).accessToken + let client = HostClient(baseURL: environment.hostURL, accessToken: { token }) + #expect(try await client.me().clientID == "athlete-app") + let refused = HostClient(baseURL: environment.hostURL, token: "not-a-token") + #expect(await code { try await refused.me() } == "sign_in_required") + } +} From 6bc7f7ca0504c74efac02f76ba445f54984b24f1 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 10:39:08 -0600 Subject: [PATCH 10/30] Stage, install, and gate the iPhone and Android packages, with runnable examples. `mobile/scripts/stage-apple.sh` zips the release XCFramework with fixed file times, writes the Swift package repository as released and a tagged staged copy that differ only in the binary target line, and runs every package test through a consumer that resolves the staged copy by version. `mobile/scripts/stage-android.sh` publishes the Android library to a local Maven repository, checks that the POM declares JNA, and has the consumer app resolve it by coordinate: it checks 16 KB alignment of every native library in a shrunk release APK and runs the library's tests through the installed copy in a debug and a shrunk release build (D332). `validate.yml` gains the `mobile-apple` and `mobile-android` jobs. The release job adds the tested zip and both reports to the GitHub release and uploads the tested Maven bundle for the maintainer to publish. `release-mobile-packages.yml`, run by hand, tags the Swift package repository with the tested checksum and installs both packages from their public locations. None of these workflows has run on GitHub yet. The Android consumer app and `swift run AthleticStandardExample` are the runnable examples: offline work on a local file, a picked document, and host sign-in with a read and a saved edit. The phone tests read the expected version from the bundle, and a test checks that every phone build file names it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release-cross-platform.yml | 90 +++++++++ .github/workflows/release-mobile-packages.yml | 140 ++++++++++++++ .github/workflows/validate.yml | 63 ++++++ build-history/README.md | 2 +- .../v3.0.0/appendix/release-evidence.md | 32 ++++ build-history/v3.0.0/progress.md | 21 +- mobile/README.md | 45 +++++ .../kotlin/ai/athleticstandard/HostTest.kt | 1 + .../ai/athleticstandard/ValidationTest.kt | 2 +- .../ai/athleticstandard/host/HostClient.kt | 15 ++ mobile/android/consumer/app/build.gradle.kts | 67 +++++++ .../app/instrumented-release-rules.pro | 7 + .../athleticstandard/consumer/MainActivity.kt | 181 ++++++++++++++++++ mobile/android/consumer/app/test-rules.pro | 3 + mobile/android/consumer/build.gradle.kts | 3 + mobile/android/consumer/gradle.properties | 3 + mobile/android/consumer/settings.gradle.kts | 27 +++ mobile/scripts/stage-android.sh | 139 ++++++++++++++ mobile/scripts/stage-apple.sh | 164 ++++++++++++++++ mobile/scripts/start-emulator.sh | 26 +++ mobile/scripts/swift-package-repository.sh | 31 +++ .../AthleticStandardExample/ExampleApp.swift | 154 +++++++++++++++ mobile/swift/Package.swift | 5 + .../ValidationTests.swift | 5 +- mobile/swift/release/Package.swift.in | 24 +++ mobile/swift/release/README.md.in | 17 ++ mobile/tests/fixtures.rs | 4 + mobile/tests/versions.rs | 31 +++ 28 files changed, 1297 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/release-mobile-packages.yml create mode 100644 mobile/android/consumer/app/build.gradle.kts create mode 100644 mobile/android/consumer/app/instrumented-release-rules.pro create mode 100644 mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt create mode 100644 mobile/android/consumer/app/test-rules.pro create mode 100644 mobile/android/consumer/build.gradle.kts create mode 100644 mobile/android/consumer/gradle.properties create mode 100644 mobile/android/consumer/settings.gradle.kts create mode 100755 mobile/scripts/stage-android.sh create mode 100755 mobile/scripts/stage-apple.sh create mode 100755 mobile/scripts/start-emulator.sh create mode 100755 mobile/scripts/swift-package-repository.sh create mode 100644 mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift create mode 100644 mobile/swift/release/Package.swift.in create mode 100644 mobile/swift/release/README.md.in create mode 100644 mobile/tests/versions.rs diff --git a/.github/workflows/release-cross-platform.yml b/.github/workflows/release-cross-platform.yml index 7a82027d..69b730d1 100644 --- a/.github/workflows/release-cross-platform.yml +++ b/.github/workflows/release-cross-platform.yml @@ -211,6 +211,96 @@ jobs: GH_TOKEN: ${{ github.token }} run: gh release create "$TAG" archives/* --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" + # The iPhone and Android packages (D332). The tested XCFramework zip and both + # reports join the GitHub release. The tested Maven bundle is uploaded to Maven + # Central as a deployment the maintainer must publish there; until then nothing + # can resolve it. A missing Central credential skips that upload and says so. + # The Swift package repository is tagged later, by the maintainer, with + # release-mobile-packages.yml. + publish-mobile: + name: Stage the iPhone and Android packages + needs: [version, validate, publish] + if: needs.version.outputs.release == 'true' + runs-on: ubuntu-latest + environment: release + permissions: + contents: write + env: + TAG: ${{ needs.version.outputs.tag }} + GH_TOKEN: ${{ github.token }} + CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + SIGNING_KEY: ${{ secrets.MAVEN_SIGNING_KEY }} + SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} + steps: + - uses: actions/download-artifact@v4 + with: + name: mobile-apple + path: apple + - uses: actions/download-artifact@v4 + with: + name: mobile-android + path: android + - name: Check both packages are this version + run: | + version="${TAG#v}" + for report in apple/apple-report.json android/android-report.json; do + found="$(jq -r .version "$report")" + [ "$found" = "$version" ] || { echo "::error::$report is version $found, not $version"; exit 1; } + done + zip="apple/AthleticStandardFFI-$version.xcframework.zip" + [ "$(sha256sum "$zip" | cut -d ' ' -f 1)" = "$(jq -r .asset_sha256 apple/apple-report.json)" ] || + { echo "::error::the zip is not the tested one"; exit 1; } + - name: Add the tested XCFramework and the reports to the GitHub release + run: | + version="${TAG#v}" + zip="apple/AthleticStandardFFI-$version.xcframework.zip" + tested="$(sha256sum "$zip" | cut -d ' ' -f 1)" + if gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "$(basename "$zip")" --dir published 2> /dev/null; then + [ "$(sha256sum "published/$(basename "$zip")" | cut -d ' ' -f 1)" = "$tested" ] || + { echo "::error::$TAG already holds a different $(basename "$zip")"; exit 1; } + echo "The release already holds the tested zip." + else + gh release upload "$TAG" "$zip" apple/apple-report.json android/android-report.json --repo "$GITHUB_REPOSITORY" + fi + - name: Upload the tested Maven bundle for the maintainer to publish + run: | + version="${TAG#v}" + path="ai/athleticstandard/athleticstandard/$version" + public="https://repo1.maven.org/maven2/$path/athleticstandard-$version.pom" + if curl -fsS -o published.pom "$public"; then + cmp -s published.pom "android/maven/$path/athleticstandard-$version.pom" || + { echo "::error::Maven Central already holds a different $version"; exit 1; } + echo "Maven Central already holds this version with the same POM." + exit 0 + fi + if [ -z "$CENTRAL_USERNAME" ] || [ -z "$SIGNING_KEY" ]; then + echo "::warning::No Maven Central credential: the Android library was not uploaded. The release is partial." + exit 0 + fi + echo "$SIGNING_KEY" | gpg --batch --import + cd android/maven + for file in "$path"/*; do + case "$file" in *.asc|*.md5|*.sha1|*.sha256|*.sha512|maven-metadata*) continue ;; esac + gpg --batch --yes --pinentry-mode loopback --passphrase "$SIGNING_PASSPHRASE" -ab "$file" + md5sum "$file" | cut -d ' ' -f 1 > "$file.md5" + sha1sum "$file" | cut -d ' ' -f 1 > "$file.sha1" + done + zip -q -r ../bundle.zip "$path" + cd .. + deployment="$(curl -fsS -u "$CENTRAL_USERNAME:$CENTRAL_PASSWORD" \ + -F "bundle=@bundle.zip" "https://central.sonatype.com/api/v1/publisher/upload?publishingType=USER_MANAGED")" + echo "Uploaded deployment $deployment. Publish it at https://central.sonatype.com/publishing/deployments." + - name: Report + run: | + { + echo "### iPhone and Android packages for $TAG" + echo + echo "- XCFramework: \`$(jq -r .asset_sha256 apple/apple-report.json)\` on the GitHub release." + echo "- Android archive: \`$(jq -r .aar_sha256 android/android-report.json)\`, uploaded to Maven Central for approval when a credential is set." + echo "- Next: publish the Maven deployment, then run release-mobile-packages.yml for $TAG to tag the Swift package and check both public installs." + } >> "$GITHUB_STEP_SUMMARY" + report: name: Report on the pull request needs: [version, validate, publish] diff --git a/.github/workflows/release-mobile-packages.yml b/.github/workflows/release-mobile-packages.yml new file mode 100644 index 00000000..9ebac9c8 --- /dev/null +++ b/.github/workflows/release-mobile-packages.yml @@ -0,0 +1,140 @@ +# The last step of an iPhone and Android release (D332). The maintainer runs it by +# hand after release-cross-platform.yml finished for a version and the Maven +# Central deployment was published. +# +# swift-package writes the Swift package repository for the tag from the tagged +# sources and the tested XCFramework on the GitHub release, after checking that +# the zip is the one the release tested. It tags the repository with the version +# and then installs the package from its public address. A tag that already names +# the same checksum is kept; a tag with another checksum stops the run. +# +# maven-check installs `ai.athleticstandard:athleticstandard` from Maven Central +# in the consumer app and runs the library's tests on an emulator, offline from +# any host except the local test host. +name: Release iPhone and Android packages + +on: + workflow_dispatch: + inputs: + tag: + description: The released version tag, such as v3.0.0 + required: true + type: string + +permissions: + contents: read + +jobs: + swift-package: + name: Tag the Swift package and install it from its public address + runs-on: macos-15 + environment: release + env: + TAG: ${{ inputs.tag }} + GH_TOKEN: ${{ github.token }} + PACKAGE_REPOSITORY: mwhitham/athleticstandard-swift + PACKAGE_TOKEN: ${{ secrets.SWIFT_PACKAGE_REPOSITORY_TOKEN }} + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ inputs.tag }} + - name: Download the tested XCFramework and its report + run: | + version="${TAG#v}" + gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "AthleticStandardFFI-$version.xcframework.zip" \ + --pattern apple-report.json --dir released + tested="$(jq -r .asset_sha256 released/apple-report.json)" + found="$(shasum -a 256 "released/AthleticStandardFFI-$version.xcframework.zip" | cut -d ' ' -f 1)" + [ "$found" = "$tested" ] || { echo "::error::the released zip is $found; the release tested $tested"; exit 1; } + [ "$(jq -r .commit released/apple-report.json)" = "$(git rev-parse HEAD)" ] || + { echo "::error::the report names another commit than $TAG"; exit 1; } + echo "CHECKSUM=$tested" >> "$GITHUB_ENV" + - name: Write, commit, and tag the package repository + run: | + if [ -z "$PACKAGE_TOKEN" ]; then + echo "::error::SWIFT_PACKAGE_REPOSITORY_TOKEN is not set; nothing was published." + exit 1 + fi + version="${TAG#v}" + git clone -q "https://x-access-token:$PACKAGE_TOKEN@github.com/$PACKAGE_REPOSITORY.git" package + if git -C package rev-parse -q --verify "refs/tags/$version" > /dev/null; then + if git -C package show "$version:Package.swift" | grep -q "checksum: \"$CHECKSUM\""; then + echo "$PACKAGE_REPOSITORY already tags $version with the tested checksum." + exit 0 + fi + echo "::error::$PACKAGE_REPOSITORY already tags $version with another checksum." + exit 1 + fi + url="https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG/AthleticStandardFFI-$version.xcframework.zip" + mobile/scripts/swift-package-repository.sh package "$version" "$(git rev-parse HEAD)" "$CHECKSUM" \ + ".binaryTarget(name: \"AthleticStandardFFI\", url: \"$url\", checksum: \"$CHECKSUM\")" + cd package + git add -A + git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -q -m "Athletic Standard $version" + git tag "$version" + git push -q origin HEAD "refs/tags/$version" + - name: Install from the public address and run offline + run: | + version="${TAG#v}" + mkdir -p check/Sources/check + cat > check/Package.swift < check/Sources/check/main.swift <<'SOURCE' + import AthleticStandard + import Foundation + let record = #"{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000064","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"}}"# + _ = try validateCurrentRecord(json: Data(record.utf8)) + print(libraryVersion()) + SOURCE + printed="$(cd check && swift run -q check)" + [ "$printed" = "$version" ] || { echo "::error::the public package reports $printed, not $version"; exit 1; } + echo "The public Swift package $version resolves, runs offline, and reports $printed." + + maven-check: + name: Install the Android library from Maven Central + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + TAG: ${{ inputs.tag }} + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ inputs.tag }} + - run: rustup show active-toolchain || rustup toolchain install + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + - name: Install the emulator + run: | + yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null || true + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install "platforms;android-36" "build-tools;36.1.0" \ + "platform-tools" "emulator" "system-images;android-36;google_apis;x86_64" > /dev/null + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: Start the emulator + run: mobile/scripts/start-emulator.sh "system-images;android-36;google_apis;x86_64" + - name: Run the library's tests against the public artifact + run: | + export PATH="$ANDROID_HOME/platform-tools:$PATH" + fixtures="$PWD/target/mobile-fixtures" + ATH_MOBILE_FIXTURES="$fixtures" cargo test --locked -p athleticstandard-mobile --test fixtures + cargo build --locked --bin ath + mobile/scripts/roundtrip.sh create "$fixtures/roundtrip" + mobile/scripts/host-test-env.sh start target/host-test + source target/host-test/env + adb reverse "tcp:$ATH_TEST_HOST_PORT" "tcp:$ATH_TEST_HOST_PORT" + adb reverse "tcp:$ATH_TEST_ISSUER_PORT" "tcp:$ATH_TEST_ISSUER_PORT" + cd mobile/android + ./gradlew --no-daemon -p consumer :app:connectedDebugAndroidTest \ + -Pathleticstandard.repository=https://repo1.maven.org/maven2 -Pathleticstandard.fixtures="$fixtures" \ + -Pandroid.testInstrumentationRunnerArguments.hostUrl="$ATH_TEST_HOST_URL" \ + -Pandroid.testInstrumentationRunnerArguments.issuer="$ATH_TEST_ISSUER" diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 88688d74..07d3a241 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -287,3 +287,66 @@ jobs: - name: Install and use the packed tarball shell: bash run: node packages/npm/scripts/smoke.mjs npm-tarball/athleticstandard-*.tgz + + # The iPhone package (D331, D332). Builds the XCFramework, stages the Swift + # package repository, installs it by version in a consumer package, and runs the + # package tests on this Mac and on an iPhone simulator, with the desktop round + # trip and a real ath-host with the test sign-in provider. Nothing is published. + mobile-apple: + name: iPhone package + runs-on: macos-15 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v5 + - run: rustup show active-toolchain || rustup toolchain install + - run: rustup target add aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios aarch64-apple-darwin x86_64-apple-darwin + - name: Stage the Swift package and test the installed copy + run: mobile/scripts/stage-apple.sh mobile-release/apple + - uses: actions/upload-artifact@v4 + with: + name: mobile-apple + path: | + mobile-release/apple/AthleticStandardFFI-*.xcframework.zip + mobile-release/apple/athleticstandard-swift + mobile-release/apple/apple-report.json + if-no-files-found: error + + # The Android library (D331, D332). Publishes it to a local Maven repository, + # builds a consumer app that resolves it by coordinate, checks 16 KB alignment + # of every native library in the shrunk release APK, and runs the library's + # tests through the installed copy on an emulator, in a debug and a shrunk + # release build. GitHub's Linux runners have no 16 KB x86_64 emulator image, + # so the 16 KB check here is the alignment check. Nothing is published. + mobile-android: + name: Android library + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@v5 + - run: rustup show active-toolchain || rustup toolchain install + - run: rustup target add aarch64-linux-android x86_64-linux-android + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + - name: Install the pinned NDK, platform, and an emulator image + run: | + yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null || true + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install "ndk;29.0.14206865" "platforms;android-36" \ + "build-tools;36.1.0" "platform-tools" "emulator" "system-images;android-36;google_apis;x86_64" > /dev/null + - name: Let the emulator use KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: Start the emulator + run: mobile/scripts/start-emulator.sh "system-images;android-36;google_apis;x86_64" + - name: Stage the Android library and test the installed copy + run: PATH="$ANDROID_HOME/platform-tools:$PATH" mobile/scripts/stage-android.sh mobile-release/android + - uses: actions/upload-artifact@v4 + with: + name: mobile-android + path: | + mobile-release/android/maven + mobile-release/android/android-report.json + if-no-files-found: error diff --git a/build-history/README.md b/build-history/README.md index 22f0e905..0d57dc96 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -41,7 +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). | -| [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. The iPhone and Android packages are being built under the same version ([plan](v3.0.0/appendix/mobile-library-plan.md)). See its [decisions](v3.0.0/decisions.md) and [progress](v3.0.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. The iPhone and Android packages are built under the same version and not published ([plan](v3.0.0/appendix/mobile-library-plan.md)). 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/v3.0.0/appendix/release-evidence.md b/build-history/v3.0.0/appendix/release-evidence.md index b120d88b..874b1fde 100644 --- a/build-history/v3.0.0/appendix/release-evidence.md +++ b/build-history/v3.0.0/appendix/release-evidence.md @@ -75,3 +75,35 @@ normally and ran only `SELECT` statements. checked. - The staged-write, sync, and test-kit scenarios on a libSQL server. They ran in remote mode against a local file in place of the server. + +## 6. iPhone and Android packages + +The phone packages (D325–D333, build steps 12 to 17) were built and tested on the same +Mac on 2026-11-28 with synthetic data. Each staging run writes `apple-report.json` and +`android-report.json` with the hashes, the source commit, the targets, and the tool +versions; the release job adds both to the GitHub release. + +| Check | Result | +|---|---| +| Model vectors through each binding | 7,399 cases: 7,285 run, 114 skipped for the four documented reasons, 0 failed | +| Coaching record examples | 20 blocks, 53 shape checks, 0 failed | +| Calculations through the database | 49 cases, 113 requests, 0 differences from the desktop | +| Calculations through the memory snapshot | 99 requests match the desktop; 14 that read device recordings or intensity references get the documented refusal (D326) | +| Both calculation readers on the desktop | 42 worked examples and 71 case requests: 30 and 69 match, 12 and 2 get the documented refusal; the 100,000-input limit holds on both | +| Swift package installed by version from a staged repository, on macOS | 25 tests passed: 20 package tests and 5 host tests | +| Android library installed by coordinate, API 36 (4 KB pages) and API 37.1 (16 KB pages) emulators | 25 tests passed on each, in a debug build and in a shrunk release build | +| 16 KB alignment of every native library in the shrunk release APK | 4 of 4 libraries aligned (both ABIs of the library and of JNA) | +| Desktop round trip | Passed on macOS and on both emulators: the desktop `ath` created the file, the phone library corrected a reading, and the desktop `ath` found the edit at revision 2, revision 1 kept, and a passing `ath check` | +| XCFramework zip | Two staging runs gave the same bytes | +| The whole workspace after the phone work | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass; `cargo test` (workspace) gives 939 passed, 0 failed, 18 ignored; npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (gate 5) passes | + +Not verified: + +- The iPhone simulator. Xcode's license was not accepted on the build machine, so + `xcodebuild` and `simctl` could not run. The `mobile-apple` CI job runs it. +- The iCloud Drive picker on a signed-in device. +- The system browser sheets with a person, and a live WorkOS environment (issue 57). +- The CI jobs and the release workflows. They were written in this build but have not + run on GitHub. +- Publication. The Maven namespace, the Swift package repository, and the publishing + credentials belong to the maintainer. diff --git a/build-history/v3.0.0/progress.md b/build-history/v3.0.0/progress.md index 97b26d73..da5d421a 100644 --- a/build-history/v3.0.0/progress.md +++ b/build-history/v3.0.0/progress.md @@ -20,7 +20,7 @@ Status: **being built; not released.** The plan is [spec.md](spec.md). | 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | Mac and two Android emulators pass; iPhone simulator and iCloud not run | | 15 | Calculations from memory and SQLite through one reader interface | Mac and two Android emulators pass; iPhone simulator not run | | 16 | Host client for Swift and Kotlin with browser sign-in | Mac and two Android emulators pass against a real host; live WorkOS not run | -| 17 | Release packaging, phone test runs, release gate | not started | +| 17 | Release packaging, phone test runs, release gate | staged and installed locally; CI, simulator, and publication not run | ## Step 2: what was built @@ -788,3 +788,22 @@ These follow the guide and the decisions. Each is open to review. person, and a live WorkOS environment with expired, wrong-audience, wrong-issuer, and wrong-app tokens. Both belong with issue 57 and need a WorkOS test environment and registered public apps. + +## Step 17: release packaging and the phone release gate + +- `mobile/scripts/stage-apple.sh` and `mobile/scripts/stage-android.sh` build the + release packages, install them the way an app does, and run every phone test + through the installed copy. Results are in + [release-evidence.md](appendix/release-evidence.md#6-iphone-and-android-packages). +- The Android consumer app keeps only the library's two ABIs, because JNA carries + more. Its shrunk release build needed two test-only rules, both in the consumer: the + AndroidX test libraries name annotation classes they do not ship, and the test APK + uses the app's copies of the Kotlin standard library and `androidx.tracing`. The + library's own consumer rules needed no change. +- The `mobile-apple` and `mobile-android` jobs in `validate.yml`, the + `publish-mobile` job in `release-cross-platform.yml`, and + `release-mobile-packages.yml` are written but have not run on GitHub. The 16 KB + emulator run is local only: GitHub's Linux runners have no 16 KB x86_64 image. +- Runnable examples: the consumer app is the Android example, and + `swift run AthleticStandardExample` is the Swift one. The Android example ran + offline on an emulator. The Swift example builds; its window was not opened. diff --git a/mobile/README.md b/mobile/README.md index e4cc742f..c1afb1d7 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -242,3 +242,48 @@ the reading at revision 2, revision 1 kept, and `ath check` passing. `test-apple.sh` needs a full Xcode whose license has been accepted for the simulator run. On this Mac it uses `swift test`. + +## Release + +Both packages ship with each release and carry its version +([D332](../build-history/v3.0.0/decisions.md#d332-how-the-packages-are-released)). +Publication stays with the maintainer. + +- `mobile/scripts/stage-apple.sh ` builds the release XCFramework, zips it with + fixed file times, and writes two copies of the Swift package repository: one whose + manifest names the release asset by address and checksum, and one, tagged with the + version, whose manifest points at the zip inside it. They differ only in that line. + A consumer package resolves the tagged copy by version and runs the package tests on + this Mac and on an iPhone simulator. `apple-report.json` records the hashes, slices, + and tool versions. +- `mobile/scripts/stage-android.sh ` publishes the Android library to a local + Maven repository and checks that its POM declares the JNA runtime. The consumer app + in `android/consumer/` resolves the library by coordinate from there, builds a shrunk + release APK, checks that every native library in it is aligned for 16 KB pages, and + runs the library's tests through the installed copy in a debug and a shrunk release + build on every connected device. `android-report.json` records the results. +- The `mobile-apple` and `mobile-android` jobs in `.github/workflows/validate.yml` run + both scripts for every release check. The release job then adds the tested zip and + both reports to the GitHub release, and uploads the tested Maven bundle to Maven + Central as a deployment that the maintainer publishes there. With no Central + credential, it skips that upload and says the release is partial. +- After that, the maintainer runs `.github/workflows/release-mobile-packages.yml` for + the tag. It writes the Swift package repository from the tagged sources, checks the + zip on the release against the tested checksum, tags the repository, and installs + both packages from their public locations. A version already published with the + same bytes is kept; one with different bytes stops the run. + +The proposed public coordinates are `ai.athleticstandard:athleticstandard` on Maven +Central and the Swift package repository `mwhitham/athleticstandard-swift`. Before the +first release, the maintainer verifies the `ai.athleticstandard` namespace on Maven +Central, creates the Swift package repository, and adds the `MAVEN_CENTRAL_USERNAME`, +`MAVEN_CENTRAL_PASSWORD`, `MAVEN_SIGNING_KEY`, `MAVEN_SIGNING_PASSPHRASE`, and +`SWIFT_PACKAGE_REPOSITORY_TOKEN` secrets to the `release` environment. + +An Android app that uses the library should keep only the two ABIs it ships, because +JNA carries more: + +```kotlin +android { defaultConfig { ndk { abiFilters += setOf("arm64-v8a", "x86_64") } } } +``` + diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt index d4e3da38..8116cc56 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt @@ -71,6 +71,7 @@ class HostTest { @Test fun signInWriteRetryAndStaleCorrection() { val client = signIn("athlete-app", "owner-${UUID.randomUUID()}").client() + assertTrue(client.capabilities().operatorDisclosure.isNotEmpty()) assertEquals("athlete-app", client.me().clientId) val athlete = client.createAthlete("Synthetic athlete") assertTrue(client.athletes().any { it.athleteId == athlete.athleteId }) diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt index 4f09c07a..e1d0a94b 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/ValidationTest.kt @@ -30,7 +30,7 @@ class ValidationTest { @Test fun libraryReportsItsVersion() { - assertEquals("3.0.0", libraryVersion()) + assertEquals(FixtureBundle.suite("library").getString("version"), libraryVersion()) } @Test diff --git a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt index 2eb9f588..f27c59d9 100644 --- a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt +++ b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt @@ -61,6 +61,14 @@ data class PreparedWrite( data class WriteResult(val databaseRevision: Long, val records: List) data class WrittenRecord(val recordId: String, val revision: Long) data class ProtectedResource(val resource: String, val authorizationServers: List) +data class Capabilities( + val apiVersion: Int, + val athleticstandardVersion: String, + val storage: String, + /** Who runs the host and where it keeps records. Show it before the person signs in. */ + val operatorDisclosure: String, + val openEnrollment: Boolean, +) data class Me(val principalId: String, val clientId: String, val coachId: String, val athletes: List) data class CreatedAthlete(val athleteId: String, val databaseRevision: Long, val operatorDisclosure: String) data class OwnedAthlete(val athleteId: String, val displayName: String?, val state: String) @@ -106,6 +114,13 @@ class HostClient( return ProtectedResource(json.getString("resource"), json.getJSONArray("authorization_servers").strings()) } + /** The API version, the storage kind, and who runs the host. No token. */ + fun capabilities(): Capabilities { + val json = JSONObject(send("GET", listOf("v1", "capabilities"), signedIn = false).text()) + return Capabilities(json.getInt("api_version"), json.getString("athleticstandard_version"), + json.getString("storage"), json.getString("operator_disclosure"), json.getBoolean("open_enrollment")) + } + fun me(): Me { val json = JSONObject(send("GET", listOf("v1", "me")).text()) return Me(json.getString("principal_id"), json.getString("client_id"), json.getString("coach_id"), diff --git a/mobile/android/consumer/app/build.gradle.kts b/mobile/android/consumer/app/build.gradle.kts new file mode 100644 index 00000000..3ea98da1 --- /dev/null +++ b/mobile/android/consumer/app/build.gradle.kts @@ -0,0 +1,67 @@ +plugins { + id("com.android.application") +} + +val athleticStandardVersion = providers.gradleProperty("athleticstandard.version").get() +val library = rootDir.resolve("../athleticstandard") +// The build type the instrumented tests run against: `debug`, or `release` to check +// the library inside a shrunk app. +val instrumentedBuild = providers.gradleProperty("consumer.testBuildType").getOrElse("debug") +// The fixture bundle that mobile/tests/fixtures.rs writes (D333). +val fixtures = providers.gradleProperty("athleticstandard.fixtures") + .getOrElse(rootDir.resolve("../../../target/mobile-fixtures").path) + +android { + namespace = "ai.athleticstandard.consumer" + compileSdk = 36 + + defaultConfig { + applicationId = "ai.athleticstandard.consumer" + minSdk = 24 + targetSdk = 36 + versionCode = 1 + versionName = athleticStandardVersion + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + manifestPlaceholders["redirectScheme"] = "ai.athleticstandard.consumer" + // The library ships these two ABIs. JNA carries more, which the app leaves out. + ndk { abiFilters += setOf("arm64-v8a", "x86_64") } + } + + buildTypes { + release { + // An app's release build shrinks code; the library's consumer rules must + // keep what JNA and the bindings find by name. + isMinifyEnabled = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) + if (instrumentedBuild == "release") proguardFiles("instrumented-release-rules.pro") + testProguardFiles("test-rules.pro") + signingConfig = signingConfigs.getByName("debug") + } + } + testBuildType = instrumentedBuild + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + sourceSets { + getByName("androidTest") { + // The library's own instrumented tests, run against the installed copy. + kotlin.directories.add(library.resolve("src/androidTest/kotlin").path) + manifest.srcFile(library.resolve("src/androidTest/AndroidManifest.xml")) + assets.directories.add(fixtures) + } + } + + packaging { + // Native libraries stay uncompressed and page aligned in the APK. + jniLibs.useLegacyPackaging = false + } +} + +dependencies { + implementation("ai.athleticstandard:athleticstandard:$athleticStandardVersion") + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test.ext:junit:1.3.0") +} diff --git a/mobile/android/consumer/app/instrumented-release-rules.pro b/mobile/android/consumer/app/instrumented-release-rules.pro new file mode 100644 index 00000000..fdf7c6a7 --- /dev/null +++ b/mobile/android/consumer/app/instrumented-release-rules.pro @@ -0,0 +1,7 @@ +# Used only when the shrunk release build is the app under instrumented test. +# The test APK uses the app's copies of the Kotlin standard library and of +# androidx.tracing, so they are kept whole. The library needs no rule here: its +# consumer rules travel in its archive, and keeping them working is what this +# build checks. +-keep class kotlin.** { *; } +-keep class androidx.tracing.** { *; } diff --git a/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt b/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt new file mode 100644 index 00000000..1c168e51 --- /dev/null +++ b/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt @@ -0,0 +1,181 @@ +package ai.athleticstandard.consumer + +import ai.athleticstandard.CalculationSkill +import ai.athleticstandard.CreateDatabaseOptions +import ai.athleticstandard.Database +import ai.athleticstandard.FileLocationAdvice +import ai.athleticstandard.ListRecordsOptions +import ai.athleticstandard.OpenDatabaseOptions +import ai.athleticstandard.PickedDocument +import ai.athleticstandard.host.CustomTabsBrowser +import ai.athleticstandard.host.HostSignIn +import ai.athleticstandard.host.HostSignInConfiguration +import ai.athleticstandard.host.KeystoreTokenStore +import ai.athleticstandard.libraryVersion +import android.app.Activity +import android.content.Intent +import android.os.Bundle +import android.widget.Button +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import kotlin.concurrent.thread + +/** + * The runnable Android example. It works offline on a file in the app's own storage, + * opens a document the person picks, and, when asked, connects to an `ath-host`: + * signs in through a Custom Tab, picks an owned record, reads it, and saves an edit. + * + * The client ID and callback below are placeholders. Register your own with the host's + * sign-in provider (mobile/README.md). + */ +class MainActivity : Activity() { + private lateinit var output: TextView + private lateinit var hostAddress: EditText + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + output = TextView(this) + hostAddress = EditText(this).apply { hint = "https://records.example.org" } + val layout = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(32, 32, 32, 32) + addView(TextView(context).apply { text = FileLocationAdvice.RECOMMENDATION }) + addView(Button(context).apply { text = "Open a file"; setOnClickListener { pickDocument() } }) + addView(hostAddress) + addView(Button(context).apply { text = "Connect to a host"; setOnClickListener { connect() } }) + addView(output) + } + setContentView(ScrollView(this).apply { addView(layout) }) + thread { show(workOffline()) } + } + + override fun onResume() { + super.onResume() + // The person came back from the sign-in tab without finishing. + CustomTabsBrowser.cancelPendingSignIn() + } + + private fun show(text: String) = runOnUiThread { output.text = text } + + /** A local file: create it once, add a reading, and summarize the readings. */ + private fun workOffline(): String { + val file = File(FileLocationAdvice.localFolder(this), "example.ath.sqlite") + val database = if (file.exists()) { + Database.open(file.path, OpenDatabaseOptions()) + } else { + Database.create(file.path, CreateDatabaseOptions(null, null)).also { addSource(it) } + } + try { + val sources = JSONArray(database.listRecords(ListRecordsOptions("source", false, null)).decodeToString()) + val sourceId = sources.getJSONObject(0).getString("record_id") + val at = ai.athleticstandard.consumer.Clock.now() + val reading = JSONObject() + .put("source_id", sourceId) + .put("received_at", at) + .put("received_at_basis", "local_write_time") + .put("quantity", "hrv_rmssd") + .put("recorded_at", at) + .put("input_timestamp", JSONObject().put("timestamp_missing_reason", "not_provided_by_source") + .put("utc_offset_missing_reason", "not_provided_by_source")) + .put("value", JSONObject().put("standard_value", 50 + (System.currentTimeMillis() / 1000) % 15) + .put("standard_unit", "ms").put("input_value_missing_reason", "not_provided_by_source") + .put("input_unit_missing_reason", "not_provided_by_source")) + val request = JSONObject().put("inputs", JSONArray().put(JSONObject() + .put("record_type", "point_measurement").put("data", reading) + .put("changed_by", JSONObject().put("author_type", "athlete")))) + database.writeRecords(request.toString().toByteArray()) + val readings = JSONArray( + database.listRecords(ListRecordsOptions("point_measurement", false, null)).decodeToString(), + ) + val last = readings.getJSONObject(readings.length() - 1).getString("record_id") + val change = database.apply(last, CalculationSkill.Shipped("hrv-change")).decodeToString() + val info = database.info() + return "Athletic Standard ${libraryVersion()}\n${file.path}\n" + + "database revision ${info.databaseRevision}, ${readings.length()} readings\n" + + "hrv-change on the newest reading: $change" + } finally { + database.closeDatabase() + } + } + + private fun addSource(database: Database) { + val source = JSONObject().put("source_type", "manual").put("data_writer", "Athletic Standard example") + .put("data_route", "manual_entry") + database.writeRecords(JSONObject().put("inputs", JSONArray().put(JSONObject().put("record_type", "source") + .put("data", source).put("changed_by", JSONObject().put("author_type", "athlete")))).toString() + .toByteArray()) + } + + private fun pickDocument() { + startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = "*/*" + }, PICK) + } + + @Deprecated("The example uses the platform result callback to avoid extra dependencies.") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + val uri = data?.data ?: return + if (requestCode != PICK || resultCode != RESULT_OK) return + contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or + Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + thread { + show(try { + PickedDocument.open(this, uri).use { picked -> + val info = picked.database.info() + "Opened a working copy of $uri\ndatabase ${info.databaseId}, revision ${info.databaseRevision}" + } + } catch (error: Exception) { + "Could not open the document: ${error.message}" + }) + } + } + + /** Sign in, pick the first owned record, read it, and save an edit. */ + private fun connect() { + val address = hostAddress.text.toString().trim() + if (address.isEmpty()) return show("Enter the host's address first.") + thread { + show(try { + val configuration = HostSignInConfiguration(address, CLIENT_ID, "$REDIRECT_SCHEME:/oauth/callback") + val signIn = HostSignIn(configuration, KeystoreTokenStore(this)) + if (!signIn.isSignedIn()) signIn.signIn(CustomTabsBrowser(this)) + val host = signIn.client() + val operator = host.capabilities().operatorDisclosure + val athlete = host.athletes().firstOrNull() ?: host.createAthlete("Example athlete").let { + host.athletes().first() + } + val records = JSONObject(host.recordsJson(athlete.athleteId).decodeToString()).getJSONArray("records") + val source = JSONObject().put("source_type", "manual").put("data_writer", "Athletic Standard example") + .put("data_route", "manual_entry") + val write = host.prepareRecordCreation(athlete.athleteId, "source", source.toString().toByteArray()) + val saved = host.send(write) + "Signed in to $address\n$operator\nrecord ${athlete.athleteId}: ${records.length()} records\n" + + "saved record ${saved.records.first().recordId} at database revision ${saved.databaseRevision}" + } catch (error: Exception) { + "Could not connect: ${error.message}" + }) + } + } + + companion object { + private const val PICK = 1 + private const val CLIENT_ID = "client_EXAMPLE" + private const val REDIRECT_SCHEME = "ai.athleticstandard.consumer" + } +} + +/** The current instant in the stored UTC form, such as `2026-11-28T16:05:07.123Z`. */ +internal object Clock { + fun now(): String { + val format = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.ROOT) + format.timeZone = java.util.TimeZone.getTimeZone("UTC") + return format.format(java.util.Date()) + } +} diff --git a/mobile/android/consumer/app/test-rules.pro b/mobile/android/consumer/app/test-rules.pro new file mode 100644 index 00000000..de612e79 --- /dev/null +++ b/mobile/android/consumer/app/test-rules.pro @@ -0,0 +1,3 @@ +# Rules for shrinking the test APK only. The AndroidX test libraries name +# annotation classes they do not ship. +-dontwarn com.google.errorprone.annotations.** diff --git a/mobile/android/consumer/build.gradle.kts b/mobile/android/consumer/build.gradle.kts new file mode 100644 index 00000000..77a3c8dd --- /dev/null +++ b/mobile/android/consumer/build.gradle.kts @@ -0,0 +1,3 @@ +plugins { + id("com.android.application") version "9.5.3" apply false +} diff --git a/mobile/android/consumer/gradle.properties b/mobile/android/consumer/gradle.properties new file mode 100644 index 00000000..dbf096f0 --- /dev/null +++ b/mobile/android/consumer/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +android.useAndroidX=true +athleticstandard.version=3.0.0 diff --git a/mobile/android/consumer/settings.gradle.kts b/mobile/android/consumer/settings.gradle.kts new file mode 100644 index 00000000..05e1d83b --- /dev/null +++ b/mobile/android/consumer/settings.gradle.kts @@ -0,0 +1,27 @@ +// An app that installs the Android library by its published coordinate (D332). It +// resolves `ai.athleticstandard:athleticstandard` from the staged repository that +// `mobile/scripts/stage-android.sh` writes, or from the repository named by +// `athleticstandard.repository`, and runs the library's instrumented tests against +// the installed copy. Its activity is the runnable Android example. +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + maven { + name = "athleticstandard" + url = uri(providers.gradleProperty("athleticstandard.repository").getOrElse("../build/repository")) + } + google() + mavenCentral() + } +} + +rootProject.name = "athleticstandard-consumer" +include(":app") diff --git a/mobile/scripts/stage-android.sh b/mobile/scripts/stage-android.sh new file mode 100755 index 00000000..1e530c74 --- /dev/null +++ b/mobile/scripts/stage-android.sh @@ -0,0 +1,139 @@ +#!/bin/bash +# Stage the Android library for a release and install it as an app would (D332). +# +# Usage: mobile/scripts/stage-android.sh +# +# Publishes `ai.athleticstandard:athleticstandard` to a local Maven repository, +# copies it to /maven, and checks that its POM declares the JNA +# runtime. Then the consumer app in mobile/android/consumer resolves the library +# by its coordinate from that repository and: +# - builds a shrunk release APK and checks that every native library in it is +# aligned for 16 KB pages; +# - runs the library's instrumented tests against the installed copy, in a debug +# build and in the shrunk release build, on every connected device; +# - saves the desktop round-trip file, which the desktop `ath` then checks. +# Writes /android-report.json. Nothing is published. +# +# ANDROID_HOME names the SDK, JAVA_HOME a JDK 17 or later. A running emulator or a +# connected phone is needed for the tests. + +set -euo pipefail + +OUT="${1:?usage: $0 }" +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +if ! command -v cargo > /dev/null && [ -x "$HOME/.cargo/bin/cargo" ]; then + export PATH="$HOME/.cargo/bin:$PATH" +fi +VERSION="$(sed -n 's/^version = "\(.*\)"/\1/p' "$ROOT/mobile/Cargo.toml" | head -n 1)" +gradle_version="$(sed -n 's/^athleticstandard.version=//p' "$ROOT/mobile/android/gradle.properties")" +[ "$gradle_version" = "$VERSION" ] || { echo "Gradle names $gradle_version, Cargo names $VERSION" >&2; exit 1; } +COMMIT="$(git -C "$ROOT" rev-parse HEAD)" +mkdir -p "$OUT" +OUT="$(cd "$OUT" && pwd -P)" +ANDROID="$ROOT/mobile/android" +BUILD_TOOLS="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -n 1)" +NDK_BIN="$(ls -d "$ANDROID_HOME"/ndk/29.0.14206865/toolchains/llvm/prebuilt/*/bin | head -n 1)" + +# 1. Publish to the staging repository and copy it out. +rm -rf "${ANDROID:?}/build/repository" +(cd "$ANDROID" && ./gradlew --no-daemon -q :athleticstandard:publishReleasePublicationToStagingRepository) +ARTIFACTS="$ANDROID/build/repository/ai/athleticstandard/athleticstandard/$VERSION" +rm -rf "${OUT:?}/maven" +cp -R "$ANDROID/build/repository" "$OUT/maven" +POM="$ARTIFACTS/athleticstandard-$VERSION.pom" +grep -q 'jna' "$POM" || { echo "the POM does not declare JNA" >&2; exit 1; } +grep -A3 'jna' "$POM" | grep -q 'aar' || + { echo "the POM does not declare JNA's Android archive" >&2; exit 1; } +for file in "athleticstandard-$VERSION.aar" "athleticstandard-$VERSION-sources.jar" "athleticstandard-$VERSION-javadoc.jar"; do + [ -f "$ARTIFACTS/$file" ] || { echo "the staged repository lacks $file" >&2; exit 1; } +done + +# 2. The test inputs, the host, and the device forwarding. +FIXTURES="$ROOT/target/mobile-fixtures" +rm -rf "${FIXTURES:?}" +ATH_MOBILE_FIXTURES="$FIXTURES" cargo test --locked -p athleticstandard-mobile --test fixtures \ + --manifest-path "$ROOT/Cargo.toml" +cargo build --locked --bin ath --manifest-path "$ROOT/Cargo.toml" +"$ROOT/mobile/scripts/roundtrip.sh" create "$FIXTURES/roundtrip" +HOST_ENV="$ROOT/target/host-test" +"$ROOT/mobile/scripts/host-test-env.sh" start "$HOST_ENV" +trap '"$ROOT/mobile/scripts/host-test-env.sh" stop "$HOST_ENV"' EXIT +# shellcheck disable=SC1091 +source "$HOST_ENV/env" +devices="$(adb devices | awk 'NR > 1 && $2 == "device" { print $1 }')" +[ -n "$devices" ] || { echo "no device or emulator is connected" >&2; exit 1; } +for device in $devices; do + adb -s "$device" reverse "tcp:$ATH_TEST_HOST_PORT" "tcp:$ATH_TEST_HOST_PORT" > /dev/null + adb -s "$device" reverse "tcp:$ATH_TEST_ISSUER_PORT" "tcp:$ATH_TEST_ISSUER_PORT" > /dev/null +done + +consumer() { + (cd "$ANDROID" && ./gradlew --no-daemon -q -p consumer "$@" \ + -Pathleticstandard.repository="$OUT/maven" -Pathleticstandard.fixtures="$FIXTURES" \ + -Pandroid.testInstrumentationRunnerArguments.hostUrl="$ATH_TEST_HOST_URL" \ + -Pandroid.testInstrumentationRunnerArguments.issuer="$ATH_TEST_ISSUER") +} + +# 3. A shrunk release APK, and 16 KB alignment of every native library in it. +consumer :app:assembleRelease +APK="$ANDROID/consumer/app/build/outputs/apk/release/app-release.apk" +"$BUILD_TOOLS/zipalign" -c -P 16 4 "$APK" || { echo "the APK is not aligned for 16 KB pages" >&2; exit 1; } +UNPACKED="$OUT/apk-libraries" +rm -rf "${UNPACKED:?}" +mkdir -p "$UNPACKED" +(cd "$UNPACKED" && unzip -q "$APK" 'lib/*') +alignment_report="" +while IFS= read -r library; do + relative="${library#"$UNPACKED"/}" + aligned=true + if ! "$NDK_BIN/llvm-readelf" -lW "$library" | awk '$1 == "LOAD" && $NF != "0x4000" && $NF != "0x10000" { bad = 1 } END { exit bad }'; then + aligned=false + fi + alignment_report="$alignment_report{\"library\":\"$relative\",\"aligned_16k\":$aligned}," + echo "$relative: aligned for 16 KB pages: $aligned" +done < <(find "$UNPACKED/lib" -name '*.so' | sort) +if echo "$alignment_report" | grep -q '"aligned_16k":false'; then + echo "a native library in the APK is not aligned for 16 KB pages" >&2 + exit 1 +fi + +# 4. The library's tests through the installed copy: debug, then the shrunk release build. +results="" +for build in debug release; do + rm -rf "${ANDROID:?}/consumer/app/build/outputs/connected_android_test_additional_output" + task="connectedDebugAndroidTest" + [ "$build" = release ] && task="connectedReleaseAndroidTest" + consumer ":app:$task" -Pconsumer.testBuildType="$build" + for report in "$ANDROID"/consumer/app/build/outputs/androidTest-results/connected/"$build"/TEST-*.xml; do + summary="$(grep -o ']*>' "$report" | grep -o 'tests="[0-9]*" failures="[0-9]*" errors="[0-9]*" skipped="[0-9]*"')" + device="$(basename "$report" .xml)" + echo "$build $device: $summary" + if ! echo "$summary" | grep -q 'failures="0" errors="0" skipped="0"'; then + echo "the $build tests failed on ${device#TEST-}; see $report" >&2 + exit 1 + fi + results="$results{\"build\":\"$build\",\"device\":\"${device#TEST-}\",\"result\":\"${summary//\"/}\"}," + done + while IFS= read -r -d '' phone_file; do + "$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$phone_file" + done < <(find "$ANDROID/consumer/app/build/outputs/connected_android_test_additional_output" -name phone-edited.ath.sqlite -print0) +done + +sha() { shasum -a 256 "$1" | cut -d ' ' -f 1; } +cat > "$OUT/android-report.json" < [--mac-only] +# +# Writes to the output folder: +# AthleticStandardFFI-.xcframework.zip the release asset, with fixed file +# times so equal input gives equal bytes +# athleticstandard-swift/ the Swift package repository as +# released: its manifest names the asset +# by address and checksum +# athleticstandard-swift-staged/ the same repository, its manifest +# pointing at the zip inside it, tagged +# with the version +# consumer/ a package that resolves the staged +# repository by version and runs the +# package tests against it +# apple-report.json hashes, targets, versions, test results +# +# The two manifests differ only in the binary target line; the script checks that. +# Nothing is published. --mac-only leaves out the iPhone simulator run. + +set -euo pipefail + +OUT="${1:?usage: $0 [--mac-only]}" +MAC_ONLY="${2:-}" +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +if ! command -v cargo > /dev/null && [ -x "$HOME/.cargo/bin/cargo" ]; then + export PATH="$HOME/.cargo/bin:$PATH" +fi +VERSION="$(sed -n 's/^version = "\(.*\)"/\1/p' "$ROOT/mobile/Cargo.toml" | head -n 1)" +COMMIT="$(git -C "$ROOT" rev-parse HEAD)" +mkdir -p "$OUT" +OUT="$(cd "$OUT" && pwd -P)" + +"$ROOT/mobile/scripts/build-apple.sh" release + +ZIP="AthleticStandardFFI-$VERSION.xcframework.zip" +rm -f "${OUT:?}/${ZIP:?}" +( + cd "$ROOT/mobile/swift/build" + find AthleticStandardFFI.xcframework -exec touch -h -t 202601010000 {} + + find AthleticStandardFFI.xcframework -type f | LC_ALL=C sort | zip -q -X -D "$OUT/$ZIP" -@ +) +CHECKSUM="$(shasum -a 256 "$OUT/$ZIP" | cut -d ' ' -f 1)" +computed="$(cd "$OUT" && swift package compute-checksum "$ZIP")" +[ "$computed" = "$CHECKSUM" ] || { echo "swift computes $computed, not $CHECKSUM" >&2; exit 1; } + +package_repository() { + rm -rf "${1:?}" + "$ROOT/mobile/scripts/swift-package-repository.sh" "$1" "$VERSION" "$COMMIT" "$CHECKSUM" "$2" +} + +ASSET_URL="https://github.com/mwhitham/ath/releases/download/v$VERSION/$ZIP" +package_repository "$OUT/athleticstandard-swift" \ + ".binaryTarget(name: \"AthleticStandardFFI\", url: \"$ASSET_URL\", checksum: \"$CHECKSUM\")" +package_repository "$OUT/athleticstandard-swift-staged" \ + ".binaryTarget(name: \"AthleticStandardFFI\", path: \"$ZIP\")" +cp "$OUT/$ZIP" "$OUT/athleticstandard-swift-staged/$ZIP" +differences="$(diff "$OUT/athleticstandard-swift/Package.swift" "$OUT/athleticstandard-swift-staged/Package.swift" | grep -c '^[<>]' || true)" +[ "$differences" = 2 ] || { echo "the manifests differ in more than the binary target line" >&2; exit 1; } +( + cd "$OUT/athleticstandard-swift-staged" + git init -q + git add -A + git -c user.name="Athletic Standard staging" -c user.email="staging@localhost" commit -q -m "Athletic Standard $VERSION" + git tag "$VERSION" +) + +# An app's view: a package that depends on the staged repository by version. +CONSUMER="$OUT/consumer" +rm -rf "${CONSUMER:?}" +mkdir -p "$CONSUMER/Tests" +cp -R "$ROOT/mobile/swift/Tests/AthleticStandardTests" "$ROOT/mobile/swift/Tests/AthleticStandardHostTests" "$CONSUMER/Tests/" +cat > "$CONSUMER/Package.swift" < "$OUT/consumer-mac.log" 2>&1 || status=$? +grep -E 'Test run with|run,|calculations:' "$OUT/consumer-mac.log" || true +if [ "$status" -ne 0 ]; then + echo "the installed package tests failed; see $OUT/consumer-mac.log" >&2 + exit 1 +fi +"$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$ROUNDTRIP_OUT/mac/phone-edited.ath.sqlite" + +SIMULATOR_RESULT="not run (--mac-only)" +if [ "$MAC_ONLY" != "--mac-only" ]; then + if ! xcodebuild -version > /dev/null 2>&1; then + echo "iPhone simulator tests cannot run: xcodebuild is not usable. Accept Xcode's license or pass --mac-only." >&2 + exit 1 + fi + SIMULATOR="${SIMULATOR:-$(xcrun simctl list devices available | awk -F'[()]' '/iPhone/ { print $2; exit }')}" + ( + cd "$CONSUMER" + TEST_RUNNER_ATH_MOBILE_FIXTURES="$FIXTURES" TEST_RUNNER_ATH_MOBILE_ROUNDTRIP_OUT="$ROUNDTRIP_OUT/simulator" \ + TEST_RUNNER_ATH_TEST_HOST_URL="$ATH_TEST_HOST_URL" TEST_RUNNER_ATH_TEST_ISSUER="$ATH_TEST_ISSUER" \ + xcodebuild test -scheme AthleticStandardConsumer -destination "platform=iOS Simulator,id=$SIMULATOR" \ + -derivedDataPath "$OUT/consumer-xcode" + ) > "$OUT/consumer-simulator.log" 2>&1 + "$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$ROUNDTRIP_OUT/simulator/phone-edited.ath.sqlite" + SIMULATOR_RESULT="passed on simulator $SIMULATOR" +fi + +slice_report() { + local library="$ROOT/mobile/swift/build/AthleticStandardFFI.xcframework/$1/libathleticstandard_mobile.a" + printf '{"identifier":"%s","architectures":"%s","sha256":"%s"}' "$1" "$(lipo -archs "$library")" \ + "$(shasum -a 256 "$library" | cut -d ' ' -f 1)" +} +GENERATED="$ROOT/mobile/swift/Sources/AthleticStandard/Generated/AthleticStandard.swift" +cat > "$OUT/apple-report.json" <&1 | head -n 1 | sed 's/"/\\"/g')", + "installed_mac_tests": "$(grep -E 'Test run with' "$OUT/consumer-mac.log" | tr '\n' ';' | sed 's/"/\\"/g')", + "installed_simulator_tests": "$SIMULATOR_RESULT" +} +REPORT +echo "staged $VERSION: $OUT/$ZIP ($CHECKSUM)" diff --git a/mobile/scripts/start-emulator.sh b/mobile/scripts/start-emulator.sh new file mode 100755 index 00000000..832672e8 --- /dev/null +++ b/mobile/scripts/start-emulator.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Create and start a headless Android emulator, and wait until it has booted. +# +# Usage: mobile/scripts/start-emulator.sh [name] +# such as "system-images;android-36;google_apis;x86_64" +# +# The image must already be installed with sdkmanager. ANDROID_HOME names the SDK. +# Used by the CI job; locally, any running emulator or connected phone will do. + +set -euo pipefail + +IMAGE="${1:?usage: $0 [name]}" +NAME="${2:-athleticstandard-test}" +echo no | "$ANDROID_HOME/cmdline-tools/latest/bin/avdmanager" create avd --force -n "$NAME" -k "$IMAGE" -d pixel_7 > /dev/null +nohup "$ANDROID_HOME/emulator/emulator" -avd "$NAME" -no-window -no-audio -no-boot-anim -no-snapshot \ + -gpu swiftshader_indirect > "${RUNNER_TEMP:-/tmp}/emulator-$NAME.log" 2>&1 & +"$ANDROID_HOME/platform-tools/adb" wait-for-device +for _ in $(seq 1 120); do + if [ "$("$ANDROID_HOME/platform-tools/adb" shell getprop sys.boot_completed 2> /dev/null | tr -d '\r')" = 1 ]; then + echo "emulator $NAME booted ($IMAGE)" + exit 0 + fi + sleep 5 +done +echo "the emulator did not boot; see ${RUNNER_TEMP:-/tmp}/emulator-$NAME.log" >&2 +exit 1 diff --git a/mobile/scripts/swift-package-repository.sh b/mobile/scripts/swift-package-repository.sh new file mode 100755 index 00000000..026891c8 --- /dev/null +++ b/mobile/scripts/swift-package-repository.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Write the Swift package repository's files for one release (D332). +# +# Usage: mobile/scripts/swift-package-repository.sh +# +# is the manifest's binary target line, such as +# `.binaryTarget(name: "AthleticStandardFFI", url: "...", checksum: "...")`. +# stage-apple.sh and release-mobile-packages.yml both call this, so the staged and +# the released repositories are written the same way. + +set -euo pipefail + +FOLDER="${1:?folder}" +VERSION="${2:?version}" +COMMIT="${3:?commit}" +CHECKSUM="${4:?checksum}" +BINARY="${5:?binary target line}" +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" + +render() { + sed -e "s|@VERSION@|$VERSION|g" -e "s|@COMMIT@|$COMMIT|g" -e "s|@CHECKSUM@|$CHECKSUM|g" \ + -e "s|@BINARY_TARGET@|$BINARY|" "$1" +} + +mkdir -p "$FOLDER" +rm -rf "${FOLDER:?}/Sources" +mkdir -p "$FOLDER/Sources" +cp -R "$ROOT/mobile/swift/Sources/AthleticStandard" "$ROOT/mobile/swift/Sources/AthleticStandardHost" "$FOLDER/Sources/" +render "$ROOT/mobile/swift/release/Package.swift.in" > "$FOLDER/Package.swift" +render "$ROOT/mobile/swift/release/README.md.in" > "$FOLDER/README.md" +cp "$ROOT/LICENSE" "$FOLDER/LICENSE" diff --git a/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift b/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift new file mode 100644 index 00000000..bcdf3808 --- /dev/null +++ b/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift @@ -0,0 +1,154 @@ +// The runnable Swift example (D330). It works offline on a file in the app's own +// storage, opens a document the person picks, and, when asked, connects to an +// `ath-host`: signs in through the system browser, picks an owned record, reads it, +// and saves an edit. `swift run AthleticStandardExample` runs it on a Mac; the same +// views run in an iPhone app. +// +// The client ID and callback are placeholders. Register your own with the host's +// sign-in provider (mobile/README.md). + +import AthleticStandard +import AthleticStandardHost +import AuthenticationServices +import SwiftUI +import UniformTypeIdentifiers + +@main +struct ExampleApp: App { + var body: some Scene { + WindowGroup("Athletic Standard example") { ContentView() } + } +} + +@MainActor +final class Example: ObservableObject { + @Published var output = "" + @Published var hostAddress = "" + @Published var clientID = "client_EXAMPLE" + @Published var redirect = "ai.athleticstandard.example:/oauth/callback" + @Published var picking = false + + /// A local file: create it once, add a reading, and run a shipped calculation. + func workOffline() { + do { + let file = try FileLocationAdvice.localFolder().appendingPathComponent("example.ath.sqlite") + let exists = FileManager.default.fileExists(atPath: file.path) + let database = + exists + ? try Database.open(path: file.path, options: OpenDatabaseOptions()) + : try Database.create(path: file.path, options: CreateDatabaseOptions()) + defer { try? database.close() } + if !exists { + let source = #"{"inputs":[{"record_type":"source","data":{"source_type":"manual","data_writer":"Athletic Standard example","data_route":"manual_entry"},"changed_by":{"author_type":"athlete"}}]}"# + _ = try database.writeRecords(request: Data(source.utf8)) + } + let sources = try JSONSerialization.jsonObject( + with: try database.listRecords(options: ListRecordsOptions(recordType: "source"))) as? [[String: Any]] + let sourceID = sources?.first?["record_id"] as? String ?? "" + let now = ISO8601DateFormatter.withMilliseconds().string(from: Date()) + let reading = #"{"inputs":[{"record_type":"point_measurement","data":{"source_id":"\#(sourceID)","received_at":"\#(now)","received_at_basis":"local_write_time","quantity":"hrv_rmssd","recorded_at":"\#(now)","input_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"value":{"standard_value":\#(50 + Int.random(in: 0..<15)),"standard_unit":"ms","input_value_missing_reason":"not_provided_by_source","input_unit_missing_reason":"not_provided_by_source"}},"changed_by":{"author_type":"athlete"}}]}"# + let written = try JSONSerialization.jsonObject(with: try database.writeRecords(request: Data(reading.utf8))) + let recordID = ((written as? [String: Any])?["records"] as? [[String: Any]])?.first?["record_id"] as? String + let change = try database.apply(recordId: recordID ?? "", skill: .shipped(name: "hrv-change")) + output = """ + Athletic Standard \(libraryVersion()) + \(file.path) + database revision \(try database.info().databaseRevision) + hrv-change: \(String(decoding: change, as: UTF8.self)) + """ + } catch { + output = "Could not work on the local file: \(error)" + } + } + + func open(_ url: URL) { + do { + let picked = try PickedDocument.open(documentURL: url) + let info = try picked.database.info() + output = "Opened a working copy of \(url.lastPathComponent): database \(info.databaseId), revision \(info.databaseRevision)" + try picked.close() + } catch { + output = "Could not open the document: \(error)" + } + } + + /// Sign in, pick the first owned record, read it, and save an edit. + func connect() async { + guard let hostURL = URL(string: hostAddress), let redirectURI = URL(string: redirect) else { + output = "Enter the host's address first." + return + } + let configuration = HostSignInConfiguration(hostURL: hostURL, clientID: clientID, redirectURI: redirectURI) + let signIn = HostSignIn(configuration: configuration, store: KeychainTokenStore(configuration: configuration)) + do { + if try await !signIn.isSignedIn() { + try await signIn.signIn(browser: SystemBrowser(anchor: Self.window)) + } + let host = signIn.client() + let capabilities = try await host.capabilities() + let athlete: String + if let first = try await host.athletes().first { + athlete = first.athleteID + } else { + athlete = try await host.createAthlete(displayName: "Example athlete").athleteID + } + let records = try JSONSerialization.jsonObject(with: try await host.recordsJSON(athleteID: athlete)) + let count = ((records as? [String: Any])?["records"] as? [Any])?.count ?? 0 + let source = Data(#"{"source_type":"manual","data_writer":"Athletic Standard example","data_route":"manual_entry"}"#.utf8) + let write = try host.prepareRecordCreation(athleteID: athlete, recordType: "source", data: source) + let saved = try await host.send(write) + output = """ + Signed in to \(hostURL.absoluteString) + \(capabilities.operatorDisclosure) + record \(athlete): \(count) records + saved record \(saved.records.first?.recordID ?? "") at database revision \(saved.databaseRevision) + """ + } catch { + output = "Could not connect: \(error)" + } + } + + static func window() -> ASPresentationAnchor { + #if os(macOS) + NSApplication.shared.keyWindow ?? NSWindow() + #else + UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first + ?? ASPresentationAnchor() + #endif + } +} + +struct ContentView: View { + @StateObject private var example = Example() + + var body: some View { + Form { + Section("This device") { + Text(FileLocationAdvice.recommendation) + Button("Add a reading to the local file") { example.workOffline() } + Button("Open a file") { example.picking = true } + } + Section("Connect to a host") { + TextField("https://records.example.org", text: $example.hostAddress) + TextField("Client ID", text: $example.clientID) + TextField("Callback address", text: $example.redirect) + Button("Connect to a host") { Task { await example.connect() } } + } + Section("Result") { Text(example.output).textSelection(.enabled) } + } + .padding() + .fileImporter(isPresented: $example.picking, allowedContentTypes: [.data]) { result in + if case let .success(url) = result { example.open(url) } + } + .onAppear { example.workOffline() } + } +} + +extension ISO8601DateFormatter { + /// The stored UTC form, such as `2026-11-28T16:05:07.123Z`. + static func withMilliseconds() -> ISO8601DateFormatter { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter + } +} diff --git a/mobile/swift/Package.swift b/mobile/swift/Package.swift index f7674106..48d7820e 100644 --- a/mobile/swift/Package.swift +++ b/mobile/swift/Package.swift @@ -24,6 +24,11 @@ let package = Package( // The optional client for ath-host, with browser sign-in (D330). It needs no // native library, and local files never need it. .target(name: "AthleticStandardHost"), + // The runnable example (`swift run AthleticStandardExample` on a Mac). Releases + // do not carry it. + .executableTarget( + name: "AthleticStandardExample", dependencies: ["AthleticStandard", "AthleticStandardHost"], + path: "Examples/AthleticStandardExample"), .testTarget(name: "AthleticStandardTests", dependencies: ["AthleticStandard"]), .testTarget(name: "AthleticStandardHostTests", dependencies: ["AthleticStandardHost"]), ] diff --git a/mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift b/mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift index 2497b86a..ad197798 100644 --- a/mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift +++ b/mobile/swift/Tests/AthleticStandardTests/ValidationTests.swift @@ -21,8 +21,9 @@ struct ValidationTests { return [] } - @Test func libraryReportsItsVersion() { - #expect(libraryVersion() == "3.0.0") + @Test func libraryReportsItsVersion() throws { + let expected = try FixtureBundle.suite("library")["version"] as? String + #expect(libraryVersion() == expected) } @Test func measuredRecordWithSourceIsAccepted() throws { diff --git a/mobile/swift/release/Package.swift.in b/mobile/swift/release/Package.swift.in new file mode 100644 index 00000000..a0bb36cd --- /dev/null +++ b/mobile/swift/release/Package.swift.in @@ -0,0 +1,24 @@ +// swift-tools-version: 6.0 +// Athletic Standard @VERSION@ for iPhone apps (D325, D332). +// Built from commit @COMMIT@ of https://github.com/mwhitham/ath by +// mobile/scripts/stage-apple.sh. Do not edit; the next release replaces it. + +import PackageDescription + +let package = Package( + name: "AthleticStandard", + platforms: [.iOS(.v17), .macOS(.v14)], + products: [ + .library(name: "AthleticStandard", targets: ["AthleticStandard"]), + .library(name: "AthleticStandardHost", targets: ["AthleticStandardHost"]), + ], + targets: [ + @BINARY_TARGET@, + .target( + name: "AthleticStandard", + dependencies: ["AthleticStandardFFI"], + linkerSettings: [.linkedFramework("CoreFoundation"), .linkedLibrary("iconv")] + ), + .target(name: "AthleticStandardHost"), + ] +) diff --git a/mobile/swift/release/README.md.in b/mobile/swift/release/README.md.in new file mode 100644 index 00000000..e8e16f25 --- /dev/null +++ b/mobile/swift/release/README.md.in @@ -0,0 +1,17 @@ +# Athletic Standard for iPhone apps + +Version @VERSION@, built from commit @COMMIT@ of +[mwhitham/ath](https://github.com/mwhitham/ath). This repository holds only what Swift +Package Manager needs. The source, the documentation, and the issue tracker are in +`mwhitham/ath`; see `mobile/README.md` there. + +```swift +.package(url: "https://github.com/mwhitham/athleticstandard-swift", exact: "@VERSION@") +``` + +- `AthleticStandard`: record checks, calculations, and `.ath.sqlite` files, through the + same Rust library as the desktop `ath` program. iOS 17 and later. +- `AthleticStandardHost`: the optional client for `ath-host`, with browser sign-in. + +The native library is `AthleticStandardFFI-@VERSION@.xcframework.zip` in the release +`v@VERSION@` of mwhitham/ath, with SHA-256 `@CHECKSUM@`. MIT license. diff --git a/mobile/tests/fixtures.rs b/mobile/tests/fixtures.rs index 621d292c..d3b196ff 100644 --- a/mobile/tests/fixtures.rs +++ b/mobile/tests/fixtures.rs @@ -153,6 +153,10 @@ fn storage_files_are_exported() { std::fs::create_dir_all(folder).unwrap(); std::fs::copy(&outdated, folder.join("outdated-2-1-0.ath.sqlite")).unwrap(); } + // The version every phone build must report. + let mut library = Map::new(); + library.insert("version".into(), Value::String(athleticstandard_mobile::library_version())); + export("library", Value::Object(library)); } /// A request as the phone tests read it: full record IDs and the binding's diff --git a/mobile/tests/versions.rs b/mobile/tests/versions.rs new file mode 100644 index 00000000..9e03e69b --- /dev/null +++ b/mobile/tests/versions.rs @@ -0,0 +1,31 @@ +//! Every phone build file names the version the library reports (D152, D325). + +use std::path::PathBuf; + +fn repository() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..") +} + +fn value_after(file: &str, prefix: &str) -> String { + let text = std::fs::read_to_string(repository().join(file)).unwrap(); + let line = text.lines().find(|line| line.starts_with(prefix)).unwrap_or_else(|| panic!("{file} has no {prefix}")); + line[prefix.len()..].trim_matches('"').to_string() +} + +#[test] +fn the_phone_builds_name_the_library_version() { + let version = athleticstandard_mobile::library_version(); + for (file, prefix) in [ + ("Cargo.toml", "version = "), + ("core/Cargo.toml", "version = "), + ("mobile/Cargo.toml", "version = "), + ("mobile/bindgen/Cargo.toml", "version = "), + ("mobile/android/gradle.properties", "athleticstandard.version="), + ("mobile/android/consumer/gradle.properties", "athleticstandard.version="), + ("packages/npm/package.json", " \"version\": "), + ] { + let found = value_after(file, prefix); + let found = found.trim_end_matches(',').trim_matches('"'); + assert_eq!(found, version, "{file} names {found}"); + } +} From 0e416f0d996fe6b16f98c3badf95e27302abad4c Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 10:42:10 -0600 Subject: [PATCH 11/30] Track the Android manifests and resource files. The root `.gitignore` ignores every `*.xml` so a real health export is never added by accident, which also left out the five Android build files the phone library needs: two library manifests, the example app's manifest, its strings, and its network rule. Each is reviewed, listed with its hash in `tools/public-data-allowlist.json`, and named in an explicit `.gitignore` exception, as `tests/public_data.rs` requires. None holds athlete data. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 8 ++++++ .../src/androidTest/AndroidManifest.xml | 7 ++++++ .../src/main/AndroidManifest.xml | 2 ++ .../consumer/app/src/main/AndroidManifest.xml | 25 +++++++++++++++++++ .../app/src/main/res/values/strings.xml | 4 +++ .../main/res/xml/network_security_config.xml | 10 ++++++++ tools/public-data-allowlist.json | 20 +++++++++++++++ 7 files changed, 76 insertions(+) create mode 100644 mobile/android/athleticstandard/src/androidTest/AndroidManifest.xml create mode 100644 mobile/android/athleticstandard/src/main/AndroidManifest.xml create mode 100644 mobile/android/consumer/app/src/main/AndroidManifest.xml create mode 100644 mobile/android/consumer/app/src/main/res/values/strings.xml create mode 100644 mobile/android/consumer/app/src/main/res/xml/network_security_config.xml diff --git a/.gitignore b/.gitignore index 06d2e3db..2bfcc77e 100644 --- a/.gitignore +++ b/.gitignore @@ -65,6 +65,14 @@ validation-data/ !tests/vectors/model/ExportManifest.json !tests/golden/routes/invented-refusal-athlete-maximum.json +# Android build files are XML. They hold no athlete data; each is reviewed and listed +# in tools/public-data-allowlist.json like the fixtures above. +!mobile/android/athleticstandard/src/androidTest/AndroidManifest.xml +!mobile/android/athleticstandard/src/main/AndroidManifest.xml +!mobile/android/consumer/app/src/main/AndroidManifest.xml +!mobile/android/consumer/app/src/main/res/values/strings.xml +!mobile/android/consumer/app/src/main/res/xml/network_security_config.xml + # Large deterministic release fixtures are generated locally or in the release job. /performance/generated/ /performance/results/local/ diff --git a/mobile/android/athleticstandard/src/androidTest/AndroidManifest.xml b/mobile/android/athleticstandard/src/androidTest/AndroidManifest.xml new file mode 100644 index 00000000..43c44656 --- /dev/null +++ b/mobile/android/athleticstandard/src/androidTest/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/mobile/android/athleticstandard/src/main/AndroidManifest.xml b/mobile/android/athleticstandard/src/main/AndroidManifest.xml new file mode 100644 index 00000000..b2d3ea12 --- /dev/null +++ b/mobile/android/athleticstandard/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + + diff --git a/mobile/android/consumer/app/src/main/AndroidManifest.xml b/mobile/android/consumer/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..e5f25eae --- /dev/null +++ b/mobile/android/consumer/app/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/android/consumer/app/src/main/res/values/strings.xml b/mobile/android/consumer/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..e9aeb2e1 --- /dev/null +++ b/mobile/android/consumer/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + Athletic Standard example + diff --git a/mobile/android/consumer/app/src/main/res/xml/network_security_config.xml b/mobile/android/consumer/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 00000000..10ace9d5 --- /dev/null +++ b/mobile/android/consumer/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,10 @@ + + + + + 127.0.0.1 + localhost + + diff --git a/tools/public-data-allowlist.json b/tools/public-data-allowlist.json index be87f125..691b03d3 100644 --- a/tools/public-data-allowlist.json +++ b/tools/public-data-allowlist.json @@ -232,6 +232,26 @@ { "path": "tests/golden/routes/invented-refusal-athlete-maximum.json", "sha256": "e1d945a461f9520d19c1fd68b3dd95f7b8c7ef041b6a2e0ced2f19df7533f67f" + }, + { + "path": "mobile/android/athleticstandard/src/androidTest/AndroidManifest.xml", + "sha256": "1759f077b1ba559d4d0d88e126c334d50feaac8876184ffae9189116e55592e0" + }, + { + "path": "mobile/android/athleticstandard/src/main/AndroidManifest.xml", + "sha256": "c8fe08b06e479efc7e3d00476fffe693a3e943e2b874b3c6a1ba5156fc180751" + }, + { + "path": "mobile/android/consumer/app/src/main/AndroidManifest.xml", + "sha256": "f5d43a6546a6bb05cbf010423786f75886801af1d37f09ad141b096844a49bc2" + }, + { + "path": "mobile/android/consumer/app/src/main/res/values/strings.xml", + "sha256": "253b00c595747bc93f8de98e9b618bcc36a67742c368129523a22c71f5b41cae" + }, + { + "path": "mobile/android/consumer/app/src/main/res/xml/network_security_config.xml", + "sha256": "6046c8e28ecf4a1ec69097368769600506b61ff0cdf2005f0c907dc244ce49a8" } ] } From 2b27a1b6ec8d3deae95a04b93f903fa1429b3d9b Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sat, 28 Nov 2026 10:43:55 -0600 Subject: [PATCH 12/30] Let the phone scripts follow CARGO_TARGET_DIR. The build, round-trip, and host scripts read Cargo's output from `target/`. Cargo writes to `CARGO_TARGET_DIR` when it is set, as a fresh clone built against a shared target folder showed, so the scripts now read from there too. Co-Authored-By: Claude Opus 5.5 --- mobile/scripts/build-android.sh | 10 ++++++---- mobile/scripts/build-apple.sh | 10 ++++++---- mobile/scripts/host-test-env.sh | 6 ++++-- mobile/scripts/roundtrip.sh | 4 +++- 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/mobile/scripts/build-android.sh b/mobile/scripts/build-android.sh index 09fe19f6..899cf582 100755 --- a/mobile/scripts/build-android.sh +++ b/mobile/scripts/build-android.sh @@ -21,6 +21,8 @@ case "$PROFILE" in esac ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +# Cargo builds into CARGO_TARGET_DIR when it is set. +TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" OUT="${2:-$ROOT/mobile/android/athleticstandard/build/rust}" NDK_VERSION=29.0.14206865 API=24 @@ -54,7 +56,7 @@ build_abi() { cargo rustc --locked -p athleticstandard-mobile --lib --crate-type cdylib \ --target "$target" --profile "$CARGO_PROFILE" --manifest-path "$ROOT/Cargo.toml" mkdir -p "$OUT/jniLibs/$abi" - cp "$ROOT/target/$target/$PROFILE_DIR/libathleticstandard_mobile.so" "$OUT/jniLibs/$abi/" + cp "$TARGET_DIR/$target/$PROFILE_DIR/libathleticstandard_mobile.so" "$OUT/jniLibs/$abi/" if [ "$PROFILE" = release ]; then "$TOOLCHAIN/llvm-strip" --strip-debug "$OUT/jniLibs/$abi/libathleticstandard_mobile.so" fi @@ -77,9 +79,9 @@ build_abi x86_64-linux-android x86_64 "x86_64-linux-android$API-clang" cargo build --locked -p athleticstandard-mobile --profile "$CARGO_PROFILE" cargo build --locked -p athleticstandard-uniffi-bindgen case "$(uname -s)" in - Darwin) HOST_LIBRARY="$ROOT/target/$PROFILE_DIR/libathleticstandard_mobile.dylib" ;; - *) HOST_LIBRARY="$ROOT/target/$PROFILE_DIR/libathleticstandard_mobile.so" ;; + Darwin) HOST_LIBRARY="$TARGET_DIR/$PROFILE_DIR/libathleticstandard_mobile.dylib" ;; + *) HOST_LIBRARY="$TARGET_DIR/$PROFILE_DIR/libathleticstandard_mobile.so" ;; esac -"$ROOT/target/debug/uniffi-bindgen" generate --no-format --language kotlin \ +"$TARGET_DIR/debug/uniffi-bindgen" generate --no-format --language kotlin \ --library "$HOST_LIBRARY" --out-dir "$OUT/kotlin" echo "wrote $OUT" diff --git a/mobile/scripts/build-apple.sh b/mobile/scripts/build-apple.sh index 7e5faec5..1107d58b 100755 --- a/mobile/scripts/build-apple.sh +++ b/mobile/scripts/build-apple.sh @@ -24,6 +24,8 @@ case "$PROFILE" in esac ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +# Cargo builds into CARGO_TARGET_DIR when it is set. +TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" SWIFT_DIR="$ROOT/mobile/swift" OUT="$SWIFT_DIR/build" FRAMEWORK="$OUT/AthleticStandardFFI.xcframework" @@ -83,8 +85,8 @@ cargo build --locked -p athleticstandard-uniffi-bindgen BINDINGS="$OUT/bindings" rm -rf "$BINDINGS" mkdir -p "$BINDINGS" -"$ROOT/target/debug/uniffi-bindgen" generate --no-format --language swift \ - --library "$ROOT/target/$PROFILE_DIR/libathleticstandard_mobile.dylib" --out-dir "$BINDINGS" +"$TARGET_DIR/debug/uniffi-bindgen" generate --no-format --language swift \ + --library "$TARGET_DIR/$PROFILE_DIR/libathleticstandard_mobile.dylib" --out-dir "$BINDINGS" rm -rf "$FRAMEWORK" "$GENERATED" mkdir -p "$FRAMEWORK" "$GENERATED" @@ -98,10 +100,10 @@ slice() { cp "$BINDINGS/AthleticStandardFFI.h" "$dir/Headers/AthleticStandardFFI.h" cp "$BINDINGS/AthleticStandardFFI.modulemap" "$dir/Headers/module.modulemap" if [ "$#" -eq 1 ]; then - cp "$ROOT/target/$1/$PROFILE_DIR/$LIB" "$dir/$LIB" + cp "$TARGET_DIR/$1/$PROFILE_DIR/$LIB" "$dir/$LIB" else local inputs=() - for target in "$@"; do inputs+=("$ROOT/target/$target/$PROFILE_DIR/$LIB"); done + for target in "$@"; do inputs+=("$TARGET_DIR/$target/$PROFILE_DIR/$LIB"); done lipo -create "${inputs[@]}" -output "$dir/$LIB" fi } diff --git a/mobile/scripts/host-test-env.sh b/mobile/scripts/host-test-env.sh index a681074b..2a6e0681 100755 --- a/mobile/scripts/host-test-env.sh +++ b/mobile/scripts/host-test-env.sh @@ -13,6 +13,8 @@ set -euo pipefail ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +# Cargo builds into CARGO_TARGET_DIR when it is set. +TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" COMMAND="${1:-}" FOLDER="${2:-}" if [ -z "$FOLDER" ]; then @@ -45,7 +47,7 @@ case "$COMMAND" in cargo build --locked -p athleticstandard-host --bin ath-host --example test-sign-in-provider \ --manifest-path "$ROOT/Cargo.toml" provider_port="$(free_port)" - "$ROOT/target/debug/examples/test-sign-in-provider" --listen "127.0.0.1:$provider_port" \ + "$TARGET_DIR/debug/examples/test-sign-in-provider" --listen "127.0.0.1:$provider_port" \ > "$FOLDER/provider.log" 2>&1 & echo $! > "$FOLDER/provider.pid" issuer="http://127.0.0.1:$provider_port" @@ -62,7 +64,7 @@ case "$COMMAND" in "open_enrollment": true } CONFIG - "$ROOT/target/debug/ath-host" serve --config "$FOLDER/host-config.json" > "$FOLDER/host.log" 2>&1 & + "$TARGET_DIR/debug/ath-host" serve --config "$FOLDER/host-config.json" > "$FOLDER/host.log" 2>&1 & echo $! > "$FOLDER/host.pid" for _ in $(seq 1 100); do if curl -fsS "$host_url/v1/capabilities" > /dev/null 2>&1 && diff --git a/mobile/scripts/roundtrip.sh b/mobile/scripts/roundtrip.sh index c6774058..89919c6d 100755 --- a/mobile/scripts/roundtrip.sh +++ b/mobile/scripts/roundtrip.sh @@ -16,7 +16,9 @@ set -euo pipefail ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -ATH="${ATH:-$ROOT/target/debug/ath}" +# Cargo builds into CARGO_TARGET_DIR when it is set. +TARGET_DIR="${CARGO_TARGET_DIR:-$ROOT/target}" +ATH="${ATH:-$TARGET_DIR/debug/ath}" COMMAND="${1:-}" FOLDER="${2:-}" if [ -z "$FOLDER" ]; then From 5e8f67b8340c0a772798ffa3226eb3089e9b18a8 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 10:16:19 -0600 Subject: [PATCH 13/30] Check the migration backup by file name in the phone storage test. The test expected the backup path to end in `/before-migration.ath.sqlite`. On Windows the path uses `\`, so the check failed although the migration and its backup worked. It now compares the file name. Co-Authored-By: Claude Opus 5.5 --- mobile/tests/store.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mobile/tests/store.rs b/mobile/tests/store.rs index aab1678f..464d6990 100644 --- a/mobile/tests/store.rs +++ b/mobile/tests/store.rs @@ -186,7 +186,9 @@ fn an_outdated_file_needs_a_migration_with_a_verified_backup() { let backup = path_in(folder.path(), "before-migration.ath.sqlite"); let result = parse(outdated.migrate(backup.clone()).unwrap()); assert_eq!(result["migrated"], Value::Bool(true), "{result:?}"); - assert!(result["backup_path"].as_str().unwrap().ends_with("/before-migration.ath.sqlite"), "{result:?}"); + // Compare the file name, so the check holds with either path separator. + let backup_path = Path::new(result["backup_path"].as_str().unwrap()); + assert_eq!(backup_path.file_name(), Some(std::ffi::OsStr::new("before-migration.ath.sqlite")), "{result:?}"); outdated.close().unwrap(); assert!(Path::new(&backup).exists()); From 36d3a743ab4dab155f48b775499ea63aa1df3fed Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 10:57:17 -0600 Subject: [PATCH 14/30] Record the phone library as version 3.1.0. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Version 3.0.0 was released before the phone library was merged, so the phone packages ship as 3.1.0. D334 says why: under D290 the release only adds packages and library calls, so it is minor, and migration step 9 records the version without changing a table, as step 4 did for 2.1.0. The Open Wearables plan moves to 3.2.0 with step 10 and keeps D272–D289, which replaces the version D317 named for it. The new `build-history/v3.1.0/` folder holds a short spec, D325–D334, the plan, the progress notes, and the evidence. These were added to the 3.0.0 folder on this branch and never released, so they move; the 3.0.0 folder is back to its released text. D325 now names 3.1.0, and the plan's links reach the files where they are now. AGENTS.md lists 3.1.0 as the current version, and the phone README links the new folder. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 15 +- build-history/README.md | 3 +- .../v3.0.0/appendix/release-evidence.md | 32 -- build-history/v3.0.0/decisions.md | 261 --------------- build-history/v3.0.0/progress.md | 123 ------- .../appendix/mobile-library-plan.md | 7 +- .../v3.1.0/appendix/release-evidence.md | 34 ++ build-history/v3.1.0/decisions.md | 300 ++++++++++++++++++ build-history/v3.1.0/progress.md | 135 ++++++++ build-history/v3.1.0/spec.md | 74 +++++ mobile/README.md | 18 +- 11 files changed, 566 insertions(+), 436 deletions(-) rename build-history/{v3.0.0 => v3.1.0}/appendix/mobile-library-plan.md (97%) create mode 100644 build-history/v3.1.0/appendix/release-evidence.md create mode 100644 build-history/v3.1.0/decisions.md create mode 100644 build-history/v3.1.0/progress.md create mode 100644 build-history/v3.1.0/spec.md diff --git a/AGENTS.md b/AGENTS.md index 19a9a859..33fd8ebd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,13 +21,14 @@ Read these before making decisions — they are the project's memory and outrank 5. **`build-history/v2.1.0/spec.md`** — version 2.1.0. Mapping files (`mappings/`, `ath import --mapping`), migration step 4, and `field_basis` are described there. 6. **`build-history/v2.1.1/spec.md`** — version 2.1.1: the complete native rebuild, SQL migration step 5, and the npm launcher and JavaScript client. Its `appendix/` holds the 2.1.0 reference evidence (D218): the command inventory, deliberate behavior changes, semantic rules, public API inventory, and test disposition. 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. +8. **`build-history/v2.1.3/spec.md`** — version 2.1.3: 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, the last released 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/v3.1.0/spec.md`** — version 3.1.0, built and not released, the current version: the library for iPhone and Android apps in `mobile/`, with Swift and Kotlin bindings generated by UniFFI, calculations that read their data through one reader interface, a host client with browser sign-in, and SQL migration step 9, which records the version (D325–D334). `mobile/README.md` is the guide for app developers. +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.1.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 0d57dc96..054bf218 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -41,7 +41,8 @@ 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). | -| [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. The iPhone and Android packages are built under the same version and not published ([plan](v3.0.0/appendix/mobile-library-plan.md)). See its [decisions](v3.0.0/decisions.md) and [progress](v3.0.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). | +| [v3.1.0](v3.1.0/spec.md) | Built, not released: the library for iPhone and Android apps, with Swift and Kotlin bindings generated by UniFFI, calculations through one reader interface, and a host client with browser sign-in. No record format change; migration step 9 records the version. See its [decisions](v3.1.0/decisions.md), [progress](v3.1.0/progress.md), [plan](v3.1.0/appendix/mobile-library-plan.md), and [build evidence](v3.1.0/appendix/release-evidence.md). | ## Drafts that were not approved diff --git a/build-history/v3.0.0/appendix/release-evidence.md b/build-history/v3.0.0/appendix/release-evidence.md index 874b1fde..b120d88b 100644 --- a/build-history/v3.0.0/appendix/release-evidence.md +++ b/build-history/v3.0.0/appendix/release-evidence.md @@ -75,35 +75,3 @@ normally and ran only `SELECT` statements. checked. - The staged-write, sync, and test-kit scenarios on a libSQL server. They ran in remote mode against a local file in place of the server. - -## 6. iPhone and Android packages - -The phone packages (D325–D333, build steps 12 to 17) were built and tested on the same -Mac on 2026-11-28 with synthetic data. Each staging run writes `apple-report.json` and -`android-report.json` with the hashes, the source commit, the targets, and the tool -versions; the release job adds both to the GitHub release. - -| Check | Result | -|---|---| -| Model vectors through each binding | 7,399 cases: 7,285 run, 114 skipped for the four documented reasons, 0 failed | -| Coaching record examples | 20 blocks, 53 shape checks, 0 failed | -| Calculations through the database | 49 cases, 113 requests, 0 differences from the desktop | -| Calculations through the memory snapshot | 99 requests match the desktop; 14 that read device recordings or intensity references get the documented refusal (D326) | -| Both calculation readers on the desktop | 42 worked examples and 71 case requests: 30 and 69 match, 12 and 2 get the documented refusal; the 100,000-input limit holds on both | -| Swift package installed by version from a staged repository, on macOS | 25 tests passed: 20 package tests and 5 host tests | -| Android library installed by coordinate, API 36 (4 KB pages) and API 37.1 (16 KB pages) emulators | 25 tests passed on each, in a debug build and in a shrunk release build | -| 16 KB alignment of every native library in the shrunk release APK | 4 of 4 libraries aligned (both ABIs of the library and of JNA) | -| Desktop round trip | Passed on macOS and on both emulators: the desktop `ath` created the file, the phone library corrected a reading, and the desktop `ath` found the edit at revision 2, revision 1 kept, and a passing `ath check` | -| XCFramework zip | Two staging runs gave the same bytes | -| The whole workspace after the phone work | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass; `cargo test` (workspace) gives 939 passed, 0 failed, 18 ignored; npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (gate 5) passes | - -Not verified: - -- The iPhone simulator. Xcode's license was not accepted on the build machine, so - `xcodebuild` and `simctl` could not run. The `mobile-apple` CI job runs it. -- The iCloud Drive picker on a signed-in device. -- The system browser sheets with a person, and a live WorkOS environment (issue 57). -- The CI jobs and the release workflows. They were written in this build but have not - run on GitHub. -- Publication. The Maven namespace, the Swift package repository, and the publishing - credentials belong to the maintainer. diff --git a/build-history/v3.0.0/decisions.md b/build-history/v3.0.0/decisions.md index c9b30009..06aa39d7 100644 --- a/build-history/v3.0.0/decisions.md +++ b/build-history/v3.0.0/decisions.md @@ -556,264 +556,3 @@ they run. The maintainer approved it on 2026-11-28. Rejected alternatives: - API version 2 for 3.0.0. Rejected because nothing an existing app uses changes. - -## D325. Phones get the library through UniFFI, in version 3.0.0 - -An iPhone app and an Android app call the Rust library through bindings that UniFFI -generates. The Swift package and the Android library hold no second implementation of -the record rules, checks, or calculations. Swift and Kotlin code adds only what each -platform owns: file pickers and file access, browser sign-in, and secure token storage. -This is [issue 64](https://github.com/mwhitham/ath/issues/64). The approved plan is -[mobile-library-plan.md](appendix/mobile-library-plan.md). - -This is the iPhone and Android build that D312 left for later. The packages report -library version 3.0.0 and ship with the 3.0.0 release, under the single version rule -(D152). They add no record field and no database migration. - -Rejected alternatives: - -- Write the rules again in Swift and Kotlin. Rejected because two more implementations - would each need every check and calculation kept equal to the desktop one. D208 made - the library the one implementation. -- Run the `ath` executable from the app. Rejected because iOS does not let an app start - another program, and Android apps cannot rely on it. -- Build the library to WebAssembly and run it in a JavaScript engine. Rejected because - it adds a runtime to each app and cannot open the SQLite file directly. -- Write a C interface and its Swift and Kotlin wrappers by hand. Rejected because UniFFI - generates both sides from one Rust definition, so a changed type cannot drift. - -## D326. Calculations ask for their data through one reader interface - -The calculation settings, methods, range arithmetic, receipts, calendar rules, and -shipped skill text move into D312's core, so a phone can calculate without SQLite. The -core gains an error type with the variants a calculation can produce: invalid, not -found, refused, and other. The desktop error type converts from it with the same codes -and messages, and keeps the SQLite, file, and migration variants. The `athleticstandard` -crate re-exports the moved modules, so its public paths stay the same. - -Each calculation names the data it needs as a typed request in the core: one current -record, other current records of the same source, records inside a window before a -record, the athlete profile, heart-rate samples during a session, range inputs, and -provider-period inputs. Two readers answer these requests. - -- The SQLite reader runs the existing indexed queries, unchanged, inside one read - snapshot. Desktop and phone databases both use it. -- The memory reader answers from immutable indexes built over records the caller - supplied. It applies the same filters and the same order as the SQL: deleted records - and manual sources are left out, and ties are broken by record ID. - -The core does everything else once: request checks, calendar boundaries, arithmetic, -limits, and receipts. Tests run both readers on the same data and compare the complete -results, including failures. - -A memory snapshot is built from batches of current records and then finished. A batch -with an invalid record or a duplicate current ID is refused and leaves the builder as -it was. A finished snapshot cannot change. The records supplied are all the data the -calculation sees. A missing source, linked record, or profile has the effect it has in -a database without that record. - -Rejected alternatives: - -- Load supplied records into an in-memory SQLite database. Rejected because the - calculation-only build would then need SQLite. -- Write the queries once in a small query language that both readers interpret. - Rejected because the eight queries are fewer lines than the interpreter, and the SQL - must stay exactly as it is to keep its index plans. - -The calculations 3.0.0 adds that read device recordings, the intensity reference in -effect, or a window of workouts (D302, D305, D322) ask for that data as one request, -which the SQLite reader answers with the queries 3.0.0 already runs. A memory snapshot -does not hold recording blocks yet, so it answers that such a calculation needs a -database, and the phone runs it on a `Database`. The fixture bundle lists those cases -with that reason (D333). - -## D327. Phones open the same SQLite file through the existing store - -The mobile crate, `athleticstandard-mobile` in `mobile/`, has a `sqlite` feature. It -depends on the `athleticstandard` crate with its new default feature, `cli`, turned -off. That feature holds the command line, terminal handling, the network runtime, -provider import readers, prediction and log planning, and the protocol operations that -use them. A phone build therefore compiles the store, files, packages, calculations, -and views, and nothing that reaches the network. - -Phone edits run the protocol's database, record, query, and calculation operations -in-process on an open store. So an edit from a phone gets the same checks, the same -stale-revision refusals, and the same messages as one from the npm client. A store -handle runs one call at a time and is closed explicitly. After it is closed, every -call is refused. A read-only open, the migration preview, and migration only after a -verified backup work as they do on the desktop. - -Each platform gets one native library that holds both the calculation module and the -storage module. An app cannot link two Rust static libraries, because each carries its -own copy of the Rust runtime and the symbols collide. The build without the `sqlite` -feature is still built and tested, and a test checks that its dependency tree has no -SQLite, HTTP, or command-line crate. - -The generated Swift and Kotlin bindings are build output and are not committed. The -release staging step generates them with the locked UniFFI version and records their -hashes. - -Rejected alternatives: - -- Use a platform database library, such as GRDB on iOS or Room on Android. Rejected - because it would write the tables without the one record encoder and its checks. -- Ship two native libraries, one per module. Rejected because of the symbol collision. -- Give each phone call its own open and close, as the protocol worker does. Rejected - because a phone keeps a file open while the person works, and reopening checks the - file again on every tap. - -## D328. Where a phone keeps the file - -The guide and the examples recommend keeping the working file on the device. iCloud -Drive and other locations in the Files picker stay selectable. The suggested wording is: -"We recommend keeping your working file on this device. Editing the same file on two -devices through iCloud Drive can cause sync conflicts." - -- A file in the app's own folders opens in place. An edit is saved when it commits. -- A document picked from another location is copied into a private working folder. - The library records the copy's SHA-256 digest. Edits commit to the working copy. - Saving writes a verified single-file copy of the database (the store's backup), then - replaces the picked document only if its content still has the recorded digest. If it - changed, the save is refused and the app can save a copy instead. A failed save keeps - every local edit. -- The library reports two separate facts: the edit has committed locally, and the - picked document has been saved. -- A single-file save does not carry attachment files. The complete package export - carries them. - -Rejected alternatives: - -- Open every picked document in place. Rejected because a sync provider can replace the - main file while SQLite's companion log holds committed edits, and the log does not - travel with the file. -- Copy the main database file back. Rejected because a copy of an active database can - miss committed edits that are still in the companion log. - -## D329. Values cross the boundary as JSON text, and failures are typed - -Record bodies, results, and receipts cross between Rust and Swift or Kotlin as UTF-8 -JSON bytes, read and written by the library's own JSON code. Options, validation -issues, and failure kinds are generated types. One failure type, -`AthleticStandardError`, has a case for each desktop error code (`invalid`, -`not_found`, `stale`, `refused`, `migration_required`, `database`, `io`, and `error`) -and three cases of its own: `malformed_json`, `unknown_shape`, and `closed`. A -validation issue keeps its path as a list of segments, each either a field name or a -list position, with the desktop code and message. - -Rejected alternatives: - -- Generate a Swift and a Kotlin type for every record shape. Rejected because record - extensions and the exact text of numbers would not survive the round trip, and the - published shapes would have a third definition to keep in step. -- Return one error string. Rejected because an app must tell a stale edit from an - invalid record without reading the message. - -## D330. The packages include a host client with browser sign-in - -Both packages include an optional client for `ath-host`: the `AthleticStandardHost` -Swift module and the `ai.athleticstandard.host` Kotlin package. Local files need no -account and no network. Connecting to a host is something the person chooses. - -An app gives the client the host's address, its registered public client ID, and its -callback address. The client reads the host's protected-resource metadata and the -sign-in provider's discovery document, then runs the authorization code flow with S256 -PKCE in the system browser: `ASWebAuthenticationSession` on iOS and a Custom Tab on -Android, as RFC 8252 asks for native apps. It checks that the callback carries the -`state` of the sign-in it started. It asks for a token for the host's resource -identifier (RFC 8707). It keeps the refresh token in the iOS Keychain or in Android -storage encrypted with a Keystore key, never in an athlete file or export. It -refreshes an expired token and supports cancelled sign-in and sign-out. An app that -already has a session can instead give the client a function that returns a current -access token for this host. - -Writes keep the rules of D261. The client makes one `Idempotency-Key` per edit and -sends the same bytes with it after a lost reply. A correction carries the revision the -person edited. A stale answer keeps the person's edit for review. Connecting does not -link a local file or upload it. Keeping a local copy in step with a host is -[issue 58](https://github.com/mwhitham/ath/issues/58). - -The sign-in code is the library's own, on the platform browser APIs, rather than the -AppAuth libraries, as `ath` does for its own host connection (D313). The flow needs three requests: discovery, the code exchange, and the -refresh. Keeping them in the package means the packages have no third-party -dependency, and the tests run the whole exchange and refresh against a local test -provider on both platforms. - -Rejected alternatives: - -- Use AppAuth for iOS and Android. Rejected because it adds a dependency to every app - for three requests. -- Show a sign-in form in the app. Rejected by RFC 8252 and D260: the app must never see - the password. -- Give the app database credentials. Rejected by D266. - -## D331. Platform floors and targets - -- iOS 17 and later. The XCFramework has an arm64 device library, an arm64 and x86_64 - simulator library, and an arm64 and x86_64 macOS library, so `swift test` runs the - bindings on a Mac without a simulator. iOS 17 matches the Swift host example. -- Android API 24 and later, for arm64-v8a phones and x86_64 emulators. Native code is - built with NDK r29, which aligns libraries for 16 KB memory pages by default. The - Android library compiles against API 36 with JDK 21. -- Rust 1.100.0 (`rust-toolchain.toml`) and UniFFI 0.33.0, locked in `Cargo.lock`. The - Gradle and NDK versions are pinned in the Android build files. - -Rejected alternatives: - -- 32-bit Android ABIs (armeabi-v7a and x86). Rejected because each ABI adds a build and - a test run, and API 24 phones that need them are rare. -- An iOS floor below 17. Rejected because the host client uses Swift concurrency - features from that release, as the example does. - -## D332. How the packages are released - -- **Swift.** The release builds the XCFramework, zips it, and records its SHA-256 - checksum. A separate Swift package repository holds a `Package.swift` that names the - release asset by address and checksum, with the generated Swift sources. Its version - tag points at the commit that names the tested checksum. The proposed repository is - `mwhitham/athleticstandard-swift`. The maintainer creates it. -- **Android.** The release builds an Android archive with the generated Kotlin, both - native libraries, a POM that declares the pinned JNA runtime, and sources and - documentation jars. It is published to Maven Central as - `ai.athleticstandard:athleticstandard`. The `ai.athleticstandard` namespace must be - verified by the maintainer, through the `athleticstandard.ai` domain that already - names the published schemas, before the coordinate is promised. -- A branch run builds both packages, installs them from a temporary Swift package - repository and a local Maven repository, and tests them, without publisher - credentials. The release job requires those tests. It uploads the tested archive, - publishes the checked Maven bundle, tags the tested Swift manifest, and then installs - from both public locations. -- A retry reuses the staged files. It skips an artifact already published with the same - bytes and stops on a published version with different bytes. A missing registry - credential blocks only publication. Publication stays with the maintainer. - -Rejected alternatives: - -- Commit the XCFramework to this repository. Rejected because Swift Package Manager - fetches the whole repository, and binary files would stay in its history. -- Build the Rust code from source inside Swift Package Manager. Rejected because a Swift - package cannot run Cargo. -- Publish through JitPack. Rejected because it builds on its own servers, so the - published bytes would not be the tested ones. -- Publish to GitHub Packages. Rejected because reading from it needs a token. - -## D333. One fixture bundle tests every platform - -A desktop exporter writes a test bundle while the tests run. It holds each model -vector with its expected verdict, issues, and checked output, after the documented -historical exceptions and message changes. It holds each worked calculation example -as complete current records, a SQLite file built from them, the request, and the -desktop result or failure. It holds each coaching record example. Inputs are synthetic. -The bundle is not committed. - -The Swift and Kotlin tests read the bundle and run every case through the installed -packages. Calculation cases run through both the memory and the SQLite entry points. -Each suite reports its run, skip, and failure counts. A new skip, a missing skill, or a -mismatch fails the run. The checked-in examples and golden files stay an independent -check, because the desktop tests already compare the desktop result with them. - -Rejected alternatives: - -- Copy the expected results into Swift and Kotlin test files. Rejected because a third - copy of thousands of results would drift. -- Run only a sample of the cases on phones. Rejected because a rule that differs on one - platform shows up only in the cases that exercise it. diff --git a/build-history/v3.0.0/progress.md b/build-history/v3.0.0/progress.md index da5d421a..26832c70 100644 --- a/build-history/v3.0.0/progress.md +++ b/build-history/v3.0.0/progress.md @@ -15,12 +15,6 @@ Status: **being built; not released.** The plan is [spec.md](spec.md). | 9 | `ath` connects to a host; host permissions; large writes; test kit | done: gate 2 passes, and the test kit passes against `ath-host` in both modes | | 10 | Guides | done: each followed by an independent reader, and fixed | | 11 | Synthetic journey and release evidence | done: gate 6 passes; release notes name step 8 | -| 12 | Phone library plan, decisions D325–D333 ([plan](appendix/mobile-library-plan.md)) | done | -| 13 | UniFFI crate, validation from the Swift package and the Android library | Mac and Android emulator pass; iPhone simulator not run | -| 14 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | Mac and two Android emulators pass; iPhone simulator and iCloud not run | -| 15 | Calculations from memory and SQLite through one reader interface | Mac and two Android emulators pass; iPhone simulator not run | -| 16 | Host client for Swift and Kotlin with browser sign-in | Mac and two Android emulators pass against a real host; live WorkOS not run | -| 17 | Release packaging, phone test runs, release gate | staged and installed locally; CI, simulator, and publication not run | ## Step 2: what was built @@ -690,120 +684,3 @@ These follow the guide and the decisions. Each is open to review. migration step 8 and its one-time rebuild of `records` first. - Step 11 is done, and so is the build of 3.0.0. Nothing was pushed or published. -## Step 13: the UniFFI crate and the first phone builds - -- `mobile/` is the UniFFI crate (UniFFI 0.33.0), built on D312's core. Its record - checks run every recorded model vector: 7,399 cases in 140 files, 7,285 run and 114 - skipped for the four documented reasons. The same counts pass in Rust, through the - Swift package on a Mac (`swift test`), and through the Android library on an API 36 - arm64 emulator. -- The vector exceptions and message changes, including 3.0.0's, moved to - `tests/vector_rules/`, so the desktop harness and the phone bundle read one list. -- A test checks that the build without storage depends on no SQLite, HTTP, or - command-line crate, and that `core/src` names no file, network, or process API. -- Both Android libraries pass a 16 KB page alignment check when they are built. -- The XCFramework is assembled by `mobile/scripts/build-apple.sh`, not by - `xcodebuild -create-xcframework`. The iPhone simulator run needs Xcode's license to be - accepted on the build machine; it has not run yet. - -## Step 14: real athlete files on phones - -- `Database` in the phone binding holds one open file through the desktop store. Its - edits run the npm client's record operations in process - (`protocol::run_in_process`), so the inputs, outputs, refusals, and messages are the - npm client's. Kotlin names its close `closeDatabase()`, because Kotlin's `close()` - frees the native object. -- The `athleticstandard` crate's default `cli` feature holds the command line, the - import readers, the network runtime, prediction and log planning, and package zips. - The phone build turns it off. -- Phones put app folders behind system links (`/var` on iOS, `/data/user/0` on - Android). The binding resolves the folder before it opens a file; a database file - that is itself a link is still refused. -- `PickedDocument` (Swift and Kotlin) copies a picked document into a working folder, - records its SHA-256, and saves back a verified single-file copy only if the document - still has that content. Tests cover a document changed by another device, a provider - that refuses the write, and resuming after a restart. -- An outdated 2.1.0 file is refused until it is migrated, after a verified backup, to - SQL step 8. -- The desktop round trip runs on each platform: the desktop `ath` creates the file, the - phone library corrects one reading, closes and resumes the file, and saves it, and the - desktop `ath` checks the saved file. Results are in step 17. -- Not run: the iPhone simulator (it needs Xcode's license accepted on this machine), - and the iCloud Drive picker on a signed-in device. - -## Step 15: calculations from memory and from a file - -- The calculation settings, methods, range arithmetic, receipts, calendar rules, and - shipped skills moved into the core, with the 3.0.0 workout operations, their - results, and the threshold outcomes. The desktop keeps the SQL in - `src/calculate/sqlite.rs`, `recorded.rs`, `recorded_inputs.rs`, and `window.rs`, - unchanged, and every existing calculation, golden, and query-plan test passed - without a change to an expected value. -- `tests/calculate_readers.rs` runs the 42 worked examples and 71 requests over seven - synthetic cases on both readers and compares the complete results. The cases cover - equal times, deleted records and a deleted source, a manual source, a corrected - record, both Chicago clock changes, a missing profile timezone, provider periods with - several periods in one record and periods that start before local midnight, two - summaries of one type in one session, mixed units, workout drift on a deleted - session, linked and removed workouts, edited, malformed, coaching, and range skill - text, and the receipt cap at 1,000 and 1,001 inputs. -- A memory snapshot does not hold device recordings, so the methods that read - recordings or intensity references are refused from memory with a message that says - to run them on a database (D326). 12 worked examples and 2 case requests get that - refusal; the test checks its exact text. The other 30 examples and 69 requests match. -- The input limit holds on both readers at 100,000 inputs and refuses 100,001. -- The phone bundle's calculation suite has 49 cases and 113 requests. Through the - database, all of them match the desktop. Through the memory snapshot, 99 match and - 14 give the documented refusal. Both hold in Rust, in the Swift package on a Mac, - and in the Android library on both emulators. The coaching suite checks the 20 - record-example blocks as 53 shape checks. -- `applyWith` on a snapshot and on a `Database` takes the options of - `ath apply --set`, so a phone runs the threshold methods on a file. -- Building `ath` alone (`cargo check -p athleticstandard --bin ath`) failed, because - the root manifest did not turn on the `ureq` JSON and `uuid` v4 features the sign-in - runtime uses; a workspace build got them from `host/`. The `cli` feature now turns - them on. -- One clock fallback remains in range arithmetic: a calendar date that does not read - falls back to today. The calendar range check refuses such a date first, so no - request reaches it. - -## Step 16: the host client with browser sign-in - -- The Swift package gains the `AthleticStandardHost` module, built from the example - client with the owner record routes, changes, export, app connections, and prepared - writes. The Android library gains `ai.athleticstandard.host` with the same calls. -- Sign-in is the library's own code on the platform browser APIs: discovery, S256 - PKCE, a `state` check, the code exchange with `resource`, refresh with rotation, and - sign-out. Tokens are kept in the Keychain on iOS and in a file encrypted with an - Android Keystore key. -- `host/examples/test-sign-in-provider.rs` is a test-only provider that answers like - the WorkOS recipe: `client_id` in the token, the audience from `resource`, and - rotated refresh tokens. It signs with the fixed test key. -- Against a real `ath-host`, the Swift tests on a Mac and the Kotlin tests on both - Android emulators each pass five cases: sign-in and owner writes with a retried - write, a stale correction, and a key reused for another request; refresh and a - refused refresh; a cancelled sign-in and callbacks with another `state` or address; - a revoked coach and a disconnected app; and a token supplied by the app. -- Not run: the system browser sheets (`ASWebAuthenticationSession`, Custom Tabs) with a - person, and a live WorkOS environment with expired, wrong-audience, wrong-issuer, - and wrong-app tokens. Both belong with issue 57 and need a WorkOS test environment - and registered public apps. - -## Step 17: release packaging and the phone release gate - -- `mobile/scripts/stage-apple.sh` and `mobile/scripts/stage-android.sh` build the - release packages, install them the way an app does, and run every phone test - through the installed copy. Results are in - [release-evidence.md](appendix/release-evidence.md#6-iphone-and-android-packages). -- The Android consumer app keeps only the library's two ABIs, because JNA carries - more. Its shrunk release build needed two test-only rules, both in the consumer: the - AndroidX test libraries name annotation classes they do not ship, and the test APK - uses the app's copies of the Kotlin standard library and `androidx.tracing`. The - library's own consumer rules needed no change. -- The `mobile-apple` and `mobile-android` jobs in `validate.yml`, the - `publish-mobile` job in `release-cross-platform.yml`, and - `release-mobile-packages.yml` are written but have not run on GitHub. The 16 KB - emulator run is local only: GitHub's Linux runners have no 16 KB x86_64 image. -- Runnable examples: the consumer app is the Android example, and - `swift run AthleticStandardExample` is the Swift one. The Android example ran - offline on an emulator. The Swift example builds; its window was not opened. diff --git a/build-history/v3.0.0/appendix/mobile-library-plan.md b/build-history/v3.1.0/appendix/mobile-library-plan.md similarity index 97% rename from build-history/v3.0.0/appendix/mobile-library-plan.md rename to build-history/v3.1.0/appendix/mobile-library-plan.md index 606e808d..500d3667 100644 --- a/build-history/v3.0.0/appendix/mobile-library-plan.md +++ b/build-history/v3.1.0/appendix/mobile-library-plan.md @@ -2,8 +2,9 @@ The approved implementation plan for [issue 64](https://github.com/mwhitham/ath/issues/64). It is copied here from the planning draft. Only the links changed, to work from this -folder. D325 to D333 record the decisions it asked for at implementation start. It was -written against 2.1.3; D312 has since made the core it asks for. +folder and to reach files where they are now. D325 to D333 record the decisions it +asked for at implementation start, and D334 the version it ships in. It was written +against 2.1.3; D312 has since made the core it asks for. An athlete can create or pick an `.ath.sqlite` file on their phone, record a workout offline, close the app, and reopen the file with the edit intact. An app can also offer **Connect to a host** to sign in and work directly with a hosted record. Swift and Kotlin use the existing Rust store for local files and the storage-free library for in-memory checks and calculations. Both platforms ship with each release. @@ -58,7 +59,7 @@ Define the data requests each method needs in Rust. Use the existing indexed SQL Embed the shipped calculation descriptions at build time. Desktop keeps its installed-skill lookup and passes the chosen text to the core. Mobile reads shipped text or text supplied by the caller. Pass the profile time zone into calendar logic and use bundled zone data. Audit clock fallbacks so a phone’s current date or system zone cannot silently change an answer. -Relevant owners today are [the model](../../../src/model/), [single-record input selection](../../../src/calculate/record.rs), [range queries and receipts](../../../src/calculate/range.rs), [calendar rules](../../../src/view/calendar.rs) and [desktop snapshot tests](../../../src/calculate/snapshot_tests.rs). +Relevant owners today are [the model](../../../core/src/model/), [single-record input selection](../../../core/src/calculate/record.rs), [range queries and receipts](../../../core/src/calculate/range.rs), [calendar rules](../../../src/view/calendar.rs) and [desktop snapshot tests](../../../src/calculate/snapshot_tests.rs). ## Build order and acceptance tests diff --git a/build-history/v3.1.0/appendix/release-evidence.md b/build-history/v3.1.0/appendix/release-evidence.md new file mode 100644 index 00000000..07b061dd --- /dev/null +++ b/build-history/v3.1.0/appendix/release-evidence.md @@ -0,0 +1,34 @@ +# Version 3.1.0 release evidence + +This is the evidence for the release gates of 3.1.0 ([spec](../spec.md) section 3). It +was gathered on an Apple silicon Mac (arm64) with synthetic data. No live provider +account was used. Each staging run writes `apple-report.json` and `android-report.json` +with the hashes, the source commit, the targets, and the tool versions; the release job +adds both to the GitHub release. + +## 1. Checks + +| Check | Result | +|---|---| +| Model vectors through each binding | 7,399 cases: 7,285 run, 114 skipped for the four documented reasons, 0 failed | +| Coaching record examples | 20 blocks, 53 shape checks, 0 failed | +| Calculations through the database | 49 cases, 113 requests, 0 differences from the desktop | +| Calculations through the memory snapshot | 99 requests match the desktop; 14 that read device recordings or intensity references get the documented refusal (D326) | +| Both calculation readers on the desktop | 42 worked examples and 71 case requests: 30 and 69 match, 12 and 2 get the documented refusal; the 100,000-input limit holds on both | +| Swift package installed by version from a staged repository, on macOS | 25 tests passed: 20 package tests and 5 host tests | +| Android library installed by coordinate, API 36 (4 KB pages) and API 37.1 (16 KB pages) emulators | 25 tests passed on each, in a debug build and in a shrunk release build | +| 16 KB alignment of every native library in the shrunk release APK | 4 of 4 libraries aligned (both ABIs of the library and of JNA) | +| Desktop round trip | Passed on macOS and on both emulators: the desktop `ath` created the file, the phone library corrected a reading, and the desktop `ath` found the edit at revision 2, revision 1 kept, and a passing `ath check` | +| XCFramework zip | Two staging runs gave the same bytes | +| The whole workspace after the phone work | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass; `cargo test` (workspace) gives 939 passed, 0 failed, 18 ignored; npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (gate 5) passes | + +## 2. Not verified + +- The iPhone simulator. Xcode's license was not accepted on the build machine, so + `xcodebuild` and `simctl` could not run. The `mobile-apple` CI job runs it. +- The iCloud Drive picker on a signed-in device. +- The system browser sheets with a person, and a live WorkOS environment (issue 57). +- The CI jobs and the release workflows. They were written in this build but have not + run on GitHub. +- Publication. The Maven namespace, the Swift package repository, and the publishing + credentials belong to the maintainer. diff --git a/build-history/v3.1.0/decisions.md b/build-history/v3.1.0/decisions.md new file mode 100644 index 00000000..58ed1202 --- /dev/null +++ b/build-history/v3.1.0/decisions.md @@ -0,0 +1,300 @@ +# v3.1.0 decisions + +Decisions continue after D324 in [v3.0.0](../v3.0.0/decisions.md). D272–D289 stay +reserved for the Open Wearables plan, which now follows as 3.2.0 (D334). The plan is +[spec.md](spec.md). + +## D325. Phones get the library through UniFFI, in version 3.1.0 + +An iPhone app and an Android app call the Rust library through bindings that UniFFI +generates. The Swift package and the Android library hold no second implementation of +the record rules, checks, or calculations. Swift and Kotlin code adds only what each +platform owns: file pickers and file access, browser sign-in, and secure token storage. +This is [issue 64](https://github.com/mwhitham/ath/issues/64). The approved plan is +[mobile-library-plan.md](appendix/mobile-library-plan.md). + +This is the iPhone and Android build that D312 left for later. The packages report +library version 3.1.0 and ship with the 3.1.0 release, under the single version rule +(D152). They add no record field. Migration step 9 records the new version and changes +no table (D334). + +Rejected alternatives: + +- Write the rules again in Swift and Kotlin. Rejected because two more implementations + would each need every check and calculation kept equal to the desktop one. D208 made + the library the one implementation. +- Run the `ath` executable from the app. Rejected because iOS does not let an app start + another program, and Android apps cannot rely on it. +- Build the library to WebAssembly and run it in a JavaScript engine. Rejected because + it adds a runtime to each app and cannot open the SQLite file directly. +- Write a C interface and its Swift and Kotlin wrappers by hand. Rejected because UniFFI + generates both sides from one Rust definition, so a changed type cannot drift. + +## D326. Calculations ask for their data through one reader interface + +The calculation settings, methods, range arithmetic, receipts, calendar rules, and +shipped skill text move into D312's core, so a phone can calculate without SQLite. The +core gains an error type with the variants a calculation can produce: invalid, not +found, refused, and other. The desktop error type converts from it with the same codes +and messages, and keeps the SQLite, file, and migration variants. The `athleticstandard` +crate re-exports the moved modules, so its public paths stay the same. + +Each calculation names the data it needs as a typed request in the core: one current +record, other current records of the same source, records inside a window before a +record, the athlete profile, heart-rate samples during a session, range inputs, and +provider-period inputs. Two readers answer these requests. + +- The SQLite reader runs the existing indexed queries, unchanged, inside one read + snapshot. Desktop and phone databases both use it. +- The memory reader answers from immutable indexes built over records the caller + supplied. It applies the same filters and the same order as the SQL: deleted records + and manual sources are left out, and ties are broken by record ID. + +The core does everything else once: request checks, calendar boundaries, arithmetic, +limits, and receipts. Tests run both readers on the same data and compare the complete +results, including failures. + +A memory snapshot is built from batches of current records and then finished. A batch +with an invalid record or a duplicate current ID is refused and leaves the builder as +it was. A finished snapshot cannot change. The records supplied are all the data the +calculation sees. A missing source, linked record, or profile has the effect it has in +a database without that record. + +Rejected alternatives: + +- Load supplied records into an in-memory SQLite database. Rejected because the + calculation-only build would then need SQLite. +- Write the queries once in a small query language that both readers interpret. + Rejected because the eight queries are fewer lines than the interpreter, and the SQL + must stay exactly as it is to keep its index plans. + +The calculations 3.0.0 adds that read device recordings, the intensity reference in +effect, or a window of workouts (D302, D305, D322) ask for that data as one request, +which the SQLite reader answers with the queries 3.0.0 already runs. A memory snapshot +does not hold recording blocks yet, so it answers that such a calculation needs a +database, and the phone runs it on a `Database`. The fixture bundle lists those cases +with that reason (D333). + +## D327. Phones open the same SQLite file through the existing store + +The mobile crate, `athleticstandard-mobile` in `mobile/`, has a `sqlite` feature. It +depends on the `athleticstandard` crate with its new default feature, `cli`, turned +off. That feature holds the command line, terminal handling, the network runtime, +provider import readers, prediction and log planning, and the protocol operations that +use them. A phone build therefore compiles the store, files, packages, calculations, +and views, and nothing that reaches the network. + +Phone edits run the protocol's database, record, query, and calculation operations +in-process on an open store. So an edit from a phone gets the same checks, the same +stale-revision refusals, and the same messages as one from the npm client. A store +handle runs one call at a time and is closed explicitly. After it is closed, every +call is refused. A read-only open, the migration preview, and migration only after a +verified backup work as they do on the desktop. + +Each platform gets one native library that holds both the calculation module and the +storage module. An app cannot link two Rust static libraries, because each carries its +own copy of the Rust runtime and the symbols collide. The build without the `sqlite` +feature is still built and tested, and a test checks that its dependency tree has no +SQLite, HTTP, or command-line crate. + +The generated Swift and Kotlin bindings are build output and are not committed. The +release staging step generates them with the locked UniFFI version and records their +hashes. + +Rejected alternatives: + +- Use a platform database library, such as GRDB on iOS or Room on Android. Rejected + because it would write the tables without the one record encoder and its checks. +- Ship two native libraries, one per module. Rejected because of the symbol collision. +- Give each phone call its own open and close, as the protocol worker does. Rejected + because a phone keeps a file open while the person works, and reopening checks the + file again on every tap. + +## D328. Where a phone keeps the file + +The guide and the examples recommend keeping the working file on the device. iCloud +Drive and other locations in the Files picker stay selectable. The suggested wording is: +"We recommend keeping your working file on this device. Editing the same file on two +devices through iCloud Drive can cause sync conflicts." + +- A file in the app's own folders opens in place. An edit is saved when it commits. +- A document picked from another location is copied into a private working folder. + The library records the copy's SHA-256 digest. Edits commit to the working copy. + Saving writes a verified single-file copy of the database (the store's backup), then + replaces the picked document only if its content still has the recorded digest. If it + changed, the save is refused and the app can save a copy instead. A failed save keeps + every local edit. +- The library reports two separate facts: the edit has committed locally, and the + picked document has been saved. +- A single-file save does not carry attachment files. The complete package export + carries them. + +Rejected alternatives: + +- Open every picked document in place. Rejected because a sync provider can replace the + main file while SQLite's companion log holds committed edits, and the log does not + travel with the file. +- Copy the main database file back. Rejected because a copy of an active database can + miss committed edits that are still in the companion log. + +## D329. Values cross the boundary as JSON text, and failures are typed + +Record bodies, results, and receipts cross between Rust and Swift or Kotlin as UTF-8 +JSON bytes, read and written by the library's own JSON code. Options, validation +issues, and failure kinds are generated types. One failure type, +`AthleticStandardError`, has a case for each desktop error code (`invalid`, +`not_found`, `stale`, `refused`, `migration_required`, `database`, `io`, and `error`) +and three cases of its own: `malformed_json`, `unknown_shape`, and `closed`. A +validation issue keeps its path as a list of segments, each either a field name or a +list position, with the desktop code and message. + +Rejected alternatives: + +- Generate a Swift and a Kotlin type for every record shape. Rejected because record + extensions and the exact text of numbers would not survive the round trip, and the + published shapes would have a third definition to keep in step. +- Return one error string. Rejected because an app must tell a stale edit from an + invalid record without reading the message. + +## D330. The packages include a host client with browser sign-in + +Both packages include an optional client for `ath-host`: the `AthleticStandardHost` +Swift module and the `ai.athleticstandard.host` Kotlin package. Local files need no +account and no network. Connecting to a host is something the person chooses. + +An app gives the client the host's address, its registered public client ID, and its +callback address. The client reads the host's protected-resource metadata and the +sign-in provider's discovery document, then runs the authorization code flow with S256 +PKCE in the system browser: `ASWebAuthenticationSession` on iOS and a Custom Tab on +Android, as RFC 8252 asks for native apps. It checks that the callback carries the +`state` of the sign-in it started. It asks for a token for the host's resource +identifier (RFC 8707). It keeps the refresh token in the iOS Keychain or in Android +storage encrypted with a Keystore key, never in an athlete file or export. It +refreshes an expired token and supports cancelled sign-in and sign-out. An app that +already has a session can instead give the client a function that returns a current +access token for this host. + +Writes keep the rules of D261. The client makes one `Idempotency-Key` per edit and +sends the same bytes with it after a lost reply. A correction carries the revision the +person edited. A stale answer keeps the person's edit for review. Connecting does not +link a local file or upload it. Keeping a local copy in step with a host is +[issue 58](https://github.com/mwhitham/ath/issues/58). + +The sign-in code is the library's own, on the platform browser APIs, rather than the +AppAuth libraries, as `ath` does for its own host connection (D313). The flow needs +three requests: discovery, the code exchange, and the +refresh. Keeping them in the package means the packages have no third-party +dependency, and the tests run the whole exchange and refresh against a local test +provider on both platforms. + +Rejected alternatives: + +- Use AppAuth for iOS and Android. Rejected because it adds a dependency to every app + for three requests. +- Show a sign-in form in the app. Rejected by RFC 8252 and D260: the app must never see + the password. +- Give the app database credentials. Rejected by D266. + +## D331. Platform floors and targets + +- iOS 17 and later. The XCFramework has an arm64 device library, an arm64 and x86_64 + simulator library, and an arm64 and x86_64 macOS library, so `swift test` runs the + bindings on a Mac without a simulator. iOS 17 matches the Swift host example. +- Android API 24 and later, for arm64-v8a phones and x86_64 emulators. Native code is + built with NDK r29, which aligns libraries for 16 KB memory pages by default. The + Android library compiles against API 36 with JDK 21. +- Rust 1.100.0 (`rust-toolchain.toml`) and UniFFI 0.33.0, locked in `Cargo.lock`. The + Gradle and NDK versions are pinned in the Android build files. + +Rejected alternatives: + +- 32-bit Android ABIs (armeabi-v7a and x86). Rejected because each ABI adds a build and + a test run, and API 24 phones that need them are rare. +- An iOS floor below 17. Rejected because the host client uses Swift concurrency + features from that release, as the example does. + +## D332. How the packages are released + +- **Swift.** The release builds the XCFramework, zips it, and records its SHA-256 + checksum. A separate Swift package repository holds a `Package.swift` that names the + release asset by address and checksum, with the generated Swift sources. Its version + tag points at the commit that names the tested checksum. The proposed repository is + `mwhitham/athleticstandard-swift`. The maintainer creates it. +- **Android.** The release builds an Android archive with the generated Kotlin, both + native libraries, a POM that declares the pinned JNA runtime, and sources and + documentation jars. It is published to Maven Central as + `ai.athleticstandard:athleticstandard`. The `ai.athleticstandard` namespace must be + verified by the maintainer, through the `athleticstandard.ai` domain that already + names the published schemas, before the coordinate is promised. +- A branch run builds both packages, installs them from a temporary Swift package + repository and a local Maven repository, and tests them, without publisher + credentials. The release job requires those tests. It uploads the tested archive, + publishes the checked Maven bundle, tags the tested Swift manifest, and then installs + from both public locations. +- A retry reuses the staged files. It skips an artifact already published with the same + bytes and stops on a published version with different bytes. A missing registry + credential blocks only publication. Publication stays with the maintainer. + +Rejected alternatives: + +- Commit the XCFramework to this repository. Rejected because Swift Package Manager + fetches the whole repository, and binary files would stay in its history. +- Build the Rust code from source inside Swift Package Manager. Rejected because a Swift + package cannot run Cargo. +- Publish through JitPack. Rejected because it builds on its own servers, so the + published bytes would not be the tested ones. +- Publish to GitHub Packages. Rejected because reading from it needs a token. + +## D333. One fixture bundle tests every platform + +A desktop exporter writes a test bundle while the tests run. It holds each model +vector with its expected verdict, issues, and checked output, after the documented +historical exceptions and message changes. It holds each worked calculation example +as complete current records, a SQLite file built from them, the request, and the +desktop result or failure. It holds each coaching record example. Inputs are synthetic. +The bundle is not committed. + +The Swift and Kotlin tests read the bundle and run every case through the installed +packages. Calculation cases run through both the memory and the SQLite entry points. +Each suite reports its run, skip, and failure counts. A new skip, a missing skill, or a +mismatch fails the run. The checked-in examples and golden files stay an independent +check, because the desktop tests already compare the desktop result with them. + +Rejected alternatives: + +- Copy the expected results into Swift and Kotlin test files. Rejected because a third + copy of thousands of results would drift. +- Run only a sample of the cases on phones. Rejected because a rule that differs on one + platform shows up only in the cases that exercise it. + +## D334. The phone library ships as 3.1.0, and the Open Wearables plan moves to 3.2.0 + +Version 3.0.0 was released before the phone library was merged, so the phone packages +cannot carry that number. They ship as 3.1.0. Under +[D290](../v3.0.0/decisions.md#d290-version-300-under-a-clearer-version-rule) this is a +minor release: it +adds the `athleticstandard-mobile` crate, the Swift package, the Android library, the +`cli` feature, and library calls, and every 3.0.0 record, package, and database stays +valid. The record format does not change. + +A database records the version that wrote it, and a new database must reach the +program's own version (`src/store/mod.rs`). So migration step 9 sets +`athleticstandard_version` to 3.1.0 and changes no table, as step 4 did for 2.1.0. A +3.0.0 program refuses a step-9 database, because its SQL schema step is newer, and asks +for an update. A 3.1.0 package declares 3.1.0; `ath import` in 3.1.0 also restores +every package version 3.0.0 restores. + +The Open Wearables plan now follows as 3.2.0 with migration step 10. It keeps D272–D289. +This replaces the version and step that +[D317](../v3.0.0/decisions.md#d317-300-ships-before-the-open-wearables-plan) named for +it; the rest of D317 stands. + +Rejected alternatives: + +- 3.0.1. Rejected because D290 keeps a patch for fixes, and this release adds packages + and library calls. +- Hold the phone packages until the Open Wearables plan, and ship both as 3.1.0. + Rejected because the phone library is built and tested, and the Open Wearables plan + is not built. +- Release 3.1.0 without a migration step. Rejected because a new database must reach + the program's version, and every earlier version recorded its own. diff --git a/build-history/v3.1.0/progress.md b/build-history/v3.1.0/progress.md new file mode 100644 index 00000000..e3c24282 --- /dev/null +++ b/build-history/v3.1.0/progress.md @@ -0,0 +1,135 @@ +# v3.1.0 progress + +Status: **built; not released.** The plan is [spec.md](spec.md). Evidence: +[release-evidence.md](appendix/release-evidence.md). + +| Step | What | Status | +|---|---|---| +| 1 | Phone library plan, decisions D325–D334 ([plan](appendix/mobile-library-plan.md)) | done | +| 2 | UniFFI crate, validation from the Swift package and the Android library | Mac and Android emulators pass; iPhone simulator not run | +| 3 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | Mac and two Android emulators pass; iPhone simulator and iCloud not run | +| 4 | Calculations from memory and SQLite through one reader interface | Mac and two Android emulators pass; iPhone simulator not run | +| 5 | Host client for Swift and Kotlin with browser sign-in | Mac and two Android emulators pass against a real host; live WorkOS not run | +| 6 | Release packaging, phone test runs, release gate | staged and installed locally; CI, simulator, and publication not run | +| 7 | Version 3.1.0 and migration step 9 | not started | + +The phone work was built on 3.0.0 as build steps 12 to 17, and moved here when 3.0.0 +was released without it (D334). + +## Step 2: the UniFFI crate and the first phone builds + +- `mobile/` is the UniFFI crate (UniFFI 0.33.0), built on D312's core. Its record + checks run every recorded model vector: 7,399 cases in 140 files, 7,285 run and 114 + skipped for the four documented reasons. The same counts pass in Rust, through the + Swift package on a Mac (`swift test`), and through the Android library on an API 36 + arm64 emulator. +- The vector exceptions and message changes, including 3.0.0's, moved to + `tests/vector_rules/`, so the desktop harness and the phone bundle read one list. +- A test checks that the build without storage depends on no SQLite, HTTP, or + command-line crate, and that `core/src` names no file, network, or process API. +- Both Android libraries pass a 16 KB page alignment check when they are built. +- The XCFramework is assembled by `mobile/scripts/build-apple.sh`, not by + `xcodebuild -create-xcframework`. The iPhone simulator run needs Xcode's license to be + accepted on the build machine; it has not run yet. + +## Step 3: real athlete files on phones + +- `Database` in the phone binding holds one open file through the desktop store. Its + edits run the npm client's record operations in process + (`protocol::run_in_process`), so the inputs, outputs, refusals, and messages are the + npm client's. Kotlin names its close `closeDatabase()`, because Kotlin's `close()` + frees the native object. +- The `athleticstandard` crate's default `cli` feature holds the command line, the + import readers, the network runtime, prediction and log planning, and package zips. + The phone build turns it off. +- Phones put app folders behind system links (`/var` on iOS, `/data/user/0` on + Android). The binding resolves the folder before it opens a file; a database file + that is itself a link is still refused. +- `PickedDocument` (Swift and Kotlin) copies a picked document into a working folder, + records its SHA-256, and saves back a verified single-file copy only if the document + still has that content. Tests cover a document changed by another device, a provider + that refuses the write, and resuming after a restart. +- An outdated 2.1.0 file is refused until it is migrated, after a verified backup, to + the program's SQL step: step 8 when this was built, step 9 after step 7. +- The desktop round trip runs on each platform: the desktop `ath` creates the file, the + phone library corrects one reading, closes and resumes the file, and saves it, and the + desktop `ath` checks the saved file. Results are in step 6. +- Not run: the iPhone simulator (it needs Xcode's license accepted on this machine), + and the iCloud Drive picker on a signed-in device. + +## Step 4: calculations from memory and from a file + +- The calculation settings, methods, range arithmetic, receipts, calendar rules, and + shipped skills moved into the core, with the 3.0.0 workout operations, their + results, and the threshold outcomes. The desktop keeps the SQL in + `src/calculate/sqlite.rs`, `recorded.rs`, `recorded_inputs.rs`, and `window.rs`, + unchanged, and every existing calculation, golden, and query-plan test passed + without a change to an expected value. +- `tests/calculate_readers.rs` runs the 42 worked examples and 71 requests over seven + synthetic cases on both readers and compares the complete results. The cases cover + equal times, deleted records and a deleted source, a manual source, a corrected + record, both Chicago clock changes, a missing profile timezone, provider periods with + several periods in one record and periods that start before local midnight, two + summaries of one type in one session, mixed units, workout drift on a deleted + session, linked and removed workouts, edited, malformed, coaching, and range skill + text, and the receipt cap at 1,000 and 1,001 inputs. +- A memory snapshot does not hold device recordings, so the methods that read + recordings or intensity references are refused from memory with a message that says + to run them on a database (D326). 12 worked examples and 2 case requests get that + refusal; the test checks its exact text. The other 30 examples and 69 requests match. +- The input limit holds on both readers at 100,000 inputs and refuses 100,001. +- The phone bundle's calculation suite has 49 cases and 113 requests. Through the + database, all of them match the desktop. Through the memory snapshot, 99 match and + 14 give the documented refusal. Both hold in Rust, in the Swift package on a Mac, + and in the Android library on both emulators. The coaching suite checks the 20 + record-example blocks as 53 shape checks. +- `applyWith` on a snapshot and on a `Database` takes the options of + `ath apply --set`, so a phone runs the threshold methods on a file. +- Building `ath` alone (`cargo check -p athleticstandard --bin ath`) failed, because + the root manifest did not turn on the `ureq` JSON and `uuid` v4 features the sign-in + runtime uses; a workspace build got them from `host/`. The `cli` feature now turns + them on. +- One clock fallback remains in range arithmetic: a calendar date that does not read + falls back to today. The calendar range check refuses such a date first, so no + request reaches it. + +## Step 5: the host client with browser sign-in + +- The Swift package gains the `AthleticStandardHost` module, built from the example + client with the owner record routes, changes, export, app connections, and prepared + writes. The Android library gains `ai.athleticstandard.host` with the same calls. +- Sign-in is the library's own code on the platform browser APIs: discovery, S256 + PKCE, a `state` check, the code exchange with `resource`, refresh with rotation, and + sign-out. Tokens are kept in the Keychain on iOS and in a file encrypted with an + Android Keystore key. +- `host/examples/test-sign-in-provider.rs` is a test-only provider that answers like + the WorkOS recipe: `client_id` in the token, the audience from `resource`, and + rotated refresh tokens. It signs with the fixed test key. +- Against a real `ath-host`, the Swift tests on a Mac and the Kotlin tests on both + Android emulators each pass five cases: sign-in and owner writes with a retried + write, a stale correction, and a key reused for another request; refresh and a + refused refresh; a cancelled sign-in and callbacks with another `state` or address; + a revoked coach and a disconnected app; and a token supplied by the app. +- Not run: the system browser sheets (`ASWebAuthenticationSession`, Custom Tabs) with a + person, and a live WorkOS environment with expired, wrong-audience, wrong-issuer, + and wrong-app tokens. Both belong with issue 57 and need a WorkOS test environment + and registered public apps. + +## Step 6: release packaging and the phone release gate + +- `mobile/scripts/stage-apple.sh` and `mobile/scripts/stage-android.sh` build the + release packages, install them the way an app does, and run every phone test + through the installed copy. Results are in + [release-evidence.md](appendix/release-evidence.md). +- The Android consumer app keeps only the library's two ABIs, because JNA carries + more. Its shrunk release build needed two test-only rules, both in the consumer: the + AndroidX test libraries name annotation classes they do not ship, and the test APK + uses the app's copies of the Kotlin standard library and `androidx.tracing`. The + library's own consumer rules needed no change. +- The `mobile-apple` and `mobile-android` jobs in `validate.yml`, the + `publish-mobile` job in `release-cross-platform.yml`, and + `release-mobile-packages.yml` are written but have not run on GitHub. The 16 KB + emulator run is local only: GitHub's Linux runners have no 16 KB x86_64 image. +- Runnable examples: the consumer app is the Android example, and + `swift run AthleticStandardExample` is the Swift one. The Android example ran + offline on an emulator. The Swift example builds; its window was not opened. diff --git a/build-history/v3.1.0/spec.md b/build-history/v3.1.0/spec.md new file mode 100644 index 00000000..59883667 --- /dev/null +++ b/build-history/v3.1.0/spec.md @@ -0,0 +1,74 @@ +# Athletic Standard 3.1.0 — the library for iPhone and Android apps + +Status: **built; not released.** The decisions are D325–D334 in +[decisions.md](decisions.md). The approved plan is +[mobile-library-plan.md](appendix/mobile-library-plan.md). Progress is in +[progress.md](progress.md), and the evidence in +[release-evidence.md](appendix/release-evidence.md). + +Version 3.1.0 lets an iPhone or Android app use the Athletic Standard library directly. +UniFFI generates a Swift package and an Android library from the Rust library, so an +app gets the same record checks, messages, calculations, and file handling as `ath` +(D325). The record format does not change. + +Local use does not change and needs no account (D75). Offline sync with a host is +separate work ([issue 58](https://github.com/mwhitham/ath/issues/58)). + +## 1. Scope + +In 3.1.0: + +- The `athleticstandard-mobile` crate in `mobile/`, the Swift package `AthleticStandard` + for iOS 17 and later, and the Android library `ai.athleticstandard:athleticstandard` + for API 24 and later (D325, D331). +- Record checks, with values crossing the boundary as JSON text and typed failures + (D329). +- Real athlete files on a phone through the existing store, and picked documents worked + on through a private copy (D327, D328). +- Calculations from records an app supplies and from a file, through one reader + interface. The settings, methods, and receipts move into the core (D326). +- A host client with browser sign-in for Swift and Kotlin (D330). +- A `cli` feature, on by default, that the phone build turns off (D327). +- Release packaging and one fixture bundle that tests every platform (D332, D333). +- Version 3.1.0 and migration step 9 (section 2). + +Not in 3.1.0: + +- Any record field, record type, or list value. +- Device recordings in a memory snapshot. Calculations that read them run on a file + (D326). +- Offline sync with a host (issue 58). +- Publishing. The maintainer publishes the packages (D332). + +## 2. Version and database + +- 3.1.0 is a minor release under D290: it adds packages and library calls, and all + 3.0.0 data stays valid (D334). +- Migration step 9 sets `athleticstandard_version` to 3.1.0 and changes no table. A + 3.0.0 program refuses a step-9 database and asks for an update. +- New packages declare 3.1.0. `ath import` restores 3.1.0 packages and every version + 3.0.0 restores. +- The Open Wearables plan follows as 3.2.0 with migration step 10 and keeps D272–D289 + (D334). + +## 3. Verification and release gates + +Before any commit, the four checks in [AGENTS.md](../../AGENTS.md) pass. Regenerate +every generated file after a version change. + +Release gates (all must pass): + +1. **Model vectors.** Every recorded model vector runs through the Swift package and + the Android library with the desktop outcome, apart from the documented skips. +2. **Calculations.** Every worked example and reader case gives the desktop result + through a phone `Database`. Through a memory snapshot it gives the desktop result, + or the documented refusal for a calculation that reads device recordings. +3. **Round trip.** On each platform the desktop `ath` creates a file, the phone library + edits it, and the desktop `ath` finds the edit, the earlier revision, and a passing + `ath check`. +4. **Installed packages.** The Swift package installed by version and the Android + library installed by coordinate pass every phone test. Every native library in a + shrunk release APK is aligned for 16 KB pages. +5. **Host client.** Both clients pass their tests against a real `ath-host` and the + test sign-in provider. +6. **iPhone simulator.** The Swift tests pass on an iPhone simulator. diff --git a/mobile/README.md b/mobile/README.md index c1afb1d7..ffa1cf36 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -1,7 +1,7 @@ # Athletic Standard for iPhone and Android This folder builds the Athletic Standard library for iPhone and Android apps -([D325](../build-history/v3.0.0/decisions.md#d325-phones-get-the-library-through-uniffi-in-version-300)). +([D325](../build-history/v3.1.0/decisions.md#d325-phones-get-the-library-through-uniffi-in-version-310)). The rules stay in Rust. UniFFI generates the Swift and Kotlin bindings, so an app gets the same record checks, messages, and results as the desktop `ath` program. @@ -16,7 +16,7 @@ gets the same record checks, messages, and results as the desktop `ath` program. The generated Swift and Kotlin, the XCFramework, and the native Android libraries are build output. They are not committed -([D327](../build-history/v3.0.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). +([D327](../build-history/v3.1.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). ## What an app can call @@ -29,7 +29,7 @@ build output. They are not committed Record bodies and results cross as UTF-8 JSON bytes: `Data` in Swift and `ByteArray` in Kotlin -([D329](../build-history/v3.0.0/decisions.md#d329-values-cross-the-boundary-as-json-text-and-failures-are-typed)). +([D329](../build-history/v3.1.0/decisions.md#d329-values-cross-the-boundary-as-json-text-and-failures-are-typed)). Every failure is `AthleticStandardError` in Swift and `AthleticStandardException` in Kotlin. Each has a `code` that matches the desktop error code, a `detail` with the desktop message, and, for an invalid value, `issues`. An issue's `path` keeps field @@ -38,7 +38,7 @@ names and list positions apart. ## Real athlete files `Database` opens one `.ath.sqlite` file through the desktop store -([D327](../build-history/v3.0.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). +([D327](../build-history/v3.1.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). Edits run the same record operations the npm client runs, with the same inputs and outputs as UTF-8 JSON, so they get the same checks and messages: @@ -61,7 +61,7 @@ file. The desktop store refuses a path through a symbolic link. ## Calculations Calculations run the desktop methods on records from memory or from a file -([D326](../build-history/v3.0.0/decisions.md#d326-calculations-ask-for-their-data-through-one-reader-interface)). +([D326](../build-history/v3.1.0/decisions.md#d326-calculations-ask-for-their-data-through-one-reader-interface)). Both entry points give the desktop JSON: the `ath apply --json` object and the `ath calculate --json` receipt. @@ -95,7 +95,7 @@ same request gives the same answer on every device. ### Where to keep the file Recommend local storage, and keep iCloud Drive and other locations selectable -([D328](../build-history/v3.0.0/decisions.md#d328-where-a-phone-keeps-the-file)). +([D328](../build-history/v3.1.0/decisions.md#d328-where-a-phone-keeps-the-file)). `FileLocationAdvice.recommendation` holds the suggested wording: "We recommend keeping your working file on this device. Editing the same file on two devices through iCloud Drive can cause sync conflicts." @@ -118,7 +118,7 @@ through iCloud Drive can cause sync conflicts." ## Connect to a host Local files need no account and no network. Connecting to an `ath-host` is optional -([D330](../build-history/v3.0.0/decisions.md#d330-the-packages-include-a-host-client-with-browser-sign-in)). +([D330](../build-history/v3.1.0/decisions.md#d330-the-packages-include-a-host-client-with-browser-sign-in)). The Swift module `AthleticStandardHost` and the Kotlin package `ai.athleticstandard.host` hold the same client. It needs no native library. @@ -222,7 +222,7 @@ Pass `-Pathleticstandard.rustProfile=debug` for a faster local build. ## Test The tests run one shared bundle of cases that the desktop library writes -([D333](../build-history/v3.0.0/decisions.md#d333-one-fixture-bundle-tests-every-platform)). +([D333](../build-history/v3.1.0/decisions.md#d333-one-fixture-bundle-tests-every-platform)). `mobile/tests/fixtures.rs` runs every case through the binding's Rust functions during `cargo test`, and writes the bundle when `ATH_MOBILE_FIXTURES` names a folder. Each suite file lists its cases, the expected outcome of each, and the skipped cases with @@ -246,7 +246,7 @@ run. On this Mac it uses `swift test`. ## Release Both packages ship with each release and carry its version -([D332](../build-history/v3.0.0/decisions.md#d332-how-the-packages-are-released)). +([D332](../build-history/v3.1.0/decisions.md#d332-how-the-packages-are-released)). Publication stays with the maintainer. - `mobile/scripts/stage-apple.sh ` builds the release XCFramework, zips it with From 320c5bf98a0257bf206770a0fa479bf3b7279f70 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 11:20:55 -0600 Subject: [PATCH 15/30] Move to version 3.1.0 with migration step 9. The program, the record, the database, the npm package, the crates, and the phone packages move to 3.1.0 under D334. Migration step 9 sets athleticstandard_version to 3.1.0 and changes no table, as step 4 did for 2.1.0. New records, packages, and databases declare 3.1.0, and 3.0.0 packages and databases are still read, imported, and migrated. 3.0.0 is released, so its migration, JSON Schemas, and host API description are pinned, and its 31 calculation skills join the released files, so `ath skill install` replaces an unedited 3.0.0 copy (D231). The generated 3.1.0 schemas match the 3.0.0 files except for the version list and the schema IDs. A test checks the published 3.0.0 files against 2.1.3, and another runs step 9 as a file after step 8. The demo database changed only in its metadata row. SPEC.md, the README, the hosting guide, AGENTS.md, and every skill name 3.1.0. The phone tests read the migrated schema step from the test bundle, as they already read the version. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release-mobile-packages.yml | 2 +- AGENTS.md | 2 +- Cargo.lock | 12 +- Cargo.toml | 2 +- README.md | 15 +- SPEC.md | 47 +- build-history/v3.1.0/progress.md | 19 +- core/Cargo.toml | 2 +- core/src/engine.rs | 5 +- core/src/model/package.rs | 9 +- core/src/save.rs | 2 +- docs/connections.md | 2 +- docs/hosting.md | 15 +- examples/demo-athlete/athlete.ath.sqlite | Bin 659456 -> 659456 bytes host/Cargo.toml | 2 +- mobile/Cargo.toml | 2 +- mobile/README.md | 2 +- .../kotlin/ai/athleticstandard/StoreTest.kt | 3 +- mobile/android/consumer/gradle.properties | 2 +- mobile/android/gradle.properties | 2 +- mobile/bindgen/Cargo.toml | 2 +- mobile/src/lib.rs | 2 +- .../AthleticStandardTests/StoreTests.swift | 3 +- mobile/tests/fixtures.rs | 4 +- packages/npm/package.json | 8 +- packages/npm/src/generated/protocol.ts | 4 +- packages/npm/src/schema.ts | 6 +- packages/npm/src/version.ts | 2 +- packages/npm/test/core.test.ts | 2 +- packages/npm/test/database.test.ts | 20 +- packages/npm/test/examples.test.ts | 2 +- packages/npm/test/host.test.ts | 2 +- packages/npm/test/public-api.test.ts | 18 +- schema/3.1.0/athleticstandard.schema.json | 22591 ++++++++++++++++ schema/3.1.0/export-manifest.schema.json | 152 + schema/3.1.0/host-api.json | 4757 ++++ schema/3.1.0/measurement-series.schema.json | 1328 + schema/athleticstandard.schema.json | 5 +- skills/athletic-standard/SKILL.md | 18 +- skills/athletic-standard/references/format.md | 2 +- skills/baseline/SKILL.md | 10 +- skills/best-efforts/SKILL.md | 10 +- skills/compare-sources/SKILL.md | 10 +- skills/correlation/SKILL.md | 10 +- skills/coverage/SKILL.md | 10 +- skills/critical-power/SKILL.md | 10 +- skills/critical-speed/SKILL.md | 10 +- skills/crossfit/SKILL.md | 10 +- skills/heart-rate-recovery/SKILL.md | 10 +- skills/heart-rate-zones/SKILL.md | 10 +- skills/hrv-change/SKILL.md | 10 +- skills/hyrox-race-splits/SKILL.md | 10 +- skills/hyrox/SKILL.md | 10 +- skills/maximum-heart-rate/SKILL.md | 10 +- skills/plan-against-result/SKILL.md | 10 +- skills/power-zones/SKILL.md | 10 +- skills/provider-period-summary/SKILL.md | 10 +- skills/resting-heart-rate-change/SKILL.md | 10 +- skills/resting-heart-rate/SKILL.md | 10 +- skills/sleep-change/SKILL.md | 10 +- skills/sleep-duration/SKILL.md | 10 +- skills/sleep-efficiency/SKILL.md | 10 +- skills/sleep-interruptions/SKILL.md | 10 +- skills/sleep-regularity/SKILL.md | 10 +- skills/sleep-stages/SKILL.md | 10 +- skills/sleep-timing/SKILL.md | 10 +- skills/strength-volume/SKILL.md | 10 +- skills/summary/SKILL.md | 10 +- skills/training-load-effort/SKILL.md | 10 +- skills/training-load-heart-rate/SKILL.md | 10 +- skills/trend/SKILL.md | 10 +- skills/work-capacity-balance/SKILL.md | 10 +- skills/workout-drift/SKILL.md | 10 +- spec/sql/README.md | 11 +- spec/sql/contract.json | 9 +- spec/sql/migrations/009-version-3-1-0.sql | 11 + src/assets/skill.rs | 36 +- src/store/migrate.rs | 6 + src/store/mod.rs | 3 +- tests/cli_golden.rs | 13 +- tests/migration.rs | 18 +- tests/published_files.rs | 10 +- tests/published_schema.rs | 45 +- tests/record_3_0_0.rs | 18 +- tests/skill_install.rs | 3 +- tools/public-data-allowlist.json | 2 +- wasm/Cargo.toml | 2 +- 87 files changed, 29273 insertions(+), 319 deletions(-) create mode 100644 schema/3.1.0/athleticstandard.schema.json create mode 100644 schema/3.1.0/export-manifest.schema.json create mode 100644 schema/3.1.0/host-api.json create mode 100644 schema/3.1.0/measurement-series.schema.json create mode 100644 spec/sql/migrations/009-version-3-1-0.sql diff --git a/.github/workflows/release-mobile-packages.yml b/.github/workflows/release-mobile-packages.yml index 9ebac9c8..218de151 100644 --- a/.github/workflows/release-mobile-packages.yml +++ b/.github/workflows/release-mobile-packages.yml @@ -17,7 +17,7 @@ on: workflow_dispatch: inputs: tag: - description: The released version tag, such as v3.0.0 + description: The released version tag, such as v3.1.0 required: true type: string diff --git a/AGENTS.md b/AGENTS.md index 33fd8ebd..f3274c80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ D83's native use of Zod and D93's local libSQL adapter. - **The two-tier wall:** measured records and athlete reports never mix. Measured records require a `source` reference; athlete reports structurally cannot claim one. Never weaken this. - **`build-history/` is append-only.** New plans get a new version folder, named for the format version it produces (`v0.2.0/`, `v1.0.0/`). D-numbers continue across folders — D25 follows D24. Within a version, append new decisions to `decisions.md`. Supporting research goes in `appendix/` and is linked from the D-number. Don't rewrite earlier D-numbers or earlier version folders. A draft that was not approved goes, unchanged, into the `appendix/` of the version that replaced it, as `draft-/` (D224). -- **The Rust model is the source of truth.** After changing the model (`core/src/model/`), a command or its help (`src/cli/`), a protocol operation (`src/protocol/`), or a host API operation or body (`host/src/operations.rs`, `host/src/shapes.rs`), run `ATH_WRITE_GENERATED=1 cargo test --test generated` and commit the regenerated files: JSON Schema in `schema/3.0.0/` and `schema/athleticstandard.schema.json`, `packages/npm/src/generated/protocol.ts`, `skills/athletic-standard/references/cli.md` (D80), the host API description in `schema/3.0.0/host-api.json` (D266, D324), and the demo database in `examples/demo-athlete/`. `cargo test --test generated` fails when a committed copy is behind. Generators never rewrite a published historical schema, `spec/sql/`, or `tests/fixtures/`. +- **The Rust model is the source of truth.** After changing the model (`core/src/model/`), a command or its help (`src/cli/`), a protocol operation (`src/protocol/`), or a host API operation or body (`host/src/operations.rs`, `host/src/shapes.rs`), run `ATH_WRITE_GENERATED=1 cargo test --test generated` and commit the regenerated files: JSON Schema in `schema/3.1.0/` and `schema/athleticstandard.schema.json`, `packages/npm/src/generated/protocol.ts`, `skills/athletic-standard/references/cli.md` (D80), the host API description in `schema/3.1.0/host-api.json` (D266, D324), and the demo database in `examples/demo-athlete/`. `cargo test --test generated` fails when a committed copy is behind. Generators never rewrite a published historical schema, `spec/sql/`, or `tests/fixtures/`. - **Naming:** "Athletic Standard" in prose; `athleticstandard` for the npm package, file extension, and version field; `ath` is the CLI command; `AthleticStandard` in code identifiers. - **Keep the repo impersonal:** no personal objectives, audience/positioning framing, or individual names in committed content. - **Never commit real health data.** Real exports stay outside Git, including private repositories. Public tests use only the synthetic files listed in `tools/public-data-allowlist.json`; `tests/public_data.rs` enforces the list and the `.gitignore` rules. diff --git a/Cargo.lock b/Cargo.lock index 1440aa8f..ef98d58f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -181,7 +181,7 @@ dependencies = [ [[package]] name = "athleticstandard" -version = "3.0.0" +version = "3.1.0" dependencies = [ "athleticstandard-core", "chrono", @@ -203,7 +203,7 @@ dependencies = [ [[package]] name = "athleticstandard-core" -version = "3.0.0" +version = "3.1.0" dependencies = [ "chrono", "chrono-tz", @@ -215,7 +215,7 @@ dependencies = [ [[package]] name = "athleticstandard-host" -version = "3.0.0" +version = "3.1.0" dependencies = [ "athleticstandard", "axum", @@ -236,7 +236,7 @@ dependencies = [ [[package]] name = "athleticstandard-mobile" -version = "3.0.0" +version = "3.1.0" dependencies = [ "athleticstandard", "athleticstandard-core", @@ -250,14 +250,14 @@ dependencies = [ [[package]] name = "athleticstandard-uniffi-bindgen" -version = "3.0.0" +version = "3.1.0" dependencies = [ "uniffi", ] [[package]] name = "athleticstandard-wasm" -version = "3.0.0" +version = "3.1.0" dependencies = [ "athleticstandard-core", ] diff --git a/Cargo.toml b/Cargo.toml index 1eb0f327..713558cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "athleticstandard" -version = "3.0.0" +version = "3.1.0" edition = "2021" rust-version = "1.95" description = "Athletic Standard: a local-first SQLite record of an athlete's training and recovery data" diff --git a/README.md b/README.md index c1f8d6aa..cf6eb38a 100644 --- a/README.md +++ b/README.md @@ -96,13 +96,15 @@ summaries and adds coaching notes with it. ## Upgrade a database -A database from version 1.0.0, 2.0.0, 2.1.0, 2.1.1, or 2.1.2 upgrades with `ath migrate`. The -command shows a preview first. It makes a verified backup with SQLite's own backup +A database from version 1.0.0, 2.0.0, 2.1.0, 2.1.1, 2.1.2, 2.1.3, or 3.0.0 upgrades with +`ath migrate`. The command shows a preview first. It makes a verified backup with SQLite's own backup interface before the first schema write. Opening a database never migrates it without confirmation. To go back, restore the backup; it does not contain work recorded after it was made. [`docs/upgrading-to-2-1-2.md`](docs/upgrading-to-2-1-2.md) lists what 2.1.2 changes, including the repaired calculation methods. [`docs/upgrading-to-2-1-1.md`](docs/upgrading-to-2-1-1.md) covers the 2.1.1 rebuild. +[`docs/upgrading-to-3-0-0.md`](docs/upgrading-to-3-0-0.md) covers 3.0.0. A 3.0.0 +database moves to 3.1.0 with one step that records the version and changes no table. When typed-table columns disagree with the current revision in meaning (for example after direct SQL edits), run `ath repair -y --from-revision @@ -439,10 +441,11 @@ keeps the ID. Evidence names both the record ID and revision. The format defines 29 record types for profile data, sources, measurements, sessions, athlete reports, nutrition, attachments, benchmarks, predictions, plans, goals, intensity references, events, approvals, and saved authored work and calculation results. [`SPEC.md`](SPEC.md) is the public field reference. -The generated JSON Schemas are in [`schema/3.0.0/`](schema/3.0.0/). The published -2.0.0, 2.1.0, 2.1.1, 2.1.2, and 2.1.3 schemas stay in [`schema/2.0.0/`](schema/2.0.0/), -[`schema/2.1.0/`](schema/2.1.0/), [`schema/2.1.1/`](schema/2.1.1/), -[`schema/2.1.2/`](schema/2.1.2/), and [`schema/2.1.3/`](schema/2.1.3/). +The generated JSON Schemas are in [`schema/3.1.0/`](schema/3.1.0/). The published +2.0.0, 2.1.0, 2.1.1, 2.1.2, 2.1.3, and 3.0.0 schemas stay in +[`schema/2.0.0/`](schema/2.0.0/), [`schema/2.1.0/`](schema/2.1.0/), +[`schema/2.1.1/`](schema/2.1.1/), [`schema/2.1.2/`](schema/2.1.2/), +[`schema/2.1.3/`](schema/2.1.3/), and [`schema/3.0.0/`](schema/3.0.0/). How the code is organized, and the path of one import and one correction to disk, is in [`docs/architecture.md`](docs/architecture.md). diff --git a/SPEC.md b/SPEC.md index 6c6ddbd9..bb70dd80 100644 --- a/SPEC.md +++ b/SPEC.md @@ -1,15 +1,15 @@ -# Athletic Standard Format Specification v3.0.0 +# Athletic Standard Format Specification v3.1.0 **Status:** current format **Live local file:** `athlete.ath.sqlite` **Portable package:** `athlete.ath.json` plus generated files **Normative model:** the Rust record model in [`core/src/model/`](core/src/model/) and its semantic checks -**Generated JSON Schemas:** [`schema/3.0.0/`](schema/3.0.0/), generated from that -model. The published 2.0.0, 2.1.0, 2.1.1, 2.1.2, and 2.1.3 schemas stay in +**Generated JSON Schemas:** [`schema/3.1.0/`](schema/3.1.0/), generated from that +model. The published 2.0.0, 2.1.0, 2.1.1, 2.1.2, 2.1.3, and 3.0.0 schemas stay in [`schema/2.0.0/`](schema/2.0.0/), [`schema/2.1.0/`](schema/2.1.0/), -[`schema/2.1.1/`](schema/2.1.1/), [`schema/2.1.2/`](schema/2.1.2/), and -[`schema/2.1.3/`](schema/2.1.3/). +[`schema/2.1.1/`](schema/2.1.1/), [`schema/2.1.2/`](schema/2.1.2/), +[`schema/2.1.3/`](schema/2.1.3/), and [`schema/3.0.0/`](schema/3.0.0/). Version 2.0.0 adds workout names, descriptions, text results, heart-rate samples, strength sets, route points, and `supplied_fields` for names the @@ -39,11 +39,17 @@ database upgrades with `ath migrate` to SQL schema step 7, which adds four inter tables (section 7.3). The optional host program that uses them is planned in [`build-history/v2.1.3/spec.md`](build-history/v2.1.3/spec.md). -Version 3.0.0 is planned in -[`build-history/v3.0.0/spec.md`](build-history/v3.0.0/spec.md) and is being built. -A version 2.1.3 database upgrades with `ath migrate` to SQL schema step 8. Step 8 -rebuilds the `records` table once, so that record types are rows in a lookup -table, `record_types` (section 7.2). Every record and revision stays as it is. +Version 3.0.0 adds thresholds, events, approvals, interval targets, device +recordings, saved calculation results, and injury and illness reports. It is in +[`build-history/v3.0.0/spec.md`](build-history/v3.0.0/spec.md). A version 2.1.3 +database upgrades with `ath migrate` to SQL schema step 8. Step 8 rebuilds the +`records` table once, so that record types are rows in a lookup table, +`record_types` (section 7.2). Every record and revision stays as it is. + +Version 3.1.0 changes no record field. It adds the library for iPhone and Android +apps. A version 3.0.0 database upgrades with `ath migrate` to SQL schema step 9, +which records the version and changes no table. The behavior is in +[`build-history/v3.1.0/spec.md`](build-history/v3.1.0/spec.md). Athletic Standard is an open, local-first record for one athlete's training and recovery data. SQLite is the sole live local record. JSON is an explicit, complete @@ -1101,7 +1107,7 @@ a version before 3.0.0 cannot contain a record of a 3.0.0 type. |---|---| | `application_marker` | `ATH1` | | `sql_schema_version` | Positive SQL migration version | -| `athleticstandard_version` | `3.0.0` | +| `athleticstandard_version` | `3.1.0` | | `database_id` | Stable UUIDv7 database ID | | `created_at` | Database creation timestamp | @@ -1464,7 +1470,7 @@ A v1 package import: and erasure markers; - refuses unknown fields and records it cannot represent; - does not delete a local record merely because the package omits it; -- accepts a `2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, `2.1.3`, or `3.0.0` package; +- accepts a `2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, `2.1.3`, `3.0.0`, or `3.1.0` package; - refuses prerelease Athletic Standard versions below `1.0.0`. A FIT activity file (3.0.0) becomes one workout per session. The workout gets @@ -1558,7 +1564,7 @@ backup operation. A closed, checkpointed database may be copied. ## 13. Version behavior -The program, the record, and the database use one version, `3.0.0` (D152, D184, +The program, the record, and the database use one version, `3.1.0` (D152, D184, D208, D290). The portable document, generated series files, export manifest, and live database metadata all carry that version. @@ -1573,12 +1579,15 @@ The version number says what kind of change a release makes (D290): Versions 2.1.2 and 2.1.3 were released under the earlier rule, which named only optional fields, and are recorded exceptions to it (D227, D254). Version 3.0.0 is major because new writes refuse two workout fields (D301). Every 2.x record that -does not use them stays valid 3.0.0 data. - -`ath migrate` moves a `2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, or `2.1.3` database to -`3.0.0` without changing its records. Software before 2.1.1 refuses a database at SQL -schema step 5, software before 2.1.2 refuses one at step 6, software before 2.1.3 -refuses one at step 7, and software before 3.0.0 refuses one at step 8. +does not use them stays valid 3.0.0 data. Version 3.1.0 is minor: it adds the library +for iPhone and Android apps and changes no record field, so all 3.0.0 data stays valid +3.1.0 data (D334). + +`ath migrate` moves a `2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, `2.1.3`, or `3.0.0` database +to `3.1.0` without changing its records. Software before 2.1.1 refuses a database at +SQL schema step 5, software before 2.1.2 refuses one at step 6, software before 2.1.3 +refuses one at step 7, software before 3.0.0 refuses one at step 8, and software +before 3.1.0 refuses one at step 9. Normative package and record data objects are strict. Unknown fields are rejected. The v1 importer refuses Athletic Standard `0.x` documents without modifying them. diff --git a/build-history/v3.1.0/progress.md b/build-history/v3.1.0/progress.md index e3c24282..cd7c7d2f 100644 --- a/build-history/v3.1.0/progress.md +++ b/build-history/v3.1.0/progress.md @@ -11,7 +11,7 @@ Status: **built; not released.** The plan is [spec.md](spec.md). Evidence: | 4 | Calculations from memory and SQLite through one reader interface | Mac and two Android emulators pass; iPhone simulator not run | | 5 | Host client for Swift and Kotlin with browser sign-in | Mac and two Android emulators pass against a real host; live WorkOS not run | | 6 | Release packaging, phone test runs, release gate | staged and installed locally; CI, simulator, and publication not run | -| 7 | Version 3.1.0 and migration step 9 | not started | +| 7 | Version 3.1.0 and migration step 9 | done | The phone work was built on 3.0.0 as build steps 12 to 17, and moved here when 3.0.0 was released without it (D334). @@ -133,3 +133,20 @@ was released without it (D334). - Runnable examples: the consumer app is the Android example, and `swift run AthleticStandardExample` is the Swift one. The Android example ran offline on an emulator. The Swift example builds; its window was not opened. + +## Step 7: version 3.1.0 and migration step 9 + +- The program, the record, the database, the npm package, the crates, and the phone + packages are 3.1.0 (D334). New records, packages, and databases declare it; 3.0.0 + packages and databases are still read, imported, and migrated. +- Migration step 9 (`spec/sql/migrations/009-version-3-1-0.sql`) sets + `athleticstandard_version` to 3.1.0 and changes no table. A test runs it as a file + after step 8, as a direct-SQL client would. The demo database changed only in its + metadata row. +- 3.0.0 is released, so its migration, its three JSON Schemas, and its host API + description are pinned (`tests/published_files.rs`). The generated 3.1.0 schemas + match the 3.0.0 files except for the version list and the schema IDs, and a test + checks the published 3.0.0 files against 2.1.3. +- The 31 calculation skills of 3.0.0 joined the list of released files, so + `ath skill install` replaces an unedited 3.0.0 copy and keeps an edited one (D231). +- `SPEC.md`, the README, the hosting guide, `AGENTS.md`, and every skill name 3.1.0. diff --git a/core/Cargo.toml b/core/Cargo.toml index 1aaeda71..0320b703 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "athleticstandard-core" -version = "3.0.0" +version = "3.1.0" edition = "2021" rust-version = "1.95" description = "Athletic Standard core: the record model, its checks, the arithmetic, and the exact database changes a save needs, with no file, database, or network access" diff --git a/core/src/engine.rs b/core/src/engine.rs index cb514334..14477103 100644 --- a/core/src/engine.rs +++ b/core/src/engine.rs @@ -214,7 +214,10 @@ mod tests { #[test] fn a_request_is_answered_or_refused_plainly() { let answer = call_text(r#"{"op":"version"}"#); - assert!(answer.contains(r#""ok":true"#) && answer.contains("3.0.0"), "{answer}"); + assert!( + answer.contains(r#""ok":true"#) && answer.contains(crate::model::ATHLETIC_STANDARD_VERSION), + "{answer}" + ); let fit = call_text( r#"{"op":"thresholds.critical_power_linear_work_time","efforts":[ {"duration_s":180,"mean":360},{"duration_s":420,"mean":298}, diff --git a/core/src/model/package.rs b/core/src/model/package.rs index 58c84109..88978849 100644 --- a/core/src/model/package.rs +++ b/core/src/model/package.rs @@ -16,15 +16,15 @@ use crate::json::{self, Value}; use crate::{model_enum, model_object}; /// The software, record, and database version (D152). -pub const ATHLETIC_STANDARD_VERSION: &str = "3.0.0"; +pub const ATHLETIC_STANDARD_VERSION: &str = "3.1.0"; /// Record files this software can read. New writes use `ATHLETIC_STANDARD_VERSION`. -pub const ACCEPTED_RECORD_VERSIONS: &[&str] = &["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0"]; +pub const ACCEPTED_RECORD_VERSIONS: &[&str] = &["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", "3.1.0"]; /// Package versions `ath import` restores. 2.1.x and 2.0.0 packages share the /// same fields. 3.0.0 adds record types and fields, and every 2.x package -/// stays valid (D290). -pub const IMPORTABLE_PACKAGE_VERSIONS: &[&str] = &["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0"]; +/// stays valid (D290). 3.1.0 packages have the 3.0.0 fields (D334). +pub const IMPORTABLE_PACKAGE_VERSIONS: &[&str] = &["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", "3.1.0"]; model_enum! { pub enum RecordFormatVersion { @@ -35,6 +35,7 @@ model_enum! { V2_1_2 = "2.1.2", V2_1_3 = "2.1.3", V3_0_0 = "3.0.0", + V3_1_0 = "3.1.0", } } diff --git a/core/src/save.rs b/core/src/save.rs index bbfd2d61..48a03e23 100644 --- a/core/src/save.rs +++ b/core/src/save.rs @@ -12,7 +12,7 @@ use crate::json; use crate::model::*; /// The SQL schema step this core writes. -pub const SQL_SCHEMA_VERSION: u32 = 8; +pub const SQL_SCHEMA_VERSION: u32 = 9; /// One SQL value, as SQLite stores it. #[derive(Debug, Clone, PartialEq, serde::Serialize)] diff --git a/docs/connections.md b/docs/connections.md index d4c9933c..567f2039 100644 --- a/docs/connections.md +++ b/docs/connections.md @@ -130,5 +130,5 @@ Universal advice, stated in the README: a CSV or zip export has the data you nee | 1 (v0.2.0) | Importers: Apple Health export.zip, WHOOP CSV, Oura CSV | ✅ shipped | | 2 (fast-follow) | `ath pull`: Oura personal-token pull (easiest), OW connector (multi-provider), WHOOP direct | designed-for (source kinds + dedup already in the spec) | | 2.0.0 | Garmin account JSON, GPX, FIT record points, and a one-day personal pull | shipped | -| 3.0.0 | Every FIT reading as device recordings, FIT totals, laps, sport, timer stops, weather, and zone settings | being built | +| 3.0.0 | Every FIT reading as device recordings, FIT totals, laps, sport, timer stops, weather, and zone settings | shipped | | 3 (v2) | iOS companion app for Apple Watch users | v2 flagship | diff --git a/docs/hosting.md b/docs/hosting.md index 20867987..60cf6791 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -5,7 +5,7 @@ athlete can let a coach read workout summaries and add notes and programming. Ap reach the records through a versioned API. This guide is for people who run a host and for people who write apps that call one. -The guide describes the code in [`host/`](../host/) as it is in version 3.0.0. +The guide describes the code in [`host/`](../host/) as it is in version 3.1.0. Where a plan asks for something the code does not do yet, the guide says so. The host was planned in [2.1.3](../build-history/v2.1.3/spec.md) (D254–D271); version [3.0.0](../build-history/v3.0.0/spec.md) adds the seven coach permissions (D315), @@ -41,7 +41,7 @@ What is built today: | `ath-host backup` and `ath-host restore` (section 10) | Built and covered by tests. `restore` works in directory mode only. | | A Litestream recipe | Not published. It has not been run with the library (D264). | | Clients: the npm host client `connectHost`, a starter app, and an example MCP server | Built. See section 7. | -| A generated description of the API (D266) | Built: `schema/3.0.0/host-api.json`, from the operation table in `host/src/operations.rs` (section 7). | +| A generated description of the API (D266) | Built: `schema/3.1.0/host-api.json`, from the operation table in `host/src/operations.rs` (section 7). | ## 2. Choosing a backend @@ -267,7 +267,7 @@ ath-host version (section 10.3). - `migrate` brings athletes' databases an older host wrote to this version's SQL step, keeping a restore copy of each first (section 10.8). -- `version` prints `ath-host 3.0.0`. +- `version` prints `ath-host 3.1.0`. `setup`, `invite`, and `backup` can run while the host serves. They do not delete the host's working copies or staged files. In remote mode, give `backup` its own data @@ -769,9 +769,10 @@ for the `basic` scope. ## 7. API version 1 The routes are described in OpenAPI 3.1 in -[`schema/3.0.0/host-api.json`](../schema/3.0.0/host-api.json), beside the record -schemas of the same version (D324). The copy released with 2.1.3 stays in -[`schema/host-api/1/openapi.json`](../schema/host-api/1/openapi.json). The description +[`schema/3.1.0/host-api.json`](../schema/3.1.0/host-api.json), beside the record +schemas of the same version (D324). The copies released with 2.1.3 and 3.0.0 stay in +[`schema/host-api/1/openapi.json`](../schema/host-api/1/openapi.json) and +[`schema/3.0.0/host-api.json`](../schema/3.0.0/host-api.json). The description is generated from the same Rust table the host builds its routes from, so it lists exactly the routes the host serves (D266, D271). Records and revisions in it point to the published package schemas in `schema//`. @@ -1312,7 +1313,7 @@ record with your own access checks, as `ath-host` does with grants. ### 13.3 Edge platform databases Storing records in edge platform databases, such as Cloudflare D1 or Durable Objects, -is not supported in 3.0.0 (D316). A study follows (#61). A builder who tries should: +is not supported in 3.0.0 or 3.1.0 (D316). A study follows (#61). A builder who tries should: - use a store with a real transaction for each athlete's database; - keep the version in the metadata table, as a libSQL server needs (D258); diff --git a/examples/demo-athlete/athlete.ath.sqlite b/examples/demo-athlete/athlete.ath.sqlite index ee68f790393b47f2ce2b9b99ede13a785f752474..f35bbe1ddd2ebf3a9d2a13d79e3bf203ae803126 100644 GIT binary patch delta 66 zcmZozpwX~EV}d;+=SGJ*c{WaCJwrW%$s22xo1e?KKbL0&VkRJF24WT;02&P#zW@LL delta 66 zcmZozpwX~EV}d;+$3}-bc{UDXJp(<1$s22xo1e?KKbL0&VkRJF24WT;02y%@yZ`_I diff --git a/host/Cargo.toml b/host/Cargo.toml index 4ea3ed9b..a3073ffd 100644 --- a/host/Cargo.toml +++ b/host/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "athleticstandard-host" -version = "3.0.0" +version = "3.1.0" edition = "2021" rust-version = "1.95" description = "ath-host: an optional program that serves many athletes' Athletic Standard records over HTTPS" diff --git a/mobile/Cargo.toml b/mobile/Cargo.toml index 777cf07a..f44f928e 100644 --- a/mobile/Cargo.toml +++ b/mobile/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "athleticstandard-mobile" -version = "3.0.0" +version = "3.1.0" edition = "2021" rust-version = "1.95" description = "Athletic Standard for iPhone and Android apps: UniFFI bindings to the record checks, calculations, and SQLite store" diff --git a/mobile/README.md b/mobile/README.md index ffa1cf36..1490271e 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -20,7 +20,7 @@ build output. They are not committed ## What an app can call -- `libraryVersion()`: the version this library writes and reports, such as `3.0.0`. +- `libraryVersion()`: the version this library writes and reports, such as `3.1.0`. - `validate(shape:json:)`: check UTF-8 JSON against a published shape, such as `CurrentRecord` or `WorkoutSessionData`. It returns the checked JSON, or throws `AthleticStandardError.Invalid` with every issue in the desktop order. diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt index 0ddcc803..ea3bdca6 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt @@ -131,7 +131,8 @@ class StoreTest { outdated.closeDatabase() assertTrue(backup.exists()) val migrated = Database.open(file.path, OpenDatabaseOptions()) - assertEquals(8u, migrated.info().sqlSchemaVersion) + val step = FixtureBundle.suite("library").getLong("sql_schema_version").toUInt() + assertEquals(step, migrated.info().sqlSchemaVersion) migrated.closeDatabase() } diff --git a/mobile/android/consumer/gradle.properties b/mobile/android/consumer/gradle.properties index dbf096f0..3f1424e4 100644 --- a/mobile/android/consumer/gradle.properties +++ b/mobile/android/consumer/gradle.properties @@ -1,3 +1,3 @@ org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 android.useAndroidX=true -athleticstandard.version=3.0.0 +athleticstandard.version=3.1.0 diff --git a/mobile/android/gradle.properties b/mobile/android/gradle.properties index 6f5f325b..21f5f61f 100644 --- a/mobile/android/gradle.properties +++ b/mobile/android/gradle.properties @@ -2,4 +2,4 @@ org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 android.useAndroidX=true # The version the library reports and publishes. It must equal the Rust crates' # version (D152); the release checks both. -athleticstandard.version=3.0.0 +athleticstandard.version=3.1.0 diff --git a/mobile/bindgen/Cargo.toml b/mobile/bindgen/Cargo.toml index aa445e51..4c8246c4 100644 --- a/mobile/bindgen/Cargo.toml +++ b/mobile/bindgen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "athleticstandard-uniffi-bindgen" -version = "3.0.0" +version = "3.1.0" edition = "2021" rust-version = "1.95" description = "Generates the Swift and Kotlin bindings for athleticstandard-mobile with the locked UniFFI version" diff --git a/mobile/src/lib.rs b/mobile/src/lib.rs index 0ff6a5c1..dc92d442 100644 --- a/mobile/src/lib.rs +++ b/mobile/src/lib.rs @@ -30,7 +30,7 @@ pub use store::{ pub use validate::{validate, validate_current_record}; /// The Athletic Standard version this library writes and reports, such as -/// `3.0.0`. The packages and the desktop program share it (D152). +/// `3.1.0`. The packages and the desktop program share it (D152). #[uniffi::export] pub fn library_version() -> String { athleticstandard_core::model::package::ATHLETIC_STANDARD_VERSION.to_string() diff --git a/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift b/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift index c6b32ded..2e2266f4 100644 --- a/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift +++ b/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift @@ -109,7 +109,8 @@ struct StoreTests { try outdated.close() #expect(FileManager.default.fileExists(atPath: backup.path)) let migrated = try Database.open(path: url.path, options: OpenDatabaseOptions()) - #expect(try migrated.info().sqlSchemaVersion == 8) + let step = try #require(try FixtureBundle.suite("library")["sql_schema_version"] as? Int) + #expect(try migrated.info().sqlSchemaVersion == UInt32(step)) } @Test func savedCopyHoldsEditsStillInTheLog() throws { diff --git a/mobile/tests/fixtures.rs b/mobile/tests/fixtures.rs index d3b196ff..14aabf3d 100644 --- a/mobile/tests/fixtures.rs +++ b/mobile/tests/fixtures.rs @@ -153,9 +153,11 @@ fn storage_files_are_exported() { std::fs::create_dir_all(folder).unwrap(); std::fs::copy(&outdated, folder.join("outdated-2-1-0.ath.sqlite")).unwrap(); } - // The version every phone build must report. + // The version every phone build must report, and the SQL schema step a + // migrated file reaches. let mut library = Map::new(); library.insert("version".into(), Value::String(athleticstandard_mobile::library_version())); + library.insert("sql_schema_version".into(), Value::from(u64::from(athleticstandard::store::SQL_SCHEMA_VERSION))); export("library", Value::Object(library)); } diff --git a/packages/npm/package.json b/packages/npm/package.json index 3eb3ebcd..e431edcc 100644 --- a/packages/npm/package.json +++ b/packages/npm/package.json @@ -1,6 +1,6 @@ { "name": "athleticstandard", - "version": "3.0.0", + "version": "3.1.0", "description": "An open, local-first SQLite format for an athlete's training and recovery data, with complete JSON import and export.", "license": "MIT", "homepage": "https://ath.fit", @@ -58,9 +58,9 @@ "import": "./dist/core.js" }, "./core/wasm": "./core/athleticstandard_core.wasm", - "./json-schema": "./schema/3.0.0/athleticstandard.schema.json", - "./json-schema/export-manifest": "./schema/3.0.0/export-manifest.schema.json", - "./json-schema/measurement-series": "./schema/3.0.0/measurement-series.schema.json", + "./json-schema": "./schema/3.1.0/athleticstandard.schema.json", + "./json-schema/export-manifest": "./schema/3.1.0/export-manifest.schema.json", + "./json-schema/measurement-series": "./schema/3.1.0/measurement-series.schema.json", "./skill": "./skills/athletic-standard/SKILL.md" }, "bin": { diff --git a/packages/npm/src/generated/protocol.ts b/packages/npm/src/generated/protocol.ts index b4502736..079f2d17 100644 --- a/packages/npm/src/generated/protocol.ts +++ b/packages/npm/src/generated/protocol.ts @@ -21,8 +21,8 @@ export const WORKER_ARGUMENT = "__client" as const; /** Values the native library defines and the JavaScript exports repeat. */ export const NATIVE_CONSTANTS = { - ATHLETIC_STANDARD_VERSION: "3.0.0", - SQL_SCHEMA_VERSION: 8, + ATHLETIC_STANDARD_VERSION: "3.1.0", + SQL_SCHEMA_VERSION: 9, SQLITE_APPLICATION_ID: 1096042545, SQLITE_APPLICATION_MARKER: "ATH1", MAX_ATTACHMENT_BYTES: 26214400, diff --git a/packages/npm/src/schema.ts b/packages/npm/src/schema.ts index b41dab60..74537525 100644 --- a/packages/npm/src/schema.ts +++ b/packages/npm/src/schema.ts @@ -19,16 +19,16 @@ import { z } from "zod"; import { RecordExtensions, validateExtensionsForRecordType } from "./extensions.js"; -export const ATHLETIC_STANDARD_VERSION = "3.0.0"; +export const ATHLETIC_STANDARD_VERSION = "3.1.0"; /** Record files this software can read. New writes use ATHLETIC_STANDARD_VERSION. */ -export const ACCEPTED_RECORD_VERSIONS = ["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0"] as const; +export const ACCEPTED_RECORD_VERSIONS = ["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", "3.1.0"] as const; /** * Package versions `ath import` restores. A minor version only adds optional * fields, so a 2.0.0 package is valid 2.1.0 data. */ -export const IMPORTABLE_PACKAGE_VERSIONS = ["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", ATHLETIC_STANDARD_VERSION] as const; +export const IMPORTABLE_PACKAGE_VERSIONS = ["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", ATHLETIC_STANDARD_VERSION] as const; export const RecordFormatVersion = z.enum(ACCEPTED_RECORD_VERSIONS); diff --git a/packages/npm/src/version.ts b/packages/npm/src/version.ts index adf78d4a..b7c63c1f 100644 --- a/packages/npm/src/version.ts +++ b/packages/npm/src/version.ts @@ -1,4 +1,4 @@ /** * The software version. The record and the database use this same number. */ -export const ATH_PACKAGE_VERSION = "3.0.0"; +export const ATH_PACKAGE_VERSION = "3.1.0"; diff --git a/packages/npm/test/core.test.ts b/packages/npm/test/core.test.ts index 6948eb08..0aaea182 100644 --- a/packages/npm/test/core.test.ts +++ b/packages/npm/test/core.test.ts @@ -17,7 +17,7 @@ describe.skipIf(!existsSync(modulePath))("the WebAssembly core", () => { const core = await loadCore(new Uint8Array(readFileSync(modulePath))); expect(core.call({ op: "version" })).toEqual({ ok: true, - result: { athleticstandard_version: "3.0.0", sql_schema_version: 8 }, + result: { athleticstandard_version: "3.1.0", sql_schema_version: 9 }, }); const fit = core.call({ op: "thresholds.critical_power_linear_work_time", diff --git a/packages/npm/test/database.test.ts b/packages/npm/test/database.test.ts index ef7abb87..34df4c43 100644 --- a/packages/npm/test/database.test.ts +++ b/packages/npm/test/database.test.ts @@ -39,8 +39,8 @@ describe("handles", () => { }); expect(await database.readDatabaseMetadata(created)).toEqual({ application_marker: "ATH1", - sql_schema_version: 8, - athleticstandard_version: "3.0.0", + sql_schema_version: 9, + athleticstandard_version: "3.1.0", database_id: "01890f3e-e7d3-7cc0-88c8-000000000001", created_at: "2026-01-01T00:00:00.000Z", }); @@ -56,7 +56,7 @@ describe("handles", () => { expect((await database.readDatabaseMetadata(opened)).database_id).toBe("01890f3e-e7d3-7cc0-88c8-000000000001"); const inspected = await database.inspectDatabase(`file://${path}`); expect(inspected.localPath).toBe(path); - expect((await database.readDatabaseMetadata(inspected)).sql_schema_version).toBe(8); + expect((await database.readDatabaseMetadata(inspected)).sql_schema_version).toBe(9); await database.releaseLocalDatabase(opened); database.markSkipWalCheckpointOnRelease(inspected); await database.releaseLocalDatabase(inspected); @@ -375,12 +375,12 @@ describe("checks, statistics, and repair", () => { it("checks and summarizes the database", async () => { const check = await database.checkDatabase(scenario.handle); expect(check).toMatchObject({ valid: true, issues: [] }); - expect(check.metadata?.athleticstandard_version).toBe("3.0.0"); + expect(check.metadata?.athleticstandard_version).toBe("3.1.0"); const stats = await database.databaseStats(scenario.handle); expect(stats.current_records.by_type).toMatchObject({ point_measurement: 5, benchmark_result: 3 }); expect(stats.benchmarks).toEqual({ defined: 1, results: 3 }); const text = database.renderDatabaseStats(stats); - expect(text).toContain("unnamed athlete · Athletic Standard 3.0.0"); + expect(text).toContain("unnamed athlete · Athletic Standard 3.1.0"); expect(text).toContain("benchmarks defined: 1 · results recorded: 3"); }); @@ -404,9 +404,9 @@ describe("checks, statistics, and repair", () => { const required = error as InstanceType; expect(required.name).toBe("MigrationRequiredError"); expect(required.preview.source_sql_schema_version).toBe(1); - expect(required.preview.target_sql_schema_version).toBe(8); + expect(required.preview.target_sql_schema_version).toBe(9); expect(required.message).toBe( - "Database SQL schema 1 must be upgraded to 8 before other commands can run. Run ath migrate.", + "Database SQL schema 1 must be upgraded to 9 before other commands can run. Run ath migrate.", ); } const handle = await database.openDatabase(copy, { allowOutdatedSchema: true, deferWal: true }); @@ -414,7 +414,7 @@ describe("checks, statistics, and repair", () => { expect(database.databaseNeedsMigration(metadata)).toBe(true); expect(await database.countProviderEncodingRepairCandidates(handle)).toBeGreaterThan(0); const preview = database.buildMigrationPreview(metadata, copy, new Date("2026-01-15T12:00:00.123Z")); - expect(preview.planned_steps.map((step) => step.target_sql_schema_version)).toEqual([2, 3, 4, 5, 6, 7, 8]); + expect(preview.planned_steps.map((step) => step.target_sql_schema_version)).toEqual([2, 3, 4, 5, 6, 7, 8, 9]); expect(preview.planned_backup_path).toMatch(/\.migration-backup\.20260115T120000\.123Z-\d+\.sqlite$/); const backup = join(folder, "npm-100.backup.sqlite"); @@ -434,7 +434,7 @@ describe("checks, statistics, and repair", () => { copyFileSync(join(repositoryRoot, "tests", "fixtures", "npm-100-encoding", "athlete.ath.sqlite"), second); const other = await database.openDatabase(second, { allowOutdatedSchema: true }); await database.migrateDatabase(other); - expect((await database.readDatabaseMetadata(other)).sql_schema_version).toBe(8); + expect((await database.readDatabaseMetadata(other)).sql_schema_version).toBe(9); await database.applyPendingDatabaseMigrations(other); other.close(); }); @@ -573,7 +573,7 @@ describe("grades, evidence, and backtests", () => { }, }); expect(requests.length).toBeGreaterThan(0); - expect(report.athleticstandard_version).toBe("3.0.0"); + expect(report.athleticstandard_version).toBe("3.1.0"); expect(report.skipped_first_result_count).toBe(1); expect(report.replayable_result_count).toBe(2); expect(report.replays.filter((replay) => replay.model === "model-b").every((replay) => replay.error === "model-b is offline")).toBe(true); diff --git a/packages/npm/test/examples.test.ts b/packages/npm/test/examples.test.ts index 29184918..df7240cc 100644 --- a/packages/npm/test/examples.test.ts +++ b/packages/npm/test/examples.test.ts @@ -34,7 +34,7 @@ describe("examples", () => { it("runs the README imports against a real database", () => { expect(runExample("readme.ts")).toEqual({ measurements: 1, - package_version: "3.0.0", + package_version: "3.1.0", package_records: 2, }); }); diff --git a/packages/npm/test/host.test.ts b/packages/npm/test/host.test.ts index 8e650a10..b8567304 100644 --- a/packages/npm/test/host.test.ts +++ b/packages/npm/test/host.test.ts @@ -120,7 +120,7 @@ describe.skipIf(!hostAvailable)(hostTitle, () => { it("lets an owner save a report with a photo, retry it, export it, and restore it", async () => { const owner = as("athlete-1", ATHLETE_APP); const capabilities = await owner.capabilities(); - expect(capabilities).toMatchObject({ api_version: 1, athleticstandard_version: "3.0.0", storage: "directory" }); + expect(capabilities).toMatchObject({ api_version: 1, athleticstandard_version: "3.1.0", storage: "directory" }); const { athlete_id: id } = await owner.createAthlete({ display_name: "Test athlete" }); expect((await owner.me()).athletes).toEqual([id]); diff --git a/packages/npm/test/public-api.test.ts b/packages/npm/test/public-api.test.ts index a5fbc5ca..dfd7f186 100644 --- a/packages/npm/test/public-api.test.ts +++ b/packages/npm/test/public-api.test.ts @@ -116,10 +116,10 @@ describe("public exports", () => { expect(database.getRecord).toBe(database.readRecord); expect(database.resolveConflict).toBe(database.resolvePackageConflict); expect(root.database).toEqual(expect.objectContaining({ openDatabase: database.openDatabase })); - expect(root.ATH_PACKAGE_VERSION).toBe("3.0.0"); - expect(root.ATHLETIC_STANDARD_VERSION).toBe("3.0.0"); - expect(schema.ACCEPTED_RECORD_VERSIONS).toEqual(["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0"]); - expect(schema.IMPORTABLE_PACKAGE_VERSIONS).toEqual(["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0"]); + expect(root.ATH_PACKAGE_VERSION).toBe("3.1.0"); + expect(root.ATHLETIC_STANDARD_VERSION).toBe("3.1.0"); + expect(schema.ACCEPTED_RECORD_VERSIONS).toEqual(["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", "3.1.0"]); + expect(schema.IMPORTABLE_PACKAGE_VERSIONS).toEqual(["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", "3.1.0"]); }); it("keeps the generated compile-time check current", () => { @@ -128,7 +128,7 @@ describe("public exports", () => { }); it("repeats the native constants", () => { - expect(database.SQL_SCHEMA_VERSION).toBe(8); + expect(database.SQL_SCHEMA_VERSION).toBe(9); expect(database.SQLITE_APPLICATION_ID).toBe(0x41544831); expect(database.SQLITE_APPLICATION_MARKER).toBe("ATH1"); expect(database.MAX_ATTACHMENT_BYTES).toBe(25 * 1024 * 1024); @@ -154,7 +154,7 @@ describe("public exports", () => { describe("package layout", () => { it("keeps the name, the ath command, and every 2.1.0 subpath", () => { expect(packageJson.name).toBe("athleticstandard"); - expect(packageJson.version).toBe("3.0.0"); + expect(packageJson.version).toBe("3.1.0"); expect(Object.keys(packageJson.bin)).toEqual(["ath"]); // 3.0.0 adds the WebAssembly core and its loader (D312). expect(Object.keys(packageJson.exports).sort()).toEqual( @@ -162,14 +162,14 @@ describe("package layout", () => { ); }); - it("generates the JSON Schema files for 3.0.0", () => { + it("generates the JSON Schema files for 3.1.0", () => { for (const subpath of ["./json-schema", "./json-schema/export-manifest", "./json-schema/measurement-series"]) { const target = packageJson.exports[subpath] as string; - expect(target).toMatch(/^\.\/schema\/3\.0\.0\//); + expect(target).toMatch(/^\.\/schema\/3\.1\.0\//); // pack.mjs copies the repository's committed schema/ files into the package. const document = JSON.parse(readFileSync(join(repositoryRoot, target), "utf8")) as { $id: string; $schema: string }; expect(document.$schema).toBe("https://json-schema.org/draft/2020-12/schema"); - expect(document.$id).toContain("/3.0.0/"); + expect(document.$id).toContain("/3.1.0/"); } }); diff --git a/schema/3.1.0/athleticstandard.schema.json b/schema/3.1.0/athleticstandard.schema.json new file mode 100644 index 00000000..ecdb6456 --- /dev/null +++ b/schema/3.1.0/athleticstandard.schema.json @@ -0,0 +1,22591 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://athleticstandard.ai/schema/3.1.0/athleticstandard.schema.json", + "title": "Athletic Standard portable package document", + "type": "object", + "properties": { + "athleticstandard_version": { + "type": "string", + "enum": [ + "1.0.0", + "2.0.0", + "2.1.0", + "2.1.1", + "2.1.2", + "2.1.3", + "3.0.0", + "3.1.0" + ] + }, + "database_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 database ID" + }, + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "records": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "athlete_profile" + }, + "data": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "birth_year": { + "type": "integer", + "minimum": 1900, + "maximum": 2100 + }, + "sex": { + "type": "string", + "enum": [ + "male", + "female" + ] + }, + "display_units": { + "type": "string", + "enum": [ + "metric", + "imperial" + ] + }, + "default_time_zone": { + "description": "IANA timezone for calendar calculations", + "type": "string", + "minLength": 1 + }, + "preferences": { + "type": "object", + "properties": { + "main_sports": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + } + }, + "machine_defaults": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + }, + "required": [ + "sport", + "machine" + ], + "additionalProperties": false + } + }, + "follow_up_questions": { + "type": "string", + "enum": [ + "ask_all", + "ask_required_only", + "ask_none" + ] + }, + "communication": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "source" + }, + "data": { + "type": "object", + "properties": { + "source_type": { + "type": "string", + "enum": [ + "wearable", + "export_file", + "connector", + "manual" + ] + }, + "data_writer": { + "type": "string", + "minLength": 1 + }, + "data_route": { + "type": "string", + "minLength": 1 + }, + "vendor": { + "type": "string", + "minLength": 1 + }, + "sensor_type": { + "type": "string", + "minLength": 1 + }, + "detail": { + "type": "string", + "minLength": 1 + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + } + }, + "required": [ + "source_type", + "data_writer", + "data_route" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "source_device" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + }, + "hardware": { + "type": "string", + "minLength": 1 + }, + "serial_number": { + "type": "string", + "minLength": 1 + }, + "coverage_start_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "coverage_end_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "accepted_record_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "source_id" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "point_measurement" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "hrv_rmssd", + "hrv_sdnn", + "resting_heart_rate", + "body_weight", + "respiratory_rate", + "vo2_max", + "hr_recovery", + "walking_heart_rate", + "oxygen_saturation", + "body_temperature", + "skin_temperature", + "wrist_temperature_sleeping", + "temperature_deviation", + "height", + "lean_body_mass", + "body_fat_percentage", + "blood_pressure_systolic", + "blood_pressure_diastolic" + ] + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "calculations": { + "type": "array", + "items": { + "type": "object", + "properties": { + "from_quantity": { + "type": "string", + "minLength": 1 + }, + "method": { + "type": "string", + "minLength": 1 + }, + "calculation_version": { + "type": "string", + "minLength": 1 + }, + "window_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "usable_sample_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "dropped_sample_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "signal_quality": { + "type": "number", + "minimum": 0 + }, + "input_records": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + } + }, + "required": [ + "from_quantity", + "method", + "calculation_version", + "input_records" + ], + "additionalProperties": false + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "quantity", + "input_timestamp", + "value" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "sleep_session" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "source_reported_summaries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "summary_type": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "standard_value", + "standard_unit", + "summary_type" + ], + "additionalProperties": false + } + }, + "asleep_seconds": { + "type": "number", + "minimum": 0 + }, + "in_bed_seconds": { + "type": "number", + "minimum": 0 + }, + "interruptions": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "stage_minutes": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "type": "number", + "minimum": 0 + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "start_at", + "end_at", + "input_start_timestamp", + "input_end_timestamp", + "source_reported_summaries" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "workout_session" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "activity_type": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string", + "minLength": 1 + }, + "text_result": { + "type": "string", + "minLength": 1 + }, + "maximum_heart_rate_bpm": { + "type": "number", + "exclusiveMinimum": 0 + }, + "resting_heart_rate_bpm": { + "type": "number", + "exclusiveMinimum": 0 + }, + "heart_rate_samples": { + "type": "array", + "items": { + "type": "object", + "properties": { + "offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "bpm": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "offset_ms", + "bpm" + ], + "additionalProperties": false + } + }, + "sets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "reps": { + "type": "number", + "exclusiveMinimum": 0 + }, + "weight": { + "type": "number", + "exclusiveMinimum": 0 + }, + "weight_unit": { + "type": "string", + "minLength": 1 + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "load_basis": { + "type": "string", + "enum": [ + "total", + "per_implement" + ] + }, + "implement_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "reps", + "weight", + "weight_unit" + ], + "additionalProperties": false + } + }, + "route": { + "type": "array", + "items": { + "type": "object", + "properties": { + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "latitude_deg": { + "type": "number", + "minimum": -90, + "maximum": 90 + }, + "longitude_deg": { + "type": "number", + "minimum": -180, + "maximum": 180 + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + } + }, + "required": [ + "recorded_at", + "latitude_deg", + "longitude_deg" + ], + "additionalProperties": false + } + }, + "source_reported_summaries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "summary_type": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "standard_value", + "standard_unit", + "summary_type" + ], + "additionalProperties": false + } + }, + "segments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "minLength": 1 + }, + "start_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "end_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "source_reported_summaries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "summary_type": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "standard_value", + "standard_unit", + "summary_type" + ], + "additionalProperties": false + } + } + }, + "required": [ + "label", + "source_reported_summaries" + ], + "additionalProperties": false + } + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "environment": { + "type": "object", + "properties": { + "altitude_m": { + "type": "number" + }, + "temperature_c": { + "type": "number" + }, + "humidity_pct": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "indoor": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "original_file": { + "type": "object", + "properties": { + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "format": { + "type": "string", + "enum": [ + "fit", + "gpx", + "tcx", + "apple_health_export", + "other" + ] + }, + "byte_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "file_name": { + "type": "string", + "minLength": 1 + }, + "entry": { + "type": "string", + "minLength": 1 + }, + "scope": { + "type": "string", + "enum": [ + "workout", + "account_export" + ] + } + }, + "required": [ + "sha256", + "format", + "byte_count", + "scope" + ], + "additionalProperties": false + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "start_at", + "end_at", + "input_start_timestamp", + "input_end_timestamp", + "source_reported_summaries" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "benchmark_result" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "benchmark_definition_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "input_score_text": { + "type": "string", + "minLength": 1 + }, + "scaling": { + "type": "string", + "enum": [ + "rx", + "scaled" + ] + }, + "workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "segments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "minLength": 1 + }, + "score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + } + }, + "required": [ + "label" + ], + "additionalProperties": false + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "benchmark_definition_id", + "recorded_at", + "input_timestamp", + "score" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "provider_summary" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "summary_type": { + "type": "string", + "minLength": 1 + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "summary_type", + "value", + "input_timestamp" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "provider_score" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "metric": { + "type": "string", + "minLength": 1 + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "scale": { + "type": "string", + "minLength": 1 + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "metric", + "value", + "scale", + "input_timestamp" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "athlete_report" + }, + "data": { + "type": "object", + "properties": { + "report_type": { + "type": "string", + "enum": [ + "sleep_quality", + "soreness", + "stress", + "mood", + "energy", + "note", + "session_effort", + "injury", + "illness" + ] + }, + "reported_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_reported_at": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "reported_via": { + "type": "string", + "enum": [ + "text", + "voice", + "photo" + ] + }, + "rating": { + "type": "number" + }, + "rating_scale": { + "type": "string", + "minLength": 1 + }, + "body_region": { + "type": "string", + "minLength": 1 + }, + "note": { + "type": "string", + "minLength": 1 + }, + "duration_seconds": { + "type": "number", + "exclusiveMinimum": 0 + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "side": { + "type": "string", + "enum": [ + "left", + "right", + "both" + ] + }, + "onset": { + "type": "string", + "enum": [ + "sudden", + "gradual" + ] + }, + "onset_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "problem_status": { + "type": "string", + "enum": [ + "new", + "ongoing", + "resolved" + ] + }, + "training_impact": { + "type": "string", + "enum": [ + "full", + "reduced", + "none" + ] + }, + "first_report_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "required": [ + "report_type", + "reported_at", + "input_reported_at", + "reported_via" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "nutrition_entry" + }, + "data": { + "type": "object", + "properties": { + "reported_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_reported_at": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "reported_via": { + "type": "string", + "enum": [ + "text", + "voice", + "photo" + ] + }, + "athlete_description": { + "type": "string", + "minLength": 1 + }, + "reported_items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "food_description": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "amount_unit": { + "type": "string", + "minLength": 1 + }, + "nutrients": { + "type": "array", + "items": { + "type": "object", + "properties": { + "nutrient_name": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "nutrient_name", + "amount", + "unit" + ], + "additionalProperties": false + } + } + }, + "required": [ + "food_description" + ], + "additionalProperties": false + } + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + }, + "required": [ + "reported_at", + "input_reported_at", + "reported_via", + "athlete_description", + "reported_items" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "attachment" + }, + "data": { + "type": "object", + "properties": { + "file_name": { + "type": "string", + "minLength": 1 + }, + "media_type": { + "type": "string", + "minLength": 1 + }, + "byte_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "description": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "file_name", + "media_type", + "byte_count", + "sha256" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "benchmark_definition" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "benchmark_key": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]*$" + }, + "benchmark_type": { + "type": "string", + "enum": [ + "named_wod", + "run", + "hyrox", + "lift", + "custom" + ] + }, + "score_type": { + "type": "string", + "enum": [ + "time", + "reps", + "load", + "power", + "distance", + "energy" + ] + }, + "definition": { + "type": "string", + "minLength": 1 + }, + "tags": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "score_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "authorship", + "benchmark_key", + "benchmark_type", + "score_type", + "definition" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "prediction" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "benchmark_definition_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "predicted_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "predicted_range": { + "type": "object", + "properties": { + "low": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "high": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + } + }, + "required": [ + "low", + "high" + ], + "additionalProperties": false + }, + "confidence": { + "type": "string", + "enum": [ + "low", + "moderate", + "high" + ] + }, + "reasoning": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "benchmark_definition_id", + "predicted_score", + "confidence", + "reasoning" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "prediction_result_link" + }, + "data": { + "type": "object", + "properties": { + "prediction": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "benchmark_result": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "created_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "linked_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "prediction", + "benchmark_result", + "created_by", + "linked_at", + "content_version", + "status" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "prediction_grade" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "prediction_result_link": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "signed_error": { + "type": "number" + }, + "absolute_error_percentage": { + "type": "number", + "minimum": 0 + }, + "result_in_predicted_range": { + "type": "boolean" + }, + "predicted_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "actual_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + } + }, + "required": [ + "authorship", + "prediction_result_link", + "signed_error", + "absolute_error_percentage", + "result_in_predicted_range", + "predicted_score", + "actual_score" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "prediction_error_analysis" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "prediction_grade": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "error_direction": { + "type": "string", + "enum": [ + "faster", + "slower", + "higher", + "lower" + ] + }, + "error_severity": { + "type": "string", + "enum": [ + "minor", + "significant", + "severe" + ] + }, + "causes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "evidence": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "explanation": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "evidence", + "explanation" + ], + "additionalProperties": false + } + }, + "unexplained": { + "type": "boolean" + }, + "lesson": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "prediction_grade", + "error_direction", + "error_severity", + "causes", + "unexplained" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "training_plan" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "objective": { + "type": "string", + "minLength": 1 + }, + "start_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "end_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "event_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "required": [ + "authorship", + "title" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "planned_session" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "training_plan_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "title": { + "type": "string", + "minLength": 1 + }, + "scheduled_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "scheduled_start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "activity_type": { + "type": "string", + "minLength": 1 + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "block_type": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string", + "minLength": 1 + }, + "instructions": { + "type": "string", + "minLength": 1 + }, + "planned_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "planned_weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "block_type": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string", + "minLength": 1 + }, + "instructions": { + "type": "string", + "minLength": 1 + }, + "planned_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "planned_weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "block_type": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string", + "minLength": 1 + }, + "instructions": { + "type": "string", + "minLength": 1 + }, + "planned_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "planned_weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "group_format": { + "type": "string", + "enum": [ + "rounds", + "amrap", + "emom", + "for_time" + ] + }, + "round_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "time_cap_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "round_interval_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "block_role": { + "type": "string", + "enum": [ + "warm_up", + "work", + "recovery", + "rest", + "cool_down" + ] + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "reps_by_round": { + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "planned_energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + }, + "ends_by": { + "type": "string", + "enum": [ + "time", + "distance", + "reps", + "energy", + "open" + ] + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "quantity": { + "type": "string", + "enum": [ + "power", + "heart_rate", + "speed", + "cadence", + "load", + "effort", + "work_capacity_used" + ] + }, + "low": { + "type": "number" + }, + "high": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "relative_to": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "relative_to_record": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "quantity", + "low", + "high", + "unit" + ], + "additionalProperties": false + } + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "required": [ + "block_type", + "title" + ], + "additionalProperties": false + } + }, + "group_format": { + "type": "string", + "enum": [ + "rounds", + "amrap", + "emom", + "for_time" + ] + }, + "round_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "time_cap_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "round_interval_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "block_role": { + "type": "string", + "enum": [ + "warm_up", + "work", + "recovery", + "rest", + "cool_down" + ] + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "reps_by_round": { + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "planned_energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + }, + "ends_by": { + "type": "string", + "enum": [ + "time", + "distance", + "reps", + "energy", + "open" + ] + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "quantity": { + "type": "string", + "enum": [ + "power", + "heart_rate", + "speed", + "cadence", + "load", + "effort", + "work_capacity_used" + ] + }, + "low": { + "type": "number" + }, + "high": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "relative_to": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "relative_to_record": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "quantity", + "low", + "high", + "unit" + ], + "additionalProperties": false + } + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "required": [ + "block_type", + "title" + ], + "additionalProperties": false + } + }, + "group_format": { + "type": "string", + "enum": [ + "rounds", + "amrap", + "emom", + "for_time" + ] + }, + "round_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "time_cap_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "round_interval_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "block_role": { + "type": "string", + "enum": [ + "warm_up", + "work", + "recovery", + "rest", + "cool_down" + ] + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "reps_by_round": { + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "planned_energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + }, + "ends_by": { + "type": "string", + "enum": [ + "time", + "distance", + "reps", + "energy", + "open" + ] + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "quantity": { + "type": "string", + "enum": [ + "power", + "heart_rate", + "speed", + "cadence", + "load", + "effort", + "work_capacity_used" + ] + }, + "low": { + "type": "number" + }, + "high": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "relative_to": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "relative_to_record": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "quantity", + "low", + "high", + "unit" + ], + "additionalProperties": false + } + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "required": [ + "block_type", + "title" + ], + "additionalProperties": false + } + }, + "completion_status": { + "type": "string", + "enum": [ + "planned", + "completed", + "skipped", + "cancelled" + ] + }, + "completed_workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + }, + "required": [ + "authorship", + "title", + "blocks", + "completion_status" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "coaching_note" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "note": { + "type": "string", + "minLength": 1 + }, + "applies_from": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "applies_to": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + } + }, + "required": [ + "authorship", + "note" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "saved_training_review" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "period_start": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "period_end": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "summary": { + "type": "string", + "minLength": 1 + }, + "recommendations": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "required": [ + "authorship", + "period_start", + "period_end", + "summary" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "goal" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string", + "minLength": 1 + }, + "target_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "target_benchmark_definition_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "target_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "event_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "required": [ + "authorship", + "title" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "nutrition_model_interpretation" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "nutrition_entry_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "interpreted_items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "food_description": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "amount_unit": { + "type": "string", + "minLength": 1 + }, + "nutrients": { + "type": "array", + "items": { + "type": "object", + "properties": { + "nutrient_name": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "nutrient_name", + "amount", + "unit" + ], + "additionalProperties": false + } + } + }, + "required": [ + "food_description" + ], + "additionalProperties": false + } + }, + "explanation": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "nutrition_entry_id", + "confidence", + "interpreted_items" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "intensity_reference" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "value": { + "type": "number", + "exclusiveMinimum": 0 + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "effective_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "basis": { + "type": "string", + "enum": [ + "test", + "model", + "device", + "set", + "recorded" + ] + }, + "method": { + "type": "string", + "minLength": 1 + }, + "environment": { + "type": "object", + "properties": { + "altitude_m": { + "type": "number" + }, + "temperature_c": { + "type": "number" + }, + "humidity_pct": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "indoor": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "note": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "quantity", + "value", + "unit", + "effective_date", + "basis", + "method" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "event" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "completion_status": { + "type": "string", + "enum": [ + "planned", + "completed", + "skipped", + "did_not_finish", + "cancelled" + ] + }, + "start_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "end_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "priority": { + "type": "string", + "enum": [ + "A", + "B", + "C" + ] + }, + "event_type": { + "type": "string", + "minLength": 1 + }, + "segments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "expected_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "label", + "sport", + "machine" + ], + "additionalProperties": false + } + }, + "expected_environment": { + "type": "object", + "properties": { + "altitude_m": { + "type": "number" + }, + "temperature_c": { + "type": "number" + }, + "humidity_pct": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "indoor": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "key_efforts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "description": { + "type": "string", + "minLength": 1 + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "expected_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "description" + ], + "additionalProperties": false + } + }, + "description": { + "type": "string", + "minLength": 1 + }, + "result_record_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + }, + "required": [ + "authorship", + "title", + "completion_status", + "start_date", + "segments" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "approval" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "subjects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "note": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "subjects" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "calculation_result" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "calculation": { + "type": "string", + "minLength": 1 + }, + "method": { + "type": "string", + "minLength": 1 + }, + "method_file_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "parameters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "value": { + "$ref": "#/$defs/__schema1" + } + }, + "required": [ + "name", + "value" + ], + "additionalProperties": false + } + }, + "period_start": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "period_end": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "results": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "value": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "name", + "value", + "unit" + ], + "additionalProperties": false + } + }, + "note": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "calculation", + "method", + "parameters", + "results" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "device_recording" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "heart_rate", + "power", + "cadence", + "speed", + "distance", + "altitude", + "temperature", + "position" + ] + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "reading_kind": { + "type": "string", + "enum": [ + "instant", + "interval_total", + "interval_held", + "counter" + ] + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "window_ms": { + "type": "integer", + "minimum": 1, + "maximum": 3600000 + }, + "reading_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "source_device_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "computed_by_source": { + "type": "boolean" + }, + "pauses": { + "type": "array", + "items": { + "type": "object", + "properties": { + "start_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "end_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "start_offset_ms", + "end_offset_ms" + ], + "additionalProperties": false + } + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "window_index": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "part": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "reading_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "first_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "last_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "window_index", + "part", + "version", + "reading_count", + "first_offset_ms", + "last_offset_ms", + "sha256" + ], + "additionalProperties": false + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "quantity", + "unit", + "reading_kind", + "start_at", + "end_at", + "input_start_timestamp", + "window_ms", + "reading_count", + "blocks" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + } + ] + } + }, + "record_revisions": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "athlete_profile" + }, + "data": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "birth_year": { + "type": "integer", + "minimum": 1900, + "maximum": 2100 + }, + "sex": { + "type": "string", + "enum": [ + "male", + "female" + ] + }, + "display_units": { + "type": "string", + "enum": [ + "metric", + "imperial" + ] + }, + "default_time_zone": { + "description": "IANA timezone for calendar calculations", + "type": "string", + "minLength": 1 + }, + "preferences": { + "type": "object", + "properties": { + "main_sports": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + } + }, + "machine_defaults": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + }, + "required": [ + "sport", + "machine" + ], + "additionalProperties": false + } + }, + "follow_up_questions": { + "type": "string", + "enum": [ + "ask_all", + "ask_required_only", + "ask_none" + ] + }, + "communication": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "source" + }, + "data": { + "type": "object", + "properties": { + "source_type": { + "type": "string", + "enum": [ + "wearable", + "export_file", + "connector", + "manual" + ] + }, + "data_writer": { + "type": "string", + "minLength": 1 + }, + "data_route": { + "type": "string", + "minLength": 1 + }, + "vendor": { + "type": "string", + "minLength": 1 + }, + "sensor_type": { + "type": "string", + "minLength": 1 + }, + "detail": { + "type": "string", + "minLength": 1 + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + } + }, + "required": [ + "source_type", + "data_writer", + "data_route" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "source_device" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + }, + "hardware": { + "type": "string", + "minLength": 1 + }, + "serial_number": { + "type": "string", + "minLength": 1 + }, + "coverage_start_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "coverage_end_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "accepted_record_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "source_id" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "point_measurement" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "hrv_rmssd", + "hrv_sdnn", + "resting_heart_rate", + "body_weight", + "respiratory_rate", + "vo2_max", + "hr_recovery", + "walking_heart_rate", + "oxygen_saturation", + "body_temperature", + "skin_temperature", + "wrist_temperature_sleeping", + "temperature_deviation", + "height", + "lean_body_mass", + "body_fat_percentage", + "blood_pressure_systolic", + "blood_pressure_diastolic" + ] + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "calculations": { + "type": "array", + "items": { + "type": "object", + "properties": { + "from_quantity": { + "type": "string", + "minLength": 1 + }, + "method": { + "type": "string", + "minLength": 1 + }, + "calculation_version": { + "type": "string", + "minLength": 1 + }, + "window_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "usable_sample_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "dropped_sample_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "signal_quality": { + "type": "number", + "minimum": 0 + }, + "input_records": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + } + }, + "required": [ + "from_quantity", + "method", + "calculation_version", + "input_records" + ], + "additionalProperties": false + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "quantity", + "input_timestamp", + "value" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "sleep_session" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "source_reported_summaries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "summary_type": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "standard_value", + "standard_unit", + "summary_type" + ], + "additionalProperties": false + } + }, + "asleep_seconds": { + "type": "number", + "minimum": 0 + }, + "in_bed_seconds": { + "type": "number", + "minimum": 0 + }, + "interruptions": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "stage_minutes": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "type": "number", + "minimum": 0 + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "start_at", + "end_at", + "input_start_timestamp", + "input_end_timestamp", + "source_reported_summaries" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "workout_session" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "activity_type": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string", + "minLength": 1 + }, + "text_result": { + "type": "string", + "minLength": 1 + }, + "maximum_heart_rate_bpm": { + "type": "number", + "exclusiveMinimum": 0 + }, + "resting_heart_rate_bpm": { + "type": "number", + "exclusiveMinimum": 0 + }, + "heart_rate_samples": { + "type": "array", + "items": { + "type": "object", + "properties": { + "offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "bpm": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "offset_ms", + "bpm" + ], + "additionalProperties": false + } + }, + "sets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "reps": { + "type": "number", + "exclusiveMinimum": 0 + }, + "weight": { + "type": "number", + "exclusiveMinimum": 0 + }, + "weight_unit": { + "type": "string", + "minLength": 1 + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "load_basis": { + "type": "string", + "enum": [ + "total", + "per_implement" + ] + }, + "implement_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "reps", + "weight", + "weight_unit" + ], + "additionalProperties": false + } + }, + "route": { + "type": "array", + "items": { + "type": "object", + "properties": { + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "latitude_deg": { + "type": "number", + "minimum": -90, + "maximum": 90 + }, + "longitude_deg": { + "type": "number", + "minimum": -180, + "maximum": 180 + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + } + }, + "required": [ + "recorded_at", + "latitude_deg", + "longitude_deg" + ], + "additionalProperties": false + } + }, + "source_reported_summaries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "summary_type": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "standard_value", + "standard_unit", + "summary_type" + ], + "additionalProperties": false + } + }, + "segments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "minLength": 1 + }, + "start_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "end_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "source_reported_summaries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "summary_type": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "standard_value", + "standard_unit", + "summary_type" + ], + "additionalProperties": false + } + } + }, + "required": [ + "label", + "source_reported_summaries" + ], + "additionalProperties": false + } + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "environment": { + "type": "object", + "properties": { + "altitude_m": { + "type": "number" + }, + "temperature_c": { + "type": "number" + }, + "humidity_pct": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "indoor": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "original_file": { + "type": "object", + "properties": { + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "format": { + "type": "string", + "enum": [ + "fit", + "gpx", + "tcx", + "apple_health_export", + "other" + ] + }, + "byte_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "file_name": { + "type": "string", + "minLength": 1 + }, + "entry": { + "type": "string", + "minLength": 1 + }, + "scope": { + "type": "string", + "enum": [ + "workout", + "account_export" + ] + } + }, + "required": [ + "sha256", + "format", + "byte_count", + "scope" + ], + "additionalProperties": false + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "start_at", + "end_at", + "input_start_timestamp", + "input_end_timestamp", + "source_reported_summaries" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "benchmark_result" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "benchmark_definition_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "input_score_text": { + "type": "string", + "minLength": 1 + }, + "scaling": { + "type": "string", + "enum": [ + "rx", + "scaled" + ] + }, + "workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "segments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "minLength": 1 + }, + "score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + } + }, + "required": [ + "label" + ], + "additionalProperties": false + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "benchmark_definition_id", + "recorded_at", + "input_timestamp", + "score" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "provider_summary" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "summary_type": { + "type": "string", + "minLength": 1 + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "summary_type", + "value", + "input_timestamp" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "provider_score" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "metric": { + "type": "string", + "minLength": 1 + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "scale": { + "type": "string", + "minLength": 1 + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "metric", + "value", + "scale", + "input_timestamp" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "athlete_report" + }, + "data": { + "type": "object", + "properties": { + "report_type": { + "type": "string", + "enum": [ + "sleep_quality", + "soreness", + "stress", + "mood", + "energy", + "note", + "session_effort", + "injury", + "illness" + ] + }, + "reported_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_reported_at": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "reported_via": { + "type": "string", + "enum": [ + "text", + "voice", + "photo" + ] + }, + "rating": { + "type": "number" + }, + "rating_scale": { + "type": "string", + "minLength": 1 + }, + "body_region": { + "type": "string", + "minLength": 1 + }, + "note": { + "type": "string", + "minLength": 1 + }, + "duration_seconds": { + "type": "number", + "exclusiveMinimum": 0 + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "side": { + "type": "string", + "enum": [ + "left", + "right", + "both" + ] + }, + "onset": { + "type": "string", + "enum": [ + "sudden", + "gradual" + ] + }, + "onset_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "problem_status": { + "type": "string", + "enum": [ + "new", + "ongoing", + "resolved" + ] + }, + "training_impact": { + "type": "string", + "enum": [ + "full", + "reduced", + "none" + ] + }, + "first_report_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "required": [ + "report_type", + "reported_at", + "input_reported_at", + "reported_via" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "nutrition_entry" + }, + "data": { + "type": "object", + "properties": { + "reported_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_reported_at": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "reported_via": { + "type": "string", + "enum": [ + "text", + "voice", + "photo" + ] + }, + "athlete_description": { + "type": "string", + "minLength": 1 + }, + "reported_items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "food_description": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "amount_unit": { + "type": "string", + "minLength": 1 + }, + "nutrients": { + "type": "array", + "items": { + "type": "object", + "properties": { + "nutrient_name": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "nutrient_name", + "amount", + "unit" + ], + "additionalProperties": false + } + } + }, + "required": [ + "food_description" + ], + "additionalProperties": false + } + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + }, + "required": [ + "reported_at", + "input_reported_at", + "reported_via", + "athlete_description", + "reported_items" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "attachment" + }, + "data": { + "type": "object", + "properties": { + "file_name": { + "type": "string", + "minLength": 1 + }, + "media_type": { + "type": "string", + "minLength": 1 + }, + "byte_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "description": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "file_name", + "media_type", + "byte_count", + "sha256" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "benchmark_definition" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "benchmark_key": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]*$" + }, + "benchmark_type": { + "type": "string", + "enum": [ + "named_wod", + "run", + "hyrox", + "lift", + "custom" + ] + }, + "score_type": { + "type": "string", + "enum": [ + "time", + "reps", + "load", + "power", + "distance", + "energy" + ] + }, + "definition": { + "type": "string", + "minLength": 1 + }, + "tags": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "score_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "authorship", + "benchmark_key", + "benchmark_type", + "score_type", + "definition" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "prediction" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "benchmark_definition_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "predicted_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "predicted_range": { + "type": "object", + "properties": { + "low": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "high": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + } + }, + "required": [ + "low", + "high" + ], + "additionalProperties": false + }, + "confidence": { + "type": "string", + "enum": [ + "low", + "moderate", + "high" + ] + }, + "reasoning": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "benchmark_definition_id", + "predicted_score", + "confidence", + "reasoning" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "prediction_result_link" + }, + "data": { + "type": "object", + "properties": { + "prediction": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "benchmark_result": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "created_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "linked_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "prediction", + "benchmark_result", + "created_by", + "linked_at", + "content_version", + "status" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "prediction_grade" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "prediction_result_link": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "signed_error": { + "type": "number" + }, + "absolute_error_percentage": { + "type": "number", + "minimum": 0 + }, + "result_in_predicted_range": { + "type": "boolean" + }, + "predicted_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "actual_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + } + }, + "required": [ + "authorship", + "prediction_result_link", + "signed_error", + "absolute_error_percentage", + "result_in_predicted_range", + "predicted_score", + "actual_score" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "prediction_error_analysis" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "prediction_grade": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "error_direction": { + "type": "string", + "enum": [ + "faster", + "slower", + "higher", + "lower" + ] + }, + "error_severity": { + "type": "string", + "enum": [ + "minor", + "significant", + "severe" + ] + }, + "causes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "evidence": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "explanation": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "evidence", + "explanation" + ], + "additionalProperties": false + } + }, + "unexplained": { + "type": "boolean" + }, + "lesson": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "prediction_grade", + "error_direction", + "error_severity", + "causes", + "unexplained" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "training_plan" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "objective": { + "type": "string", + "minLength": 1 + }, + "start_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "end_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "event_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "required": [ + "authorship", + "title" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "planned_session" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "training_plan_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "title": { + "type": "string", + "minLength": 1 + }, + "scheduled_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "scheduled_start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "activity_type": { + "type": "string", + "minLength": 1 + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "block_type": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string", + "minLength": 1 + }, + "instructions": { + "type": "string", + "minLength": 1 + }, + "planned_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "planned_weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "block_type": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string", + "minLength": 1 + }, + "instructions": { + "type": "string", + "minLength": 1 + }, + "planned_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "planned_weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "block_type": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string", + "minLength": 1 + }, + "instructions": { + "type": "string", + "minLength": 1 + }, + "planned_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "planned_reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "planned_weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "group_format": { + "type": "string", + "enum": [ + "rounds", + "amrap", + "emom", + "for_time" + ] + }, + "round_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "time_cap_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "round_interval_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "block_role": { + "type": "string", + "enum": [ + "warm_up", + "work", + "recovery", + "rest", + "cool_down" + ] + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "reps_by_round": { + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "planned_energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + }, + "ends_by": { + "type": "string", + "enum": [ + "time", + "distance", + "reps", + "energy", + "open" + ] + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "quantity": { + "type": "string", + "enum": [ + "power", + "heart_rate", + "speed", + "cadence", + "load", + "effort", + "work_capacity_used" + ] + }, + "low": { + "type": "number" + }, + "high": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "relative_to": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "relative_to_record": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "quantity", + "low", + "high", + "unit" + ], + "additionalProperties": false + } + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "required": [ + "block_type", + "title" + ], + "additionalProperties": false + } + }, + "group_format": { + "type": "string", + "enum": [ + "rounds", + "amrap", + "emom", + "for_time" + ] + }, + "round_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "time_cap_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "round_interval_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "block_role": { + "type": "string", + "enum": [ + "warm_up", + "work", + "recovery", + "rest", + "cool_down" + ] + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "reps_by_round": { + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "planned_energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + }, + "ends_by": { + "type": "string", + "enum": [ + "time", + "distance", + "reps", + "energy", + "open" + ] + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "quantity": { + "type": "string", + "enum": [ + "power", + "heart_rate", + "speed", + "cadence", + "load", + "effort", + "work_capacity_used" + ] + }, + "low": { + "type": "number" + }, + "high": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "relative_to": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "relative_to_record": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "quantity", + "low", + "high", + "unit" + ], + "additionalProperties": false + } + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "required": [ + "block_type", + "title" + ], + "additionalProperties": false + } + }, + "group_format": { + "type": "string", + "enum": [ + "rounds", + "amrap", + "emom", + "for_time" + ] + }, + "round_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "time_cap_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "round_interval_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "block_role": { + "type": "string", + "enum": [ + "warm_up", + "work", + "recovery", + "rest", + "cool_down" + ] + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "reps_by_round": { + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "planned_energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + }, + "ends_by": { + "type": "string", + "enum": [ + "time", + "distance", + "reps", + "energy", + "open" + ] + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "quantity": { + "type": "string", + "enum": [ + "power", + "heart_rate", + "speed", + "cadence", + "load", + "effort", + "work_capacity_used" + ] + }, + "low": { + "type": "number" + }, + "high": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "relative_to": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "relative_to_record": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "quantity", + "low", + "high", + "unit" + ], + "additionalProperties": false + } + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "required": [ + "block_type", + "title" + ], + "additionalProperties": false + } + }, + "completion_status": { + "type": "string", + "enum": [ + "planned", + "completed", + "skipped", + "cancelled" + ] + }, + "completed_workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + } + }, + "required": [ + "authorship", + "title", + "blocks", + "completion_status" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "coaching_note" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "note": { + "type": "string", + "minLength": 1 + }, + "applies_from": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "applies_to": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + } + }, + "required": [ + "authorship", + "note" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "saved_training_review" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "period_start": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "period_end": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "summary": { + "type": "string", + "minLength": 1 + }, + "recommendations": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "required": [ + "authorship", + "period_start", + "period_end", + "summary" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "goal" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string", + "minLength": 1 + }, + "target_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "target_benchmark_definition_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "target_score": { + "type": "object", + "properties": { + "duration_s": { + "type": "number", + "exclusiveMinimum": 0 + }, + "reps": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "weight_kg": { + "type": "number", + "exclusiveMinimum": 0 + }, + "power_w": { + "type": "number", + "exclusiveMinimum": 0 + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "energy_kcal": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "additionalProperties": false + }, + "event_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + "required": [ + "authorship", + "title" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "nutrition_model_interpretation" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "nutrition_entry_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "interpreted_items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "food_description": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "amount_unit": { + "type": "string", + "minLength": 1 + }, + "nutrients": { + "type": "array", + "items": { + "type": "object", + "properties": { + "nutrient_name": { + "type": "string", + "minLength": 1 + }, + "amount": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "nutrient_name", + "amount", + "unit" + ], + "additionalProperties": false + } + } + }, + "required": [ + "food_description" + ], + "additionalProperties": false + } + }, + "explanation": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "nutrition_entry_id", + "confidence", + "interpreted_items" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "intensity_reference" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "threshold_power", + "threshold_heart_rate", + "threshold_speed", + "maximum_heart_rate", + "one_rep_max", + "work_capacity_above_threshold", + "peak_power", + "time_to_exhaustion", + "aerobic_threshold_heart_rate", + "aerobic_threshold_power", + "aerobic_threshold_speed", + "distance_capacity_above_threshold" + ] + }, + "value": { + "type": "number", + "exclusiveMinimum": 0 + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "movement": { + "type": "string", + "minLength": 1 + }, + "effective_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "basis": { + "type": "string", + "enum": [ + "test", + "model", + "device", + "set", + "recorded" + ] + }, + "method": { + "type": "string", + "minLength": 1 + }, + "environment": { + "type": "object", + "properties": { + "altitude_m": { + "type": "number" + }, + "temperature_c": { + "type": "number" + }, + "humidity_pct": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "indoor": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "note": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "quantity", + "value", + "unit", + "effective_date", + "basis", + "method" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "event" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "title": { + "type": "string", + "minLength": 1 + }, + "completion_status": { + "type": "string", + "enum": [ + "planned", + "completed", + "skipped", + "did_not_finish", + "cancelled" + ] + }, + "start_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "end_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "priority": { + "type": "string", + "enum": [ + "A", + "B", + "C" + ] + }, + "event_type": { + "type": "string", + "minLength": 1 + }, + "segments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": { + "type": "string", + "minLength": 1 + }, + "sport": { + "type": "string", + "enum": [ + "running", + "walking", + "cycling", + "swimming", + "rowing", + "cross_country_skiing", + "strength", + "functional_fitness", + "other" + ] + }, + "machine": { + "type": "string", + "enum": [ + "none", + "treadmill", + "stationary_bike", + "air_bike", + "rowing_machine", + "ski_erg", + "other", + "unknown" + ] + }, + "machine_details": { + "type": "object", + "properties": { + "manufacturer": { + "type": "string", + "minLength": 1 + }, + "model": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "distance_m": { + "type": "number", + "exclusiveMinimum": 0 + }, + "expected_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "label", + "sport", + "machine" + ], + "additionalProperties": false + } + }, + "expected_environment": { + "type": "object", + "properties": { + "altitude_m": { + "type": "number" + }, + "temperature_c": { + "type": "number" + }, + "humidity_pct": { + "type": "number", + "minimum": 0, + "maximum": 100 + }, + "indoor": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "key_efforts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "description": { + "type": "string", + "minLength": 1 + }, + "after": { + "type": "object", + "properties": { + "time_s": { + "type": "number", + "minimum": 0 + }, + "distance_m": { + "type": "number", + "minimum": 0 + }, + "work_kj": { + "type": "number", + "minimum": 0 + }, + "work_above_threshold_kj": { + "type": "number", + "minimum": 0 + }, + "threshold_reference": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "expected_duration_s": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "description" + ], + "additionalProperties": false + } + }, + "description": { + "type": "string", + "minLength": 1 + }, + "result_record_ids": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + }, + "required": [ + "authorship", + "title", + "completion_status", + "start_date", + "segments" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "approval" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "subjects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "note": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "subjects" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "calculation_result" + }, + "data": { + "type": "object", + "properties": { + "authorship": { + "type": "object", + "properties": { + "author": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "model": { + "type": "string", + "minLength": 1 + }, + "model_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "agent", + "model" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + }, + "calculation_version": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "author_type", + "tool", + "tool_version", + "calculation_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "authored_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "evidence": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + } + }, + "content_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "status": { + "type": "string", + "enum": [ + "draft", + "active", + "completed", + "superseded", + "cancelled" + ] + } + }, + "required": [ + "author", + "authored_at", + "evidence", + "content_version", + "status" + ], + "additionalProperties": false + }, + "calculation": { + "type": "string", + "minLength": 1 + }, + "method": { + "type": "string", + "minLength": 1 + }, + "method_file_sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "parameters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "value": { + "$ref": "#/$defs/__schema1" + } + }, + "required": [ + "name", + "value" + ], + "additionalProperties": false + } + }, + "period_start": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "period_end": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "results": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "value": { + "type": "number" + }, + "unit": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "name", + "value", + "unit" + ], + "additionalProperties": false + } + }, + "note": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "authorship", + "calculation", + "method", + "parameters", + "results" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "device_recording" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "heart_rate", + "power", + "cadence", + "speed", + "distance", + "altitude", + "temperature", + "position" + ] + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "reading_kind": { + "type": "string", + "enum": [ + "instant", + "interval_total", + "interval_held", + "counter" + ] + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "window_ms": { + "type": "integer", + "minimum": 1, + "maximum": 3600000 + }, + "reading_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "workout_session_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "source_device_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "computed_by_source": { + "type": "boolean" + }, + "pauses": { + "type": "array", + "items": { + "type": "object", + "properties": { + "start_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "end_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "start_offset_ms", + "end_offset_ms" + ], + "additionalProperties": false + } + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "window_index": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "part": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "reading_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "first_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "last_offset_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "window_index", + "part", + "version", + "reading_count", + "first_offset_ms", + "last_offset_ms", + "sha256" + ], + "additionalProperties": false + } + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "quantity", + "unit", + "reading_kind", + "start_at", + "end_at", + "input_start_timestamp", + "window_ms", + "reading_count", + "blocks" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + } + ] + } + }, + "record_deletions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "record_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "deleted_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "deleted_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "record_id", + "record_revision", + "deleted_at", + "deleted_by" + ], + "additionalProperties": false + } + }, + "record_erasure_markers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "erased_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "reason_code": { + "type": "string", + "enum": [ + "athlete_request", + "legal_requirement", + "recorded_in_error", + "other" + ] + } + }, + "required": [ + "record_id", + "erased_at", + "reason_code" + ], + "additionalProperties": false + } + }, + "record_import_keys": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "match_key_method": { + "type": "string", + "minLength": 1 + }, + "match_key": { + "type": "string", + "minLength": 1 + }, + "imported_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + } + }, + "required": [ + "record_id", + "match_key_method", + "match_key", + "imported_at" + ], + "additionalProperties": false + } + }, + "measurement_series_files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file": { + "type": "string", + "minLength": 1, + "pattern": "^(?!\\/)(?!.*\\\\)(?!.*(?:^|\\/)\\.\\.(?:\\/|$)).+$" + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "quantity": { + "type": "string", + "enum": [ + "heart_rate", + "hrv_beats", + "ecg_beats", + "hrv_sdnn", + "respiratory_rate", + "oxygen_saturation", + "steps", + "active_energy", + "distance_walking_running", + "distance_cycling", + "distance_swimming", + "running_speed", + "running_power", + "running_stride_length", + "running_vertical_oscillation", + "running_ground_contact_time", + "physical_effort", + "basal_energy", + "exercise_time", + "flights_climbed", + "walking_speed", + "walking_step_length", + "walking_asymmetry_percentage", + "time_in_daylight" + ] + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "sample_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "revision_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "deletion_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "import_key_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "file", + "sha256", + "source_id", + "quantity", + "start_at", + "end_at", + "sample_count", + "revision_count", + "deletion_count", + "import_key_count" + ], + "additionalProperties": false + } + } + }, + "required": [ + "athleticstandard_version", + "database_id", + "database_revision", + "records", + "record_revisions", + "record_deletions", + "record_erasure_markers", + "record_import_keys", + "measurement_series_files" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "maxItems": 256, + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + }, + "__schema1": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema1" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + } + ] + } + } +} diff --git a/schema/3.1.0/export-manifest.schema.json b/schema/3.1.0/export-manifest.schema.json new file mode 100644 index 00000000..c21d4854 --- /dev/null +++ b/schema/3.1.0/export-manifest.schema.json @@ -0,0 +1,152 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://athleticstandard.ai/schema/3.1.0/export-manifest.schema.json", + "title": "Athletic Standard export manifest", + "type": "object", + "properties": { + "athleticstandard_version": { + "type": "string", + "enum": [ + "1.0.0", + "2.0.0", + "2.1.0", + "2.1.1", + "2.1.2", + "2.1.3", + "3.0.0", + "3.1.0" + ] + }, + "source_database_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 database ID" + }, + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "exported_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "files": { + "type": "array", + "items": { + "type": "object", + "properties": { + "file": { + "type": "string", + "minLength": 1, + "pattern": "^(?!\\/)(?!.*\\\\)(?!.*(?:^|\\/)\\.\\.(?:\\/|$)).+$" + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "byte_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "file", + "sha256", + "byte_count" + ], + "additionalProperties": false + } + }, + "record_counts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_type": { + "type": "string", + "enum": [ + "athlete_profile", + "source", + "source_device", + "point_measurement", + "measurement_sample", + "sleep_session", + "workout_session", + "benchmark_result", + "provider_summary", + "provider_score", + "athlete_report", + "nutrition_entry", + "attachment", + "benchmark_definition", + "prediction", + "prediction_result_link", + "prediction_grade", + "prediction_error_analysis", + "training_plan", + "planned_session", + "coaching_note", + "saved_training_review", + "goal", + "nutrition_model_interpretation", + "intensity_reference", + "event", + "approval", + "calculation_result", + "device_recording" + ] + }, + "current_record_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "revision_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "deletion_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "import_key_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_type", + "current_record_count", + "revision_count", + "deletion_count", + "import_key_count" + ], + "additionalProperties": false + } + }, + "erasure_marker_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "partial": { + "type": "boolean" + } + }, + "required": [ + "athleticstandard_version", + "source_database_id", + "database_revision", + "files", + "record_counts", + "erasure_marker_count" + ], + "additionalProperties": false +} diff --git a/schema/3.1.0/host-api.json b/schema/3.1.0/host-api.json new file mode 100644 index 00000000..b688bb21 --- /dev/null +++ b/schema/3.1.0/host-api.json @@ -0,0 +1,4757 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Athletic Standard host API", + "version": "1", + "summary": "Read and write Athletic Standard records on an ath-host, within the athlete's grants.", + "description": "Generated from the Rust definitions in `host/src/operations.rs` and `host/src/shapes.rs` (D266). Do not edit by hand. The guide for this API is `docs/hosting.md` section 7. Every error answer is JSON with a stable code (`Error`). Records and revisions use the published package schemas of the record format version the host reports in `/v1/capabilities`.", + "license": { + "name": "MIT", + "identifier": "MIT" + } + }, + "jsonSchemaDialect": "https://json-schema.org/draft/2020-12/schema", + "tags": [ + { + "name": "discovery", + "description": "Finding the sign-in provider, the host's features, and the signed-in person." + }, + { + "name": "athletes", + "description": "Records the caller owns." + }, + { + "name": "records", + "description": "The owner's reads and writes. Every write goes through the Athletic Standard library." + }, + { + "name": "grants", + "description": "Coach access, which the athlete offers and can revoke (D262)." + }, + { + "name": "apps", + "description": "The apps the owner uses with a record, which the owner can disconnect (D270)." + }, + { + "name": "coaching", + "description": "What a coach can do under a grant." + }, + { + "name": "moves", + "description": "Moving a record to another host, with one writer at every step (D267)." + } + ], + "security": [ + { + "bearer": [] + } + ], + "paths": { + "/.well-known/oauth-protected-resource": { + "get": { + "operationId": "getProtectedResource", + "tags": [ + "discovery" + ], + "summary": "Protected-resource metadata (RFC 9728), naming the sign-in provider.", + "description": "Who may call: anyone. No token is needed.", + "security": [], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProtectedResource" + } + } + } + } + } + } + }, + "/v1/capabilities": { + "get": { + "operationId": "getCapabilities", + "tags": [ + "discovery" + ], + "summary": "The API version, record format version, storage, and enrollment.", + "description": "Who may call: anyone. No token is needed.", + "security": [], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Capabilities" + } + } + } + } + } + } + }, + "/v1/me": { + "get": { + "operationId": "getMe", + "tags": [ + "discovery" + ], + "summary": "The signed-in person, the app, and the records they own that this app may see.", + "description": "Who may call: any signed-in person.", + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Me" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes": { + "post": { + "operationId": "createAthlete", + "tags": [ + "athletes" + ], + "summary": "Create an empty record. Without open enrollment, an unused invitation is required. With `incoming`, the record is staged for a move.", + "description": "Who may call: any signed-in person.", + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewAthleteRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedAthlete" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + }, + "get": { + "operationId": "listAthletes", + "tags": [ + "athletes" + ], + "summary": "The caller's records, except retired ones and ones this app was disconnected from.", + "description": "Who may call: any signed-in person.", + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AthleteList" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}": { + "get": { + "operationId": "getAthlete", + "tags": [ + "athletes" + ], + "summary": "The caller's role and the record's state. The owner also gets the database revision.", + "description": "Who may call: the owner, or a coach with an active grant through this app.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AthleteSummary" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/package": { + "put": { + "operationId": "restorePackage", + "tags": [ + "records" + ], + "summary": "Restore a complete package into an empty record: the first transfer of an existing record.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "description": "A zip of a complete package folder: the files `ath export` writes, at the root of the zip.", + "content": { + "application/zip": {} + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DatabaseRevision" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/export": { + "get": { + "operationId": "exportPackage", + "tags": [ + "records" + ], + "summary": "The complete package as a zip, or with `since` the partial package of what changed after that revision. `x-manifest-digest` is the SHA-256 of its manifest. A `since` the change list no longer reaches gets `409 stale`.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "since", + "in": "query", + "required": false, + "description": "Only the records changed after this database revision, each with its complete history: a partial package for a sync (D313).", + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + } + ], + "responses": { + "200": { + "description": "The complete package as a zip.", + "headers": { + "x-manifest-digest": { + "description": "The SHA-256 of the package's `export-manifest.json`, as 64 lowercase hexadecimal digits.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/zip": {} + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/merge": { + "post": { + "operationId": "mergeChanges", + "tags": [ + "records" + ], + "summary": "Merge a partial package of the owner's changes from another copy of this record (D313). A record that changed here too gets `409 stale`, and nothing changes. The same package again changes nothing.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "requestBody": { + "required": true, + "description": "A zip of a complete package folder: the files `ath export` writes, at the root of the zip.", + "content": { + "application/zip": {} + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MergeResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/changes": { + "get": { + "operationId": "listChanges", + "tags": [ + "records" + ], + "summary": "The record changes since a database revision, in order (D263). When `complete` is false, download the export.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "since", + "in": "query", + "required": true, + "description": "The database revision the device last verified.", + "schema": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeList" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/records": { + "get": { + "operationId": "listRecords", + "tags": [ + "records" + ], + "summary": "Current records, oldest first.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_type", + "in": "query", + "required": false, + "description": "Only records of this type.", + "schema": { + "$ref": "#/components/schemas/RecordType" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "At most this many records. The default and maximum are the host's `page_size`.", + "schema": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecordList" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + }, + "post": { + "operationId": "createRecord", + "tags": [ + "records" + ], + "summary": "Create a record, with any uploaded attachments. New attachment records come first in the result.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKeyRequired" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateRecordRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/records/{record_id}": { + "get": { + "operationId": "getRecord", + "tags": [ + "records" + ], + "summary": "One record and its complete history.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecordWithHistory" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/records/{record_id}/corrections": { + "post": { + "operationId": "correctRecord", + "tags": [ + "records" + ], + "summary": "Correct a record. An out-of-date `expected_revision` gets `409 stale`.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKeyRequired" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CorrectionRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/records/{record_id}/deletion": { + "post": { + "operationId": "deleteRecord", + "tags": [ + "records" + ], + "summary": "Delete a record. Its history stays.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKeyRequired" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeletionRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/records/{record_id}/erasure": { + "post": { + "operationId": "eraseRecord", + "tags": [ + "records" + ], + "summary": "Erase a record and its history for privacy (D107). Without a key, a repeat fails because the record is gone.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErasureRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DatabaseRevision" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/staged-writes": { + "post": { + "operationId": "startStagedWrite", + "tags": [ + "records" + ], + "summary": "Start a large write, such as a long ride's recordings, sent in pieces. Nothing is in the record until the commit.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StagedWriteRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StagedWrite" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/staged-writes/{write_id}": { + "get": { + "operationId": "getStagedWrite", + "tags": [ + "records" + ], + "summary": "The pieces a staged write has received, so an interrupted upload can send only the missing ones.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "write_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StagedWrite" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/staged-writes/{write_id}/pieces/{record_index}/{piece}": { + "put": { + "operationId": "putReadingsPiece", + "tags": [ + "records" + ], + "summary": "One piece of a recording's readings. Sending the same piece again changes nothing; a different piece under the same number gets `409 request_conflict`.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "write_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "record_index", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "name": "piece", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReadingsPiece" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StagedWrite" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/staged-writes/{write_id}/commit": { + "post": { + "operationId": "commitStagedWrite", + "tags": [ + "records" + ], + "summary": "Write every record and its readings in one change. A repeat with the same key gets the first answer.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "write_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "$ref": "#/components/parameters/IdempotencyKeyRequired" + } + ], + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/uploads": { + "post": { + "operationId": "uploadAttachment", + "tags": [ + "records" + ], + "summary": "Upload an attachment file. Name its `upload_id` when creating the record, within one hour.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "description": "The file's bytes. Other file types get `422 refused`.", + "content": { + "image/png": {}, + "image/jpeg": {}, + "image/webp": {}, + "application/pdf": {} + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Upload" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/attachments/{record_id}": { + "get": { + "operationId": "downloadAttachment", + "tags": [ + "records" + ], + "summary": "An attachment's file, with its media type.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + ], + "responses": { + "200": { + "description": "The file's bytes, with its media type.", + "content": { + "image/png": {}, + "image/jpeg": {}, + "image/webp": {}, + "application/pdf": {} + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/grant-offers": { + "post": { + "operationId": "createGrantOffer", + "tags": [ + "grants" + ], + "summary": "Offer a coach access through one app. The code is shown once. A repeat makes a second offer.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "x-athleticstandard-repeat": "Not answered from memory: the answer carries a one-time code that the host stores only as a hash. The summary says what a repeat does.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GrantOfferRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GrantOffer" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/grant-offers/pending": { + "get": { + "operationId": "listPendingOffers", + "tags": [ + "grants" + ], + "summary": "Offers nobody has accepted that have not expired. Codes are never shown again.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PendingOffers" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/grant-offers/{offer_id}": { + "delete": { + "operationId": "cancelGrantOffer", + "tags": [ + "grants" + ], + "summary": "Cancel a pending offer.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "offer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CancelledOffer" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/grants": { + "get": { + "operationId": "listGrants", + "tags": [ + "grants" + ], + "summary": "Every grant for the record, revoked ones included.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GrantList" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/grants/{grant_id}": { + "delete": { + "operationId": "revokeGrant", + "tags": [ + "grants" + ], + "summary": "Revoke a grant. The coach's next request fails, and a coach write already waiting fails too.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "grant_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RevokedGrant" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/grants/{grant_id}/permissions": { + "put": { + "operationId": "narrowGrant", + "tags": [ + "grants" + ], + "summary": "Switch permissions off. Each kept permission must already be in the grant; a coach write already waiting fails.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "grant_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GrantPermissionsRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangedGrant" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/grant-offers/accept": { + "post": { + "operationId": "acceptGrantOffer", + "tags": [ + "grants" + ], + "summary": "Accept an offer, through the app it names.", + "description": "Who may call: any signed-in person.", + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AcceptOfferRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AcceptedGrant" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/apps": { + "get": { + "operationId": "listApps", + "tags": [ + "apps" + ], + "summary": "The apps the owner has used with this record.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AppList" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/apps/{client_id}": { + "delete": { + "operationId": "disconnectApp", + "tags": [ + "apps" + ], + "summary": "Disconnect an app from this record. Its next request gets `403 app_disconnected`. The last connected app cannot be disconnected.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "client_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "description": "The app's client ID, percent-encoded." + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DisconnectedApp" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + }, + "put": { + "operationId": "connectApp", + "tags": [ + "apps" + ], + "summary": "Connect a disconnected app again, from an app that is still connected.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "client_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "description": "The app's client ID, percent-encoded." + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConnectedApp" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/roster": { + "get": { + "operationId": "getRoster", + "tags": [ + "coaching" + ], + "summary": "Each record that granted the caller access through this app.", + "description": "Who may call: any signed-in person.", + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Roster" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/workouts": { + "get": { + "operationId": "listWorkouts", + "tags": [ + "coaching" + ], + "summary": "Workout summaries, newest start first: exactly the fields the read grant allows.", + "description": "Who may call: a coach with an active grant through this app that includes `read_workout_summaries` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "At most this many workouts. The default and maximum are the host's `page_size`.", + "schema": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + { + "name": "after", + "in": "query", + "required": false, + "description": "A `next` value from an earlier page. Treat it as opaque.", + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkoutPage" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/workouts/{record_id}": { + "get": { + "operationId": "getWorkoutDetail", + "tags": [ + "coaching" + ], + "summary": "A workout's data and its recordings. Without `read_gps_routes`, the route and position recordings are left out.", + "description": "Who may call: a coach with an active grant through this app that includes `read_workout_details` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkoutDetail" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/recordings/{record_id}": { + "get": { + "operationId": "getRecordingReadings", + "tags": [ + "coaching" + ], + "summary": "A recording's current readings. A position recording needs `read_gps_routes` too.", + "description": "Who may call: a coach with an active grant through this app that includes `read_workout_details` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "name": "record_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecordingReadings" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/problem-reports": { + "get": { + "operationId": "listProblemReports", + "tags": [ + "coaching" + ], + "summary": "Current injury and illness reports, oldest first.", + "description": "Who may call: a coach with an active grant through this app that includes `read_injury_illness_reports` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecordList" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/training-setup": { + "get": { + "operationId": "getTrainingSetup", + "tags": [ + "coaching" + ], + "summary": "Current goals, events, intensity references, plans, planned sessions, and saved calculations.", + "description": "Who may call: a coach with an active grant through this app that includes `read_training_setup` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecordList" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/programming": { + "post": { + "operationId": "addProgramming", + "tags": [ + "coaching" + ], + "summary": "Add an intensity reference, an event, or an approval of a plan or planned session. The host writes the coach author.", + "description": "Who may call: a coach with an active grant through this app that includes `add_programming` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKeyRequired" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProgrammingRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/notes": { + "post": { + "operationId": "addCoachNote", + "tags": [ + "coaching" + ], + "summary": "Add a coach note. The host writes the coach author. Evidence needs the read grant too.", + "description": "Who may call: a coach with an active grant through this app that includes `add_coach_notes` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKeyRequired" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NoteRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/programs": { + "post": { + "operationId": "addProgram", + "tags": [ + "coaching" + ], + "summary": "Add a training plan and its planned sessions. The result lists the plan, then its sessions.", + "description": "Who may call: a coach with an active grant through this app that includes `add_programming` (D262).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKeyRequired" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProgramRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WriteResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/move/freeze": { + "post": { + "operationId": "freezeForMove", + "tags": [ + "moves" + ], + "summary": "On the source: stop writes and fix the final package. A repeat returns the same transfer.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "x-athleticstandard-repeat": "Not answered from memory: the answer carries a one-time code that the host stores only as a hash. The summary says what a repeat does.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FreezeRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FrozenRecord" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/move/abort": { + "post": { + "operationId": "abortMove", + "tags": [ + "moves" + ], + "summary": "On the source, before retiring: reopen the record for writes.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "x-athleticstandard-repeat": "Not answered from memory: the answer carries a one-time code that the host stores only as a hash. The summary says what a repeat does.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TransferRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReopenedRecord" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/move/retire": { + "post": { + "operationId": "retireForMove", + "tags": [ + "moves" + ], + "summary": "On the source: retire the writer and issue a single-use activation code. A repeat issues a new code; only the newest works.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "x-athleticstandard-repeat": "Not answered from memory: the answer carries a one-time code that the host stores only as a hash. The summary says what a repeat does.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TransferRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RetiredRecord" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/move/activate": { + "post": { + "operationId": "activateMove", + "tags": [ + "moves" + ], + "summary": "On the destination: ask the source to confirm the code, then accept writes.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "x-athleticstandard-repeat": "Not answered from memory: the answer carries a one-time code that the host stores only as a hash. The summary says what a repeat does.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActivateRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ActivatedRecord" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "409": { + "$ref": "#/components/responses/Error409" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "422": { + "$ref": "#/components/responses/Error422" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/athletes/{id}/move/recovery-copy": { + "get": { + "operationId": "getRecoveryCopy", + "tags": [ + "moves" + ], + "summary": "On the source, after retiring: the retired record's package as a zip.", + "description": "Who may call: the record's owner, through an app not disconnected from the record (D270).", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + ], + "responses": { + "200": { + "description": "The complete package as a zip.", + "headers": { + "x-manifest-digest": { + "description": "The SHA-256 of the package's `export-manifest.json`, as 64 lowercase hexadecimal digits.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/zip": {} + } + }, + "401": { + "$ref": "#/components/responses/Error401" + }, + "403": { + "$ref": "#/components/responses/Error403" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + }, + "/v1/transfers/{transfer_id}/verify": { + "post": { + "operationId": "verifyTransfer", + "tags": [ + "moves" + ], + "summary": "Called by the destination host. The code works once, for the destination and digest it names.", + "description": "Who may call: anyone holding the activation code; the destination host calls it.", + "security": [], + "x-athleticstandard-repeat": "Not answered from memory: the answer carries a one-time code that the host stores only as a hash. The summary says what a repeat does.", + "parameters": [ + { + "name": "transfer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifyRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Success.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifiedTransfer" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error400" + }, + "404": { + "$ref": "#/components/responses/Error404" + }, + "413": { + "$ref": "#/components/responses/Error413" + }, + "500": { + "$ref": "#/components/responses/Error500" + } + } + } + } + }, + "components": { + "schemas": { + "NewAthleteRequest": { + "type": "object", + "properties": { + "display_name": { + "type": "string", + "minLength": 1 + }, + "invitation": { + "type": "string", + "minLength": 1 + }, + "incoming": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "CreateRecordRequest": { + "type": "object", + "properties": { + "record_type": { + "$ref": "#/components/schemas/RecordType" + }, + "data": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + }, + "description": "The record's data, in the shape the package schema gives for `record_type`" + }, + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "attachments": { + "type": "array", + "items": { + "type": "string", + "description": "An `upload_id` from the uploads route" + } + } + }, + "required": [ + "record_type", + "data" + ], + "additionalProperties": false + }, + "CorrectionRequest": { + "type": "object", + "properties": { + "expected_revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + }, + "data": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + }, + "description": "The complete new data, in the shape the package schema gives for the record's type" + } + }, + "required": [ + "expected_revision", + "data" + ], + "additionalProperties": false + }, + "DeletionRequest": { + "type": "object", + "properties": { + "expected_revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + } + }, + "required": [ + "expected_revision" + ], + "additionalProperties": false + }, + "ErasureRequest": { + "type": "object", + "properties": { + "expected_revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + }, + "reason_code": { + "$ref": "#/components/schemas/ErasureReasonCode" + } + }, + "required": [ + "expected_revision", + "reason_code" + ], + "additionalProperties": false + }, + "GrantOfferRequest": { + "type": "object", + "properties": { + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Permission" + } + }, + "client_id": { + "type": "string", + "minLength": 1, + "description": "The app the coach must use to accept the offer" + }, + "coach_label": { + "type": "string", + "minLength": 1 + }, + "valid_seconds": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "How long the code works, from 60 seconds to 30 days. The default is 7 days" + } + }, + "required": [ + "permissions", + "client_id" + ], + "additionalProperties": false + }, + "AcceptOfferRequest": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "code" + ], + "additionalProperties": false + }, + "Evidence": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "NoteRequest": { + "type": "object", + "properties": { + "note": { + "type": "string", + "minLength": 1 + }, + "title": { + "type": "string", + "minLength": 1 + }, + "applies_from": { + "type": "string", + "minLength": 1 + }, + "applies_to": { + "type": "string", + "minLength": 1 + }, + "evidence": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Evidence" + } + } + }, + "required": [ + "note" + ], + "additionalProperties": false + }, + "ProgramRequest": { + "type": "object", + "properties": { + "plan": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + }, + "description": "Training plan data, without `authorship`" + }, + "sessions": { + "type": "array", + "items": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + }, + "description": "Planned session data, without `authorship`, `training_plan_id`, `completion_status`, or `completed_workout_session_id`" + } + } + }, + "required": [ + "plan" + ], + "additionalProperties": false + }, + "FreezeRequest": { + "type": "object", + "properties": { + "destination": { + "type": "string", + "minLength": 1, + "description": "The destination host's `public_url`" + } + }, + "required": [ + "destination" + ], + "additionalProperties": false + }, + "TransferRequest": { + "type": "object", + "properties": { + "transfer_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "transfer_id" + ], + "additionalProperties": false + }, + "ActivateRequest": { + "type": "object", + "properties": { + "source": { + "type": "string", + "minLength": 1, + "description": "The source host's `public_url`" + }, + "transfer_id": { + "type": "string", + "minLength": 1 + }, + "activation": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "source", + "transfer_id", + "activation" + ], + "additionalProperties": false + }, + "VerifyRequest": { + "type": "object", + "properties": { + "activation": { + "type": "string", + "minLength": 1 + }, + "destination": { + "type": "string", + "minLength": 1 + }, + "manifest_digest": { + "type": "string", + "description": "A SHA-256 digest as 64 lowercase hexadecimal digits" + } + }, + "required": [ + "activation", + "destination", + "manifest_digest" + ], + "additionalProperties": false + }, + "Error": { + "type": "object", + "properties": { + "error": { + "$ref": "#/components/schemas/ErrorDetail" + } + }, + "required": [ + "error" + ], + "additionalProperties": false + }, + "ErrorDetail": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "sign_in_required", + "permission_denied", + "app_disconnected", + "not_found", + "stale", + "request_conflict", + "host_moving", + "limit_reached", + "invalid", + "refused", + "internal" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + }, + "ProtectedResource": { + "type": "object", + "properties": { + "resource": { + "type": "string", + "minLength": 1 + }, + "authorization_servers": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "bearer_methods_supported": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "resource_name": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "resource", + "authorization_servers", + "bearer_methods_supported", + "resource_name" + ], + "additionalProperties": false + }, + "Capabilities": { + "type": "object", + "properties": { + "api_version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "athleticstandard_version": { + "type": "string", + "minLength": 1 + }, + "storage": { + "type": "string", + "enum": [ + "directory", + "libsql" + ] + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Permission" + } + }, + "operator_disclosure": { + "type": "string" + }, + "open_enrollment": { + "type": "boolean" + } + }, + "required": [ + "api_version", + "athleticstandard_version", + "storage", + "permissions", + "operator_disclosure", + "open_enrollment" + ], + "additionalProperties": false + }, + "Me": { + "type": "object", + "properties": { + "principal_id": { + "type": "string", + "minLength": 1 + }, + "client_id": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "minLength": 1 + }, + "athletes": { + "type": "array", + "items": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + } + } + }, + "required": [ + "principal_id", + "client_id", + "coach_id", + "athletes" + ], + "additionalProperties": false + }, + "CreatedAthlete": { + "type": "object", + "properties": { + "athlete_id": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + }, + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "operator_disclosure": { + "type": "string" + } + }, + "required": [ + "athlete_id", + "database_revision", + "operator_disclosure" + ], + "additionalProperties": false + }, + "AthleteEntry": { + "type": "object", + "properties": { + "athlete_id": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + }, + "display_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "state": { + "type": "string", + "enum": [ + "active", + "frozen", + "staged" + ] + } + }, + "required": [ + "athlete_id", + "display_name", + "state" + ], + "additionalProperties": false + }, + "AthleteList": { + "type": "object", + "properties": { + "athletes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AthleteEntry" + } + } + }, + "required": [ + "athletes" + ], + "additionalProperties": false + }, + "AthleteSummary": { + "type": "object", + "properties": { + "athlete_id": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + }, + "role": { + "type": "string", + "enum": [ + "owner", + "coach" + ] + }, + "state": { + "type": "string", + "enum": [ + "active", + "frozen", + "staged" + ] + }, + "operator_disclosure": { + "type": "string" + }, + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "athlete_id", + "role", + "state", + "operator_disclosure" + ], + "additionalProperties": false + }, + "DatabaseRevision": { + "type": "object", + "properties": { + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "database_revision" + ], + "additionalProperties": false + }, + "LoggedChange": { + "type": "object", + "properties": { + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "record_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "0 for an erasure" + }, + "kind": { + "type": "string", + "enum": [ + "revision", + "deletion", + "erasure" + ] + } + }, + "required": [ + "database_revision", + "record_id", + "record_revision", + "kind" + ], + "additionalProperties": false + }, + "ChangeList": { + "type": "object", + "properties": { + "from": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "to": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "complete": { + "type": "boolean" + }, + "changes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/LoggedChange" + } + } + }, + "required": [ + "from", + "to", + "complete", + "changes" + ], + "additionalProperties": false + }, + "RecordList": { + "type": "object", + "properties": { + "records": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CurrentRecord" + } + } + }, + "required": [ + "records" + ], + "additionalProperties": false + }, + "RecordWithHistory": { + "type": "object", + "properties": { + "record": { + "$ref": "#/components/schemas/CurrentRecord" + }, + "revisions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RecordRevision" + } + } + }, + "required": [ + "record", + "revisions" + ], + "additionalProperties": false + }, + "WrittenRecord": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + } + }, + "required": [ + "record_id", + "revision" + ], + "additionalProperties": false + }, + "WriteResult": { + "type": "object", + "properties": { + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "records": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WrittenRecord" + } + } + }, + "required": [ + "database_revision", + "records" + ], + "additionalProperties": false + }, + "Upload": { + "type": "object", + "properties": { + "upload_id": { + "type": "string", + "minLength": 1 + }, + "byte_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "sha256": { + "type": "string", + "description": "A SHA-256 digest as 64 lowercase hexadecimal digits" + }, + "media_type": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "upload_id", + "byte_count", + "sha256", + "media_type" + ], + "additionalProperties": false + }, + "GrantOffer": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1 + }, + "expires_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Permission" + } + }, + "client_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "code", + "expires_at", + "permissions", + "client_id" + ], + "additionalProperties": false + }, + "PendingOffer": { + "type": "object", + "properties": { + "offer_id": { + "type": "string", + "minLength": 1 + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Permission" + } + }, + "client_id": { + "type": "string", + "minLength": 1 + }, + "coach_label": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "expires_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + } + }, + "required": [ + "offer_id", + "permissions", + "client_id", + "coach_label", + "created_at", + "expires_at" + ], + "additionalProperties": false + }, + "PendingOffers": { + "type": "object", + "properties": { + "offers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PendingOffer" + } + } + }, + "required": [ + "offers" + ], + "additionalProperties": false + }, + "CancelledOffer": { + "type": "object", + "properties": { + "cancelled": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "cancelled" + ], + "additionalProperties": false + }, + "Grant": { + "type": "object", + "properties": { + "grant_id": { + "type": "string", + "minLength": 1 + }, + "resource_id": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + }, + "coach_principal_id": { + "type": "string", + "minLength": 1 + }, + "client_id": { + "type": "string", + "minLength": 1 + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Permission" + } + }, + "coach_label": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "revoked_at": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "grant_id", + "resource_id", + "coach_principal_id", + "client_id", + "permissions", + "coach_label", + "created_at", + "revoked_at" + ], + "additionalProperties": false + }, + "GrantList": { + "type": "object", + "properties": { + "grants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Grant" + } + } + }, + "required": [ + "grants" + ], + "additionalProperties": false + }, + "AcceptedGrant": { + "type": "object", + "properties": { + "grant": { + "$ref": "#/components/schemas/Grant" + } + }, + "required": [ + "grant" + ], + "additionalProperties": false + }, + "RevokedGrant": { + "type": "object", + "properties": { + "revoked": { + "type": "string", + "minLength": 1 + }, + "access_epoch": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "revoked", + "access_epoch" + ], + "additionalProperties": false + }, + "App": { + "type": "object", + "properties": { + "client_id": { + "type": "string", + "minLength": 1 + }, + "state": { + "type": "string", + "enum": [ + "connected", + "disconnected" + ] + }, + "connected_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "last_used_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "disconnected_at": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + { + "type": "null" + } + ] + }, + "this_app": { + "type": "boolean" + } + }, + "required": [ + "client_id", + "state", + "connected_at", + "last_used_at", + "disconnected_at", + "this_app" + ], + "additionalProperties": false + }, + "AppList": { + "type": "object", + "properties": { + "apps": { + "type": "array", + "items": { + "$ref": "#/components/schemas/App" + } + } + }, + "required": [ + "apps" + ], + "additionalProperties": false + }, + "DisconnectedApp": { + "type": "object", + "properties": { + "app": { + "$ref": "#/components/schemas/App" + }, + "access_epoch": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "app", + "access_epoch" + ], + "additionalProperties": false + }, + "ConnectedApp": { + "type": "object", + "properties": { + "app": { + "$ref": "#/components/schemas/App" + } + }, + "required": [ + "app" + ], + "additionalProperties": false + }, + "RosterEntry": { + "type": "object", + "properties": { + "athlete_id": { + "type": "string", + "pattern": "^ath_[0-9a-f]{32}$", + "description": "An athlete ID: `ath_` and 32 lowercase hexadecimal digits" + }, + "display_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Permission" + } + }, + "grant_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "athlete_id", + "display_name", + "permissions", + "grant_id" + ], + "additionalProperties": false + }, + "Roster": { + "type": "object", + "properties": { + "athletes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RosterEntry" + } + } + }, + "required": [ + "athletes" + ], + "additionalProperties": false + }, + "WorkoutSummary": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "activity_type": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "record_id", + "revision", + "start_at", + "end_at", + "activity_type" + ], + "additionalProperties": false + }, + "WorkoutPage": { + "type": "object", + "properties": { + "workouts": { + "type": "array", + "items": { + "$ref": "#/components/schemas/WorkoutSummary" + } + }, + "next": { + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "workouts", + "next" + ], + "additionalProperties": false + }, + "RecordingSummary": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + }, + "quantity": { + "type": "string", + "minLength": 1 + }, + "unit": { + "type": "string", + "minLength": 1 + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "reading_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_id", + "revision", + "quantity", + "unit", + "start_at", + "end_at", + "reading_count" + ], + "additionalProperties": false + }, + "WorkoutDetail": { + "type": "object", + "properties": { + "record": { + "$ref": "#/components/schemas/CurrentRecord" + }, + "recordings": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RecordingSummary" + } + } + }, + "required": [ + "record", + "recordings" + ], + "additionalProperties": false + }, + "RecordingReadings": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991, + "description": "A record revision, from 1" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "offsets_ms": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "values": { + "type": "array", + "items": { + "$ref": "#/components/schemas/JsonValue" + } + } + }, + "required": [ + "record_id", + "revision", + "start_at", + "offsets_ms", + "values" + ], + "additionalProperties": false + }, + "ProgrammingRequest": { + "type": "object", + "properties": { + "record_type": { + "type": "string", + "enum": [ + "intensity_reference", + "event", + "approval" + ] + }, + "data": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + }, + "description": "The record's data, without `authorship`" + } + }, + "required": [ + "record_type", + "data" + ], + "additionalProperties": false + }, + "GrantPermissionsRequest": { + "type": "object", + "properties": { + "permissions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Permission" + } + } + }, + "required": [ + "permissions" + ], + "additionalProperties": false + }, + "ChangedGrant": { + "type": "object", + "properties": { + "grant": { + "$ref": "#/components/schemas/Grant" + }, + "access_epoch": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "grant", + "access_epoch" + ], + "additionalProperties": false + }, + "StagedRecord": { + "type": "object", + "properties": { + "record_type": { + "$ref": "#/components/schemas/RecordType" + }, + "data": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + }, + "description": "The record's data. A device recording gives `reading_count` 0 and an empty `blocks` list; its readings follow in pieces" + }, + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "piece_count": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_type", + "data" + ], + "additionalProperties": false + }, + "StagedWriteRequest": { + "type": "object", + "properties": { + "records": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StagedRecord" + } + } + }, + "required": [ + "records" + ], + "additionalProperties": false + }, + "ReadingsPiece": { + "type": "object", + "properties": { + "offsets_ms": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "values": { + "type": "array", + "items": { + "$ref": "#/components/schemas/JsonValue" + } + }, + "durations_ms": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + } + }, + "required": [ + "offsets_ms", + "values" + ], + "additionalProperties": false + }, + "PieceRef": { + "type": "object", + "properties": { + "record_index": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "piece": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "record_index", + "piece" + ], + "additionalProperties": false + }, + "StagedWrite": { + "type": "object", + "properties": { + "write_id": { + "type": "string", + "minLength": 1 + }, + "record_count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "pieces": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PieceRef" + } + }, + "expires_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + } + }, + "required": [ + "write_id", + "record_count", + "pieces", + "expires_at" + ], + "additionalProperties": false + }, + "MergeResult": { + "type": "object", + "properties": { + "from_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "database_revision": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "added": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "changed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "deleted": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "erased": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "required": [ + "from_revision", + "database_revision", + "added", + "changed", + "deleted", + "erased" + ], + "additionalProperties": false + }, + "FrozenRecord": { + "type": "object", + "properties": { + "transfer_id": { + "type": "string", + "minLength": 1 + }, + "manifest_digest": { + "anyOf": [ + { + "type": "string", + "description": "A SHA-256 digest as 64 lowercase hexadecimal digits" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "transfer_id", + "manifest_digest" + ], + "additionalProperties": false + }, + "RetiredRecord": { + "type": "object", + "properties": { + "transfer_id": { + "type": "string", + "minLength": 1 + }, + "activation": { + "type": "string", + "minLength": 1 + }, + "manifest_digest": { + "anyOf": [ + { + "type": "string", + "description": "A SHA-256 digest as 64 lowercase hexadecimal digits" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "transfer_id", + "activation", + "manifest_digest" + ], + "additionalProperties": false + }, + "ReopenedRecord": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "active" + ] + } + }, + "required": [ + "state" + ], + "additionalProperties": false + }, + "ActivatedRecord": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "active" + ] + }, + "manifest_digest": { + "type": "string", + "description": "A SHA-256 digest as 64 lowercase hexadecimal digits" + } + }, + "required": [ + "state", + "manifest_digest" + ], + "additionalProperties": false + }, + "VerifiedTransfer": { + "type": "object", + "properties": { + "verified": { + "type": "boolean" + } + }, + "required": [ + "verified" + ], + "additionalProperties": false + }, + "Permission": { + "type": "string", + "enum": [ + "read_workout_summaries", + "read_workout_details", + "read_gps_routes", + "read_injury_illness_reports", + "read_training_setup", + "add_coach_notes", + "add_programming" + ] + }, + "RecordType": { + "type": "string", + "enum": [ + "athlete_profile", + "source", + "source_device", + "point_measurement", + "measurement_sample", + "sleep_session", + "workout_session", + "benchmark_result", + "provider_summary", + "provider_score", + "athlete_report", + "nutrition_entry", + "attachment", + "benchmark_definition", + "prediction", + "prediction_result_link", + "prediction_grade", + "prediction_error_analysis", + "training_plan", + "planned_session", + "coaching_note", + "saved_training_review", + "goal", + "nutrition_model_interpretation", + "intensity_reference", + "event", + "approval", + "calculation_result", + "device_recording" + ] + }, + "ErasureReasonCode": { + "type": "string", + "enum": [ + "athlete_request", + "legal_requirement", + "recorded_in_error", + "other" + ] + }, + "CurrentRecord": { + "description": "A current record, as in `records` of the package schema, or a measurement sample, as in `records` of the measurement-series schema.", + "anyOf": [ + { + "$ref": "athleticstandard.schema.json#/properties/records/items" + }, + { + "$ref": "measurement-series.schema.json#/properties/records/items" + } + ] + }, + "RecordRevision": { + "description": "One revision of a record, as in `record_revisions` of the package schema or of the measurement-series schema.", + "anyOf": [ + { + "$ref": "athleticstandard.schema.json#/properties/record_revisions/items" + }, + { + "$ref": "measurement-series.schema.json#/properties/record_revisions/items" + } + ] + }, + "JsonValue": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/JsonValue" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/JsonValue" + } + } + ] + } + }, + "parameters": { + "IdempotencyKey": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "1 to 200 characters. Send the same key when you repeat a request. A repeat with the same key, method, path, and body gets the first answer; the same key with another request gets `409 request_conflict` (D261).", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + }, + "IdempotencyKeyRequired": { + "name": "Idempotency-Key", + "in": "header", + "required": true, + "description": "1 to 200 characters. Send the same key when you repeat a request. A repeat with the same key, method, path, and body gets the first answer; the same key with another request gets `409 request_conflict` (D261).", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + } + }, + "responses": { + "Error400": { + "description": "`invalid`: the request is malformed, or a body does not match its shape.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "Error401": { + "description": "`sign_in_required`: no token, or a token the host refuses. The answer has a `WWW-Authenticate` header naming the protected-resource metadata.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "Error403": { + "description": "`permission_denied`: the route or permission is not the caller's. `app_disconnected`: the owner disconnected this app from the record.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "Error404": { + "description": "`not_found`: no such resource, or nothing the caller may see. An unknown record and one that is not shared get the same answer.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "Error409": { + "description": "`stale`, `request_conflict`, or `host_moving`.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "Error413": { + "description": "`limit_reached`: the body is larger than the host allows.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "Error422": { + "description": "`refused`: the library refused the change.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "Error500": { + "description": "`internal`: the host could not finish. Details stay in the host's log.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "securitySchemes": { + "bearer": { + "type": "http", + "scheme": "bearer", + "description": "An OAuth access token from the host's OpenID Connect provider (D260). The token must name the app it was issued to in `azp` or `client_id`. `/.well-known/oauth-protected-resource` names the provider." + } + } + } +} diff --git a/schema/3.1.0/measurement-series.schema.json b/schema/3.1.0/measurement-series.schema.json new file mode 100644 index 00000000..5c2b4881 --- /dev/null +++ b/schema/3.1.0/measurement-series.schema.json @@ -0,0 +1,1328 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://athleticstandard.ai/schema/3.1.0/measurement-series.schema.json", + "title": "Athletic Standard measurement-series file", + "type": "object", + "properties": { + "athleticstandard_version": { + "type": "string", + "enum": [ + "1.0.0", + "2.0.0", + "2.1.0", + "2.1.1", + "2.1.2", + "2.1.3", + "3.0.0", + "3.1.0" + ] + }, + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "quantity": { + "type": "string", + "enum": [ + "heart_rate", + "hrv_beats", + "ecg_beats", + "hrv_sdnn", + "respiratory_rate", + "oxygen_saturation", + "steps", + "active_energy", + "distance_walking_running", + "distance_cycling", + "distance_swimming", + "running_speed", + "running_power", + "running_stride_length", + "running_vertical_oscillation", + "running_ground_contact_time", + "physical_effort", + "basal_energy", + "exercise_time", + "flights_climbed", + "walking_speed", + "walking_step_length", + "walking_asymmetry_percentage", + "time_in_daylight" + ] + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "records": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "created_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "current_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "is_deleted": { + "type": "boolean" + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + }, + "record_type": { + "type": "string", + "const": "measurement_sample" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "heart_rate", + "hrv_beats", + "ecg_beats", + "hrv_sdnn", + "respiratory_rate", + "oxygen_saturation", + "steps", + "active_energy", + "distance_walking_running", + "distance_cycling", + "distance_swimming", + "running_speed", + "running_power", + "running_stride_length", + "running_vertical_oscillation", + "running_ground_contact_time", + "physical_effort", + "basal_energy", + "exercise_time", + "flights_climbed", + "walking_speed", + "walking_step_length", + "walking_asymmetry_percentage", + "time_in_daylight" + ] + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "duration_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "timestamp_base_text": { + "type": "string", + "minLength": 1 + }, + "timestamp_reconstruction_method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "quantity", + "recorded_at", + "input_timestamp", + "value" + ], + "additionalProperties": false + } + }, + "required": [ + "record_id", + "created_at", + "current_revision", + "is_deleted", + "record_type", + "data" + ], + "additionalProperties": false + } + }, + "record_revisions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "previous_revision": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "became_known_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "became_known_at_basis": { + "type": "string", + "enum": [ + "local_write", + "provider_import", + "package_restore", + "package_merge" + ] + }, + "changed_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + }, + "record_type": { + "type": "string", + "const": "measurement_sample" + }, + "data": { + "type": "object", + "properties": { + "source_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "provider_record_id": { + "type": "string", + "minLength": 1 + }, + "provider_reporting_periods": { + "type": "array", + "items": { + "type": "object", + "properties": { + "period_type": { + "type": "string", + "enum": [ + "whoop_physiological_cycle", + "oura_activity_day", + "oura_sleep_day", + "oura_calendar_day", + "oura_day_unspecified", + "apple_activity_summary_day" + ] + }, + "provider_period_id": { + "type": "string", + "minLength": 1 + }, + "provider_date": { + "type": "string", + "format": "date", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$", + "description": "ISO 8601 calendar date" + }, + "start_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "end_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_start_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "input_end_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "timezone_offset_text": { + "type": "string", + "minLength": 1 + }, + "timezone_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "timezone_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "period_type" + ], + "additionalProperties": false + } + }, + "received_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "received_at_basis": { + "type": "string", + "enum": [ + "provider_supplied", + "connector_received_time", + "file_modified_time", + "import_time", + "local_write_time" + ] + }, + "supplied_fields": { + "type": "object", + "propertyNames": { + "type": "string", + "minLength": 1 + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + }, + "field_basis": { + "type": "object", + "properties": { + "activity_type": { + "type": "string", + "enum": [ + "aggregator_normalized", + "provider_label" + ] + }, + "value": { + "type": "string", + "enum": [ + "provider_or_aggregator", + "provider", + "hrv_mean_rmssd", + "provider_documented_rmssd", + "calculated_on_import", + "entered_by_hand" + ] + }, + "route_summaries": { + "type": "string", + "const": "calculated_on_import" + }, + "machine": { + "type": "string", + "enum": [ + "source", + "athlete", + "preference_default", + "assumed" + ] + } + }, + "additionalProperties": false + }, + "quantity": { + "type": "string", + "enum": [ + "heart_rate", + "hrv_beats", + "ecg_beats", + "hrv_sdnn", + "respiratory_rate", + "oxygen_saturation", + "steps", + "active_energy", + "distance_walking_running", + "distance_cycling", + "distance_swimming", + "running_speed", + "running_power", + "running_stride_length", + "running_vertical_oscillation", + "running_ground_contact_time", + "physical_effort", + "basal_energy", + "exercise_time", + "flights_climbed", + "walking_speed", + "walking_step_length", + "walking_asymmetry_percentage", + "time_in_daylight" + ] + }, + "recorded_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "input_timestamp": { + "type": "object", + "properties": { + "timestamp_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_text": { + "type": "string", + "minLength": 1 + }, + "utc_offset_meaning": { + "type": "string", + "enum": [ + "documented_recording_offset", + "provider_cycle_offset", + "route_rendering_offset", + "meaning_not_documented" + ] + }, + "source_time_zone": { + "type": "string", + "minLength": 1 + }, + "source_time_zone_meaning": { + "type": "string", + "enum": [ + "apple_health_object_creation_time_zone" + ] + }, + "timestamp_basis": { + "type": "string", + "enum": [ + "source_instant", + "source_offset_timestamp", + "source_local_timestamp_with_documented_offset", + "reconstructed_from_series_start" + ] + }, + "timestamp_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "utc_offset_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "additionalProperties": false + }, + "value": { + "type": "object", + "properties": { + "standard_value": { + "type": "number" + }, + "standard_unit": { + "type": "string", + "minLength": 1 + }, + "input_value": { + "type": "number" + }, + "input_unit": { + "type": "string", + "minLength": 1 + }, + "input_value_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + }, + "input_unit_missing_reason": { + "type": "string", + "enum": [ + "not_provided_by_source", + "not_exposed_by_route", + "not_applicable" + ] + } + }, + "required": [ + "standard_value", + "standard_unit" + ], + "additionalProperties": false + }, + "duration_ms": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "timestamp_base_text": { + "type": "string", + "minLength": 1 + }, + "timestamp_reconstruction_method": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "source_id", + "received_at", + "received_at_basis", + "quantity", + "recorded_at", + "input_timestamp", + "value" + ], + "additionalProperties": false + }, + "extensions": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + }, + "required": [ + "record_id", + "revision", + "previous_revision", + "became_known_at", + "became_known_at_basis", + "changed_by", + "record_type", + "data" + ], + "additionalProperties": false + } + }, + "record_deletions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "record_revision": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "deleted_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + }, + "deleted_by": { + "oneOf": [ + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "athlete" + } + }, + "required": [ + "author_type" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "agent" + }, + "agent": { + "type": "string", + "minLength": 1 + }, + "agent_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "agent" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "tool" + }, + "tool": { + "type": "string", + "minLength": 1 + }, + "tool_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" + } + }, + "required": [ + "author_type", + "tool", + "tool_version" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "author_type": { + "type": "string", + "const": "coach" + }, + "coach": { + "type": "string", + "minLength": 1 + }, + "coach_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + } + }, + "required": [ + "author_type", + "coach", + "coach_id" + ], + "additionalProperties": false + } + ] + } + }, + "required": [ + "record_id", + "record_revision", + "deleted_at", + "deleted_by" + ], + "additionalProperties": false + } + }, + "record_import_keys": { + "type": "array", + "items": { + "type": "object", + "properties": { + "record_id": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", + "description": "Stable UUIDv7 record ID" + }, + "match_key_method": { + "type": "string", + "minLength": 1 + }, + "match_key": { + "type": "string", + "minLength": 1 + }, + "imported_at": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}(?:Z))$", + "description": "Normalized ISO 8601 timestamp in UTC with millisecond precision" + } + }, + "required": [ + "record_id", + "match_key_method", + "match_key", + "imported_at" + ], + "additionalProperties": false + } + } + }, + "required": [ + "athleticstandard_version", + "source_id", + "quantity", + "start_at", + "end_at", + "records", + "record_revisions", + "record_deletions", + "record_import_keys" + ], + "additionalProperties": false, + "$defs": { + "__schema0": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096 + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "maxItems": 256, + "type": "array", + "items": { + "$ref": "#/$defs/__schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema0" + } + } + ] + }, + "__schema1": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/__schema1" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/$defs/__schema1" + } + } + ] + } + } +} diff --git a/schema/athleticstandard.schema.json b/schema/athleticstandard.schema.json index ff77129d..ecdb6456 100644 --- a/schema/athleticstandard.schema.json +++ b/schema/athleticstandard.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://athleticstandard.ai/schema/3.0.0/athleticstandard.schema.json", + "$id": "https://athleticstandard.ai/schema/3.1.0/athleticstandard.schema.json", "title": "Athletic Standard portable package document", "type": "object", "properties": { @@ -13,7 +13,8 @@ "2.1.1", "2.1.2", "2.1.3", - "3.0.0" + "3.0.0", + "3.1.0" ] }, "database_id": { diff --git a/skills/athletic-standard/SKILL.md b/skills/athletic-standard/SKILL.md index c4dfb407..619297e2 100644 --- a/skills/athletic-standard/SKILL.md +++ b/skills/athletic-standard/SKILL.md @@ -1,10 +1,10 @@ --- name: athletic-standard -description: Reads and writes an athlete's Athletic Standard SQLite database (.ath.sqlite) with the ath CLI. Applies when someone logs a workout, lift, named benchmark such as Fran, HRV as RMSSD or SDNN, resting heart rate, sleep, soreness, nutrition, or another athlete report; asks what training or recovery data shows; asks for a benchmark prediction or backtest; reports a result to grade; imports Apple Health, WHOOP, Oura, Garmin, or Strava, or an Athletic Standard 2.0.0, 2.1.0, 2.1.1, 2.1.2, 2.1.3, or 3.0.0 package; reads an Open Wearables or Junction JSON file through a mapping file; exports a complete package; runs ath apply on one record; or asks about Athletic Standard records, revisions, calculations, deletion, or privacy erasure. +description: Reads and writes an athlete's Athletic Standard SQLite database (.ath.sqlite) with the ath CLI. Applies when someone logs a workout, lift, named benchmark such as Fran, HRV as RMSSD or SDNN, resting heart rate, sleep, soreness, nutrition, or another athlete report; asks what training or recovery data shows; asks for a benchmark prediction or backtest; reports a result to grade; imports Apple Health, WHOOP, Oura, Garmin, or Strava, or an Athletic Standard 2.0.0, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 3.0.0, or 3.1.0 package; reads an Open Wearables or Junction JSON file through a mapping file; exports a complete package; runs ath apply on one record; or asks about Athletic Standard records, revisions, calculations, deletion, or privacy erasure. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later on PATH, from the athleticstandard npm package or a native release archive. Local database use needs no network. Optional terminal model calls need a configured gateway. +compatibility: Requires the ath CLI 3.1.0 or later on PATH, from the athleticstandard npm package or a native release archive. Local database use needs no network. Optional terminal model calls need a configured gateway. metadata: - version: "3.0.0" + version: "3.1.0" kind: tool --- @@ -14,9 +14,9 @@ The live local record is one SQLite database named `athlete.ath.sqlite`. `ath` r and writes it. A JSON package is an explicit complete snapshot. It is not a second live copy. -This skill expects Athletic Standard **3.0.0**. A version 1.0.0, 2.0.0, 2.1.0, 2.1.1, -2.1.2, or 2.1.3 database upgrades with `ath migrate`. A 2.0.0, 2.1.0, 2.1.1, 2.1.2, or -2.1.3 package still imports. +This skill expects Athletic Standard **3.1.0**. A version 1.0.0, 2.0.0, 2.1.0, 2.1.1, +2.1.2, 2.1.3, or 3.0.0 database upgrades with `ath migrate`. A 2.0.0, 2.1.0, 2.1.1, +2.1.2, 2.1.3, or 3.0.0 package still imports. Prerelease `0.x` JSON documents are not imported. Local use needs no account, network connection, subscription, or hosted service. @@ -33,16 +33,16 @@ authored record. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/athletic-standard/references/format.md b/skills/athletic-standard/references/format.md index 1eccc38a..fac38ec7 100644 --- a/skills/athletic-standard/references/format.md +++ b/skills/athletic-standard/references/format.md @@ -8,7 +8,7 @@ JSON exists only as an explicit complete export or import package. It is not a l copy and does not stay synchronized. The full public field reference is `SPEC.md`. Exhaustive generated schemas are in -`schema/3.0.0/`. +`schema/3.1.0/`. ## Common record fields diff --git a/skills/baseline/SKILL.md b/skills/baseline/SKILL.md index cf766b71..d28e062b 100644 --- a/skills/baseline/SKILL.md +++ b/skills/baseline/SKILL.md @@ -2,9 +2,9 @@ name: baseline description: Gives an athlete's normal value and spread for one measurement over a period, separately for each device, with a fair daily-mean version when the time zone is known. Use when someone asks what their normal or baseline HRV (RMSSD or SDNN), resting heart rate, or other reading is, or what range counts as normal for them. Not for whether one day differs from normal (use hrv-change or resting-heart-rate-change) or direction over time (use trend). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate baseline . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate baseline . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ when the day is known, the same for calendar-day means. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/best-efforts/SKILL.md b/skills/best-efforts/SKILL.md index 59b0f26b..6b3a9017 100644 --- a/skills/best-efforts/SKILL.md +++ b/skills/best-efforts/SKILL.md @@ -2,9 +2,9 @@ name: best-efforts description: Finds one workout's best mean power and best mean speed over 5 seconds, 1, 5, 20, and 60 minutes from its device recordings, counting only fully covered efforts. Use when someone asks for a ride's or run's best efforts, peak power, or best 20 minutes. Not a threshold: critical-power and critical-speed fit thresholds from many workouts. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply best-efforts --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply best-efforts --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ The best mean power and speed a workout held over fixed durations, read from its ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/compare-sources/SKILL.md b/skills/compare-sources/SKILL.md index 2b3d5b5a..daa4c7e9 100644 --- a/skills/compare-sources/SKILL.md +++ b/skills/compare-sources/SKILL.md @@ -2,9 +2,9 @@ name: compare-sources description: Compares the same measurement from two devices, such as a ring and a watch, by their separate averages and, when the day is known, on the days both devices read. Use when someone asks why two devices disagree on HRV, resting heart rate, or another reading, how far apart they are, or before switching devices. Never merges the two sources. Not for a single device's normal (use baseline). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate compare-sources --source --compare-source . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate compare-sources --source --compare-source . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ with a time zone, the mean difference on days both devices read. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/correlation/SKILL.md b/skills/correlation/SKILL.md index 1748cf25..de10600c 100644 --- a/skills/correlation/SKILL.md +++ b/skills/correlation/SKILL.md @@ -2,9 +2,9 @@ name: correlation description: Measures how two measurements move together day by day, such as HRV and resting heart rate or HRV and respiratory rate, using each calendar day's mean and needing at least three paired days. Use when someone asks whether two of their readings are related, or whether one tends to be low when the other is high. Reports association only; never shows cause. Not for one quantity over time (use trend). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate correlation --other-quantity --timezone . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate correlation --other-quantity --timezone . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ both have a reading. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/coverage/SKILL.md b/skills/coverage/SKILL.md index 162c2dba..63e64d41 100644 --- a/skills/coverage/SKILL.md +++ b/skills/coverage/SKILL.md @@ -2,9 +2,9 @@ name: coverage description: Lists which calendar days have at least one reading of a measurement and which are missing, separately for each device, with the share of days covered. Use before describing a week or month of HRV, resting heart rate, sleep-related readings, or any other quantity, or when someone asks how consistently they wore their device or why a summary looks odd. Not for the values themselves (use summary or baseline). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate coverage . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate coverage . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ for each source. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/critical-power/SKILL.md b/skills/critical-power/SKILL.md index b334ada6..8c40f8bc 100644 --- a/skills/critical-power/SKILL.md +++ b/skills/critical-power/SKILL.md @@ -2,9 +2,9 @@ name: critical-power description: Estimates threshold power and the work capacity above it from the athlete's own best efforts: four published critical power fits, two fixed-fraction rules, the 3-minute all-out cycling and rowing tests, and best 1- and 5-second peak power. Use when someone asks what their threshold power or FTP is from their rides, or wants to set power zones from data. Results are shown first and saved only when a person asks. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply critical-power --set sport= --set machine=. +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply critical-power --set sport= --set machine=. metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Threshold power (critical power) and the work capacity above it, from the athlet ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/critical-speed/SKILL.md b/skills/critical-speed/SKILL.md index b9648ea5..9363b542 100644 --- a/skills/critical-speed/SKILL.md +++ b/skills/critical-speed/SKILL.md @@ -2,9 +2,9 @@ name: critical-speed description: Estimates threshold speed and the distance that can be covered above it from the athlete's own best efforts: four published critical speed fits, the 3-minute all-out running test, critical swim speed from 400 m and 200 m, and the 30-minute running time trial, which also gives threshold heart rate. Use when someone asks for their threshold pace or speed from their runs or swims. Results are shown first and saved only when a person asks. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply critical-speed --set sport= --set machine=. +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply critical-speed --set sport= --set machine=. metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Threshold speed (critical speed) and the distance above it, from the athlete's o ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/crossfit/SKILL.md b/skills/crossfit/SKILL.md index 4fbe4f5e..c33ca842 100644 --- a/skills/crossfit/SKILL.md +++ b/skills/crossfit/SKILL.md @@ -2,9 +2,9 @@ name: crossfit description: Coaches one CrossFit athlete from their Athletic Standard record. Assesses goals, training age, and movement competence; plans weeks and blocks across strength, gymnastics, and conditioning; scales workouts to keep the intended stimulus; fits extra work around gym classes; compares benchmark attempts only when the versions match; prepares for the CrossFit Open under the named season's rules; and reviews a training week. Use when someone asks for a CrossFit plan, scaling advice, a benchmark comparison such as Fran or Helen, Open preparation, or a weekly review. Not for HYROX (use hyrox), one calculation (use the calculation skills), or medical questions. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install crossfit. +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install crossfit. metadata: - version: "3.0.0" + version: "3.1.0" kind: coaching --- @@ -77,16 +77,16 @@ What research supports, and what it does not, is in ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/heart-rate-recovery/SKILL.md b/skills/heart-rate-recovery/SKILL.md index d3318f6d..91483bbe 100644 --- a/skills/heart-rate-recovery/SKILL.md +++ b/skills/heart-rate-recovery/SKILL.md @@ -2,9 +2,9 @@ name: heart-rate-recovery description: Measures how far heart rate falls in the 60 seconds after an effort ends, from one workout's heart-rate samples. Use when someone asks how fast their heart rate came down after an interval, a workout, or a test, or whether their one-minute recovery is improving. Needs samples recorded after the effort ends, such as a lap marked recovery. Not for resting heart rate (use resting-heart-rate) or a device's own recovery number (read the hr_recovery measurement). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-recovery --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-recovery --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -16,16 +16,16 @@ recovery. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/heart-rate-zones/SKILL.md b/skills/heart-rate-zones/SKILL.md index 64eba22e..8117bb3b 100644 --- a/skills/heart-rate-zones/SKILL.md +++ b/skills/heart-rate-zones/SKILL.md @@ -2,9 +2,9 @@ name: heart-rate-zones description: Splits one workout's heart rate into five zones by percentage of the athlete's maximum heart rate in effect that day, crediting only time the readings cover. Use when someone asks how long a run, ride, row, or conditioning session spent in each zone, or how hard a session was by heart rate. Needs a maximum_heart_rate intensity reference; never estimates it from age. Not for training load (use training-load-heart-rate). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-zones --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-zones --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Time in five zones, split at 60, 70, 80, and 90 % of the athlete's maximum heart ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/hrv-change/SKILL.md b/skills/hrv-change/SKILL.md index f6167729..d4b64832 100644 --- a/skills/hrv-change/SKILL.md +++ b/skills/hrv-change/SKILL.md @@ -2,9 +2,9 @@ name: hrv-change description: Compares one day's heart-rate variability with the athlete's own earlier days, keeping RMSSD and SDNN apart. Use when someone asks whether their HRV is up or down, how today's or last night's HRV compares with normal, or whether HRV has dropped after hard training, travel, illness, or poor sleep. Works for nightly RMSSD (WHOOP, Oura) and intraday SDNN samples (Apple Watch). Not for a long-run HRV trend (use trend) or a plain average (use baseline). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hrv-change --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hrv-change --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ recent normal, measured the same way by the same device? ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/hyrox-race-splits/SKILL.md b/skills/hyrox-race-splits/SKILL.md index 8756a25c..fbf3c9de 100644 --- a/skills/hyrox-race-splits/SKILL.md +++ b/skills/hyrox-race-splits/SKILL.md @@ -2,9 +2,9 @@ name: hyrox-race-splits description: Divides one HYROX race or simulation result into its eight runs, eight stations, Roxzone, and penalties, refusing any layout that would count time twice, and summarises run pacing and each station's share of the finish time. Use when someone asks where their HYROX time went, how their runs held up after stations, which station cost the most, or how much time Roxzone took. Needs a benchmark result with labelled segments. Not for training plans or race strategy (use the hyrox coaching skill). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hyrox-race-splits --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hyrox-race-splits --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -16,16 +16,16 @@ finish time. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/hyrox/SKILL.md b/skills/hyrox/SKILL.md index 79b6ade7..36e254d6 100644 --- a/skills/hyrox/SKILL.md +++ b/skills/hyrox/SKILL.md @@ -2,9 +2,9 @@ name: hyrox description: Coaches one athlete for HYROX racing under the 2026/27 Singles, Doubles, Relay, and Adaptive rulebooks, and saves the advice as authored records. Use when someone asks for a HYROX race plan or training block, how to train a station or running after stations, a pacing plan or finish-time budget, Doubles or Relay tactics, Adaptive race rules, or what a race result means and what to change. Not for splitting one result into parts alone (use hyrox-race-splits), CrossFit (use crossfit), medical questions, or deciding Adaptive eligibility. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install hyrox. +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install hyrox. metadata: - version: "3.0.0" + version: "3.1.0" kind: coaching --- @@ -78,16 +78,16 @@ say so when asked what science says is best. Details are in ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/maximum-heart-rate/SKILL.md b/skills/maximum-heart-rate/SKILL.md index 5024efc0..ad2d97ed 100644 --- a/skills/maximum-heart-rate/SKILL.md +++ b/skills/maximum-heart-rate/SKILL.md @@ -2,9 +2,9 @@ name: maximum-heart-rate description: Estimates the athlete's maximum heart rate two labelled ways: the highest heart rate held for 5 seconds in their own recordings of the past year, which is a lower bound, or the age formula 208 minus 0.7 times age, which may be about 10 bpm off and runs only when the athlete asks. Use when no maximum heart rate is in effect and zones or loads need one. Never saved without the athlete's yes. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply maximum-heart-rate --set end_date=. +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply maximum-heart-rate --set end_date=. metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ A labelled estimate of maximum heart rate, for when none is in effect (D318, D32 ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/plan-against-result/SKILL.md b/skills/plan-against-result/SKILL.md index 6d6359c4..7768dfbf 100644 --- a/skills/plan-against-result/SKILL.md +++ b/skills/plan-against-result/SKILL.md @@ -2,9 +2,9 @@ name: plan-against-result description: Compares each block of a planned session with the lap of the completed workout that carried it out: planned and actual duration and distance, and each power, heart-rate, speed, or cadence target against the lap's average, with percent targets worked out from the intensity reference in effect. Use when someone asks whether they hit the plan. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply plan-against-result --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply plan-against-result --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Each planned block against the lap that carried it out, in order. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/power-zones/SKILL.md b/skills/power-zones/SKILL.md index 5c0bb529..9565def2 100644 --- a/skills/power-zones/SKILL.md +++ b/skills/power-zones/SKILL.md @@ -2,9 +2,9 @@ name: power-zones description: Splits one workout's power recording into seven zones by percentage of the athlete's threshold power in effect on that day for the workout's sport and machine. Use when someone asks how long a ride or row spent in each power zone, or how hard a session was by power. Needs a threshold_power intensity reference; never estimates one. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply power-zones --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply power-zones --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Time in seven zones, split at 55, 75, 90, 105, 120, and 150 % of the threshold p ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/provider-period-summary/SKILL.md b/skills/provider-period-summary/SKILL.md index cc809ee0..4f6cb2ce 100644 --- a/skills/provider-period-summary/SKILL.md +++ b/skills/provider-period-summary/SKILL.md @@ -2,9 +2,9 @@ name: provider-period-summary description: Summarises one measurement, provider score, or provider summary by the provider's own period stored on each record, such as an Oura sleep day, a WHOOP physiological cycle, or an Apple activity-summary day, without turning it into a calendar day. Use when someone asks for values per Oura day or per WHOOP cycle, or when a value has only a provider date and no exact time. Not for calendar-day summaries (use summary). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate provider-period-summary --period-type . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate provider-period-summary --period-type . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ as the provider defined the period. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/resting-heart-rate-change/SKILL.md b/skills/resting-heart-rate-change/SKILL.md index 46789bb9..bc113dc9 100644 --- a/skills/resting-heart-rate-change/SKILL.md +++ b/skills/resting-heart-rate-change/SKILL.md @@ -2,9 +2,9 @@ name: resting-heart-rate-change description: Compares one day's resting heart rate with the athlete's own earlier days from the same device. Use when someone asks whether their resting heart rate is up, whether a raised resting pulse after hard training, travel, illness, or poor sleep is unusual for them, or how this morning compares with normal. Reads resting_heart_rate readings. Not for estimating resting heart rate from raw samples (use resting-heart-rate). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate-change --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate-change --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ recent normal, as the same device measures it? ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/resting-heart-rate/SKILL.md b/skills/resting-heart-rate/SKILL.md index 0e39cf9e..7dd9ef3d 100644 --- a/skills/resting-heart-rate/SKILL.md +++ b/skills/resting-heart-rate/SKILL.md @@ -2,9 +2,9 @@ name: resting-heart-rate description: Finds the lowest sustained heart rate, the lowest 5-minute mean, during a sleep session from that device's heart-rate samples, or during a workout from its own samples. Use when someone asks for their overnight or sleeping resting heart rate from raw samples, or how low their heart rate settled during a night. Not for a device's own resting heart rate value (read the resting_heart_rate measurement) or day-to-day change (use resting-heart-rate-change). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -16,16 +16,16 @@ lowest sustained rate during that workout. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/sleep-change/SKILL.md b/skills/sleep-change/SKILL.md index 282d1aa1..e1269af7 100644 --- a/skills/sleep-change/SKILL.md +++ b/skills/sleep-change/SKILL.md @@ -2,9 +2,9 @@ name: sleep-change description: Compares one night's time asleep with the athlete's earlier main sleeps from the same device, leaving naps out. Use when someone asks whether they slept less than usual, how last night compares with their normal, or whether a short night is unusual for them. Reads asleep_seconds on a sleep session. Not for total daily sleep including naps, sleep timing (use sleep-timing), or regularity (use sleep-regularity). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-change --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-change --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ compared with their recent main sleeps on the same device? ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/sleep-duration/SKILL.md b/skills/sleep-duration/SKILL.md index 9e57a1fd..8a6be46e 100644 --- a/skills/sleep-duration/SKILL.md +++ b/skills/sleep-duration/SKILL.md @@ -2,9 +2,9 @@ name: sleep-duration description: Reads how long the athlete slept on one sleep session, as the device estimated it. Use when someone asks how much they slept last night or on a given night. Reads asleep_seconds; awake time in bed is not sleep. Not for comparison with their usual sleep (use sleep-change), sleep against time in bed (use sleep-efficiency), or consistency (use sleep-regularity). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-duration --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-duration --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Time asleep on one sleep session, in seconds, exactly as the source recorded it. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/sleep-efficiency/SKILL.md b/skills/sleep-efficiency/SKILL.md index f6e7bc89..ab6e69c9 100644 --- a/skills/sleep-efficiency/SKILL.md +++ b/skills/sleep-efficiency/SKILL.md @@ -2,9 +2,9 @@ name: sleep-efficiency description: Divides time asleep by time in bed for one sleep session and checks that the two agree. Use when someone asks what share of their time in bed they actually slept, or whether they lie awake a lot. Needs asleep_seconds and in_bed_seconds. Not for total sleep (use sleep-duration) or interruptions (use sleep-interruptions). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-efficiency --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-efficiency --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Sleep efficiency is total sleep time divided by time in bed. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/sleep-interruptions/SKILL.md b/skills/sleep-interruptions/SKILL.md index 32b439f6..71f75a84 100644 --- a/skills/sleep-interruptions/SKILL.md +++ b/skills/sleep-interruptions/SKILL.md @@ -2,9 +2,9 @@ name: sleep-interruptions description: Reads how many times sleep was interrupted on one sleep session, as the source counted it. Use when someone asks how broken or restless a night was, or how often they woke up. Reads the interruptions field. Not for minutes awake (use sleep-stages or sleep-efficiency) or comparison with other nights (use summary or sleep-change). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-interruptions --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-interruptions --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ How many times the source says sleep was interrupted during one session. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/sleep-regularity/SKILL.md b/skills/sleep-regularity/SKILL.md index bccbf4f3..c7987ba1 100644 --- a/skills/sleep-regularity/SKILL.md +++ b/skills/sleep-regularity/SKILL.md @@ -2,9 +2,9 @@ name: sleep-regularity description: Scores how regular sleep timing has been over the last 14 days with the Sleep Regularity Index, from -100 to 100, using the sleep sessions from one device. Use when someone asks whether they keep a consistent sleep schedule, how irregular their bedtimes are, or whether shifting sleep around weekends or shifts is showing. Needs at least 7 consecutive recorded days. Not for one night's times (use sleep-timing) or amount (use sleep-duration). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-regularity --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-regularity --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -17,16 +17,16 @@ opposite pattern. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/sleep-stages/SKILL.md b/skills/sleep-stages/SKILL.md index c10925eb..1f4f4bd8 100644 --- a/skills/sleep-stages/SKILL.md +++ b/skills/sleep-stages/SKILL.md @@ -2,9 +2,9 @@ name: sleep-stages description: Splits one night's sleep into the stages the source supplied, such as deep, light, and REM, keeps awake minutes apart, and gives each stage's share of sleep. Use when someone asks how much deep or REM sleep they got, or how their sleep was made up. Reads stage_minutes. Not for total sleep (use sleep-duration); never invents a stage the record lacks. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-stages --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-stages --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ time counted apart. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/sleep-timing/SKILL.md b/skills/sleep-timing/SKILL.md index 2204566c..1c5472ef 100644 --- a/skills/sleep-timing/SKILL.md +++ b/skills/sleep-timing/SKILL.md @@ -2,9 +2,9 @@ name: sleep-timing description: Gives when one sleep session started, its midpoint, and when it ended, in the athlete's own time zone. Use when someone asks what time they fell asleep or woke up, how late they went to bed, or the clock time of their sleep midpoint. Not for how regular sleep is across nights (use sleep-regularity) or how long it was (use sleep-duration). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-timing --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-timing --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ local clock. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/strength-volume/SKILL.md b/skills/strength-volume/SKILL.md index 13997b83..785288e1 100644 --- a/skills/strength-volume/SKILL.md +++ b/skills/strength-volume/SKILL.md @@ -2,9 +2,9 @@ name: strength-volume description: Adds up volume load, repetitions times load in kilograms, for every strength set on one workout, converting pounds, counting per-implement loads such as two dumbbells, and splitting by movement. Use when someone asks how much total weight they lifted, the volume of a strength session, or volume per lift. Needs sets with reps, weight, and weight_unit. Not for heart-rate or effort load (use training-load-heart-rate or training-load-effort). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply strength-volume --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply strength-volume --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Volume load: for every set, repetitions × load, added together, in kilograms. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/summary/SKILL.md b/skills/summary/SKILL.md index 9b744a4b..f0c470cd 100644 --- a/skills/summary/SKILL.md +++ b/skills/summary/SKILL.md @@ -2,9 +2,9 @@ name: summary description: Counts and summarises one measurement over a period, separately for each device, with optional day, week, or month groups. Use when someone asks for their average, minimum, maximum, or number of readings of one quantity, such as RMSSD, SDNN, resting heart rate, heart rate, or body weight, over a period, or per week. Not for a change on one day (use hrv-change), a trend (use trend), or missing days (use coverage). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate summary . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate summary . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ quantity, for each source separately. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/training-load-effort/SKILL.md b/skills/training-load-effort/SKILL.md index 3216b569..46906396 100644 --- a/skills/training-load-effort/SKILL.md +++ b/skills/training-load-effort/SKILL.md @@ -2,9 +2,9 @@ name: training-load-effort description: Computes session-RPE training load, the athlete's rating of a whole session times the minutes it covers, from a session_effort athlete report. Use when someone rates how hard a session felt and asks for its training load, or wants weekly load from their own effort ratings, including for lifting, CrossFit, or HYROX work where heart rate misleads. Refuses soreness, mood, or any other rating. Not for heart-rate load (use training-load-heart-rate). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-effort --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-effort --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -16,16 +16,16 @@ measurement, and it stays on the athlete side of the two-tier wall. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/training-load-heart-rate/SKILL.md b/skills/training-load-heart-rate/SKILL.md index 4d75114b..82228280 100644 --- a/skills/training-load-heart-rate/SKILL.md +++ b/skills/training-load-heart-rate/SKILL.md @@ -2,9 +2,9 @@ name: training-load-heart-rate description: Computes Banister's heart-rate training load (TRIMP) for one workout from its heart rate, the maximum heart rate in effect that day, the latest measured resting heart rate on or before it, and the athlete's sex-specific weighting. Use when someone asks how much load a session put on them by heart rate, or wants to compare the internal load of two sessions or weeks. Not for load from the athlete's own effort rating (use training-load-effort) or time in zones (use heart-rate-zones). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-heart-rate --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-heart-rate --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ Banister's training impulse: minutes weighted by how far heart rate sits between ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/trend/SKILL.md b/skills/trend/SKILL.md index 48286018..b7961693 100644 --- a/skills/trend/SKILL.md +++ b/skills/trend/SKILL.md @@ -2,9 +2,9 @@ name: trend description: Fits a straight-line trend to one measurement over time, separately for each device, and reports the slope per day with its standard error. Use when someone asks whether their HRV, resting heart rate, body weight, or another reading is going up or down over weeks, or how fast it is changing. Not for one day against normal (use hrv-change), an average (use baseline), or cause and effect (no calculation shows that). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate trend . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate trend . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ source. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/work-capacity-balance/SKILL.md b/skills/work-capacity-balance/SKILL.md index 5071229b..287e5c16 100644 --- a/skills/work-capacity-balance/SKILL.md +++ b/skills/work-capacity-balance/SKILL.md @@ -2,9 +2,9 @@ name: work-capacity-balance description: Tracks how much of the athlete's work capacity above threshold power is left through one workout, with the published exponential model, from the power recording and the threshold power and work capacity in effect. Use when someone asks how deep an interval session went, when they ran out, or for work_capacity_used targets. Needs both intensity references. license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply work-capacity-balance --record . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply work-capacity-balance --record . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -14,16 +14,16 @@ How much of the work capacity above threshold power (W′) is left at each momen ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/skills/workout-drift/SKILL.md b/skills/workout-drift/SKILL.md index cf5e0731..4a735f9d 100644 --- a/skills/workout-drift/SKILL.md +++ b/skills/workout-drift/SKILL.md @@ -2,9 +2,9 @@ name: workout-drift description: Compares the average of a measurement, usually heart rate, in the first and second halves of one workout, separately for each device. Use when someone asks whether their heart rate drifted upward during a steady run, ride, or row, or how much it rose late in a long session. This is cardiac drift only, not aerobic efficiency. Not for zones (use heart-rate-zones) or load (use training-load-heart-rate). license: MIT -compatibility: Requires the ath CLI 3.0.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate workout-drift --session . +compatibility: Requires the ath CLI 3.1.0 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate workout-drift --session . metadata: - version: "3.0.0" + version: "3.1.0" kind: calculation --- @@ -15,16 +15,16 @@ first half, with the percentage change. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 3.0.0 or later. +This skill runs `ath`, the Athletic Standard program, version 3.1.0 or later. Check it once with `ath --version`. - If `ath` is not found, it is not installed. It comes from the npm package `athleticstandard`. The npm package named `ath` is a different program. Install it with `npm install -g athleticstandard`, which needs Node.js 22 or later. Other ways to install it are at https://www.npmjs.com/package/athleticstandard. -- If the version is older than 3.0.0, update it with `ath --update`. +- If the version is older than 3.1.0, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 3.0.0, say so and stop. + it is still older than 3.1.0, say so and stop. If the answer needs the athlete's records or a calculation and `ath` cannot run, stop. Tell the person what is missing and how to fix it. Do not read the database another diff --git a/spec/sql/README.md b/spec/sql/README.md index f0ba63fd..9abaebc5 100644 --- a/spec/sql/README.md +++ b/spec/sql/README.md @@ -79,6 +79,7 @@ Then run the record steps below and `COMMIT`. On failure, `ROLLBACK`. | 6 | `migrations/006-version-2-1-2.sql` | 6 | | 7 | `migrations/007-version-2-1-3.sql` | 7 | | 8 | `migrations/008-version-3-0-0.sql` | 8 | +| 9 | `migrations/009-version-3-1-0.sql` | 9 | Rules: @@ -113,16 +114,18 @@ Rules: every row that refers to it, so the file's first statement stops the step when foreign keys are on and records exist. A new, empty database may run it with foreign keys on. +- Migration `009-version-3-1-0.sql` records software version 3.1.0. It changes no + table, column, or row (D334). - Roll back the transaction on failure. A failed migration must leave the prior file usable. - `ath migrate` makes a verified backup with SQLite's backup API first. It then runs every pending step in one write transaction. If the database changed after the backup, nothing is migrated and the preview must be made again. - Software before 2.1.1 refuses a database at SQL schema 5, software before 2.1.2 - refuses one at schema 6, software before 2.1.3 refuses one at schema 7, and software - before 3.0.0 refuses one at schema 8. To go - back, restore the - verified pre-migration backup and keep the newer file separately. The backup does + refuses one at schema 6, software before 2.1.3 refuses one at schema 7, software + before 3.0.0 refuses one at schema 8, and software before 3.1.0 refuses one at + schema 9. To go back, restore the verified pre-migration backup and keep the newer + file separately. The backup does not contain work recorded after it was made. npm `athleticstandard@1.0.0` ships SQL schema version 1. npm `1.1.0` adds migration diff --git a/spec/sql/contract.json b/spec/sql/contract.json index abd57689..f3ce0f75 100644 --- a/spec/sql/contract.json +++ b/spec/sql/contract.json @@ -1,6 +1,6 @@ { "contract": "athleticstandard-sql", - "sql_schema_version": 8, + "sql_schema_version": 9, "minimum_sqlite_version": "3.45.0", "user_version_mirror": { "description": "On local SQLite files, PRAGMA user_version equals database_metadata.sql_schema_version after creation.", @@ -56,6 +56,11 @@ "version": 8, "file": "migrations/008-version-3-0-0.sql", "description": "Upgrade the database to software version 3.0.0. Rebuilds the records table once so record types are rows in the new record_types table. Every record, revision, and typed row stays as it is." + }, + { + "version": 9, + "file": "migrations/009-version-3-1-0.sql", + "description": "Upgrade the database to software version 3.1.0. No table, column, or row changes. The step records the version, as step 4 did for 2.1.0." } ], "metadata_insert": { @@ -66,7 +71,7 @@ ], "header_pragmas": [ "PRAGMA application_id = 1096042545;", - "PRAGMA user_version = 8;" + "PRAGMA user_version = 9;" ] }, "file_header_pragmas": { diff --git a/spec/sql/migrations/009-version-3-1-0.sql b/spec/sql/migrations/009-version-3-1-0.sql new file mode 100644 index 00000000..dba2a320 --- /dev/null +++ b/spec/sql/migrations/009-version-3-1-0.sql @@ -0,0 +1,11 @@ +-- Athletic Standard upgrade to software version 3.1.0 (migration step 9). +-- This file is the executable migration. The ath program embeds it unchanged. +-- +-- See build-history/v3.1.0/spec.md section 2 and decision D334. No table, +-- column, or row changes. The step stores athleticstandard_version 3.1.0 and +-- sql_schema_version 9, as step 4 did for 2.1.0. + +UPDATE database_metadata +SET sql_schema_version = 9, + athleticstandard_version = '3.1.0' +WHERE singleton_id = 1; diff --git a/src/assets/skill.rs b/src/assets/skill.rs index 91b92eea..e653921e 100644 --- a/src/assets/skill.rs +++ b/src/assets/skill.rs @@ -64,8 +64,8 @@ pub enum SkillKind { /// The SHA-256 of every calculation `SKILL.md` an earlier release shipped /// (D231). A copy with one of these hashes was never edited, so it is /// replaced by the current file. The 2.0.0, 2.1.0, and 2.1.1 files are the -/// same; `tests/fixtures/calculations-2-1-1` keeps them. The 2.1.2 and 2.1.3 -/// files follow, read from the released commits. +/// same; `tests/fixtures/calculations-2-1-1` keeps them. The 2.1.2, 2.1.3, +/// and 3.0.0 files follow, read from the released commits. pub const PREVIOUSLY_SHIPPED_CALCULATIONS: &[(&str, &str)] = &[ ("baseline", "b89283be4e217b785b17b96c711dce4c17e660cdcff8a58838f9ad7e829f9e9f"), ("compare-sources", "3977b56322124b91e95bf870deb8d2b6d3f2411b8545cd1336471787f5e55dff"), @@ -140,6 +140,38 @@ pub const PREVIOUSLY_SHIPPED_CALCULATIONS: &[(&str, &str)] = &[ ("training-load-heart-rate", "c5962d271429984e90fce7c347de0bc419df350f20af3a254677df336b3d4fe7"), ("trend", "0ed51dc95c803c77766008dcbd20bc338b90b3b990aeb031afc6b3b687828ad9"), ("workout-drift", "43d1760ffe033c397d92d54310d614b39c2684a34aa78223bb3d820180036a3f"), + // 3.0.0 + ("baseline", "708c77d989d1dc4cec60bbffaf3da411ebc8f3546df682b30ff54a15e7409385"), + ("best-efforts", "7bd35596c1052f1bc5ab902e9c3e4e8e7ce1dda7bd94a9901ebb882a9f3be32b"), + ("compare-sources", "d1523b43a6ad3d88066c7a9b9efa44d9bf3d0f93ba933c055798251eb4ff93fa"), + ("correlation", "6cd7ee4edf6310f47192df96c4608da678a4bf8426853f2866524abcf0af2583"), + ("coverage", "4436e5f0abce59bb343a8b14ca269b887b09b2cc50f6e7ee8a46395f6471cbbc"), + ("critical-power", "d7e4cbd006a03e8d5878eb9f8c9f09f6eaead17ed1935bfc5b9dc221d3b2115f"), + ("critical-speed", "1b74ffe1c267a7129651e087747964f5666094bc4b6f2fff84143f7375a77a2f"), + ("heart-rate-recovery", "bee97b73e2218aec4c886cedb31b56c562a41a58aa026a3874ec863b823c5f9e"), + ("heart-rate-zones", "f127bbe1a55f902bc15f0b0df5ac6f35af18699390e195e9568bc6a4d172b2b9"), + ("hrv-change", "540977b3c2f54175272711235eb122b9a5eeac0244e69022e88b79917509a82e"), + ("hyrox-race-splits", "0d625580b3ada0e11483c1084ee0481348537ecbc2a8d2972831f5e9cdc9777f"), + ("maximum-heart-rate", "e6760ce47c27d72df9ad9ca5dc5dea5675db746f54c43306c688fc9be6351ec7"), + ("plan-against-result", "2143de3cfb8f9285bfc177eceae48e644d68ef895f5881f0fd61fa15654328d7"), + ("power-zones", "5be0e885975082eaef54e2744fbf8fcb3fe4735d75f1ddc075ee4e13ff2e8014"), + ("provider-period-summary", "81884c5f53cc3211d73c9134e7ded761d1b5979ea32056da34f272cddfd59238"), + ("resting-heart-rate-change", "312e65e625284bcffd8fc3ddfbd3378a2e45c0bbb26b4c36d999233fe271b2ca"), + ("resting-heart-rate", "3370f6f58d50bd1b4f9d486b98c9e280c91b113e85632758b749a0dda2690ad1"), + ("sleep-change", "0c4033aeb381974658881a3edef652670a550ab0707fe62357588102b06b9de5"), + ("sleep-duration", "4e70ef4730bd6683da62f182e9b0dacf5b851eaf9c5f1c86eb6209ca60b9f756"), + ("sleep-efficiency", "90093c0ddd0f469f9cd764016d113d03606a5e60e61f208342e91c65a17705d8"), + ("sleep-interruptions", "4d53ef7014b1797c1704b3de8ef8dbdf0bb151264988bf18737fec37afec0cd9"), + ("sleep-regularity", "0ad6a4ff1cc3d1e9039cfedef8185329e3ede14763e7535e578c573c33bf7ee0"), + ("sleep-stages", "3cee8c66d6432d5f6cbfb90918da8658267e0c5ff3508698b5895df5b4242f93"), + ("sleep-timing", "d73bfa301c63cacdd65d550ad3ecbca654a02e08168aa28f6b08dd45a807fbf6"), + ("strength-volume", "93e423946fbcf489f217c7b98775a67a1b0af5ea805b1b3b1448eb5c56d338c3"), + ("summary", "da8dbc5311d74771b8ddfc53e86e97f31a9e93237d197d2429515e5e53664232"), + ("training-load-effort", "2c4a277ccff4d0bcea723dc6fe765d2ef4ba12a8ced91392dd56cbe4e7287c6f"), + ("training-load-heart-rate", "bda67463e4fbb94564a1ce5228783eb1dfacc6fb2b7c2ff114a8008722c681f6"), + ("trend", "9389968f13ee2a8373ec4bc88492c301c4ed6270aa4aae3c22e240620aa99131"), + ("work-capacity-balance", "cb1059a31cce8203cec521ba15d094aa84de776660904716d9e5595020f1d658"), + ("workout-drift", "32b11309c619952c065010d45b8a84a2bbfae347fe99e31f99f7e0de4174b090"), ]; /// One place a skill could be installed. `ath skill --json` lists these. diff --git a/src/store/migrate.rs b/src/store/migrate.rs index 753409f2..0cc134ae 100644 --- a/src/store/migrate.rs +++ b/src/store/migrate.rs @@ -77,6 +77,12 @@ pub const MIGRATION_CHAIN: &[MigrationStep] = &[ description: "Upgrade the database to software version 3.0.0. Rebuilds the records table once so record types are rows in the new record_types table. Every record, revision, and typed row stays as it is.", sql: include_str!("../../spec/sql/migrations/008-version-3-0-0.sql"), }, + MigrationStep { + version: 9, + file: "migrations/009-version-3-1-0.sql", + description: "Upgrade the database to software version 3.1.0. No table, column, or row changes. The step records the version, as step 4 did for 2.1.0.", + sql: include_str!("../../spec/sql/migrations/009-version-3-1-0.sql"), + }, ]; /// The first step that rebuilds a table. From it on, the steps run with diff --git a/src/store/mod.rs b/src/store/mod.rs index 350617ce..3908118a 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -44,7 +44,8 @@ pub const SQLITE_APPLICATION_MARKER: &str = "ATH1"; pub const SQLITE_BUSY_TIMEOUT: Duration = Duration::from_millis(5_000); /// Database versions this software reads. -pub const READABLE_DATABASE_VERSIONS: &[&str] = &["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0"]; +pub const READABLE_DATABASE_VERSIONS: &[&str] = + &["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", "3.1.0"]; /// The default database file name in a working directory. pub const DEFAULT_FILENAME: &str = "athlete.ath.sqlite"; diff --git a/tests/cli_golden.rs b/tests/cli_golden.rs index 4092d8d5..e35c10f0 100644 --- a/tests/cli_golden.rs +++ b/tests/cli_golden.rs @@ -12,9 +12,9 @@ //! //! - A refusal is printed once (cli-changes.md 1, quirk S4). Where 2.1.0 //! printed the same `ath:` line twice in a row, one copy is expected. -//! - The native program writes SQL schema step 8 (D211, D227, D254, D292). -//! Steps 5 to 8 are removed from native migration plans, and a source, -//! target, or required step 5, 6, 7, or 8 reads 4. +//! - The native program writes SQL schema step 9 (D211, D227, D254, D292, +//! D334). Steps 5 to 9 are removed from native migration plans, and a +//! source, target, or required step 5, 6, 7, 8, or 9 reads 4. //! - `log` lists record data in published field order (deliberate-changes.md //! 25), so its output lines are compared without their order. //! - `share` finds the report `backtest` writes (deliberate-changes.md 5). @@ -216,8 +216,8 @@ fn manifest_hashes(text: &str) -> String { out.join("\n") } -/// The native program writes SQL schema step 8 (2.1.1 added step 5, 2.1.2 -/// step 6, 2.1.3 step 7, 3.0.0 step 8); 2.1.0 wrote step 4. +/// The native program writes SQL schema step 9 (2.1.1 added step 5, 2.1.2 +/// step 6, 2.1.3 step 7, 3.0.0 step 8, 3.1.0 step 9); 2.1.0 wrote step 4. fn step_five_as_four(text: &str) -> String { let mut out = text.to_string(); for file in [ @@ -225,6 +225,7 @@ fn step_five_as_four(text: &str) -> String { "migrations/006-version-2-1-2.sql", "migrations/007-version-2-1-3.sql", "migrations/008-version-3-0-0.sql", + "migrations/009-version-3-1-0.sql", ] { let marker = format!("\"migration_file\": \"{file}\""); while let Some(position) = out.find(&marker) { @@ -234,7 +235,7 @@ fn step_five_as_four(text: &str) -> String { out.replace_range(start..end, ""); } } - for step in ["5", "6", "7", "8"] { + for step in ["5", "6", "7", "8", "9"] { out = out .replace(&format!("\"target_sql_schema_version\": {step}"), "\"target_sql_schema_version\": 4") .replace(&format!("\"source_sql_schema_version\": {step}"), "\"source_sql_schema_version\": 4") diff --git a/tests/migration.rs b/tests/migration.rs index e4a95008..8f6023b2 100644 --- a/tests/migration.rs +++ b/tests/migration.rs @@ -338,19 +338,20 @@ fn foreign_and_mismatched_headers_are_refused_without_change() { assert_eq!(file_hash(&path), before); // A newer schema than this program writes. + let newer = SQL_SCHEMA_VERSION + 1; let path = copy_fixture(&demo_fixture(), "ath-migrate-newer-", false); direct(&path) - .execute_batch( + .execute_batch(&format!( "PRAGMA journal_mode = DELETE; - UPDATE database_metadata SET sql_schema_version = 9; - PRAGMA user_version = 9;", - ) + UPDATE database_metadata SET sql_schema_version = {newer}; + PRAGMA user_version = {newer};" + )) .unwrap(); let error = inspect_migration(&path, None).unwrap_err().to_string(); assert_eq!( error, format!( - "Database SQL schema 9 is newer than supported schema {SQL_SCHEMA_VERSION}. A newer ath wrote this database. Update ath to open it, for example with ath --update." + "Database SQL schema {newer} is newer than supported schema {SQL_SCHEMA_VERSION}. A newer ath wrote this database. Update ath to open it, for example with ath --update." ) ); } @@ -468,12 +469,12 @@ fn migrated_tables_match_the_2_1_0_migration() { serde_json::Value::from(preview.source_sql_schema_version), old_preview["source_sql_schema_version"] ); - // 2.1.0 planned the same steps, ending four steps earlier. + // 2.1.0 planned the same steps, ending five steps earlier. let old_steps = old_preview["planned_steps"].as_array().unwrap(); for (ours, theirs) in preview.planned_steps.iter().zip(old_steps) { assert_eq!(serde_json::to_value(ours).unwrap(), *theirs, "{name}"); } - assert_eq!(preview.planned_steps.len(), old_steps.len() + 4, "{name}"); + assert_eq!(preview.planned_steps.len(), old_steps.len() + 5, "{name}"); let added: Vec<&str> = preview.planned_steps[old_steps.len()..].iter().map(|step| step.migration_file.as_str()).collect(); assert_eq!( @@ -482,7 +483,8 @@ fn migrated_tables_match_the_2_1_0_migration() { "migrations/005-version-2-1-1.sql", "migrations/006-version-2-1-2.sql", "migrations/007-version-2-1-3.sql", - "migrations/008-version-3-0-0.sql" + "migrations/008-version-3-0-0.sql", + "migrations/009-version-3-1-0.sql" ] ); diff --git a/tests/published_files.rs b/tests/published_files.rs index e8b3102a..0fbacf8c 100644 --- a/tests/published_files.rs +++ b/tests/published_files.rs @@ -11,8 +11,9 @@ //! `schema/athleticstandard.schema.json`) are checked by `tests/generated.rs`. //! The host API description of the current version //! (`schema//host-api.json`) is generated too, and -//! `host/tests/generated.rs` checks it (D271, D324). The copy released with -//! 2.1.3, `schema/host-api/1/openapi.json`, is pinned below. +//! `host/tests/generated.rs` checks it (D271, D324). The copies released with +//! 2.1.3, `schema/host-api/1/openapi.json`, and with 3.0.0, +//! `schema/3.0.0/host-api.json`, are pinned below. //! The current SQL migration step is still part of this build. When a version //! is released, its files join the list below. @@ -34,6 +35,7 @@ const PUBLISHED: &[(&str, &str)] = &[ ("spec/sql/migrations/005-version-2-1-1.sql", "e393d69ba46a2f79cc40a34014e1fdf7da0cd8350a5d2dd151d88fe814ca2dbb"), ("spec/sql/migrations/006-version-2-1-2.sql", "b9e6be1fc880929aae2a585d0cd7b9b5185f48299981a4c07997df36131b7422"), ("spec/sql/migrations/007-version-2-1-3.sql", "384822e53105cc8eb6a5c7a27d00a107e6b50cec775db34f6467aaa63fc99397"), + ("spec/sql/migrations/008-version-3-0-0.sql", "ec3cf1801657a964572e76ce5873063e9dcc12317273285c67af5053280b8eb9"), ("schema/0.4.3/athleticstandard.schema.json", "9b8675c8bf69fe3bc4b9d9957bab617a10dbd665af67c17ea098415b94901c32"), ("schema/1.0.0/athleticstandard.schema.json", "68ebd0c8a0f6b1659d7d3df78cfcc9d9851937d38351ca182d72432d678af56e"), ("schema/1.0.0/export-manifest.schema.json", "22be5db19afec81fd4a2a68f1925974833ff474c245a31310f88eaa67666d236"), @@ -53,6 +55,10 @@ const PUBLISHED: &[(&str, &str)] = &[ ("schema/2.1.3/athleticstandard.schema.json", "39a0a2b9613e70f08d52f324afbb7a2156d9ed9cabf8b3e0738b54bca0b12156"), ("schema/2.1.3/export-manifest.schema.json", "22f5028fc22529930b7ef7ceb34acf0eccdfd68fe25ac894c9a72a2f6372cb29"), ("schema/2.1.3/measurement-series.schema.json", "62973d5f4112f42db6674c14642c3e02c86c4cdc349703b6d75205da6889c9e1"), + ("schema/3.0.0/athleticstandard.schema.json", "310688b5c7a85cde487bced47ff9dac980eb1dc975871bd109ae88c22317e844"), + ("schema/3.0.0/export-manifest.schema.json", "a732de9d421d618454c4c99deac5f6dd4cf0a0f712f04d62c80350c9644a1a97"), + ("schema/3.0.0/measurement-series.schema.json", "b1d8e12d5d2580f8e4821723954b3d277130abe5842c2cb022433d3e5ca77ecd"), + ("schema/3.0.0/host-api.json", "bed9d8c28fd8d60e5b14ee54b3defc8dedbb2baf44eb19210897f8859b89b8a0"), ("schema/host-api/1/openapi.json", "15c96d65d3a23b28bc9a02a02259f521f01d9e2a6b80d826b8a1ab1a0fe1053a"), ]; diff --git a/tests/published_schema.rs b/tests/published_schema.rs index 87cd0a52..0961d98d 100644 --- a/tests/published_schema.rs +++ b/tests/published_schema.rs @@ -1,5 +1,7 @@ -//! The generated JSON Schema must match the published 2.1.3 files except for -//! the version list, the schema IDs, and the 3.0.0 additions that +//! The generated JSON Schema must match the published 3.0.0 files except for +//! the version list and the schema IDs, because 3.1.0 changes no record field +//! (D334). The published 3.0.0 files must match the published 2.1.3 files +//! except for those markers and the 3.0.0 additions that //! `remove_3_0_0_additions` names. The published 2.1.3 files must match the //! published 2.1.2 files except for those markers and the 2.1.3 coach author //! (D255). The published 2.1.2 files must match the published 2.1.1 files except for @@ -191,13 +193,11 @@ fn first_difference(expected: &str, actual: &str, name: &str) { } } -/// Compare a generated document with the published 2.1.3 file. `additions` is -/// how many 3.0.0 additions the document must contain. -fn compare(generated: Value, name: &str, additions: usize) { +/// Compare a generated document with the published 3.0.0 file. +fn compare(generated: Value, name: &str) { let mut generated = generated; - rewrite_versions(&mut generated, package::ATHLETIC_STANDARD_VERSION, "2.1.3"); - assert_eq!(remove_3_0_0_additions(&mut generated), additions, "{name}: the 3.0.0 additions"); - first_difference(&json::to_pretty(&published("2.1.3", name)), &json::to_pretty(&generated), name); + rewrite_versions(&mut generated, package::ATHLETIC_STANDARD_VERSION, "3.0.0"); + first_difference(&json::to_pretty(&published("3.0.0", name)), &json::to_pretty(&generated), name); } #[test] @@ -206,14 +206,9 @@ fn package_schema_matches_published_layout() { "https://athleticstandard.ai/schema/{}/athleticstandard.schema.json", package::ATHLETIC_STANDARD_VERSION ); - // Each new record type has a variant for current records and one for - // retained revisions (2 × 5). The rest are the new fields and list values - // on earlier types, counted in every place their shapes appear. - let additions = 146; compare( json_schema::document(package::package_schema(), &id, "Athletic Standard portable package document"), "athleticstandard.schema.json", - additions, ); } @@ -230,8 +225,6 @@ fn series_schema_matches_published_layout() { "Athletic Standard measurement-series file", ), "measurement-series.schema.json", - // field_basis.machine on the sample record and its revision. - 2, ); } @@ -245,11 +238,29 @@ fn manifest_schema_matches_published_layout() { compare( json_schema::document(package::ExportManifest::schema(), &id, "Athletic Standard export manifest"), "export-manifest.schema.json", - // The five new names in the record-count type list, and `partial` (D313). - 6, ); } +#[test] +fn the_published_3_0_0_files_match_2_1_3_except_versions_and_additions() { + // In the package schema, each new record type has a variant for current + // records and one for retained revisions (2 × 5). The rest are the new + // fields and list values on earlier types, counted in every place their + // shapes appear. In the series file, field_basis.machine on the sample + // record and its revision. In the manifest, the five new names in the + // record-count type list, and `partial` (D313). + for (name, additions) in [ + ("athleticstandard.schema.json", 146), + ("measurement-series.schema.json", 2), + ("export-manifest.schema.json", 6), + ] { + let mut document = published("3.0.0", name); + rewrite_versions(&mut document, "3.0.0", "2.1.3"); + assert_eq!(remove_3_0_0_additions(&mut document), additions, "{name}: the 3.0.0 additions"); + first_difference(&json::to_pretty(&published("2.1.3", name)), &json::to_pretty(&document), name); + } +} + #[test] fn the_published_2_1_3_files_match_2_1_2_except_versions_and_the_coach() { // Each record shape appears twice in the package schema, once for current diff --git a/tests/record_3_0_0.rs b/tests/record_3_0_0.rs index 003f061a..0bdf909a 100644 --- a/tests/record_3_0_0.rs +++ b/tests/record_3_0_0.rs @@ -9,7 +9,7 @@ use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; -use athleticstandard::model::RecordType; +use athleticstandard::model::{RecordType, ATHLETIC_STANDARD_VERSION}; use athleticstandard::store::check::check_database; use athleticstandard::store::contract; use athleticstandard::store::migrate::{execute_confirmed_migration, MigrationOptions}; @@ -112,7 +112,10 @@ fn every_2_x_fixture_moves_to_step_8_with_every_row_unchanged() { assert!(before["record_revisions"].len() > 1, "{name} has history to keep"); migrate(&path); - assert_eq!(maintenance_support::stored_versions(&path), ("3.0.0".to_string(), SQL_SCHEMA_VERSION)); + assert_eq!( + maintenance_support::stored_versions(&path), + (ATHLETIC_STANDARD_VERSION.to_string(), SQL_SCHEMA_VERSION) + ); assert_eq!(every_row(&path), before, "{name}: a row changed"); let definition = records_definition(&path); @@ -197,7 +200,9 @@ fn step_8_stops_when_foreign_keys_are_on_and_records_exist() { } /// The published recipe for direct-SQL runners: foreign keys off before the -/// transaction, the file, an empty foreign-key check, and commit. +/// transaction, the file, an empty foreign-key check, and commit. The later +/// published steps then run as files too, so the database reaches the +/// program's step. #[test] fn step_8_runs_from_the_published_file_with_foreign_keys_off() { let path = at_step_7(&demo_fixture(), "ath-step-8-direct-"); @@ -210,6 +215,9 @@ fn step_8_runs_from_the_published_file_with_foreign_keys_off() { connection.query_row("SELECT count(*) FROM pragma_foreign_key_check", [], |row| row.get(0)).unwrap(); assert_eq!(broken, 0); connection.execute_batch("PRAGMA user_version = 8; COMMIT; PRAGMA foreign_keys = ON;").unwrap(); + // Step 9 records the version and changes no table (D334). + let step_9 = fs::read_to_string(repository().join("spec/sql/migrations/009-version-3-1-0.sql")).unwrap(); + connection.execute_batch(&format!("BEGIN IMMEDIATE; {step_9} PRAGMA user_version = 9; COMMIT;")).unwrap(); drop(connection); assert_eq!(every_row(&path), before); let store = Store::open(&path, OpenOptions { read_only: true, allow_outdated_schema: false }).unwrap(); @@ -597,7 +605,7 @@ pub mod new_types { let current = json::parse(&text).unwrap(); assert_eq!(registry::shape("AthleticStandardPackage").unwrap().issues(¤t).len(), 0); let older = json::parse(&text.replacen( - "\"athleticstandard_version\": \"3.0.0\"", + &format!("\"athleticstandard_version\": \"{}\"", athleticstandard::model::ATHLETIC_STANDARD_VERSION), "\"athleticstandard_version\": \"2.1.3\"", 1, )) @@ -975,7 +983,7 @@ mod new_fields { export_package(&store, &out, &ExportOptions::default()).unwrap(); let text = fs::read_to_string(out.join(PACKAGE_DOCUMENT)).unwrap(); let older = json::parse(&text.replacen( - "\"athleticstandard_version\": \"3.0.0\"", + &format!("\"athleticstandard_version\": \"{}\"", athleticstandard::model::ATHLETIC_STANDARD_VERSION), "\"athleticstandard_version\": \"2.1.3\"", 1, )) diff --git a/tests/skill_install.rs b/tests/skill_install.rs index 9e45c6f5..5607133b 100644 --- a/tests/skill_install.rs +++ b/tests/skill_install.rs @@ -49,7 +49,8 @@ fn the_known_hashes_are_the_2_1_1_files() { first.sort(); assert_eq!(first, expected, "every 2.1.1 calculation skill"); // The 2.1.2 and 2.1.3 files follow: 24 skills each, with hyrox-race-splits. - assert_eq!(actual.len(), 23 + 24 + 24); + // Then the 31 calculation skills of 3.0.0. + assert_eq!(actual.len(), 23 + 24 + 24 + 31); } #[test] diff --git a/tools/public-data-allowlist.json b/tools/public-data-allowlist.json index 691b03d3..daaaa932 100644 --- a/tools/public-data-allowlist.json +++ b/tools/public-data-allowlist.json @@ -3,7 +3,7 @@ "fixtures": [ { "path": "examples/demo-athlete/athlete.ath.sqlite", - "sha256": "5b3717b9135f525f33a7f6444355c0f8bda4b3d9823847a4bac2ffe26da5c926" + "sha256": "74b2b31af63883c0d8781809420f322832aed11491b3507636599379ef22614c" }, { "path": "examples/demo-athlete/attachments/01890f3e-e7d3-7cc0-88c8-00000000000e.png", diff --git a/wasm/Cargo.toml b/wasm/Cargo.toml index fd839c46..01620bb7 100644 --- a/wasm/Cargo.toml +++ b/wasm/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "athleticstandard-wasm" -version = "3.0.0" +version = "3.1.0" edition = "2021" rust-version = "1.95" description = "Athletic Standard core as WebAssembly: one JSON request in, one answer out" From c0754316800e28fa7709d4ef7c624b394fdb1361 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 11:24:08 -0600 Subject: [PATCH 16/30] End only the test person's sessions in the host refresh test. The refresh test asks the test sign-in provider to forget refresh tokens, then checks that the next refresh asks for sign-in. The provider forgot every token, so when two emulators ran the test at once, one device could end the other's session between its sign-in and its refresh. The staged Android run failed that way once. The provider's test route now takes a `subject` and forgets only that person's tokens, and the Swift and Kotlin tests name the person each signed in as. Co-Authored-By: Claude Opus 5.5 --- host/examples/test-sign-in-provider.rs | 14 ++++++++++---- .../kotlin/ai/athleticstandard/HostTest.kt | 6 ++++-- .../AthleticStandardHostTests/HostTests.swift | 8 ++++++-- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/host/examples/test-sign-in-provider.rs b/host/examples/test-sign-in-provider.rs index 591c8680..7deaa7fb 100644 --- a/host/examples/test-sign-in-provider.rs +++ b/host/examples/test-sign-in-provider.rs @@ -195,10 +195,16 @@ async fn token(State(provider): State>, Form(form): Form>) -> StatusCode { - provider.refresh_tokens.lock().unwrap().clear(); +/// Test control: forget the refresh tokens of the person `subject` names, as a +/// provider does when a person's sessions are ended, or every refresh token +/// without one. Tests that run on several devices at once name their own +/// person, so one device does not end another's sessions. +async fn revoke_all(State(provider): State>, Query(query): Query>) -> StatusCode { + let mut tokens = provider.refresh_tokens.lock().unwrap(); + match query.get("subject") { + Some(subject) => tokens.retain(|_, grant| &grant.subject != subject), + None => tokens.clear(), + } StatusCode::NO_CONTENT } diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt index 8116cc56..69ed494a 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt @@ -103,7 +103,8 @@ class HostTest { fun anExpiredTokenIsRefreshedAndARefusedRefreshAsksForSignIn() { val context = InstrumentationRegistry.getInstrumentation().targetContext val store = KeystoreTokenStore(context, "test-${UUID.randomUUID()}") - val signIn = signIn("athlete-app", "refresh-${UUID.randomUUID()}", store) + val person = "refresh-${UUID.randomUUID()}" + val signIn = signIn("athlete-app", person, store) val tokens = store.load()!! store.save(tokens.copy(expiresAtMillis = System.currentTimeMillis() - 10_000)) signIn.client().me() @@ -113,7 +114,8 @@ class HostTest { assertTrue(refreshed.expiresAtMillis > System.currentTimeMillis()) // The provider ends the person's sessions: the next refresh is refused. - val revoke = URL("$issuer/test/revoke-refresh-tokens").openConnection() as HttpURLConnection + // Only this person's, so a test on another device keeps its own. + val revoke = URL("$issuer/test/revoke-refresh-tokens?subject=$person").openConnection() as HttpURLConnection revoke.requestMethod = "POST" assertEquals(204, revoke.responseCode) store.save(refreshed.copy(expiresAtMillis = System.currentTimeMillis() - 10_000)) diff --git a/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift b/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift index f62be70b..8f97636a 100644 --- a/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift +++ b/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift @@ -121,7 +121,8 @@ struct HostTests { @Test func anExpiredTokenIsRefreshedAndARefusedRefreshAsksForSignIn() async throws { let environment = try TestEnvironment.load() let store = MemoryTokenStore() - let signIn = try await AthleticStandardHostTests.signIn(environment, client: "athlete-app", person: "refresh-\(UUID().uuidString)", store: store) + let person = "refresh-\(UUID().uuidString)" + let signIn = try await AthleticStandardHostTests.signIn(environment, client: "athlete-app", person: person, store: store) var tokens = try #require(try store.load()) let firstRefresh = tokens.refreshToken tokens.expiresAt = Date().addingTimeInterval(-10) @@ -134,7 +135,10 @@ struct HostTests { #expect(refreshed.expiresAt > Date()) // The provider ends the person's sessions: the next refresh is refused. - var request = URLRequest(url: environment.issuer.appending(path: "test/revoke-refresh-tokens")) + // Only this person's, so a test running at the same time keeps its own. + var request = URLRequest( + url: environment.issuer.appending(path: "test/revoke-refresh-tokens") + .appending(queryItems: [URLQueryItem(name: "subject", value: person)])) request.httpMethod = "POST" _ = try await URLSession.shared.data(for: request) var expired = refreshed From 78b76c9c551a61938a4ae0b88eca39ab987368f7 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 11:31:47 -0600 Subject: [PATCH 17/30] Record the 3.1.0 phone test runs. The evidence for 3.1.0 now comes from the 3.1.0 build: the Swift package installed by version, the Android library installed by coordinate on emulators with 4 KB and 16 KB pages in a debug and a shrunk release build, the desktop round trip on each platform, two Swift staging runs with the same zip bytes, and the whole workspace. It also names the two test problems found while gathering it. The simulator, the release CI jobs, and publication are still not run. Co-Authored-By: Claude Opus 5.5 --- .../v3.1.0/appendix/release-evidence.md | 26 ++++++++++++++----- build-history/v3.1.0/progress.md | 2 +- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/build-history/v3.1.0/appendix/release-evidence.md b/build-history/v3.1.0/appendix/release-evidence.md index 07b061dd..fcf1f320 100644 --- a/build-history/v3.1.0/appendix/release-evidence.md +++ b/build-history/v3.1.0/appendix/release-evidence.md @@ -1,10 +1,11 @@ # Version 3.1.0 release evidence This is the evidence for the release gates of 3.1.0 ([spec](../spec.md) section 3). It -was gathered on an Apple silicon Mac (arm64) with synthetic data. No live provider -account was used. Each staging run writes `apple-report.json` and `android-report.json` -with the hashes, the source commit, the targets, and the tool versions; the release job -adds both to the GitHub release. +was gathered on 2026-11-29 on an Apple silicon Mac (arm64) with Rust 1.100.0, from +commit `fda0047` of the build, with synthetic data. No live provider account was used. +Each staging run writes `apple-report.json` and `android-report.json` with the hashes, +the source commit, the targets, and the tool versions; the release job adds both to the +GitHub release. ## 1. Checks @@ -19,10 +20,21 @@ adds both to the GitHub release. | Android library installed by coordinate, API 36 (4 KB pages) and API 37.1 (16 KB pages) emulators | 25 tests passed on each, in a debug build and in a shrunk release build | | 16 KB alignment of every native library in the shrunk release APK | 4 of 4 libraries aligned (both ABIs of the library and of JNA) | | Desktop round trip | Passed on macOS and on both emulators: the desktop `ath` created the file, the phone library corrected a reading, and the desktop `ath` found the edit at revision 2, revision 1 kept, and a passing `ath check` | -| XCFramework zip | Two staging runs gave the same bytes | -| The whole workspace after the phone work | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass; `cargo test` (workspace) gives 939 passed, 0 failed, 18 ignored; npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (gate 5) passes | +| XCFramework zip | Two staging runs gave the same bytes for `AthleticStandardFFI-3.1.0.xcframework.zip` | +| Version | Each binding reports 3.1.0, and an outdated 2.1.0 file migrates to SQL step 9 on macOS and on both emulators | +| The whole workspace | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass, also without the `cli` feature for the library and the phone crate; `cargo test` (workspace) gives 940 passed, 0 failed, 18 ignored; npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (3.0.0 gate 5) passes | -## 2. Not verified +## 2. Found and fixed while gathering this evidence + +- **A path check on Windows.** A phone storage test expected the backup path to end in + `/before-migration.ath.sqlite`. On Windows the path uses `\`, so the check failed + although the migration worked. It now compares the file name. +- **Two devices sharing one test provider.** The host refresh test asked the test + sign-in provider to forget every refresh token. When both emulators ran it at once, + one device could end the other's session between its sign-in and its refresh. The + provider now forgets only the tokens of the person the test signed in as. + +## 3. Not verified - The iPhone simulator. Xcode's license was not accepted on the build machine, so `xcodebuild` and `simctl` could not run. The `mobile-apple` CI job runs it. diff --git a/build-history/v3.1.0/progress.md b/build-history/v3.1.0/progress.md index cd7c7d2f..518c9ca2 100644 --- a/build-history/v3.1.0/progress.md +++ b/build-history/v3.1.0/progress.md @@ -10,7 +10,7 @@ Status: **built; not released.** The plan is [spec.md](spec.md). Evidence: | 3 | SQLite on phones: create, open, edit, close, reopen, save a copy, picked documents | Mac and two Android emulators pass; iPhone simulator and iCloud not run | | 4 | Calculations from memory and SQLite through one reader interface | Mac and two Android emulators pass; iPhone simulator not run | | 5 | Host client for Swift and Kotlin with browser sign-in | Mac and two Android emulators pass against a real host; live WorkOS not run | -| 6 | Release packaging, phone test runs, release gate | staged and installed locally; CI, simulator, and publication not run | +| 6 | Release packaging, phone test runs, release gate | staged and installed locally at 3.1.0; release CI jobs, simulator, and publication not run | | 7 | Version 3.1.0 and migration step 9 | done | The phone work was built on 3.0.0 as build steps 12 to 17, and moved here when 3.0.0 From 825e444cdee11d15945b306390f8055a2e520d34 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 22:42:13 -0600 Subject: [PATCH 18/30] Name the model's free-form JSON values. `supplied_fields`, sleep stage minutes, and record extensions were plain JSON maps, and a calculation parameter's value was a plain JSON value. They become `JsonObject` and `JsonValue`, which hold the same JSON and read and write the same text. The Swift and Kotlin bindings need a type of their own to carry them across as JSON text, and a plain map would take the name `Map`, which Kotlin already uses. Nothing in the format or the published schema changes. Co-Authored-By: Claude Opus 5.5 --- core/src/calculate/memory.rs | 2 +- core/src/json.rs | 92 ++++++++++++++++++++++++++++++++ core/src/model/common.rs | 6 +-- core/src/model/record.rs | 10 ++-- core/src/model/training.rs | 2 +- src/import/apple/mod.rs | 2 +- src/import/apple/routes.rs | 2 +- src/import/apple/xml.rs | 2 +- src/log.rs | 2 +- src/package/restore.rs | 4 +- src/protocol/ops/prediction.rs | 2 +- src/protocol/ops/records.rs | 2 +- src/store/read.rs | 6 +-- src/store/write.rs | 4 +- tests/calculation_support/mod.rs | 2 +- tests/import_garmin.rs | 4 +- tests/log.rs | 2 +- tests/package_import.rs | 9 +++- tests/scenario_support/mod.rs | 3 +- 19 files changed, 128 insertions(+), 30 deletions(-) diff --git a/core/src/calculate/memory.rs b/core/src/calculate/memory.rs index 2fda183f..4e4775b7 100644 --- a/core/src/calculate/memory.rs +++ b/core/src/calculate/memory.rs @@ -49,7 +49,7 @@ impl Entry { // The same JSON text the store writes and a calculation reads back. let data = json::parse(&record.data.to_json())?; let extensions = match &record.extensions { - Some(map) => Some(json::parse(&json::to_string(&Value::Object(map.clone())))?), + Some(map) => Some(json::parse(&json::to_string(&Value::Object(map.0.clone())))?), None => None, }; Ok(Entry { diff --git a/core/src/json.rs b/core/src/json.rs index f914b5f7..f95500a6 100644 --- a/core/src/json.rs +++ b/core/src/json.rs @@ -18,6 +18,98 @@ use std::fmt::Write as _; pub use serde_json::{Map, Number, Value}; +/// A JSON object the format keeps as given, with its keys in order: the names a +/// source supplied, sleep stage minutes, and record extensions. It has its own +/// name so the Swift and Kotlin bindings can carry it as JSON text. +#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct JsonObject(pub Map); + +/// Any JSON value the format keeps as given, such as a calculation parameter. +/// It has its own name so the Swift and Kotlin bindings can carry it as JSON +/// text. +#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct JsonValue(pub Value); + +impl JsonObject { + pub fn new() -> Self { + JsonObject(Map::new()) + } +} + +impl std::ops::Deref for JsonObject { + type Target = Map; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for JsonObject { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl From> for JsonObject { + fn from(map: Map) -> Self { + JsonObject(map) + } +} + +impl From for Map { + fn from(object: JsonObject) -> Self { + object.0 + } +} + +impl From for Value { + fn from(object: JsonObject) -> Self { + Value::Object(object.0) + } +} + +impl FromIterator<(String, Value)> for JsonObject { + fn from_iter>(items: I) -> Self { + JsonObject(items.into_iter().collect()) + } +} + +impl<'a> IntoIterator for &'a JsonObject { + type Item = (&'a String, &'a Value); + type IntoIter = serde_json::map::Iter<'a>; + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl IntoIterator for JsonObject { + type Item = (String, Value); + type IntoIter = serde_json::map::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl std::ops::Deref for JsonValue { + type Target = Value; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl From for JsonValue { + fn from(value: Value) -> Self { + JsonValue(value) + } +} + +impl From for Value { + fn from(value: JsonValue) -> Self { + value.0 + } +} + /// A JSON text could not be read. #[derive(Debug, Clone, PartialEq, Eq)] pub struct JsonError { diff --git a/core/src/model/common.rs b/core/src/model/common.rs index 8de89b86..89105a1b 100644 --- a/core/src/model/common.rs +++ b/core/src/model/common.rs @@ -7,7 +7,7 @@ use super::schema::{ SchemaRef, Shape, StringFormat, }; use super::time; -use crate::json::{Map, Value}; +use crate::json::Value; use crate::{model_enum, model_object}; // ---- Checked strings ---------------------------------------------------- @@ -224,10 +224,10 @@ fn positive_int_schema() -> Schema { } /// A value kept under the name it arrived with (`supplied_fields`). -pub type SuppliedFields = Map; +pub type SuppliedFields = crate::json::JsonObject; /// Stage name to minutes. -pub type StageMinutes = Map; +pub type StageMinutes = crate::json::JsonObject; // ---- Enums -------------------------------------------------------------- diff --git a/core/src/model/record.rs b/core/src/model/record.rs index 6f97da10..51820d44 100644 --- a/core/src/model/record.rs +++ b/core/src/model/record.rs @@ -278,7 +278,7 @@ impl RecordData { } /// Optional record extensions, validated against the published limits. -pub type Extensions = Map; +pub type Extensions = crate::json::JsonObject; /// The current state of a record. #[derive(Debug, Clone, PartialEq)] @@ -318,7 +318,7 @@ impl CurrentRecord { created_at: string_field(value, "created_at"), current_revision: value["current_revision"].as_f64().unwrap_or(0.0) as u64, is_deleted: value["is_deleted"].as_bool().unwrap_or(false), - extensions: value.get("extensions").and_then(Value::as_object).cloned(), + extensions: value.get("extensions").and_then(Value::as_object).cloned().map(crate::json::JsonObject), data: RecordData::from_checked(record_type, &value["data"])?, }) } @@ -331,7 +331,7 @@ impl CurrentRecord { map.insert("current_revision".into(), Value::from(self.current_revision)); map.insert("is_deleted".into(), Value::Bool(self.is_deleted)); if let Some(extensions) = &self.extensions { - map.insert("extensions".into(), Value::Object(extensions.clone())); + map.insert("extensions".into(), Value::Object(extensions.0.clone())); } map.insert("record_type".into(), Value::String(self.record_type().as_str().into())); map.insert("data".into(), self.data.to_value()); @@ -380,7 +380,7 @@ impl RecordRevision { became_known_at_basis: from_checked_value(&value["became_known_at_basis"])?, changed_by: from_checked_value(&value["changed_by"])?, data: RecordData::from_checked(record_type, &value["data"])?, - extensions: value.get("extensions").and_then(Value::as_object).cloned(), + extensions: value.get("extensions").and_then(Value::as_object).cloned().map(crate::json::JsonObject), }) } @@ -395,7 +395,7 @@ impl RecordRevision { map.insert("record_type".into(), Value::String(self.record_type().as_str().into())); map.insert("data".into(), self.data.to_value()); if let Some(extensions) = &self.extensions { - map.insert("extensions".into(), Value::Object(extensions.clone())); + map.insert("extensions".into(), Value::Object(extensions.0.clone())); } Value::Object(map) } diff --git a/core/src/model/training.rs b/core/src/model/training.rs index 4cb07885..d21029a7 100644 --- a/core/src/model/training.rs +++ b/core/src/model/training.rs @@ -377,7 +377,7 @@ model_object! { /// One setting a calculation method used. pub struct CalculationParameter { name: String, - value: Value = super::schema::json_value(), + value: crate::json::JsonValue = super::schema::json_value(), } } diff --git a/src/import/apple/mod.rs b/src/import/apple/mod.rs index 6a60b99f..c0bc1573 100644 --- a/src/import/apple/mod.rs +++ b/src/import/apple/mod.rs @@ -512,7 +512,7 @@ impl<'s, 'a> Import<'s, 'a> { provider_reporting_periods: None, received_at: self.sink.received_at().to_string(), received_at_basis: ReceivedAtBasis::ImportTime, - supplied_fields, + supplied_fields: supplied_fields.map(Into::into), field_basis: Some(field_basis), start_at: start_at.clone(), end_at, diff --git a/src/import/apple/routes.rs b/src/import/apple/routes.rs index d2a1660f..0696e16b 100644 --- a/src/import/apple/routes.rs +++ b/src/import/apple/routes.rs @@ -289,7 +289,7 @@ pub fn route_from_gpx(text: &str) -> (Vec, Vec) { supplied_fields: elevation.map(|elevation| { let mut fields = crate::json::Map::new(); fields.insert("ele".into(), crate::json::Value::String(elevation.to_string())); - fields + fields.into() }), }); } diff --git a/src/import/apple/xml.rs b/src/import/apple/xml.rs index db1e5e9d..1f4cc97d 100644 --- a/src/import/apple/xml.rs +++ b/src/import/apple/xml.rs @@ -1059,7 +1059,7 @@ fn location_point(attrs: &Attributes) -> std::result::Result latitude_deg: latitude, longitude_deg: longitude, input_timestamp: Some(timestamp_receipt(&original, None)), - supplied_fields: (!extra.is_empty()).then_some(extra), + supplied_fields: (!extra.is_empty()).then(|| extra.into()), }) } diff --git a/src/log.rs b/src/log.rs index 0b909804..2a956458 100644 --- a/src/log.rs +++ b/src/log.rs @@ -170,7 +170,7 @@ pub fn render_log_plan(plan: &LogPlan) -> String { indented(&input.data.to_value(), &mut lines); if let Some(extensions) = &input.extensions { lines.push(" extensions".into()); - indented(&Value::Object(extensions.clone()), &mut lines); + indented(&Value::Object(extensions.0.clone()), &mut lines); } } if !plan.asked.open.is_empty() { diff --git a/src/package/restore.rs b/src/package/restore.rs index 60695ba1..3b78d090 100644 --- a/src/package/restore.rs +++ b/src/package/restore.rs @@ -524,7 +524,7 @@ fn insert_revision(tx: &Transaction<'_>, revision: &RecordRevision) -> Result<() revision.revision as i64, revision.record_type().as_str(), revision.data.to_json(), - revision.extensions.as_ref().map(|map| json::to_string(&Value::Object(map.clone()))), + revision.extensions.as_ref().map(|map| json::to_string(&Value::Object(map.0.clone()))), revision.became_known_at, revision.became_known_at_basis.as_str(), json::encode(&revision.changed_by), @@ -930,7 +930,7 @@ fn resolve_in( record_value.insert("current_revision".into(), Value::from(next)); record_value.insert("is_deleted".into(), Value::Bool(false)); if let Some(extensions) = &extensions { - record_value.insert("extensions".into(), Value::Object(extensions.clone())); + record_value.insert("extensions".into(), Value::Object(extensions.0.clone())); } record_value.insert("data".into(), data_value); let record = CurrentRecord::from_value(&Value::Object(record_value))?; diff --git a/src/protocol/ops/prediction.rs b/src/protocol/ops/prediction.rs index 2274ab65..9ad8efc7 100644 --- a/src/protocol/ops/prediction.rs +++ b/src/protocol/ops/prediction.rs @@ -128,7 +128,7 @@ fn log_record_value(record: &LogRecord) -> Value { let mut out = write_input(record.record_type(), &record.record_id, &record.created_at, &record.changed_by, &record.data); if let Some(extensions) = &record.extensions { - out.insert("extensions".into(), Value::Object(extensions.clone())); + out.insert("extensions".into(), Value::Object(extensions.0.clone())); } Value::Object(out) } diff --git a/src/protocol/ops/records.rs b/src/protocol/ops/records.rs index b423b17e..abc427aa 100644 --- a/src/protocol/ops/records.rs +++ b/src/protocol/ops/records.rs @@ -238,7 +238,7 @@ fn corrected( } (None, true) => { if let Some(existing) = ¤t.extensions { - candidate.insert("extensions".into(), Value::Object(existing.clone())); + candidate.insert("extensions".into(), Value::Object(existing.0.clone())); } } (None, false) => {} diff --git a/src/store/read.rs b/src/store/read.rs index 56e83a23..33a2406e 100644 --- a/src/store/read.rs +++ b/src/store/read.rs @@ -42,7 +42,7 @@ fn parse_extensions(text: Option) -> Result> { value @ Value::Object(_) => { crate::model::extensions::record_extensions().validate(&value)?; match value { - Value::Object(map) => Ok(Some(map)), + Value::Object(map) => Ok(Some(crate::json::JsonObject(map))), _ => unreachable!(), } } @@ -66,7 +66,7 @@ pub fn current_from_row(row: &Row<'_>) -> Result { value.insert("current_revision".into(), Value::from(current_revision)); value.insert("is_deleted".into(), Value::Bool(is_deleted == 1)); if let Some(extensions) = parse_extensions(extensions_json)? { - value.insert("extensions".into(), Value::Object(extensions)); + value.insert("extensions".into(), Value::Object(extensions.0)); } value.insert("record_type".into(), Value::String(record_type)); value.insert("data".into(), json::parse(&record_json)?); @@ -94,7 +94,7 @@ pub fn revision_from_row(row: &Row<'_>) -> Result { value.insert("record_type".into(), Value::String(record_type)); value.insert("data".into(), json::parse(&record_json)?); if let Some(extensions) = parse_extensions(extensions_json)? { - value.insert("extensions".into(), Value::Object(extensions)); + value.insert("extensions".into(), Value::Object(extensions.0)); } Ok(RecordRevision::from_value(&Value::Object(value))?) } diff --git a/src/store/write.rs b/src/store/write.rs index 4dc8b76d..23ed67db 100644 --- a/src/store/write.rs +++ b/src/store/write.rs @@ -337,7 +337,7 @@ fn insert_revision( basis: BecameKnownAtBasis, changed_by: &RecordActor, ) -> Result<()> { - let extensions_json = extensions.map(|map| json::to_string(&Value::Object(map.clone()))); + let extensions_json = extensions.map(|map| json::to_string(&Value::Object(map.0.clone()))); tx.prepare_cached( "INSERT INTO record_revisions ( record_id, revision, record_type, record_json, extensions_json, @@ -503,7 +503,7 @@ fn correct_record( let extensions = match correction.extensions { ExtensionsUpdate::Keep => match ¤t.extensions_json { Some(text) => match json::parse(text)? { - Value::Object(map) => Some(map), + Value::Object(map) => Some(crate::json::JsonObject(map)), Value::Null => None, _ => return Err(Error::other("extensions_json must be an object")), }, diff --git a/tests/calculation_support/mod.rs b/tests/calculation_support/mod.rs index 55c9403c..fcc54fbe 100644 --- a/tests/calculation_support/mod.rs +++ b/tests/calculation_support/mod.rs @@ -159,7 +159,7 @@ impl Lab { let data = RecordData::decode(record_type, &value).unwrap_or_else(|error| panic!("{record_type:?} {id}: {error:?}")); let extensions = extensions.map(|value| match json::parse(&value.to_string()).unwrap() { - Value::Object(map) => map, + Value::Object(map) => athleticstandard::json::JsonObject(map), _ => panic!("extensions must be an object"), }); let record = NewRecord { diff --git a/tests/import_garmin.rs b/tests/import_garmin.rs index 37b07258..8e2c3bb3 100644 --- a/tests/import_garmin.rs +++ b/tests/import_garmin.rs @@ -416,7 +416,7 @@ fn a_changed_activity_keeps_its_extensions() { record_id: workout.clone(), expected_revision: 1, data: current.data.clone(), - extensions: athleticstandard::store::ExtensionsUpdate::Set(Some(extensions.clone())), + extensions: athleticstandard::store::ExtensionsUpdate::Set(Some(extensions.clone().into())), changed_by: athleticstandard::model::RecordActor::Athlete, became_known_at: Some(step_time(1)), became_known_at_basis: athleticstandard::model::BecameKnownAtBasis::LocalWrite, @@ -429,7 +429,7 @@ fn a_changed_activity_keeps_its_extensions() { import_shared(&mut store, &file, SharedImport::Garmin, &step_time(2)); let after = store.get_record(&workout).unwrap().unwrap(); assert_eq!(after.current_revision, 3); - assert_eq!(after.extensions, Some(extensions)); + assert_eq!(after.extensions, Some(extensions.into())); } /// A file over the per-file limit is refused before it is read. diff --git a/tests/log.rs b/tests/log.rs index 3f30c988..963139ee 100644 --- a/tests/log.rs +++ b/tests/log.rs @@ -218,7 +218,7 @@ fn structured_logs_refuse_unknown_fields_and_check_extensions() { json::to_string(&json!({ "record_type": "athlete_report", "extensions": extensions, "data": note("x") })); write_log(&mut store, &valid, RecordActor::Athlete); let report = records(&store, RecordType::AthleteReport).remove(0); - assert_eq!(json::to_string(&Value::Object(report.extensions.unwrap())), json::to_string(&extensions)); + assert_eq!(json::to_string(&Value::Object(report.extensions.unwrap().0)), json::to_string(&extensions)); let bad_namespace = json::to_string(&json!({ "record_type": "athlete_report", "extensions": { "example.com/x": { "app_mood": "great" } }, "data": note("x"), diff --git a/tests/package_import.rs b/tests/package_import.rs index a9e3e713..a8cf16cc 100644 --- a/tests/package_import.rs +++ b/tests/package_import.rs @@ -254,7 +254,9 @@ fn a_resolved_conflict_keeps_the_chosen_side_s_extensions() { let base = materialize_golden_package("demo", &directory); let local = restored_copy(&base, &directory, "local"); let imported = restored_copy(&base, &directory, "imported"); - let side = |name: &str| json!({ "example.com/side": { "from": name } }).as_object().cloned(); + let side = |name: &str| { + json!({ "example.com/side": { "from": name } }).as_object().cloned().map(athleticstandard::json::JsonObject) + }; correct_profile(&local, "Local name", ExtensionsUpdate::Set(side("local"))); correct_profile(&imported, "Imported name", ExtensionsUpdate::Set(side("imported"))); let incoming = directory.join("incoming"); @@ -542,7 +544,10 @@ fn a_database_s_own_export_imports_without_conflicts() { ) .unwrap(); let mut create = NewRecord::new(data, RecordActor::Athlete); - create.extensions = json!({ "example.com/zz": { "b": 1, "a": 2 }, "example.com/aa": 1 }).as_object().cloned(); + create.extensions = json!({ "example.com/zz": { "b": 1, "a": 2 }, "example.com/aa": 1 }) + .as_object() + .cloned() + .map(athleticstandard::json::JsonObject); let written = store.apply(Changes { creates: vec![create], ..Changes::default() }).unwrap(); let id = written.records[0].record_id.clone(); let before = stored_texts(&store, &id); diff --git a/tests/scenario_support/mod.rs b/tests/scenario_support/mod.rs index 333d9f5c..5b07da83 100644 --- a/tests/scenario_support/mod.rs +++ b/tests/scenario_support/mod.rs @@ -89,7 +89,8 @@ pub fn new_record(input: &Value) -> NewRecord { record.created_at = text(input, "created_at"); record.became_known_at = text(input, "became_known_at"); record.became_known_at_basis = basis(input.get("became_known_at_basis")); - record.extensions = input.get("extensions").and_then(Value::as_object).cloned(); + record.extensions = + input.get("extensions").and_then(Value::as_object).cloned().map(athleticstandard::json::JsonObject); record } From a6d603f43351fcd94c5611f34753131459a39513 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 23:35:01 -0600 Subject: [PATCH 19/30] Give phone apps typed records and calculation answers. UniFFI now generates a Swift and a Kotlin type for every record type, every part of a record, every list of allowed values, the record wrapper, and every calculation answer, from the Rust model and result types (D329). The core marks them under an optional `uniffi` feature, so the desktop program and the WebAssembly build do not depend on UniFFI. Phone writes take the typed values and run the npm client's request through the same protocol operation, so they get the desktop checks and messages. Reads check the stored JSON before returning a type. JSON stays available through converters, `addRecordsJson`, and `runOperation`. An app keeps its own values as extensions under its own key. The library reads and sets one key and checks the key and the format's limits. The Swift package adds Codable helpers; the Kotlin library adds helpers that take the app's own JSON text. The host clients read and write the typed records too. Result types that UniFFI cannot carry change shape without changing their JSON: whole-number counts are u64, fixed names are String, readings around the best power are (offset, value) pairs, and a threshold answer is one untagged enum. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + build-history/v3.1.0/decisions.md | 74 +++- build-history/v3.1.0/spec.md | 4 +- core/Cargo.toml | 4 + core/src/calculate/hyrox.rs | 9 +- core/src/calculate/methods.rs | 93 +++-- core/src/calculate/mod.rs | 2 +- core/src/calculate/range.rs | 93 +++-- core/src/calculate/record.rs | 21 +- core/src/calculate/recorded.rs | 2 + core/src/calculate/window.rs | 113 ++++- core/src/calculate/workout_ops.rs | 21 +- core/src/json.rs | 18 + core/src/lib.rs | 3 + core/src/model/common.rs | 2 + core/src/model/record.rs | 3 + core/src/model/schema.rs | 8 +- core/src/model/training.rs | 1 + core/src/thresholds.rs | 150 ++++--- core/uniffi.toml | 29 ++ host/Cargo.toml | 6 + mobile/Cargo.toml | 2 +- .../android/athleticstandard/build.gradle.kts | 1 + .../ai/athleticstandard/CalculationTest.kt | 123 ++++-- .../kotlin/ai/athleticstandard/HostTest.kt | 29 +- .../ai/athleticstandard/RoundTripTest.kt | 29 +- .../kotlin/ai/athleticstandard/StoreTest.kt | 228 ++++++++-- .../ai/athleticstandard/RecordExtensions.kt | 44 ++ .../ai/athleticstandard/host/HostClient.kt | 41 ++ .../athleticstandard/consumer/MainActivity.kt | 92 +++-- mobile/scripts/build-android.sh | 8 +- mobile/scripts/build-apple.sh | 27 +- mobile/src/calculate.rs | 178 ++------ mobile/src/error.rs | 6 +- mobile/src/lib.rs | 25 +- mobile/src/records.rs | 388 ++++++++++++++++++ mobile/src/store.rs | 188 ++++++--- .../AthleticStandardExample/ExampleApp.swift | 36 +- mobile/swift/Package.swift | 8 +- .../AthleticStandard/RecordExtensions.swift | 72 ++++ .../AthleticStandardHost/TypedRecords.swift | 43 ++ .../AthleticStandardHostTests/HostTests.swift | 24 +- .../CalculationTests.swift | 76 +++- .../AthleticStandardTests/DocumentTests.swift | 3 +- .../RoundTripTests.swift | 31 +- .../AthleticStandardTests/StoreTests.swift | 209 ++++++++-- mobile/tests/fixtures.rs | 69 ++-- mobile/tests/store.rs | 114 +++-- mobile/uniffi.toml | 5 +- src/calculate/mod.rs | 2 +- src/calculate/window.rs | 97 ++--- 51 files changed, 2172 insertions(+), 683 deletions(-) create mode 100644 core/uniffi.toml create mode 100644 mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/RecordExtensions.kt create mode 100644 mobile/src/records.rs create mode 100644 mobile/swift/Sources/AthleticStandard/RecordExtensions.swift create mode 100644 mobile/swift/Sources/AthleticStandardHost/TypedRecords.swift diff --git a/Cargo.lock b/Cargo.lock index ef98d58f..ee6c8db0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -211,6 +211,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "uniffi", ] [[package]] diff --git a/build-history/v3.1.0/decisions.md b/build-history/v3.1.0/decisions.md index 58ed1202..0d4205fa 100644 --- a/build-history/v3.1.0/decisions.md +++ b/build-history/v3.1.0/decisions.md @@ -137,22 +137,70 @@ Rejected alternatives: - Copy the main database file back. Rejected because a copy of an active database can miss committed edits that are still in the companion log. -## D329. Values cross the boundary as JSON text, and failures are typed - -Record bodies, results, and receipts cross between Rust and Swift or Kotlin as UTF-8 -JSON bytes, read and written by the library's own JSON code. Options, validation -issues, and failure kinds are generated types. One failure type, -`AthleticStandardError`, has a case for each desktop error code (`invalid`, -`not_found`, `stale`, `refused`, `migration_required`, `database`, `io`, and `error`) -and three cases of its own: `malformed_json`, `unknown_shape`, and `closed`. A -validation issue keeps its path as a list of segments, each either a field name or a -list position, with the desktop code and message. +## D329. Records and results are generated Swift and Kotlin types + +Every record type, every part of a record, every list of allowed values, the record +wrapper, and every calculation answer is a Swift and a Kotlin type. UniFFI generates +them from the Rust model in `core/src/model/` and the result types in +`core/src/calculate/`. The core marks them under an optional `uniffi` feature, so the +desktop program and the WebAssembly build do not depend on UniFFI. + +Writes take these types. The library turns each write into the npm client's JSON +request and runs the same protocol operation, so a phone write gets the desktop checks +and messages (D327). Reads check the stored JSON as a complete record before they +return the type. Calculations return the `ath apply --json` and `ath calculate --json` +answers as types. + +Rules: + +- **Free-form values.** A model field that holds any JSON object or value + (`supplied_fields`, `extensions`, a provider period kept exactly as stored, a + calculation parameter's value) is `JsonObject` or `JsonValue` in Rust. It crosses as + JSON text: a `String` in Swift and Kotlin. +- **App values.** An app keeps its own values on a record as extensions, under a key of + its own domain written backwards, such as `com.example.myapp/notes`. The app writes + its own Swift or Kotlin type for each value. `extensionJson` reads one key and + `withExtensionJson` sets one; the library checks the key and the format's limits for + extensions. The Swift package adds `Codable` helpers. The Kotlin library adds + `extension` and `withExtension`, which take JSON text from the app's own JSON library. +- **JSON stays available.** Converters turn every record, revision, and answer into its + desktop JSON and back. `RecordSnapshotBuilder.addRecordsJson` takes a host's or + `ath`'s record list. `runOperation` takes the npm client's request. +- **Numbers.** The desktop already reads JSON numbers as 64-bit floating point and + writes them as JavaScript does, so a typed value gives the desktop's text. +- **Names.** Types keep their Rust names. A name that would clash in Swift or Kotlin is + renamed: `Environment` is `TrainingEnvironment`; a range calculation's `Operation`, + `RecordKind`, and `Group` are `CalculationOperation`, `CalculationRecordKind`, and + `CalculationGroup`; its options are `RangeRequest`. `CalculationGroup.None` is + `ungrouped` in Swift, where `none` would mean an empty optional, and `UNGROUPED` in + Kotlin. +- **Modules.** In Swift both generated files compile into the one `AthleticStandard` + module. In Kotlin the core's types are in the package `ai.athleticstandard.core`, + because each generated Kotlin file declares its own copy of UniFFI's helper types. +- **Editing.** Swift records have `var` fields, so app code changes one field of a + copy. Kotlin records have `val` fields and change through `copy(...)`. +- **Failures.** One failure type, `AthleticStandardError`, has a case for each desktop + error code (`invalid`, `not_found`, `stale`, `refused`, `migration_required`, + `database`, `io`, and `error`) and three cases of its own: `malformed_json`, + `unknown_shape`, and `closed`. A validation issue keeps its path as a list of + segments, each either a field name or a list position, with the desktop code and + message. `migration_required` carries the migration preview. Rejected alternatives: -- Generate a Swift and a Kotlin type for every record shape. Rejected because record - extensions and the exact text of numbers would not survive the round trip, and the - published shapes would have a third definition to keep in step. +- Carry record bodies and results as JSON bytes, the first version of this decision. + Rejected because every app would write its own types for 29 record types and keep + them in step with the format by hand. Its two reasons do not hold: extensions stay + JSON text, and the generated types come from the Rust model, so they are not a third + definition. +- Write the Swift and Kotlin types by hand. Rejected because they would be a third + definition to keep in step. +- Generate the types from the JSON Schema with a separate generator. Rejected because + those types would not share the library's checks, and two generators would disagree + on names and optional fields. +- Let apps write their extension types in Rust, so UniFFI generates them too. Rejected + because each app would then build the native library itself, and an app's values + belong to the app, not to the format. - Return one error string. Rejected because an app must tell a stale edit from an invalid record without reading the message. diff --git a/build-history/v3.1.0/spec.md b/build-history/v3.1.0/spec.md index 59883667..d3a84ddd 100644 --- a/build-history/v3.1.0/spec.md +++ b/build-history/v3.1.0/spec.md @@ -21,8 +21,8 @@ In 3.1.0: - The `athleticstandard-mobile` crate in `mobile/`, the Swift package `AthleticStandard` for iOS 17 and later, and the Android library `ai.athleticstandard:athleticstandard` for API 24 and later (D325, D331). -- Record checks, with values crossing the boundary as JSON text and typed failures - (D329). +- Record checks, with every record, part of a record, list of allowed values, and + calculation answer as a generated Swift and Kotlin type, and typed failures (D329). - Real athlete files on a phone through the existing store, and picked documents worked on through a private copy (D327, D328). - Calculations from records an app supplies and from a file, through one reader diff --git a/core/Cargo.toml b/core/Cargo.toml index 0320b703..8f52faa4 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -18,3 +18,7 @@ ryu-js = "1.0.3" serde = { version = "1.0.229", features = ["derive"] } serde_json = { version = "1.0.154", features = ["preserve_order", "float_roundtrip"] } sha2 = "0.11.0" +uniffi = { version = "=0.33.0", optional = true } + +[features] +uniffi = ["dep:uniffi"] diff --git a/core/src/calculate/hyrox.rs b/core/src/calculate/hyrox.rs index f2aa7019..bd5e2303 100644 --- a/core/src/calculate/hyrox.rs +++ b/core/src/calculate/hyrox.rs @@ -22,12 +22,14 @@ pub const STATIONS: [&str; 8] = ["ski_erg", "sled_push", "sled_pull", "burpee_broad_jumps", "row", "farmers_carry", "sandbag_lunges", "wall_balls"]; #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct Split { pub label: String, pub seconds: f64, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct StationSplit { pub label: String, pub seconds: f64, @@ -35,8 +37,9 @@ pub struct StationSplit { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RunSummary { - pub count: usize, + pub count: u64, pub mean_seconds: f64, pub fastest: Split, pub slowest: Split, @@ -50,6 +53,7 @@ pub struct RunSummary { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SharePercent { pub runs: f64, pub stations: f64, @@ -59,6 +63,7 @@ pub struct SharePercent { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct HyroxSplitsResult { pub total_seconds: f64, pub runs_seconds: f64, @@ -205,7 +210,7 @@ pub(super) fn hyrox_splits(context: &mut Context<'_>, record: &StoredRecord) -> let first = runs.iter().find(|(number, _)| *number == 1).map(|(_, split)| split.seconds); let later: Vec = runs.iter().filter(|(number, _)| *number > 1).map(|(_, split)| split.seconds).collect(); RunSummary { - count: runs.len(), + count: runs.len() as u64, mean_seconds: round(runs_seconds / runs.len() as f64), spread_seconds: round(slowest.seconds - fastest.seconds), fastest, diff --git a/core/src/calculate/methods.rs b/core/src/calculate/methods.rs index 8adeb990..3320e9bc 100644 --- a/core/src/calculate/methods.rs +++ b/core/src/calculate/methods.rs @@ -169,19 +169,21 @@ fn heart_rate_at(samples: &[(i64, f64)], at: i64, max_gap_ms: i64, tolerance_ms: /// The earlier values a change compares against. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct Comparison { pub mean: f64, /// The sample standard deviation (n − 1) of the compared values. pub standard_deviation: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub days: Option, + pub days: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub nights: Option, + pub nights: Option, pub from: String, pub to: String, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct WindowChangeResult { #[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option, @@ -192,18 +194,19 @@ pub struct WindowChangeResult { /// The target value: the mean of the target's day so far, or the night. pub value: f64, #[serde(skip_serializing_if = "Option::is_none")] - pub target_day_readings: Option, + pub target_day_readings: Option, pub change: f64, pub change_percent: Option, /// The change in standard deviations of the compared values. pub standardized_change: Option, pub comparison: Comparison, - pub compared_records: usize, + pub compared_records: u64, #[serde(skip_serializing_if = "Option::is_none")] pub time_zone: Option, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RecoveryResult { pub drop_bpm: f64, pub end_bpm: f64, @@ -211,54 +214,59 @@ pub struct RecoveryResult { pub end_offset_ms: i64, pub later_offset_ms: i64, /// `recovery segment` or `workout end`. - pub anchor: &'static str, + pub anchor: String, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RegularityResult { /// −100 (opposite states) to 100 (the same state 24 hours apart). pub index: f64, - pub day_pairs: usize, - pub days_observed: usize, + pub day_pairs: u64, + pub days_observed: u64, pub window_days: u32, pub window_from: String, pub window_to: String, - pub sessions: usize, + pub sessions: u64, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct MovementVolume { pub movement: Option, pub volume: f64, - pub sets: usize, + pub sets: u64, pub reps: f64, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct VolumeResult { pub volume: f64, - pub weight_unit: &'static str, - pub sets: usize, + pub weight_unit: String, + pub sets: u64, pub reps: f64, #[serde(skip_serializing_if = "Option::is_none")] pub by_movement: Option>, - pub unstated_load_basis_sets: usize, + pub unstated_load_basis_sets: u64, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortLoadResult { pub load: f64, - pub unit: &'static str, + pub unit: String, pub rating: f64, pub rating_scale: String, /// `10-point` or `6-20`. Loads on different scales are never comparable. - pub scale_family: &'static str, + pub scale_family: String, pub duration_minutes: f64, /// `report` or `linked workout session`. - pub duration_from: &'static str, + pub duration_from: String, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct TrimpResult { pub load: f64, pub weighting: String, @@ -269,6 +277,7 @@ pub struct TrimpResult { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ZonesResult { pub seconds: Vec, pub uncovered_seconds: f64, @@ -277,6 +286,7 @@ pub struct ZonesResult { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RestingResult { pub bpm: f64, #[serde(skip_serializing_if = "Option::is_none")] @@ -284,11 +294,12 @@ pub struct RestingResult { #[serde(skip_serializing_if = "Option::is_none")] pub window_start_at: Option, pub window_minutes: f64, - pub samples_in_window: usize, - pub samples_read: usize, + pub samples_in_window: u64, + pub samples_read: u64, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EfficiencyResult { pub efficiency: f64, pub percent: f64, @@ -297,16 +308,18 @@ pub struct EfficiencyResult { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct StageSplitResult { - pub stages: Map, + pub stages: crate::json::JsonObject, pub asleep_minutes: f64, pub awake_minutes: f64, pub total_minutes: f64, /// Each sleep stage as a percentage of asleep minutes. - pub percent_of_asleep: Map, + pub percent_of_asleep: crate::json::JsonObject, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ClockTimesResult { pub start_at: String, pub midpoint_at: String, @@ -316,7 +329,7 @@ pub struct ClockTimesResult { pub local_end: String, pub time_zone: String, /// `athlete_profile.default_time_zone`, `source offset`, or `utc`. - pub time_zone_basis: &'static str, + pub time_zone_basis: String, pub duration_hours: f64, } @@ -427,19 +440,19 @@ fn measurement_change( field: None, basis: Some(basis), value: round_to(target, 3), - target_day_readings: Some(same_day.len()), + target_day_readings: Some(same_day.len() as u64), change: round_to(change, 3), change_percent: (center != 0.0).then(|| round_to(change / center * 100.0, 1)), standardized_change: spread.filter(|spread| *spread > 0.0).map(|spread| round_to(change / spread, 2)), comparison: Comparison { mean: round_to(center, 3), standard_deviation: spread.map(|spread| round_to(spread, 3)), - days: Some(days), + days: Some(days as u64), nights: None, from: window_from.to_string(), to: (day - chrono::Duration::days(1)).to_string(), }, - compared_records, + compared_records: compared_records as u64, time_zone: Some(zone_name), })) } @@ -533,11 +546,11 @@ fn sleep_change( mean: round_to(center, 3), standard_deviation: spread.map(|spread| round_to(spread, 3)), days: None, - nights: Some(values.len()), + nights: Some(values.len() as u64), from: time::format_utc_millis(window_from), to: time::format_utc_millis(start), }, - compared_records: values.len(), + compared_records: values.len() as u64, time_zone: None, })) } @@ -598,7 +611,7 @@ pub(super) fn drop_after_effort_end(context: &mut Context<'_>, settings: &Recove later_bpm: round_to(later_bpm, 1), end_offset_ms: end_offset, later_offset_ms: later_offset, - anchor, + anchor: anchor.to_string(), })) } @@ -680,12 +693,12 @@ pub(super) fn sleep_regularity_index( let share = agreements as f64 / (day_pairs as f64 * 1440.0); Some(OneRecordResult::SleepRegularity(RegularityResult { index: round_to(-100.0 + 200.0 * share, 1), - day_pairs, - days_observed, + day_pairs: day_pairs as u64, + days_observed: days_observed as u64, window_days, window_from: time::format_utc_millis(window_from), window_to: time::format_utc_millis(window_to), - sessions, + sessions: sessions as u64, })) } @@ -758,11 +771,11 @@ pub(super) fn volume_load(context: &mut Context<'_>, field: &str) -> Option, field: &str) -> Optio } context.exclusions.push("a stage named awake is counted apart from asleep minutes".into()); Some(OneRecordResult::StageSplit(StageSplitResult { - stages: named, + stages: named.into(), asleep_minutes: asleep, awake_minutes: awake, total_minutes: asleep + awake, - percent_of_asleep: shares, + percent_of_asleep: shares.into(), })) } @@ -1160,7 +1173,7 @@ pub(super) fn sleep_clock_times( local_midpoint: local(midpoint), local_end: local(end), time_zone: zone_name, - time_zone_basis: basis, + time_zone_basis: basis.to_string(), duration_hours: round_to((end - start) as f64 / 3_600_000.0, 2), })) } diff --git a/core/src/calculate/mod.rs b/core/src/calculate/mod.rs index 333daeeb..6e210a1e 100644 --- a/core/src/calculate/mod.rs +++ b/core/src/calculate/mod.rs @@ -123,7 +123,7 @@ pub fn apply_with( missing, result, inputs: (!run.evidence.is_empty()).then(|| range::ReceiptInput { - record_count: run.evidence.len(), + record_count: run.evidence.len() as u64, record_references: run.evidence.iter().take(MAX_RECEIPT_REFERENCES).cloned().collect(), references_truncated: run.evidence.len() > MAX_RECEIPT_REFERENCES, }), diff --git a/core/src/calculate/range.rs b/core/src/calculate/range.rs index f0b85146..a01bf09d 100644 --- a/core/src/calculate/range.rs +++ b/core/src/calculate/range.rs @@ -40,8 +40,9 @@ pub const MAX_RECEIPT_REFERENCES: usize = 1_000; macro_rules! named_enum { ($(#[$meta:meta])* pub enum $name:ident { $($variant:ident = $text:literal),* $(,)? }) => { - $(#[$meta])* #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] + $(#[$meta])* pub enum $name { $($variant),* } impl $name { @@ -71,6 +72,7 @@ macro_rules! named_enum { named_enum! { /// A named range calculation. + #[cfg_attr(feature = "uniffi", uniffi(name = "CalculationOperation"))] pub enum Operation { Summary = "summary", Baseline = "baseline", @@ -85,6 +87,7 @@ named_enum! { named_enum! { /// Which typed rows a calculation reads. + #[cfg_attr(feature = "uniffi", uniffi(name = "CalculationRecordKind"))] pub enum RecordKind { Measurement = "measurement", ProviderScore = "provider-score", @@ -95,6 +98,7 @@ named_enum! { named_enum! { /// Calendar grouping for summary and baseline. + #[cfg_attr(feature = "uniffi", uniffi(name = "CalculationGroup"))] pub enum Group { None = "none", Day = "day", @@ -105,19 +109,29 @@ named_enum! { /// A range calculation request. #[derive(Debug, Clone, PartialEq)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] +#[cfg_attr(feature = "uniffi", uniffi(name = "RangeRequest"))] pub struct CalculateOptions { pub operation: Operation, /// A measurement quantity, provider metric, or summary type. pub quantity: String, pub record_kind: RecordKind, + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub provider_period_type: Option, + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub source_id: Option, + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub compare_source_id: Option, + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub other_quantity: Option, + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub workout_session_id: Option, /// A calendar day (`YYYY-MM-DD`) or an exact UTC instant. + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub from: Option, + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub to: Option, + #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub time_zone: Option, pub group: Group, } @@ -143,6 +157,7 @@ impl CalculateOptions { /// The window a receipt reports. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReceiptRange { #[serde(skip_serializing_if = "Option::is_none")] pub from: Option, @@ -154,8 +169,9 @@ pub struct ReceiptRange { /// The records a calculation used. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReceiptInput { - pub record_count: usize, + pub record_count: u64, /// The exact record revisions used, in input order, at most 1,000. pub record_references: Vec, /// True when `record_references` was shortened to the receipt limit. @@ -165,8 +181,9 @@ pub struct ReceiptInput { /// Count, minimum, maximum, mean, sum, and population standard deviation. /// The mean, sum, and deviation are rounded to four decimal places. #[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct NumericSummary { - pub count: usize, + pub count: u64, pub minimum: f64, pub maximum: f64, pub mean: f64, @@ -175,6 +192,7 @@ pub struct NumericSummary { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct GroupSummary { pub period: String, #[serde(flatten)] @@ -184,14 +202,16 @@ pub struct GroupSummary { /// A baseline of calendar-day means, so a source that reads many times a day /// does not outweigh one that reads once (D244). #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct DailySummary { pub time_zone: String, - pub days: usize, + pub days: u64, pub mean: f64, pub standard_deviation: f64, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum SourceSummary { Whole { @@ -208,9 +228,10 @@ pub enum SourceSummary { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SourceTrend { pub source_id: String, - pub count: usize, + pub count: u64, pub slope_per_day: f64, pub first_value: f64, pub last_value: f64, @@ -222,18 +243,20 @@ pub struct SourceTrend { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SourceCoverage { pub source_id: String, pub first_date: Option, pub last_date: Option, - pub days_expected: usize, - pub days_present: usize, + pub days_expected: u64, + pub days_present: u64, pub missing_dates: Vec, /// `days_present / days_expected`. pub coverage_ratio: f64, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct NamedSummary { pub source_id: String, #[serde(flatten)] @@ -241,6 +264,7 @@ pub struct NamedSummary { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CompareSourcesResult { pub source: NamedSummary, pub comparison_source: NamedSummary, @@ -252,17 +276,19 @@ pub struct CompareSourcesResult { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PairedComparison { pub time_zone: String, - pub days: usize, + pub days: u64, /// Null when no day has both sources. pub mean_difference: Option, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CorrelationResult { pub other_quantity: String, - pub paired_day_count: usize, + pub paired_day_count: u64, /// Null when fewer than three days pair or a side does not vary. pub correlation: Option, pub paired_dates: Vec, @@ -272,6 +298,7 @@ pub struct CorrelationResult { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum SourceDrift { Available { @@ -281,31 +308,34 @@ pub enum SourceDrift { second_half_mean: f64, change: f64, change_percentage: f64, - first_half_count: usize, - second_half_count: usize, + first_half_count: u64, + second_half_count: u64, }, Unavailable { source_id: String, available: bool, - reason: &'static str, + reason: String, }, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct WorkoutDriftResult { pub workout_session_id: String, pub sources: Vec, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PeriodSummary { /// The provider period exactly as stored. - pub provider_period: Value, + pub provider_period: crate::json::JsonValue, #[serde(flatten)] pub summary: NumericSummary, } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SourcePeriods { pub source_id: String, pub periods: Vec, @@ -313,6 +343,7 @@ pub struct SourcePeriods { /// The operation-specific part of a receipt. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum CalculationResult { Summaries(Vec), @@ -326,8 +357,9 @@ pub enum CalculationResult { /// The `ath calculate --json` receipt. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CalculationReceipt { - pub calculation_version: &'static str, + pub calculation_version: String, pub operation: Operation, pub record_kind: RecordKind, pub method: String, @@ -592,7 +624,11 @@ fn workout_drift(reader: &R, request: &Request<'_>) -> Res .map(|input| input.value) .collect(); if first.is_empty() || second.is_empty() { - return SourceDrift::Unavailable { source_id, available: false, reason: "one half has no samples" }; + return SourceDrift::Unavailable { + source_id, + available: false, + reason: ("one half has no samples").to_string(), + }; } let first_mean = summarize(&first).mean; let second_mean = summarize(&second).mean; @@ -603,8 +639,8 @@ fn workout_drift(reader: &R, request: &Request<'_>) -> Res second_half_mean: second_mean, change: round4(second_mean - first_mean), change_percentage: round4(((second_mean - first_mean) / first_mean) * 100.0), - first_half_count: first.len(), - second_half_count: second.len(), + first_half_count: first.len() as u64, + second_half_count: second.len() as u64, } }) .collect(); @@ -644,8 +680,8 @@ fn coverage(request: &Request<'_>, unit: String, inputs: &[Input]) -> Result( left_days.iter().filter_map(|(date, value)| right_days.get(date).map(|other| value - other)).collect(); Some(PairedComparison { time_zone: zone, - days: differences.len(), + days: differences.len() as u64, mean_difference: (!differences.is_empty()) .then(|| round4(differences.iter().sum::() / differences.len() as f64)), }) @@ -750,7 +786,7 @@ fn correlate( "Pearson correlation of same-calendar-day means".into(), CalculationResult::Correlation(CorrelationResult { other_quantity, - paired_day_count: dates.len(), + paired_day_count: dates.len() as u64, correlation, paired_dates: dates, reason, @@ -820,7 +856,7 @@ fn summarize(values: &[f64]) -> NumericSummary { let mean = sum / count; let variance = values.iter().map(|value| (value - mean).powi(2)).sum::() / count; NumericSummary { - count: values.len(), + count: values.len() as u64, minimum: values.iter().copied().fold(f64::INFINITY, f64::min), maximum: values.iter().copied().fold(f64::NEG_INFINITY, f64::max), mean: round4(mean), @@ -853,7 +889,7 @@ fn trend(source_id: String, inputs: &[&Input]) -> Result { }); Ok(SourceTrend { source_id, - count: points.len(), + count: points.len() as u64, slope_per_day: round4(slope), first_value: inputs[0].value, last_value: inputs[inputs.len() - 1].value, @@ -893,7 +929,10 @@ fn period_summaries(inputs: &[Input]) -> Vec { source_id, periods: periods .into_iter() - .map(|(_, period, values)| PeriodSummary { provider_period: period, summary: summarize(&values) }) + .map(|(_, period, values)| PeriodSummary { + provider_period: period.into(), + summary: summarize(&values), + }) .collect(), } }) @@ -949,7 +988,7 @@ fn daily_summary(inputs: &[&Input], zone: &str) -> Result { let summary = summarize(&means); Ok(DailySummary { time_zone: zone.to_string(), - days: means.len(), + days: means.len() as u64, mean: summary.mean, standard_deviation: summary.standard_deviation, }) @@ -1005,7 +1044,7 @@ fn receipt( .map(|input| EvidenceReference { record_id: input.record_id.clone(), revision: input.revision }) .collect(); CalculationReceipt { - calculation_version: CALCULATION_VERSION, + calculation_version: CALCULATION_VERSION.to_string(), operation: request.options.operation, record_kind: request.options.record_kind, method, @@ -1014,7 +1053,7 @@ fn receipt( range, sources, input: ReceiptInput { - record_count: inputs.len(), + record_count: inputs.len() as u64, record_references, references_truncated: inputs.len() > MAX_RECEIPT_REFERENCES, }, diff --git a/core/src/calculate/record.rs b/core/src/calculate/record.rs index b938fe54..dc71d2ba 100644 --- a/core/src/calculate/record.rs +++ b/core/src/calculate/record.rs @@ -33,6 +33,7 @@ pub struct StoredRecord { /// One field a calculation looked for. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct FieldRead { pub field: String, pub present: bool, @@ -43,6 +44,7 @@ pub struct FieldRead { /// The value a one-record calculation produced. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum OneRecordResult { Zones { seconds: Vec }, @@ -51,11 +53,11 @@ pub enum OneRecordResult { Value { value: f64 }, Efficiency { efficiency: f64 }, Timing { start_at: String, midpoint_at: Option }, - Stages { stages: Map, total_minutes: f64 }, - Regularity { nights: usize, regularity: f64 }, + Stages { stages: crate::json::JsonObject, total_minutes: f64 }, + Regularity { nights: u64, regularity: f64 }, Volume { volume: f64, weight_unit: Option }, - QuantityChange { quantity: String, change: f64, compared_records: usize }, - Change { change: f64, compared_records: usize }, + QuantityChange { quantity: String, change: f64, compared_records: u64 }, + Change { change: f64, compared_records: u64 }, WindowChange(methods::WindowChangeResult), Recovery(methods::RecoveryResult), SleepRegularity(methods::RegularityResult), @@ -79,6 +81,7 @@ pub enum OneRecordResult { /// The `ath apply --json` object. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ApplyResult { pub calculation: String, /// The operation the file named (`use:`), which carries the method (D230). @@ -370,7 +373,7 @@ pub fn run(file: &CalculationFile, record: &StoredRecord, extra: &MethodInputs) } }; let inputs = (!context.inputs.is_empty()).then(|| ReceiptInput { - record_count: context.inputs.len(), + record_count: context.inputs.len() as u64, record_references: context.inputs.iter().take(MAX_RECEIPT_REFERENCES).cloned().collect(), references_truncated: context.inputs.len() > MAX_RECEIPT_REFERENCES, }); @@ -630,7 +633,7 @@ impl<'a> Context<'a> { total += minutes; } } - Some(OneRecordResult::Stages { stages: named, total_minutes: total }) + Some(OneRecordResult::Stages { stages: named.into(), total_minutes: total }) } fn regularity( @@ -651,7 +654,7 @@ impl<'a> Context<'a> { let agreements: Vec = nights.windows(2).map(|pair| night_agreement(&pair[0].data, &pair[1].data)).collect(); let mean = agreements.iter().sum::() / agreements.len() as f64; - Some(OneRecordResult::Regularity { nights: nights.len(), regularity: round3(mean) }) + Some(OneRecordResult::Regularity { nights: nights.len() as u64, regularity: round3(mean) }) } fn volume(&mut self, field: &str) -> Option { @@ -714,7 +717,7 @@ impl<'a> Context<'a> { Some(OneRecordResult::QuantityChange { quantity: quantity.to_string(), change: round3(value - mean), - compared_records: earlier.len(), + compared_records: earlier.len() as u64, }) } @@ -738,7 +741,7 @@ impl<'a> Context<'a> { return None; } let mean = earlier.iter().sum::() / earlier.len() as f64; - Some(OneRecordResult::Change { change: value - mean, compared_records: earlier.len() }) + Some(OneRecordResult::Change { change: value - mean, compared_records: earlier.len() as u64 }) } } diff --git a/core/src/calculate/recorded.rs b/core/src/calculate/recorded.rs index d4407a83..cc0b683e 100644 --- a/core/src/calculate/recorded.rs +++ b/core/src/calculate/recorded.rs @@ -92,6 +92,7 @@ pub struct Grid { /// The best mean over one duration. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct Effort { pub duration_s: u64, pub mean: f64, @@ -157,6 +158,7 @@ pub struct WindowWorkout { /// The best mean over each duration across recordings, with the recording /// and workout each came from. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct WindowEffort { #[serde(flatten)] pub effort: Effort, diff --git a/core/src/calculate/window.rs b/core/src/calculate/window.rs index 66373a04..6cb9f783 100644 --- a/core/src/calculate/window.rs +++ b/core/src/calculate/window.rs @@ -13,12 +13,12 @@ use serde::Serialize; use super::record::StoredRecord; use super::recorded::WindowEffort; -use crate::json::Value; use crate::model::EvidenceReference; use crate::thresholds::{self as t, EffortLabels}; /// An intensity reference a person may save from the outcome. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceToSave { pub quantity: String, pub value: f64, @@ -40,17 +40,124 @@ pub struct ReferenceToSave { pub only_when_asked: bool, } +/// A threshold method's own result, one variant for each kind of method. It is +/// written as the method's result object alone, as before. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(untagged)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] +pub enum ThresholdResult { + CriticalPower(t::CriticalPowerResult), + CriticalPowerThreeParameter(t::CriticalPowerThreeParameterResult), + CriticalSpeed(t::CriticalSpeedResult), + CriticalSpeedThreeParameter(t::CriticalSpeedThreeParameterResult), + FractionOf20Minute(t::FractionOf20MinuteResult), + FractionOf8Minute(t::FractionOf8MinuteResult), + ThreeMinuteCycling(t::ThreeMinuteCyclingResult), + ThreeMinuteRowing(t::ThreeMinuteRowingResult), + ThreeMinuteRunning(t::ThreeMinuteRunningResult), + CriticalSwimSpeed(t::CriticalSwimSpeedResult), + ThirtyMinuteTimeTrial(t::ThirtyMinuteTimeTrialResult), + PeakPower(t::PeakPowerResult), + AgeFormula(t::AgeFormulaResult), + HeldHeartRate(t::HeldHeartRateResult), +} + +impl From for ThresholdResult { + fn from(result: t::CriticalPowerResult) -> Self { + ThresholdResult::CriticalPower(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::CriticalPowerThreeParameterResult) -> Self { + ThresholdResult::CriticalPowerThreeParameter(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::CriticalSpeedResult) -> Self { + ThresholdResult::CriticalSpeed(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::CriticalSpeedThreeParameterResult) -> Self { + ThresholdResult::CriticalSpeedThreeParameter(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::FractionOf20MinuteResult) -> Self { + ThresholdResult::FractionOf20Minute(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::FractionOf8MinuteResult) -> Self { + ThresholdResult::FractionOf8Minute(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::ThreeMinuteCyclingResult) -> Self { + ThresholdResult::ThreeMinuteCycling(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::ThreeMinuteRowingResult) -> Self { + ThresholdResult::ThreeMinuteRowing(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::ThreeMinuteRunningResult) -> Self { + ThresholdResult::ThreeMinuteRunning(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::CriticalSwimSpeedResult) -> Self { + ThresholdResult::CriticalSwimSpeed(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::ThirtyMinuteTimeTrialResult) -> Self { + ThresholdResult::ThirtyMinuteTimeTrial(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::PeakPowerResult) -> Self { + ThresholdResult::PeakPower(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::AgeFormulaResult) -> Self { + ThresholdResult::AgeFormula(result) + } +} + +impl From for ThresholdResult { + fn from(result: t::HeldHeartRateResult) -> Self { + ThresholdResult::HeldHeartRate(result) + } +} + /// What a threshold method found. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThresholdOutcome { pub operation: String, - pub parameters: BTreeMap, + pub parameters: crate::json::JsonObject, #[serde(skip_serializing_if = "Option::is_none")] pub period_start: Option, #[serde(skip_serializing_if = "Option::is_none")] pub period_end: Option, /// The method's own result, with the names and units of its study. - pub result: Value, + pub result: ThresholdResult, #[serde(skip_serializing_if = "Vec::is_empty")] pub efforts: Vec, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/core/src/calculate/workout_ops.rs b/core/src/calculate/workout_ops.rs index 1cbf3c6e..d9d8de9c 100644 --- a/core/src/calculate/workout_ops.rs +++ b/core/src/calculate/workout_ops.rs @@ -32,6 +32,7 @@ pub const DEFAULT_EFFORT_DURATIONS_S: [u64; 5] = [5, 60, 300, 1200, 3600]; /// An intensity reference used by a calculation, as the result names it. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceUsed { pub record_id: String, pub revision: u64, @@ -64,6 +65,7 @@ impl ReferenceUsed { /// One best effort. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortFound { pub quantity: String, pub duration_s: u64, @@ -75,6 +77,7 @@ pub struct EffortFound { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BestEffortsResult { pub max_gap_s: u64, pub efforts: Vec, @@ -127,6 +130,7 @@ pub fn best_mean_efforts( // ---- time_in_power_zones ---------------------------------------------------------------------- #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PowerZonesResult { pub seconds: Vec, pub uncovered_seconds: f64, @@ -188,6 +192,7 @@ fn workout_span_ms(workout: &Value) -> Option { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceZonesResult { pub seconds: Vec, pub uncovered_seconds: f64, @@ -228,6 +233,7 @@ pub fn time_in_zones_from_reference( /// The resting heart rate a load used: the latest measured value on or /// before the workout's day. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RestingUsed { pub record_id: String, pub revision: u64, @@ -236,6 +242,7 @@ pub struct RestingUsed { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceTrimpResult { pub load: f64, pub weighting: String, @@ -294,6 +301,7 @@ pub fn banister_trimp( // ---- work_capacity_balance_exponential -------------------------------------------------------- #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BalanceResult { pub threshold: ReferenceUsed, pub capacity: ReferenceUsed, @@ -363,6 +371,7 @@ pub fn work_capacity_balance( /// One target compared with the lap. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct TargetCompared { pub quantity: String, pub low: f64, @@ -378,6 +387,7 @@ pub struct TargetCompared { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BlockCompared { pub block: String, pub lap: Option, @@ -389,13 +399,14 @@ pub struct BlockCompared { } #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PlanAgainstResult { pub workout_id: String, pub blocks: Vec, - pub laps_without_block: usize, - pub targets_met: usize, - pub targets_missed: usize, - pub targets_not_measured: usize, + pub laps_without_block: u64, + pub targets_met: u64, + pub targets_missed: u64, + pub targets_not_measured: u64, } /// A percent target worked out: its low, high, unit, and the reference used. @@ -516,7 +527,7 @@ pub fn plan_against_laps( PlanAgainstResult { workout_id: workout_id.to_string(), blocks, - laps_without_block: laps.len().saturating_sub(steps.len()), + laps_without_block: laps.len().saturating_sub(steps.len()) as u64, targets_met: met, targets_missed: missed, targets_not_measured: not_measured, diff --git a/core/src/json.rs b/core/src/json.rs index f95500a6..372fd8e4 100644 --- a/core/src/json.rs +++ b/core/src/json.rs @@ -398,3 +398,21 @@ mod tests { assert!(parse(r#""\ud800""#).is_err()); } } + +// The Swift and Kotlin bindings carry both wrappers as JSON text, written and +// read by this module's own JSON code. +#[cfg(feature = "uniffi")] +uniffi::custom_type!(JsonObject, String, { + lower: |object| to_string(&Value::Object(object.0)), + try_lift: |text| match parse(&text) { + Ok(Value::Object(map)) => Ok(JsonObject(map)), + Ok(_) => Err(uniffi::deps::anyhow::anyhow!("a JSON object was expected")), + Err(error) => Err(uniffi::deps::anyhow::anyhow!(error.message)), + }, +}); + +#[cfg(feature = "uniffi")] +uniffi::custom_type!(JsonValue, String, { + lower: |value| to_string(&value.0), + try_lift: |text| parse(&text).map(JsonValue).map_err(|error| uniffi::deps::anyhow::anyhow!(error.message)), +}); diff --git a/core/src/lib.rs b/core/src/lib.rs index 1baa41cd..88b85a46 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -27,3 +27,6 @@ pub mod save; pub mod thresholds; pub use error::{Error, Result}; + +#[cfg(feature = "uniffi")] +uniffi::setup_scaffolding!("athleticstandard_core"); diff --git a/core/src/model/common.rs b/core/src/model/common.rs index 89105a1b..81d02f97 100644 --- a/core/src/model/common.rs +++ b/core/src/model/common.rs @@ -384,6 +384,7 @@ model_object! { /// Who made a change. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(tag = "author_type", rename_all = "snake_case")] pub enum RecordActor { Athlete, @@ -422,6 +423,7 @@ impl RecordActor { /// The author of an authored record. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(tag = "author_type", rename_all = "snake_case")] pub enum AuthoredRecordAuthor { Athlete, diff --git a/core/src/model/record.rs b/core/src/model/record.rs index 51820d44..d54a9c00 100644 --- a/core/src/model/record.rs +++ b/core/src/model/record.rs @@ -22,6 +22,7 @@ macro_rules! record_types { /// at a time, so boxing it would add a heap allocation to every read /// and change every match for no measured gain. #[derive(Debug, Clone, PartialEq)] + #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[allow(clippy::large_enum_variant)] pub enum RecordData { $($variant($data)),* @@ -282,6 +283,7 @@ pub type Extensions = crate::json::JsonObject; /// The current state of a record. #[derive(Debug, Clone, PartialEq)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CurrentRecord { pub record_id: String, pub created_at: String, @@ -341,6 +343,7 @@ impl CurrentRecord { /// One retained revision of a record. #[derive(Debug, Clone, PartialEq)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RecordRevision { pub record_id: String, pub revision: u64, diff --git a/core/src/model/schema.rs b/core/src/model/schema.rs index ee317ef7..a4befda3 100644 --- a/core/src/model/schema.rs +++ b/core/src/model/schema.rs @@ -852,7 +852,7 @@ macro_rules! model_object { $(#[$field_meta:meta])* $field:ident ? : $ty:ty = $schema:expr $(, $($rest:tt)*)? ) => { $crate::model_object!(@munch $meta $name $refine $description - [$($fields)* $(#[$field_meta])* #[serde(default, skip_serializing_if = "Option::is_none")] pub $field: Option<$ty>,] + [$($fields)* $(#[$field_meta])* #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub $field: Option<$ty>,] [$($shape)* $crate::model::schema::Field { name: stringify!($field), schema: $schema, optional: true },] $($($rest)*)? ); @@ -862,7 +862,7 @@ macro_rules! model_object { $(#[$field_meta:meta])* $field:ident ? : $ty:ty $(, $($rest:tt)*)? ) => { $crate::model_object!(@munch $meta $name $refine $description - [$($fields)* $(#[$field_meta])* #[serde(default, skip_serializing_if = "Option::is_none")] pub $field: Option<$ty>,] + [$($fields)* $(#[$field_meta])* #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub $field: Option<$ty>,] [$($shape)* $crate::model::schema::Field { name: stringify!($field), schema: <$ty as $crate::model::schema::Shape>::schema(), optional: true },] $($($rest)*)? ); @@ -889,8 +889,9 @@ macro_rules! model_object { }; (@munch [$($meta:tt)*] $name:ident [$($refine:path),*] [$($description:expr)?] [$($fields:tt)*] [$($shape:tt)*]) => { - $($meta)* #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] + #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] + $($meta)* #[serde(deny_unknown_fields)] pub struct $name { $($fields)* } @@ -920,6 +921,7 @@ macro_rules! model_enum { ) => { $(#[$meta])* #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] + #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] pub enum $name { $($(#[$variant_meta])* #[serde(rename = $text)] $variant),* } diff --git a/core/src/model/training.rs b/core/src/model/training.rs index d21029a7..431989f6 100644 --- a/core/src/model/training.rs +++ b/core/src/model/training.rs @@ -68,6 +68,7 @@ fn percent() -> SchemaRef { model_object! { /// The surroundings (D296): altitude, temperature, humidity, and whether /// it was indoors. It says nothing about the athlete. + #[cfg_attr(feature = "uniffi", uniffi(name = "TrainingEnvironment"))] pub struct Environment { altitude_m?: f64, temperature_c?: f64, diff --git a/core/src/thresholds.rs b/core/src/thresholds.rs index 2327c5a7..c599fe6b 100644 --- a/core/src/thresholds.rs +++ b/core/src/thresholds.rs @@ -298,6 +298,7 @@ pub fn check_sport_machine(operation: &str, sport: &str, machine: &str) -> Resul /// One best effort: the duration in seconds and the best mean power (W) or /// mean speed (m/s) over it. #[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BestEffort { pub duration_s: f64, pub mean: f64, @@ -306,6 +307,7 @@ pub struct BestEffort { /// Where one best effort came from, for the labels in main study 5.1. /// `start_ms` and `end_ms` are instants; the range is `[start_ms, end_ms)`. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortOrigin { pub workout: String, pub source: String, @@ -315,10 +317,11 @@ pub struct EffortOrigin { /// The labels every fitted method reports (main study 5.1). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortLabels { - pub rides_used: usize, - pub overlapping_efforts: usize, - pub sources_used: usize, + pub rides_used: u64, + pub overlapping_efforts: u64, + pub sources_used: u64, } /// Counts the distinct workouts, the effort pairs whose time ranges overlap, @@ -338,7 +341,7 @@ pub fn effort_labels(origins: &[EffortOrigin]) -> EffortLabels { } } } - EffortLabels { rides_used: workouts.len(), overlapping_efforts, sources_used: sources.len() } + EffortLabels { rides_used: workouts.len() as u64, overlapping_efforts, sources_used: sources.len() as u64 } } #[derive(Clone, Copy)] @@ -871,8 +874,9 @@ fn three_parameter( /// supplement 4.1 and 4.2). The nonlinear form adds `iterations`, /// `sum_of_squares` (s²), and its starting values. #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CriticalPowerResult { - pub operation: &'static str, + pub operation: String, /// W. pub threshold_power: f64, /// kJ. @@ -904,7 +908,7 @@ fn power_result(operation: &'static str, fit: TwoParameterFit, efforts: Vec Result Result Result<(), /// The result of `three_minute_all_out_cycling_test` (supplement 6.2). #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThreeMinuteCyclingResult { - pub operation: &'static str, + pub operation: String, /// W. pub threshold_power: f64, /// kJ. @@ -1351,8 +1361,9 @@ pub struct ThreeMinuteCyclingResult { /// The result of `three_minute_all_out_rowing_test` (supplement 6.3). #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThreeMinuteRowingResult { - pub operation: &'static str, + pub operation: String, /// W. pub threshold_power: f64, /// kJ. Stays in the calculation result only. @@ -1422,7 +1433,7 @@ pub fn three_minute_all_out_cycling_test( check_resistance_mode(resistance_mode)?; let test = power_test(operation, power, interval_ms)?; Ok(ThreeMinuteCyclingResult { - operation, + operation: operation.to_string(), threshold_power: round4(test.threshold), work_capacity_above_threshold: round4(test.work_above / 1000.0), mean_power_first_150_s: round4(test.mean_150), @@ -1442,7 +1453,7 @@ pub fn three_minute_all_out_rowing_test( let operation = THREE_MINUTE_ALL_OUT_ROWING_TEST; let test = power_test(operation, power, interval_ms)?; Ok(ThreeMinuteRowingResult { - operation, + operation: operation.to_string(), threshold_power: round4(test.threshold), work_above_end_test_power: round4(test.work_above / 1000.0), mean_power_first_150_s: round4(test.mean_150), @@ -1455,8 +1466,9 @@ pub fn three_minute_all_out_rowing_test( /// The result of `three_minute_all_out_running_test` (supplement 6.4). #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThreeMinuteRunningResult { - pub operation: &'static str, + pub operation: String, /// m/s. pub threshold_speed: f64, /// m. @@ -1505,7 +1517,7 @@ pub fn three_minute_all_out_running_test( } } Ok(ThreeMinuteRunningResult { - operation, + operation: operation.to_string(), threshold_speed: round4(threshold), distance_above_threshold: round4(capacity), mean_speed_first_150_s: round4(mean_150), @@ -1530,8 +1542,9 @@ pub struct Swim { /// The result of `critical_swim_speed_400_and_200_m` (supplement 8.1). #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CriticalSwimSpeedResult { - pub operation: &'static str, + pub operation: String, /// m/s. pub threshold_speed: f64, /// m. Stays in the calculation result only. @@ -1574,7 +1587,7 @@ pub fn critical_swim_speed_400_and_200_m( let threshold = (400.0 - 200.0) / (t400 - t200); let capacity = 400.0 - threshold * t400; Ok(CriticalSwimSpeedResult { - operation, + operation: operation.to_string(), threshold_speed: round4(threshold), distance_above_threshold: round4(capacity), time_400_m: round4(t400), @@ -1584,8 +1597,9 @@ pub fn critical_swim_speed_400_and_200_m( /// The result of `thirty_minute_running_time_trial` (supplement 8.2). #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThirtyMinuteTimeTrialResult { - pub operation: &'static str, + pub operation: String, /// m/s. pub threshold_speed: f64, /// bpm. @@ -1621,7 +1635,7 @@ pub fn thirty_minute_running_time_trial( let last_20 = covered_integral(&sorted, heart_rate_interval_ms, 600_000, 1_800_000).ok_or_else(gap)?; let covered = series.reading_at(1_800_000) - series.reading_at(0); Ok(ThirtyMinuteTimeTrialResult { - operation, + operation: operation.to_string(), threshold_speed: round4(covered / 1800.0), threshold_heart_rate: round4(whole / 1800.0), distance_30_min: round4(covered), @@ -1634,6 +1648,29 @@ pub fn thirty_minute_running_time_trial( // Peak power // --------------------------------------------------------------------------- +/// One reading in a result: milliseconds from the recording's start, and the +/// value. It is written as a two-item list, `[offset_ms, value]`, as the +/// published results have always been. +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[serde(into = "(i64, f64)")] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] +pub struct TimedReading { + pub offset_ms: i64, + pub value: f64, +} + +impl From for (i64, f64) { + fn from(reading: TimedReading) -> Self { + (reading.offset_ms, reading.value) + } +} + +impl From<(i64, f64)> for TimedReading { + fn from((offset_ms, value): (i64, f64)) -> Self { + TimedReading { offset_ms, value } + } +} + /// One power recording in the window: `(offset_ms, watts)` and its interval. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct PowerRecording { @@ -1643,17 +1680,18 @@ pub struct PowerRecording { /// The result of `best_1_second_power` or `best_5_second_power` (supplement 9.1). #[derive(Debug, Clone, PartialEq, Serialize)] +#[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PeakPowerResult { - pub operation: &'static str, + pub operation: String, /// W. pub peak_power: f64, /// The index of the recording in the input list. - pub recording_index: usize, + pub recording_index: u64, /// The effort's range `[start_offset_ms, end_offset_ms)`. pub start_offset_ms: i64, pub end_offset_ms: i64, /// The readings from 5 s before the effort to 5 s after it. - pub readings_around_best: Vec<(i64, f64)>, + pub readings_around_best: Vec, } fn best_power( @@ -1690,11 +1728,12 @@ fn best_power( .iter() .copied() .filter(|reading| reading.0 >= start - 5000 && reading.0 < end + 5000) + .map(TimedReading::from) .collect(); Ok(PeakPowerResult { - operation, + operation: operation.to_string(), peak_power: round4(peak), - recording_index: index, + recording_index: index as u64, start_offset_ms: start, end_offset_ms: end, readings_around_best, @@ -1717,8 +1756,9 @@ pub fn best_5_second_power(recordings: &[PowerRecording]) -> Result, pub lower_bound: bool, pub found_in: Option, pub highest_single_reading_bpm: Option, - pub workouts_read: usize, - pub workouts_with_runs: usize, + pub workouts_read: u64, + pub workouts_with_runs: u64, pub excluded: Vec, #[serde(skip_serializing_if = "Vec::is_empty")] - pub missing: Vec<&'static str>, - #[serde(serialize_with = "serialize_date")] - pub period_start: NaiveDate, - #[serde(serialize_with = "serialize_date")] - pub period_end: NaiveDate, + pub missing: Vec, + /// The first and last day of the window, `YYYY-MM-DD`. + pub period_start: String, + pub period_end: String, } const HOLD_MS: i64 = 5000; @@ -1905,7 +1947,7 @@ pub fn highest_heart_rate_held_5_s( workout: recording.workout.clone(), time_s: start as f64 / 1000.0, value_bpm: held, - reason: "matches_step_rate", + reason: "matches_step_rate".to_string(), }); continue; } @@ -1940,17 +1982,17 @@ pub fn highest_heart_rate_held_5_s( None => (None, None), }; HeldHeartRateResult { - operation: HIGHEST_HEART_RATE_HELD_5_S, + operation: HIGHEST_HEART_RATE_HELD_5_S.to_string(), lower_bound: maximum.is_some(), - missing: if maximum.is_none() { vec!["held_heart_rate_readings"] } else { Vec::new() }, + missing: if maximum.is_none() { vec!["held_heart_rate_readings".to_string()] } else { Vec::new() }, maximum_heart_rate_bpm: maximum, found_in, highest_single_reading_bpm: highest_single, - workouts_read: workouts_read.len(), - workouts_with_runs: workouts_with_runs.len(), + workouts_read: workouts_read.len() as u64, + workouts_with_runs: workouts_with_runs.len() as u64, excluded, - period_start, - period_end: date, + period_start: period_start.format("%Y-%m-%d").to_string(), + period_end: date.format("%Y-%m-%d").to_string(), } } @@ -2372,8 +2414,8 @@ mod tests { let five = best_5_second_power(&recordings).unwrap(); assert_eq!(five.peak_power, 1154.0); assert_eq!((five.start_offset_ms, five.end_offset_ms), (3000, 8000)); - assert_eq!(five.readings_around_best.first(), Some(&(0, 300.0))); - assert_eq!(five.readings_around_best.last(), Some(&(11_000, 300.0))); + assert_eq!(five.readings_around_best.first(), Some(&TimedReading::from((0, 300.0)))); + assert_eq!(five.readings_around_best.last(), Some(&TimedReading::from((11_000, 300.0)))); } #[test] @@ -2464,11 +2506,11 @@ mod tests { workout: "workout-3".to_string(), time_s: 0.0, value_bpm: 188.0, - reason: "matches_step_rate", + reason: "matches_step_rate".to_string(), }] ); - assert_eq!(result.period_start, date("2025-11-27")); - assert_eq!(result.period_end, date("2026-11-27")); + assert_eq!(result.period_start, "2025-11-27"); + assert_eq!(result.period_end, "2026-11-27"); assert!(result.missing.is_empty()); } diff --git a/core/uniffi.toml b/core/uniffi.toml new file mode 100644 index 00000000..3ddcb52a --- /dev/null +++ b/core/uniffi.toml @@ -0,0 +1,29 @@ +# Settings for the Swift and Kotlin types generated from the core's record and +# result types (D329). They are used only when the phone library is built. + +[bindings.swift] +# Swift: the core's types compile into the same `AthleticStandard` module as +# the phone library. This name only sets the generated file's name, +# AthleticStandardCore.swift. Both generated files share one C module. +module_name = "AthleticStandardCore" +ffi_module_name = "AthleticStandardFFI" +ffi_module_filename = "AthleticStandardCoreFFI" +# Swift records keep `var` fields, so app code can change one field of a copy. +# Kotlin records are read-only; change a field with `copy(...)`. +# Lists of allowed values list their cases, for pickers. +generate_case_iterable_conformance = true + +# `none` would read as Swift's own `Optional.none`. +[bindings.swift.rename] +"CalculationGroup.None" = "ungrouped" + +[bindings.kotlin] +# Kotlin: each generated file declares its own copy of UniFFI's helper types, +# so the core's types need their own package. +package_name = "ai.athleticstandard.core" +cdylib_name = "athleticstandard_mobile" +android = true +generate_immutable_records = true + +[bindings.kotlin.rename] +"CalculationGroup.None" = "Ungrouped" diff --git a/host/Cargo.toml b/host/Cargo.toml index a3073ffd..35712e5e 100644 --- a/host/Cargo.toml +++ b/host/Cargo.toml @@ -36,3 +36,9 @@ zip = "2.2" jsonwebtoken = { version = "12.0.0", features = ["rust_crypto"] } rusqlite = { version = "0.42", features = ["bundled"] } ureq = { version = "2.12", features = ["json"] } + +[lints.rust] +# The core's model macros mark a type for the phone bindings only when the core +# itself is built with its `uniffi` feature. Here the condition is checked in +# this crate, which has no such feature, so the host's types are never marked. +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(feature, values("uniffi"))'] } diff --git a/mobile/Cargo.toml b/mobile/Cargo.toml index f44f928e..489d0669 100644 --- a/mobile/Cargo.toml +++ b/mobile/Cargo.toml @@ -22,7 +22,7 @@ default = ["sqlite"] sqlite = ["dep:athleticstandard", "dep:sha2"] [dependencies] -athleticstandard-core = { path = "../core" } +athleticstandard-core = { path = "../core", features = ["uniffi"] } # The desktop library without its `cli` feature: the store, files, packages, # calculations, and views, and no command line or network runtime. athleticstandard = { path = "..", default-features = false, optional = true } diff --git a/mobile/android/athleticstandard/build.gradle.kts b/mobile/android/athleticstandard/build.gradle.kts index 723f6e3f..8ce230f7 100644 --- a/mobile/android/athleticstandard/build.gradle.kts +++ b/mobile/android/athleticstandard/build.gradle.kts @@ -65,6 +65,7 @@ val buildRust = tasks.register("buildRust") { inputs.dir(repositoryRoot.resolve("skills")) inputs.file(repositoryRoot.resolve("Cargo.lock")) inputs.file(repositoryRoot.resolve("mobile/uniffi.toml")) + inputs.file(repositoryRoot.resolve("core/uniffi.toml")) outputs.dir(output) } diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt index 8147cc2f..de3f4056 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/CalculationTest.kt @@ -1,5 +1,19 @@ package ai.athleticstandard +import ai.athleticstandard.core.ApplyResult +import ai.athleticstandard.core.CalculationGroup +import ai.athleticstandard.core.CalculationOperation +import ai.athleticstandard.core.CalculationReceipt +import ai.athleticstandard.core.CalculationRecordKind +import ai.athleticstandard.core.MissingReason +import ai.athleticstandard.core.PointMeasurementData +import ai.athleticstandard.core.PointMeasurementType +import ai.athleticstandard.core.ProviderReportingPeriodType +import ai.athleticstandard.core.RangeRequest +import ai.athleticstandard.core.ReceivedAtBasis +import ai.athleticstandard.core.RecordActor +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.SourceValue import android.util.Log import androidx.test.ext.junit.runners.AndroidJUnit4 import org.json.JSONObject @@ -20,28 +34,38 @@ import java.io.File @RunWith(AndroidJUnit4::class) class CalculationTest { private fun operation(name: String) = when (name) { - "summary" -> RangeOperation.SUMMARY - "baseline" -> RangeOperation.BASELINE - "trend" -> RangeOperation.TREND - "coverage" -> RangeOperation.COVERAGE - "compare-sources" -> RangeOperation.COMPARE_SOURCES - "correlation" -> RangeOperation.CORRELATION - "workout-drift" -> RangeOperation.WORKOUT_DRIFT - else -> RangeOperation.PROVIDER_PERIOD_SUMMARY + "summary" -> CalculationOperation.SUMMARY + "baseline" -> CalculationOperation.BASELINE + "trend" -> CalculationOperation.TREND + "coverage" -> CalculationOperation.COVERAGE + "compare-sources" -> CalculationOperation.COMPARE_SOURCES + "correlation" -> CalculationOperation.CORRELATION + "workout-drift" -> CalculationOperation.WORKOUT_DRIFT + else -> CalculationOperation.PROVIDER_PERIOD_SUMMARY } private fun recordKind(name: String) = when (name) { - "measurement" -> RangeRecordKind.MEASUREMENT - "provider-score" -> RangeRecordKind.PROVIDER_SCORE - "provider-summary" -> RangeRecordKind.PROVIDER_SUMMARY - else -> RangeRecordKind.SESSION_SUMMARY + "measurement" -> CalculationRecordKind.MEASUREMENT + "provider-score" -> CalculationRecordKind.PROVIDER_SCORE + "provider-summary" -> CalculationRecordKind.PROVIDER_SUMMARY + else -> CalculationRecordKind.SESSION_SUMMARY } private fun group(name: String) = when (name) { - "none" -> RangeGroup.UNGROUPED - "day" -> RangeGroup.DAY - "week" -> RangeGroup.WEEK - else -> RangeGroup.MONTH + "none" -> CalculationGroup.UNGROUPED + "day" -> CalculationGroup.DAY + "week" -> CalculationGroup.WEEK + else -> CalculationGroup.MONTH + } + + private fun periodType(name: String?) = when (name) { + null -> null + "whoop_physiological_cycle" -> ProviderReportingPeriodType.WHOOP_PHYSIOLOGICAL_CYCLE + "oura_activity_day" -> ProviderReportingPeriodType.OURA_ACTIVITY_DAY + "oura_sleep_day" -> ProviderReportingPeriodType.OURA_SLEEP_DAY + "oura_calendar_day" -> ProviderReportingPeriodType.OURA_CALENDAR_DAY + "oura_day_unspecified" -> ProviderReportingPeriodType.OURA_DAY_UNSPECIFIED + else -> ProviderReportingPeriodType.APPLE_ACTIVITY_SUMMARY_DAY } private fun JSONObject.text(key: String): String? = if (isNull(key)) null else getString(key) @@ -58,7 +82,7 @@ class CalculationTest { compareSourceId = fields.text("compare_source_id"), otherQuantity = fields.text("other_quantity"), workoutSessionId = fields.text("workout_session_id"), - providerPeriodType = fields.text("provider_period_type"), + providerPeriodType = periodType(fields.text("provider_period_type")), ) /** `ok ` or `error ` from a bundle's expected outcome. */ @@ -69,9 +93,18 @@ class CalculationTest { "error ${error.getString("code")} ${error.getString("detail")}" } - /** `ok ` or `error `, the same for both entry points. */ - private fun outcome(body: () -> ByteArray): String = try { - "ok " + body().decodeToString() + /** + * `ok ` or `error `, the same for both entry points. The typed + * answer is turned back into the desktop JSON, so the comparison is exact. + */ + private fun outcome(body: () -> ApplyResult): String = try { + "ok " + applyResultToJson(body()).decodeToString() + } catch (error: AthleticStandardException) { + "error ${error.code} ${error.detail}" + } + + private fun receiptOutcome(body: () -> CalculationReceipt): String = try { + "ok " + calculationReceiptToJson(body()).decodeToString() } catch (error: AthleticStandardException) { "error ${error.code} ${error.detail}" } @@ -91,7 +124,7 @@ class CalculationTest { val builder = RecordSnapshotBuilder() val batches = item.getJSONArray("record_batches") for (index in 0 until batches.length()) { - builder.addRecords(batches.getString(index).toByteArray(Charsets.UTF_8)) + builder.addRecordsJson(batches.getString(index).toByteArray(Charsets.UTF_8)) } assertEquals(item.getLong("record_count").toULong(), builder.recordCount()) val snapshot = builder.finish() @@ -129,8 +162,8 @@ class CalculationTest { } } else { val range = rangeRequest(request.getJSONObject("request")) - memory = outcome { snapshot.calculate(range) } - file = outcome { database.calculate(range) } + memory = receiptOutcome { snapshot.calculate(range) } + file = receiptOutcome { database.calculate(range) } } if (memory != wantedMemory || file != wanted) { failures += "$name: expected ${wanted.take(200)}\n memory ${memory.take(200)}\n file ${file.take(200)}" @@ -152,6 +185,48 @@ class CalculationTest { assertTrue(failures.take(10).joinToString("\n"), failures.isEmpty()) } + @Test + fun typedRecordsGiveTypedAnswers() { + val database = StoreTest.create(File(StoreTest.folder(), "athlete.ath.sqlite")) + StoreTest.writeWorkout(database) + fun reading(value: Double, time: String) = NewRecord( + data = RecordData.PointMeasurement( + PointMeasurementData( + sourceId = StoreTest.SOURCE_ID, + receivedAt = time, + receivedAtBasis = ReceivedAtBasis.IMPORT_TIME, + quantity = PointMeasurementType.HRV_RMSSD, + recordedAt = time, + inputTimestamp = StoreTest.notReported, + value = SourceValue( + standardValue = value, + standardUnit = "ms", + inputValueMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + inputUnitMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ), + ), + ), + changedBy = RecordActor.Athlete, + ) + database.writeRecords(listOf(reading(50.0, "2026-01-03T06:00:00.000Z"), reading(60.0, "2026-01-04T06:00:00.000Z"))) + val builder = RecordSnapshotBuilder() + assertEquals(4uL, builder.addRecords(database.listRecords(ListRecordsOptions()))) + val snapshot = builder.finish() + val request = RangeRequest( + operation = CalculationOperation.SUMMARY, + quantity = "hrv_rmssd", + recordKind = CalculationRecordKind.MEASUREMENT, + timeZone = "UTC", + group = CalculationGroup.UNGROUPED, + ) + val memory = snapshot.calculate(request) + assertEquals(memory, database.calculate(request)) + assertEquals(CalculationOperation.SUMMARY, memory.operation) + assertEquals("ms", memory.unit) + assertEquals(2uL, memory.input.recordCount) + database.closeDatabase() + } + @Test fun shippedSkillsAreListed() { val names = shippedCalculationNames() @@ -165,7 +240,7 @@ class CalculationTest { fun aRefusedBatchLeavesTheBuilderAsItWas() { val builder = RecordSnapshotBuilder() try { - builder.addRecords("""[{"record_id":"x"}]""".toByteArray()) + builder.addRecordsJson("""[{"record_id":"x"}]""".toByteArray()) fail("an invalid batch was accepted") } catch (error: AthleticStandardException) { assertEquals("invalid", error.code) diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt index 69ed494a..56f00e65 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/HostTest.kt @@ -1,5 +1,9 @@ package ai.athleticstandard +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.RecordType +import ai.athleticstandard.core.SourceData +import ai.athleticstandard.core.SourceType import ai.athleticstandard.host.AuthorizationBrowser import ai.athleticstandard.host.HostClient import ai.athleticstandard.host.HostException @@ -91,9 +95,30 @@ class HostTest { assertEquals(1, records.length()) // The host's list feeds a memory snapshot directly. val builder = RecordSnapshotBuilder() - builder.addRecords(records.toString().toByteArray()) + builder.addRecordsJson(client.recordsJson(athlete.athleteId)) assertEquals(1uL, builder.finish().recordCount()) - assertEquals(2, client.changes(athlete.athleteId, 0).changes.size) + + // The same reads and writes with the generated record types. + val current = client.records(athlete.athleteId).single() + assertEquals(sourceId, current.recordId) + val sourceData = (current.data as RecordData.Source).v1 + assertEquals("Example Band 2", sourceData.dataWriter) + val typed = client.prepareCorrection( + athlete.athleteId, + current, + RecordData.Source(sourceData.copy(dataWriter = "Example Band 3")), + ) + assertEquals(3L, client.send(typed).records.first().revision) + val history = client.record(athlete.athleteId, sourceId) + assertEquals(3uL, history.record.currentRevision) + assertEquals(listOf(1uL, 2uL, 3uL), history.revisions.map { it.revision }) + val manual = RecordData.Source(SourceData(SourceType.MANUAL, "Example app", "manual_entry")) + val added = client.send(client.prepareRecordCreation(athlete.athleteId, manual)).records.first().recordId + assertEquals( + listOf(sourceId, added), + client.records(athlete.athleteId, RecordType.SOURCE).map { it.recordId }, + ) + assertEquals(4, client.changes(athlete.athleteId, 0).changes.size) val zip = client.export(athlete.athleteId) assertEquals(0x50, zip[0].toInt()) assertEquals(0x4b, zip[1].toInt()) diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt index 97f7b9e4..8a9a0487 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/RoundTripTest.kt @@ -3,6 +3,8 @@ package ai.athleticstandard import android.net.Uri import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry +import ai.athleticstandard.core.RecordActor +import ai.athleticstandard.core.RecordData import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue @@ -36,25 +38,24 @@ class RoundTripTest { val picked = PickedDocument.open(context, Uri.fromFile(document), StoreTest.folder()) assertEquals(facts.getString("database_id"), picked.database.info().databaseId) - val record = JSONObject(picked.database.getRecord(recordId)!!.decodeToString()) - assertEquals(1, record.getInt("current_revision")) - val data = record.getJSONObject("data") - data.getJSONObject("value").put("standard_value", 63).put("input_value", 63) - val request = JSONObject() - .put("record_id", recordId) - .put("expected_revision", 1) - .put("data", data) - .put("changed_by", JSONObject().put("author_type", "athlete")) - picked.database.correctRecord(request.toString().toByteArray()) + val record = picked.database.getRecord(recordId)!! + assertEquals(1uL, record.currentRevision) + val measurement = (record.data as RecordData.PointMeasurement).v1 + val value = measurement.value.copy(standardValue = 63.0, inputValue = 63.0) + picked.database.correctRecord( + RecordCorrection( + recordId = recordId, + expectedRevision = record.currentRevision, + data = RecordData.PointMeasurement(measurement.copy(value = value)), + changedBy = RecordActor.Athlete, + ), + ) // Close the working copy and resume it, as after the app restarts. val state = picked.state picked.close(removingWorkingCopy = false) PickedDocument.resume(context, state).use { resumed -> - assertEquals( - 2, - JSONObject(resumed.database.getRecord(recordId)!!.decodeToString()).getInt("current_revision"), - ) + assertEquals(2uL, resumed.database.getRecord(recordId)!!.currentRevision) assertTrue(resumed.hasUnsavedEdits()) val saved = resumed.save() assertEquals(fileSha256(document.path), saved.sha256) diff --git a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt index ea3bdca6..3a7c6531 100644 --- a/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt +++ b/mobile/android/athleticstandard/src/androidTest/kotlin/ai/athleticstandard/StoreTest.kt @@ -1,8 +1,17 @@ package ai.athleticstandard +import ai.athleticstandard.core.CurrentRecord +import ai.athleticstandard.core.InputTimestampReceipt +import ai.athleticstandard.core.MissingReason +import ai.athleticstandard.core.ReceivedAtBasis +import ai.athleticstandard.core.RecordActor +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.RecordType +import ai.athleticstandard.core.SourceData +import ai.athleticstandard.core.SourceType +import ai.athleticstandard.core.WorkoutSessionData import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry -import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -14,38 +23,77 @@ import org.junit.runner.RunWith import java.io.File import java.util.UUID -/** The storage steps mobile/tests/store.rs runs, through the Android library (D327). */ +/** + * The storage steps mobile/tests/store.rs runs, through the Android library, with the + * generated record types (D327, D329). + */ @RunWith(AndroidJUnit4::class) class StoreTest { companion object { const val SOURCE_ID = "01890f3e-e7d3-7cc0-88c8-000000000003" const val WORKOUT_ID = "01890f3e-e7d3-7cc0-88c8-000000000064" + const val CREATED_AT = "2026-01-02T03:04:05.678Z" fun folder(): File { val context = InstrumentationRegistry.getInstrumentation().targetContext return File(context.cacheDir, "athleticstandard-${UUID.randomUUID()}").apply { mkdirs() } } - fun workoutData(endAt: String) = - """{"source_id":"$SOURCE_ID","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","start_at":"2026-01-02T03:04:05.678Z","end_at":"$endAt","input_start_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"input_end_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"source_reported_summaries":[]}""" + /** A timestamp the source did not report. */ + val notReported = InputTimestampReceipt( + timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ) + + fun workoutData(endAt: String): RecordData = RecordData.WorkoutSession( + WorkoutSessionData( + sourceId = SOURCE_ID, + receivedAt = CREATED_AT, + receivedAtBasis = ReceivedAtBasis.IMPORT_TIME, + startAt = CREATED_AT, + endAt = endAt, + inputStartTimestamp = notReported, + inputEndTimestamp = notReported, + sourceReportedSummaries = emptyList(), + ), + ) fun create(file: File): Database = Database.create( file.path, - CreateDatabaseOptions("01890f3e-e7d3-7cc0-88c8-0000000000aa", "2026-01-02T03:04:05.678Z"), + CreateDatabaseOptions("01890f3e-e7d3-7cc0-88c8-0000000000aa", CREATED_AT), ) - fun writeWorkout(database: Database) { - val request = """{"inputs":[{"record_id":"$SOURCE_ID","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","data":{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"},"changed_by":{"author_type":"athlete"}},{"record_id":"$WORKOUT_ID","record_type":"workout_session","created_at":"2026-01-02T03:04:05.678Z","data":${workoutData("2026-01-02T04:04:05.678Z")},"changed_by":{"author_type":"athlete"}}]}""" - database.writeRecords(request.toByteArray()) + fun writeWorkout(database: Database): WrittenRecords { + val source = RecordData.Source( + SourceData(sourceType = SourceType.WEARABLE, dataWriter = "Example Band", dataRoute = "provider_export"), + ) + return database.writeRecords( + listOf( + NewRecord(data = source, changedBy = RecordActor.Athlete, recordId = SOURCE_ID, createdAt = CREATED_AT), + NewRecord( + data = workoutData("2026-01-02T04:04:05.678Z"), + changedBy = RecordActor.Athlete, + recordId = WORKOUT_ID, + createdAt = CREATED_AT, + ), + ), + ) } - fun correctWorkout(database: Database, expectedRevision: Int, endAt: String): ByteArray { - val request = """{"record_id":"$WORKOUT_ID","expected_revision":$expectedRevision,"data":${workoutData(endAt)},"changed_by":{"author_type":"athlete"},"became_known_at":"2026-01-03T00:00:00.000Z"}""" - return database.correctRecord(request.toByteArray()) - } + fun correctWorkout(database: Database, expectedRevision: Long, endAt: String): CorrectedRecord = + database.correctRecord( + RecordCorrection( + recordId = WORKOUT_ID, + expectedRevision = expectedRevision.toULong(), + data = workoutData(endAt), + changedBy = RecordActor.Athlete, + becameKnownAt = "2026-01-03T00:00:00.000Z", + ), + ) - fun endAt(database: Database): String = - JSONObject(database.getRecord(WORKOUT_ID)!!.decodeToString()).getJSONObject("data").getString("end_at") + /** The workout's end time, read through the typed record. */ + fun endAt(database: Database): String? = + (database.getRecord(WORKOUT_ID)?.data as? RecordData.WorkoutSession)?.v1?.endAt /** Copy a file from the fixture bundle into the app's storage. */ fun fixture(name: String, into: File): File { @@ -62,8 +110,9 @@ class StoreTest { val database = create(file) assertEquals(0uL, database.info().databaseRevision) assertTrue(database.info().writable) - writeWorkout(database) - correctWorkout(database, 1, "2026-01-02T04:30:05.678Z") + val written = writeWorkout(database) + assertEquals(listOf(SOURCE_ID, WORKOUT_ID), written.records.map { it.recordId }) + assertEquals(2uL, correctWorkout(database, 1, "2026-01-02T04:30:05.678Z").record.currentRevision) assertEquals(2uL, database.info().databaseRevision) database.closeDatabase() assertTrue(database.isClosed()) @@ -75,14 +124,38 @@ class StoreTest { } val reopened = Database.open(file.path, OpenDatabaseOptions()) - val record = JSONObject(reopened.getRecord(WORKOUT_ID)!!.decodeToString()) - assertEquals(2, record.getInt("current_revision")) + assertEquals(2uL, reopened.getRecord(WORKOUT_ID)!!.currentRevision) assertEquals("2026-01-02T04:30:05.678Z", endAt(reopened)) - assertEquals(2, JSONArray(reopened.recordRevisions(WORKOUT_ID).decodeToString()).length()) + val revisions = reopened.recordRevisions(WORKOUT_ID) + assertEquals(listOf(1uL, 2uL), revisions.map { it.revision }) + assertEquals("2026-01-03T00:00:00.000Z", revisions.last().becameKnownAt) + assertEquals(listOf(SOURCE_ID), reopened.listRecords(ListRecordsOptions(recordType = RecordType.SOURCE)).map { it.recordId }) assertNull(reopened.getRecord("01890f3e-e7d3-7cc0-88c8-0000000000ff")) reopened.closeDatabase() } + @Test + fun aRecordChangesThroughItsTypedFields() { + val database = create(File(folder(), "athlete.ath.sqlite")) + writeWorkout(database) + val current = database.getRecord(WORKOUT_ID)!! + val workout = (current.data as RecordData.WorkoutSession).v1 + val changed = workout.copy(name = "Morning row", activityType = "rowing") + database.correctRecord( + RecordCorrection( + recordId = current.recordId, + expectedRevision = current.currentRevision, + data = RecordData.WorkoutSession(changed), + changedBy = RecordActor.Athlete, + ), + ) + val saved = (database.getRecord(WORKOUT_ID)!!.data as RecordData.WorkoutSession).v1 + assertEquals("Morning row", saved.name) + assertEquals("rowing", saved.activityType) + assertEquals(workout.endAt, saved.endAt) + database.closeDatabase() + } + @Test fun staleCorrectionIsRefused() { val database = create(File(folder(), "athlete.ath.sqlite")) @@ -99,6 +172,29 @@ class StoreTest { database.closeDatabase() } + @Test + fun anInvalidEditReturnsTheDesktopIssues() { + val database = create(File(folder(), "athlete.ath.sqlite")) + writeWorkout(database) + try { + correctWorkout(database, 1, "2026-01-01T00:00:00.000Z") + fail("a workout that ends before it starts was accepted") + } catch (error: AthleticStandardException) { + assertEquals("invalid", error.code) + assertEquals("data.end_at: Workout session end cannot precede its start", error.detail) + assertEquals(listOf("data.end_at"), error.issues.map { it.pathText }) + } + // The same check runs before a write, for a form that is still open. + try { + checkRecordData(workoutData("2026-01-01T00:00:00.000Z")) + fail("the check accepted a workout that ends before it starts") + } catch (error: AthleticStandardException) { + assertEquals("invalid", error.code) + } + checkRecordData(workoutData("2026-01-02T04:04:05.678Z")) + database.closeDatabase() + } + @Test fun readOnlyOpenRefusesWrites() { val file = File(folder(), "athlete.ath.sqlite") @@ -114,6 +210,20 @@ class StoreTest { readOnly.closeDatabase() } + @Test + fun aDeletionKeepsHistory() { + val database = create(File(folder(), "athlete.ath.sqlite")) + writeWorkout(database) + val deleted = database.deleteRecord(DeleteRequest(WORKOUT_ID, 1uL, RecordActor.Athlete)) + assertEquals(1uL, deleted.recordRevision) + assertTrue(database.getRecord(WORKOUT_ID)!!.isDeleted) + assertEquals(1uL, database.recordRevisions(WORKOUT_ID).first().revision) + assertTrue(database.listRecords(ListRecordsOptions(recordType = RecordType.WORKOUT_SESSION)).isEmpty()) + val all = database.listRecords(ListRecordsOptions(recordType = RecordType.WORKOUT_SESSION, includeDeleted = true)) + assertEquals(listOf(WORKOUT_ID), all.map { it.recordId }) + database.closeDatabase() + } + @Test fun outdatedFileNeedsMigrationWithBackup() { val folder = folder() @@ -121,13 +231,16 @@ class StoreTest { try { Database.open(file.path, OpenDatabaseOptions()) fail("an outdated database opened without a migration") - } catch (error: AthleticStandardException) { + } catch (error: AthleticStandardException.MigrationRequired) { assertEquals("migration_required", error.code) + assertTrue(error.preview.migrationNeeded) + assertTrue(error.preview.plannedSteps.isNotEmpty()) } val outdated = Database.open(file.path, OpenDatabaseOptions(allowOutdatedSchema = true)) val backup = File(folder, "before-migration.ath.sqlite") - val result = JSONObject(outdated.migrate(backup.path).decodeToString()) - assertTrue(result.getBoolean("migrated")) + val result = outdated.migrate(backup.path) + assertTrue(result.migrated) + assertEquals(backup.canonicalPath, File(result.backupPath!!).canonicalPath) outdated.closeDatabase() assertTrue(backup.exists()) val migrated = Database.open(file.path, OpenDatabaseOptions()) @@ -149,8 +262,77 @@ class StoreTest { assertEquals(fileSha256(saved.path), saved.sha256) assertFalse(File(saved.path + "-wal").exists()) val copy = Database.open(saved.path, OpenDatabaseOptions(readOnly = true)) - assertEquals(2, JSONObject(copy.getRecord(WORKOUT_ID)!!.decodeToString()).getInt("current_revision")) + assertEquals(2uL, copy.getRecord(WORKOUT_ID)!!.currentRevision) copy.closeDatabase() database.closeDatabase() } + + @Test + fun recordsConvertToAndFromTheirJson() { + val database = create(File(folder(), "athlete.ath.sqlite")) + writeWorkout(database) + val record: CurrentRecord = database.getRecord(WORKOUT_ID)!! + val json = currentRecordToJson(record) + assertEquals("workout_session", JSONObject(json.decodeToString()).getString("record_type")) + assertEquals(record, currentRecordFromJson(json)) + assertEquals(record.data, recordDataFromJson(RecordType.WORKOUT_SESSION, recordDataToJson(record.data))) + assertEquals(RecordType.WORKOUT_SESSION, recordTypeOf(record.data)) + assertEquals("workout_session", recordTypeName(RecordType.WORKOUT_SESSION)) + assertEquals(RecordType.WORKOUT_SESSION, recordTypeFromName("workout_session")) + database.closeDatabase() + } +} + +/** An app's own values on a record (D329). */ +@RunWith(AndroidJUnit4::class) +class ExtensionTest { + private val key = "com.example.myapp/notes" + + @Test + fun anAppValueIsWrittenAndReadBack() { + val database = StoreTest.create(File(StoreTest.folder(), "athlete.ath.sqlite")) + StoreTest.writeWorkout(database) + val current = database.getRecord(StoreTest.WORKOUT_ID)!! + assertNull(current.extension(key)) + + val notes = JSONObject().put("mood", "rested").put("hours_slept", 7.5).toString() + val correction = RecordCorrection( + recordId = current.recordId, + expectedRevision = current.currentRevision, + data = current.data, + changedBy = RecordActor.Athlete, + extensions = current.extensions, + ).withExtension(key, notes) + database.correctRecord(correction) + + val saved = database.getRecord(StoreTest.WORKOUT_ID)!! + assertEquals("rested", saved.extension(key) { JSONObject(it).getString("mood") }) + // A later correction without extensions keeps them. + database.correctRecord( + RecordCorrection( + recordId = saved.recordId, + expectedRevision = saved.currentRevision, + data = saved.data, + changedBy = RecordActor.Athlete, + ), + ) + val kept = database.getRecord(StoreTest.WORKOUT_ID)!! + assertEquals(7.5, kept.extension(key) { JSONObject(it).getDouble("hours_slept") }!!, 0.0) + database.closeDatabase() + } + + @Test + fun aKeyOutsideTheAppsOwnNameIsRefused() { + val record = NewRecord( + data = RecordData.Source(SourceData(SourceType.MANUAL, "Example", "manual_entry")), + changedBy = RecordActor.Athlete, + ) + try { + record.withExtension("notes", "\"value\"") + fail("a key without a domain was accepted") + } catch (error: AthleticStandardException) { + assertEquals("invalid", error.code) + } + assertNull(record.extensions) + } } diff --git a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/RecordExtensions.kt b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/RecordExtensions.kt new file mode 100644 index 00000000..b737da27 --- /dev/null +++ b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/RecordExtensions.kt @@ -0,0 +1,44 @@ +package ai.athleticstandard + +import ai.athleticstandard.core.CurrentRecord +import ai.athleticstandard.core.RecordRevision + +// An app's own values on a record (D329). An extension is stored under a key the +// app owns: its domain name written backwards, then a name, such as +// `com.example.myapp/notes`. The value is JSON text; decode it with the app's +// own JSON library and type. The library checks the key and the format's +// limits for extensions when a value is set, and again when the record is +// written. + +/** + * The JSON text the app stored under [key] on this record, or null when the key is + * absent. Throws [AthleticStandardException.Invalid] for a key that is not an + * extension key. + */ +fun CurrentRecord.extension(key: String): String? = extensionJson(extensions, key) + +/** The app's value under [key], decoded by [decode], or null when the key is absent. */ +inline fun CurrentRecord.extension(key: String, decode: (String) -> T): T? = extension(key)?.let(decode) + +/** The JSON text the app stored under [key] on this revision, or null when the key is absent. */ +fun RecordRevision.extension(key: String): String? = extensionJson(extensions, key) + +/** The app's value under [key] on this revision, decoded by [decode], or null when absent. */ +inline fun RecordRevision.extension(key: String, decode: (String) -> T): T? = extension(key)?.let(decode) + +/** + * A copy of this record to write with [json], the app's value as JSON text, stored + * under [key]. Other keys keep their values and order. Throws + * [AthleticStandardException.Invalid] when the key or the result breaks the format's + * rules for extensions. + */ +fun NewRecord.withExtension(key: String, json: String): NewRecord = + copy(extensions = withExtensionJson(extensions, key, json)) + +/** + * A copy of this correction with [json] stored under [key]. Start from the current + * record's extensions to keep its other keys. A correction without extensions keeps + * the record's extensions as they are. + */ +fun RecordCorrection.withExtension(key: String, json: String): RecordCorrection = + copy(extensions = withExtensionJson(extensions, key, json)) diff --git a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt index f27c59d9..5d29a33a 100644 --- a/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt +++ b/mobile/android/athleticstandard/src/main/kotlin/ai/athleticstandard/host/HostClient.kt @@ -1,5 +1,14 @@ package ai.athleticstandard.host +import ai.athleticstandard.RecordHistory +import ai.athleticstandard.core.CurrentRecord +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.RecordType +import ai.athleticstandard.currentRecordsFromJson +import ai.athleticstandard.recordDataToJson +import ai.athleticstandard.recordHistoryFromJson +import ai.athleticstandard.recordTypeName +import ai.athleticstandard.recordTypeOf import android.net.Uri import org.json.JSONArray import org.json.JSONObject @@ -167,6 +176,14 @@ class HostClient( fun recordJson(athleteId: String, recordId: String): ByteArray = send("GET", listOf("v1", "athletes", athleteId, "records", recordId)) + /** Current records, oldest first, as the generated record types (D329). */ + fun records(athleteId: String, recordType: RecordType? = null, limit: Int? = null): List = + currentRecordsFromJson(recordsJson(athleteId, recordType?.let { recordTypeName(it) }, limit)) + + /** One record and every retained revision, oldest first, as the generated types. */ + fun record(athleteId: String, recordId: String): RecordHistory = + recordHistoryFromJson(recordJson(athleteId, recordId)) + /** The changes since a database revision (D263). */ fun changes(athleteId: String, since: Long): ChangesPage { val json = JSONObject( @@ -210,6 +227,30 @@ class HostClient( return PreparedWrite("POST", listOf("v1", "athletes", athleteId, "records"), joined(fields), idempotencyKey) } + /** A new record from the generated types. The case of [data] names the record type. */ + fun prepareRecordCreation( + athleteId: String, + data: RecordData, + recordId: String? = null, + idempotencyKey: String = UUID.randomUUID().toString(), + ): PreparedWrite = prepareRecordCreation( + athleteId, recordTypeName(recordTypeOf(data)), recordDataToJson(data), recordId, idempotencyKey, + ) + + /** + * A correction of [record] with the complete new [data], at the revision the person + * edited. If the record changed since, the host answers `stale`; keep the person's + * edit for review. + */ + fun prepareCorrection( + athleteId: String, + record: CurrentRecord, + data: RecordData, + idempotencyKey: String = UUID.randomUUID().toString(), + ): PreparedWrite = prepareCorrection( + athleteId, record.recordId, record.currentRevision.toLong(), recordDataToJson(data), idempotencyKey, + ) + /** * A correction: the complete new data, and the revision the person edited. If the * record changed since, the host answers `stale`; keep the person's edit for review. diff --git a/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt b/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt index 1c168e51..faf0bfc7 100644 --- a/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt +++ b/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt @@ -5,8 +5,21 @@ import ai.athleticstandard.CreateDatabaseOptions import ai.athleticstandard.Database import ai.athleticstandard.FileLocationAdvice import ai.athleticstandard.ListRecordsOptions +import ai.athleticstandard.NewRecord import ai.athleticstandard.OpenDatabaseOptions import ai.athleticstandard.PickedDocument +import ai.athleticstandard.applyResultToJson +import ai.athleticstandard.core.InputTimestampReceipt +import ai.athleticstandard.core.MissingReason +import ai.athleticstandard.core.PointMeasurementData +import ai.athleticstandard.core.PointMeasurementType +import ai.athleticstandard.core.ReceivedAtBasis +import ai.athleticstandard.core.RecordActor +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.RecordType +import ai.athleticstandard.core.SourceData +import ai.athleticstandard.core.SourceType +import ai.athleticstandard.core.SourceValue import ai.athleticstandard.host.CustomTabsBrowser import ai.athleticstandard.host.HostSignIn import ai.athleticstandard.host.HostSignInConfiguration @@ -20,8 +33,6 @@ import android.widget.EditText import android.widget.LinearLayout import android.widget.ScrollView import android.widget.TextView -import org.json.JSONArray -import org.json.JSONObject import java.io.File import kotlin.concurrent.thread @@ -62,53 +73,55 @@ class MainActivity : Activity() { private fun show(text: String) = runOnUiThread { output.text = text } - /** A local file: create it once, add a reading, and summarize the readings. */ + /** A local file: create it once, add a reading, and run a shipped calculation. */ private fun workOffline(): String { val file = File(FileLocationAdvice.localFolder(this), "example.ath.sqlite") val database = if (file.exists()) { Database.open(file.path, OpenDatabaseOptions()) } else { - Database.create(file.path, CreateDatabaseOptions(null, null)).also { addSource(it) } + Database.create(file.path, CreateDatabaseOptions()).also { addSource(it) } } try { - val sources = JSONArray(database.listRecords(ListRecordsOptions("source", false, null)).decodeToString()) - val sourceId = sources.getJSONObject(0).getString("record_id") - val at = ai.athleticstandard.consumer.Clock.now() - val reading = JSONObject() - .put("source_id", sourceId) - .put("received_at", at) - .put("received_at_basis", "local_write_time") - .put("quantity", "hrv_rmssd") - .put("recorded_at", at) - .put("input_timestamp", JSONObject().put("timestamp_missing_reason", "not_provided_by_source") - .put("utc_offset_missing_reason", "not_provided_by_source")) - .put("value", JSONObject().put("standard_value", 50 + (System.currentTimeMillis() / 1000) % 15) - .put("standard_unit", "ms").put("input_value_missing_reason", "not_provided_by_source") - .put("input_unit_missing_reason", "not_provided_by_source")) - val request = JSONObject().put("inputs", JSONArray().put(JSONObject() - .put("record_type", "point_measurement").put("data", reading) - .put("changed_by", JSONObject().put("author_type", "athlete")))) - database.writeRecords(request.toString().toByteArray()) - val readings = JSONArray( - database.listRecords(ListRecordsOptions("point_measurement", false, null)).decodeToString(), + val sourceId = database.listRecords(ListRecordsOptions(recordType = RecordType.SOURCE)).first().recordId + val at = Clock.now() + val reading = PointMeasurementData( + sourceId = sourceId, + receivedAt = at, + receivedAtBasis = ReceivedAtBasis.LOCAL_WRITE_TIME, + quantity = PointMeasurementType.HRV_RMSSD, + recordedAt = at, + inputTimestamp = InputTimestampReceipt( + timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ), + value = SourceValue( + standardValue = 50.0 + (System.currentTimeMillis() / 1000) % 15, + standardUnit = "ms", + inputValueMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + inputUnitMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ), ) - val last = readings.getJSONObject(readings.length() - 1).getString("record_id") - val change = database.apply(last, CalculationSkill.Shipped("hrv-change")).decodeToString() + val written = database.writeRecords( + listOf(NewRecord(data = RecordData.PointMeasurement(reading), changedBy = RecordActor.Athlete)), + ) + val readings = database.listRecords(ListRecordsOptions(recordType = RecordType.POINT_MEASUREMENT)) + val change = database.apply(written.records.first().recordId, CalculationSkill.Shipped("hrv-change")) val info = database.info() return "Athletic Standard ${libraryVersion()}\n${file.path}\n" + - "database revision ${info.databaseRevision}, ${readings.length()} readings\n" + - "hrv-change on the newest reading: $change" + "database revision ${info.databaseRevision}, ${readings.size} readings\n" + + "hrv-change on the newest reading: ${applyResultToJson(change).decodeToString()}" } finally { database.closeDatabase() } } private fun addSource(database: Database) { - val source = JSONObject().put("source_type", "manual").put("data_writer", "Athletic Standard example") - .put("data_route", "manual_entry") - database.writeRecords(JSONObject().put("inputs", JSONArray().put(JSONObject().put("record_type", "source") - .put("data", source).put("changed_by", JSONObject().put("author_type", "athlete")))).toString() - .toByteArray()) + val source = SourceData( + sourceType = SourceType.MANUAL, + dataWriter = "Athletic Standard example", + dataRoute = "manual_entry", + ) + database.writeRecords(listOf(NewRecord(data = RecordData.Source(source), changedBy = RecordActor.Athlete))) } private fun pickDocument() { @@ -151,12 +164,15 @@ class MainActivity : Activity() { val athlete = host.athletes().firstOrNull() ?: host.createAthlete("Example athlete").let { host.athletes().first() } - val records = JSONObject(host.recordsJson(athlete.athleteId).decodeToString()).getJSONArray("records") - val source = JSONObject().put("source_type", "manual").put("data_writer", "Athletic Standard example") - .put("data_route", "manual_entry") - val write = host.prepareRecordCreation(athlete.athleteId, "source", source.toString().toByteArray()) + val records = host.records(athlete.athleteId) + val source = SourceData( + sourceType = SourceType.MANUAL, + dataWriter = "Athletic Standard example", + dataRoute = "manual_entry", + ) + val write = host.prepareRecordCreation(athlete.athleteId, RecordData.Source(source)) val saved = host.send(write) - "Signed in to $address\n$operator\nrecord ${athlete.athleteId}: ${records.length()} records\n" + + "Signed in to $address\n$operator\nrecord ${athlete.athleteId}: ${records.size} records\n" + "saved record ${saved.records.first().recordId} at database revision ${saved.databaseRevision}" } catch (error: Exception) { "Could not connect: ${error.message}" diff --git a/mobile/scripts/build-android.sh b/mobile/scripts/build-android.sh index 899cf582..ecad79d8 100755 --- a/mobile/scripts/build-android.sh +++ b/mobile/scripts/build-android.sh @@ -7,9 +7,11 @@ # # Usage: mobile/scripts/build-android.sh [debug|release] [output directory] # -# The output directory gets jniLibs//libathleticstandard_mobile.so and -# kotlin/ai/athleticstandard/athleticstandard_mobile.kt. Neither is committed -# (D327). ANDROID_NDK_HOME names the NDK; otherwise ANDROID_HOME/ndk/. +# The output directory gets jniLibs//libathleticstandard_mobile.so, +# kotlin/ai/athleticstandard/athleticstandard_mobile.kt (the phone library), and +# kotlin/ai/athleticstandard/core/athleticstandard_core.kt (the core's record and +# result types, D329). None is committed (D327). ANDROID_NDK_HOME names the NDK; +# otherwise ANDROID_HOME/ndk/. set -euo pipefail diff --git a/mobile/scripts/build-apple.sh b/mobile/scripts/build-apple.sh index 1107d58b..cb5e2a14 100755 --- a/mobile/scripts/build-apple.sh +++ b/mobile/scripts/build-apple.sh @@ -7,6 +7,11 @@ # mobile/swift/build/AthleticStandardFFI.xcframework. The generated Swift goes to # mobile/swift/Sources/AthleticStandard/Generated/. Neither is committed (D327). # +# UniFFI writes one Swift file and one C header for each crate: the phone +# library (AthleticStandard.swift) and the core's record and result types +# (AthleticStandardCore.swift, D329). Both Swift files compile into the one +# AthleticStandard module, and one C module lists both headers. +# # Usage: mobile/scripts/build-apple.sh [debug|release] # # The XCFramework is assembled directly rather than with @@ -90,15 +95,29 @@ mkdir -p "$BINDINGS" rm -rf "$FRAMEWORK" "$GENERATED" mkdir -p "$FRAMEWORK" "$GENERATED" -cp "$BINDINGS/AthleticStandard.swift" "$GENERATED/AthleticStandard.swift" +cp "$BINDINGS/AthleticStandard.swift" "$BINDINGS/AthleticStandardCore.swift" "$GENERATED/" + +# The C module for both headers. UniFFI writes one module map for each crate, +# each naming only its own header. +MODULE_MAP="$BINDINGS/module.modulemap" +cat > "$MODULE_MAP" <<'MAP' +module AthleticStandardFFI { + header "AthleticStandardFFI.h" + header "AthleticStandardCoreFFI.h" + export * + use "Darwin" + use "_Builtin_stdbool" + use "_Builtin_stdint" +} +MAP slice() { local identifier="$1" shift local dir="$FRAMEWORK/$identifier" mkdir -p "$dir/Headers" - cp "$BINDINGS/AthleticStandardFFI.h" "$dir/Headers/AthleticStandardFFI.h" - cp "$BINDINGS/AthleticStandardFFI.modulemap" "$dir/Headers/module.modulemap" + cp "$BINDINGS/AthleticStandardFFI.h" "$BINDINGS/AthleticStandardCoreFFI.h" "$dir/Headers/" + cp "$MODULE_MAP" "$dir/Headers/module.modulemap" if [ "$#" -eq 1 ]; then cp "$TARGET_DIR/$1/$PROFILE_DIR/$LIB" "$dir/$LIB" else @@ -161,4 +180,4 @@ for identifier in ios-arm64 ios-arm64_x86_64-simulator macos-arm64_x86_64; do echo "$identifier: $(lipo -archs "$FRAMEWORK/$identifier/$LIB")" done echo "wrote $FRAMEWORK" -echo "wrote $GENERATED/AthleticStandard.swift" +echo "wrote $GENERATED/AthleticStandard.swift and $GENERATED/AthleticStandardCore.swift" diff --git a/mobile/src/calculate.rs b/mobile/src/calculate.rs index 8c6c2a6b..182fc189 100644 --- a/mobile/src/calculate.rs +++ b/mobile/src/calculate.rs @@ -1,10 +1,11 @@ //! Calculations on a phone (D326). //! -//! A `RecordSnapshotBuilder` takes batches of current records as UTF-8 JSON -//! and gives an immutable `RecordSnapshot`. `apply`, `apply_with`, and -//! `calculate` on the snapshot run the desktop calculations on those records. -//! `Database` runs the same calls on an open file. Results are the desktop -//! JSON: the `ath apply --json` object and the `ath calculate --json` receipt. +//! A `RecordSnapshotBuilder` takes batches of current records and gives an +//! immutable `RecordSnapshot`. `apply`, `apply_with`, and `calculate` on the +//! snapshot run the desktop calculations on those records. `Database` runs the +//! same calls on an open file. Results are typed: the `ath apply --json` +//! object as `ApplyResult` and the `ath calculate --json` receipt as +//! `CalculationReceipt`. //! //! A snapshot does not hold device recordings yet, so it refuses the 3.0.0 //! methods that read recordings or the intensity references in effect, with a @@ -13,9 +14,9 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::{Arc, Mutex}; -use athleticstandard_core::calculate::{self, CalculateOptions, Group, Operation, RecordKind}; -use athleticstandard_core::json; -use athleticstandard_core::model::ProviderReportingPeriodType; +use athleticstandard_core::calculate::{self, ApplyResult, CalculateOptions, CalculationReceipt}; +use athleticstandard_core::json::{self, Value}; +use athleticstandard_core::model::CurrentRecord; use crate::error::AthleticStandardError; use crate::validate::parse_json; @@ -58,113 +59,6 @@ impl CalculationSkill { } } -/// A named range calculation. -#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] -pub enum RangeOperation { - Summary, - Baseline, - Trend, - Coverage, - CompareSources, - Correlation, - WorkoutDrift, - ProviderPeriodSummary, -} - -/// Which typed rows a range calculation reads. -#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] -pub enum RangeRecordKind { - Measurement, - ProviderScore, - ProviderSummary, - SessionSummary, -} - -/// Calendar grouping for summary and baseline. `Ungrouped` is the desktop's -/// `none`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] -pub enum RangeGroup { - Ungrouped, - Day, - Week, - Month, -} - -/// A range calculation request, with the options `ath calculate` takes. -#[derive(Debug, Clone, PartialEq, uniffi::Record)] -pub struct RangeRequest { - pub operation: RangeOperation, - /// A measurement quantity, provider metric, or summary type. - pub quantity: String, - pub record_kind: RangeRecordKind, - pub group: RangeGroup, - /// A calendar day (`YYYY-MM-DD`) or an exact UTC instant. - #[uniffi(default = None)] - pub from: Option, - #[uniffi(default = None)] - pub to: Option, - #[uniffi(default = None)] - pub time_zone: Option, - #[uniffi(default = None)] - pub source_id: Option, - #[uniffi(default = None)] - pub compare_source_id: Option, - #[uniffi(default = None)] - pub other_quantity: Option, - #[uniffi(default = None)] - pub workout_session_id: Option, - /// A provider reporting period type, such as `oura_sleep_day`. - #[uniffi(default = None)] - pub provider_period_type: Option, -} - -impl RangeRequest { - pub(crate) fn options(&self) -> Result { - let operation = match self.operation { - RangeOperation::Summary => Operation::Summary, - RangeOperation::Baseline => Operation::Baseline, - RangeOperation::Trend => Operation::Trend, - RangeOperation::Coverage => Operation::Coverage, - RangeOperation::CompareSources => Operation::CompareSources, - RangeOperation::Correlation => Operation::Correlation, - RangeOperation::WorkoutDrift => Operation::WorkoutDrift, - RangeOperation::ProviderPeriodSummary => Operation::ProviderPeriodSummary, - }; - let mut options = CalculateOptions::new(operation, self.quantity.clone()); - options.record_kind = match self.record_kind { - RangeRecordKind::Measurement => RecordKind::Measurement, - RangeRecordKind::ProviderScore => RecordKind::ProviderScore, - RangeRecordKind::ProviderSummary => RecordKind::ProviderSummary, - RangeRecordKind::SessionSummary => RecordKind::SessionSummary, - }; - options.group = match self.group { - RangeGroup::Ungrouped => Group::None, - RangeGroup::Day => Group::Day, - RangeGroup::Week => Group::Week, - RangeGroup::Month => Group::Month, - }; - options.from = self.from.clone(); - options.to = self.to.clone(); - options.time_zone = self.time_zone.clone(); - options.source_id = self.source_id.clone(); - options.compare_source_id = self.compare_source_id.clone(); - options.other_quantity = self.other_quantity.clone(); - options.workout_session_id = self.workout_session_id.clone(); - options.provider_period_type = match &self.provider_period_type { - None => None, - Some(name) => { - Some(ProviderReportingPeriodType::parse(name).ok_or_else(|| AthleticStandardError::Failed { - detail: format!( - "Unknown provider period type '{name}'. Known types: {}", - ProviderReportingPeriodType::NAMES.join(", ") - ), - })?) - } - }; - Ok(options) - } -} - /// Collects batches of current records for a `RecordSnapshot`. A refused /// batch leaves the builder as it was. After `finish`, the builder is spent. #[derive(uniffi::Object)] @@ -172,6 +66,16 @@ pub struct RecordSnapshotBuilder { builder: Mutex>, } +impl RecordSnapshotBuilder { + fn add_batch(&self, batch: &Value) -> Result { + let mut guard = self.builder.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let builder = guard + .as_mut() + .ok_or_else(|| AthleticStandardError::Closed { detail: "this snapshot builder already finished".into() })?; + Ok(builder.add_batch(batch)? as u64) + } +} + #[uniffi::export] impl RecordSnapshotBuilder { #[uniffi::constructor] @@ -179,26 +83,25 @@ impl RecordSnapshotBuilder { Arc::new(RecordSnapshotBuilder { builder: Mutex::new(Some(calculate::SnapshotBuilder::new())) }) } - /// Add a batch: a UTF-8 JSON array of current records, the shape - /// `listRecords` returns, or an object that holds that array under - /// `records`, as the host's record list and `ath records list --json` do. + /// Add a batch of current records, such as those `listRecords` returns. /// Include sources, the athlete profile, and the samples a calculation /// reads. Deleted records may be included. Returns the number of records /// held after the batch. - pub fn add_records(&self, records: Vec) -> Result { + pub fn add_records(&self, records: Vec) -> Result { + self.add_batch(&Value::Array(records.iter().map(CurrentRecord::to_value).collect())) + } + + /// Add a batch given as UTF-8 JSON: an array of current records, or an + /// object that holds that array under `records`, as the host's record list + /// and `ath records list --json` do. + pub fn add_records_json(&self, records: Vec) -> Result { let mut batch = parse_json(&records)?; - // The host's record list and `ath records list --json` hold the array - // under `records`. if let json::Value::Object(map) = &mut batch { if let Some(list @ json::Value::Array(_)) = map.remove("records") { batch = list; } } - let mut guard = self.builder.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - let builder = guard - .as_mut() - .ok_or_else(|| AthleticStandardError::Closed { detail: "this snapshot builder already finished".into() })?; - Ok(builder.add_batch(&batch)? as u64) + self.add_batch(&batch) } /// The number of records added so far. @@ -231,12 +134,10 @@ impl RecordSnapshot { self.snapshot.len() as u64 } - /// Run a calculation skill on one current record: the `ath apply --json` - /// object as UTF-8 JSON. - pub fn apply(&self, record_id: String, skill: CalculationSkill) -> Result, AthleticStandardError> { + /// Run a calculation skill on one current record. + pub fn apply(&self, record_id: String, skill: CalculationSkill) -> Result { let text = skill.text()?; - let result = calculate::apply_text(&self.snapshot, &text, &record_id)?; - Ok(json::encode(&result).into_bytes()) + Ok(calculate::apply_text(&self.snapshot, &text, &record_id)?) } /// Run a calculation skill with the options of `ath apply --set`: a @@ -249,22 +150,19 @@ impl RecordSnapshot { record_id: Option, skill: CalculationSkill, parameters: HashMap, - ) -> Result, AthleticStandardError> { + ) -> Result { let text = skill.text()?; - let result = calculate::apply_with( + Ok(calculate::apply_with( &self.snapshot, &text, record_id.as_deref(), &crate::calculate::parameters(parameters), - )?; - Ok(json::encode(&result).into_bytes()) + )?) } - /// Run a named range calculation: the `ath calculate --json` receipt as - /// UTF-8 JSON. - pub fn calculate(&self, request: RangeRequest) -> Result, AthleticStandardError> { - let receipt = calculate::calculate_range(&self.snapshot, &request.options()?)?; - Ok(json::encode(&receipt).into_bytes()) + /// Run a named range calculation. + pub fn calculate(&self, request: CalculateOptions) -> Result { + Ok(calculate::calculate_range(&self.snapshot, &request)?) } } diff --git a/mobile/src/error.rs b/mobile/src/error.rs index 47d75013..c6dea0bb 100644 --- a/mobile/src/error.rs +++ b/mobile/src/error.rs @@ -23,9 +23,9 @@ pub enum AthleticStandardError { Stale { detail: String }, /// The operation is refused to protect data or files. Refused { detail: String }, - /// The database needs a migration first. `preview` is the desktop - /// migration preview as JSON. - MigrationRequired { detail: String, preview: Vec }, + /// The database needs a migration first. `preview` says what the + /// migration would do. + MigrationRequired { detail: String, preview: crate::records::MigrationPreview }, /// SQLite reported an error. Database { detail: String }, /// A file operation failed. diff --git a/mobile/src/lib.rs b/mobile/src/lib.rs index dc92d442..b59345a9 100644 --- a/mobile/src/lib.rs +++ b/mobile/src/lib.rs @@ -1,27 +1,42 @@ //! Athletic Standard for iPhone and Android apps (D325). //! -//! UniFFI generates the Swift and Kotlin bindings from this crate. Every rule -//! lives in Rust: this crate only turns calls and values into the generated -//! types. Record bodies and results cross as UTF-8 JSON bytes (D329). +//! UniFFI generates the Swift and Kotlin bindings from this crate and from the +//! core's record and result types, so every record shape and every +//! calculation answer is a Swift and a Kotlin type (D329). Every rule lives in +//! Rust: this crate only turns calls and values into the generated types. //! //! Without the `sqlite` feature the crate depends only on the storage-free //! core: it checks records and runs calculations on records the app supplies. //! With it, `Database` opens and edits `.ath.sqlite` files through the //! desktop store (D327). +// `AthleticStandardError::MigrationRequired` carries the whole migration +// preview, so an app can show it without another call. That makes the error +// type large. Errors cross to Swift or Kotlin once and are rare, so its size +// does not matter here. +#![allow(clippy::result_large_err)] + uniffi::setup_scaffolding!(); mod calculate; mod error; +mod records; #[cfg(feature = "sqlite")] mod store; mod validate; pub use calculate::{ - shipped_calculation_names, shipped_skill_text, CalculationSkill, RangeGroup, RangeOperation, RangeRecordKind, - RangeRequest, RecordSnapshot, RecordSnapshotBuilder, + shipped_calculation_names, shipped_skill_text, CalculationSkill, RecordSnapshot, RecordSnapshotBuilder, }; pub use error::{AthleticStandardError, PathSegment, ValidationIssue}; +pub use records::{ + apply_result_to_json, calculation_receipt_to_json, check_record_data, current_record_from_json, + current_record_to_json, current_records_from_json, extension_json, record_data_from_json, record_data_to_json, + record_history_from_json, record_revision_from_json, record_revision_to_json, record_type_from_name, + record_type_name, record_type_of, with_extension_json, CorrectedRecord, DeleteRequest, DeletedRecord, + ExpectedRevision, MigrationPreview, MigrationResult, MigrationStepPreview, NewRecord, RecordChanges, + RecordCorrection, RecordHistory, WrittenRecords, +}; #[cfg(feature = "sqlite")] pub use store::{ file_sha256, CreateDatabaseOptions, Database, DatabaseInfo, ListRecordsOptions, OpenDatabaseOptions, diff --git a/mobile/src/records.rs b/mobile/src/records.rs new file mode 100644 index 00000000..db1c5c44 --- /dev/null +++ b/mobile/src/records.rs @@ -0,0 +1,388 @@ +//! Records, writes, and results as Swift and Kotlin values (D329). +//! +//! The record types come from the core model, so Swift and Kotlin get one +//! generated type for each record shape. A write built from these values +//! becomes the npm client's JSON request and runs the same record operation, +//! so it gets the same checks and messages. JSON text stays available through +//! the converters below. + +use athleticstandard_core::calculate::{ApplyResult, CalculationReceipt}; +#[cfg(feature = "sqlite")] +use athleticstandard_core::json::Map; +use athleticstandard_core::json::{self, JsonObject, JsonValue, Value}; +use athleticstandard_core::model::{ + self, BecameKnownAtBasis, CurrentRecord, RecordActor, RecordData, RecordRevision, RecordType, +}; + +use crate::error::AthleticStandardError; +use crate::validate::parse_json; + +/// A record to write. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct NewRecord { + /// The record's data. Its case names the record type. + pub data: RecordData, + /// Who made the change. + pub changed_by: RecordActor, + /// The app's own values, under keys of its own domain, as one JSON object. + /// Set one with `with_extension_json`. + #[uniffi(default = None)] + pub extensions: Option, + /// A record ID the app chose. The library makes one when absent. + #[uniffi(default = None)] + pub record_id: Option, + /// When the record was created. Now when absent. + #[uniffi(default = None)] + pub created_at: Option, + /// When the information became known. `created_at` when absent. + #[uniffi(default = None)] + pub became_known_at: Option, + /// How `became_known_at` is known. `local_write` when absent. + #[uniffi(default = None)] + pub became_known_at_basis: Option, +} + +/// The revision a write expects a record to be at. A record at another +/// revision refuses the whole write with `Stale`. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct ExpectedRevision { + pub record_id: String, + pub revision: u64, +} + +/// A new revision of one record. The record keeps its type and ID. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct RecordCorrection { + pub record_id: String, + /// The revision the person edited. Another current revision refuses the + /// correction with `Stale` and changes nothing. + pub expected_revision: u64, + /// The complete new data, of the record's own type. + pub data: RecordData, + pub changed_by: RecordActor, + /// New extensions for the record. The current ones are kept when absent. + /// `write_record_changes` always keeps them. + #[uniffi(default = None)] + pub extensions: Option, + /// When the correction became known. Now when absent. + #[uniffi(default = None)] + pub became_known_at: Option, + /// How `became_known_at` is known. `local_write` when absent. + #[uniffi(default = None)] + pub became_known_at_basis: Option, +} + +/// A normal deletion. The record's history stays. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct DeleteRequest { + pub record_id: String, + /// The revision the person saw. Another current revision refuses the + /// deletion with `Stale`. + pub expected_revision: u64, + pub deleted_by: RecordActor, + /// When it was deleted. Now when absent. + #[uniffi(default = None)] + pub deleted_at: Option, +} + +/// Corrections and new records written in one change. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct RecordChanges { + #[uniffi(default = [])] + pub corrections: Vec, + #[uniffi(default = [])] + pub records: Vec, + #[uniffi(default = [])] + pub expected_current_revisions: Vec, +} + +/// What a write changed. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct WrittenRecords { + /// The records as written, in the order given. + pub records: Vec, + /// The database revision of the change. + pub database_revision: u64, +} + +/// The record a correction wrote. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct CorrectedRecord { + pub record: CurrentRecord, + pub database_revision: u64, +} + +/// What a deletion changed. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct DeletedRecord { + pub record_id: String, + /// The revision that was deleted. + pub record_revision: u64, + pub database_revision: u64, +} + +/// One step a migration runs. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct MigrationStepPreview { + pub target_sql_schema_version: u32, + pub migration_file: String, + pub description: String, +} + +/// What a migration would do. Reading it changes nothing. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct MigrationPreview { + pub migration_needed: bool, + pub source_sql_schema_version: u32, + pub target_sql_schema_version: u32, + pub database_id: String, + pub planned_steps: Vec, + /// Where the verified backup would go, when a migration can run. + pub planned_backup_path: Option, + /// What the migration means for older programs, as a person reads it. + pub compatibility_effect: String, +} + +/// What a migration did. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct MigrationResult { + /// The verified backup, or `None` when no migration was needed. + pub backup_path: Option, + pub migrated: bool, + pub preview: MigrationPreview, +} + +#[cfg(feature = "sqlite")] +impl NewRecord { + /// The npm client's `WriteRecordInput`. + pub(crate) fn to_input(&self) -> Value { + let mut input = Map::new(); + input.insert("record_type".into(), Value::String(self.data.record_type().as_str().into())); + input.insert("data".into(), self.data.to_value()); + input.insert("changed_by".into(), json::to_value(&self.changed_by)); + if let Some(extensions) = &self.extensions { + input.insert("extensions".into(), Value::Object(extensions.0.clone())); + } + insert_text(&mut input, "record_id", &self.record_id); + insert_text(&mut input, "created_at", &self.created_at); + insert_text(&mut input, "became_known_at", &self.became_known_at); + if let Some(basis) = self.became_known_at_basis { + input.insert("became_known_at_basis".into(), Value::String(basis.as_str().into())); + } + Value::Object(input) + } +} + +#[cfg(feature = "sqlite")] +impl RecordCorrection { + /// The npm client's `CorrectRecordInput`. + pub(crate) fn to_input(&self) -> Value { + let mut input = Map::new(); + input.insert("record_id".into(), Value::String(self.record_id.clone())); + input.insert("expected_revision".into(), Value::from(self.expected_revision)); + input.insert("data".into(), self.data.to_value()); + input.insert("changed_by".into(), json::to_value(&self.changed_by)); + if let Some(extensions) = &self.extensions { + input.insert("extensions".into(), Value::Object(extensions.0.clone())); + } + insert_text(&mut input, "became_known_at", &self.became_known_at); + if let Some(basis) = self.became_known_at_basis { + input.insert("became_known_at_basis".into(), Value::String(basis.as_str().into())); + } + Value::Object(input) + } +} + +#[cfg(feature = "sqlite")] +impl DeleteRequest { + /// The npm client's `DeleteRecordInput`. + pub(crate) fn to_input(&self) -> Value { + let mut input = Map::new(); + input.insert("record_id".into(), Value::String(self.record_id.clone())); + input.insert("expected_revision".into(), Value::from(self.expected_revision)); + input.insert("deleted_by".into(), json::to_value(&self.deleted_by)); + insert_text(&mut input, "deleted_at", &self.deleted_at); + Value::Object(input) + } +} + +#[cfg(feature = "sqlite")] +impl ExpectedRevision { + pub(crate) fn to_input(&self) -> Value { + let mut input = Map::new(); + input.insert("record_id".into(), Value::String(self.record_id.clone())); + input.insert("revision".into(), Value::from(self.revision)); + Value::Object(input) + } +} + +#[cfg(feature = "sqlite")] +fn insert_text(input: &mut Map, key: &str, value: &Option) { + if let Some(value) = value { + input.insert(key.into(), Value::String(value.clone())); + } +} + +#[cfg(feature = "sqlite")] +/// The records of a write's JSON output, decoded. +pub(crate) fn records_of(value: &Value) -> Result, AthleticStandardError> { + value + .as_array() + .ok_or_else(|| AthleticStandardError::Failed { detail: "a write returned no record list".into() })? + .iter() + .map(|record| Ok(CurrentRecord::from_value(record)?)) + .collect() +} + +#[cfg(feature = "sqlite")] +pub(crate) fn whole(value: &Value, key: &str) -> u64 { + value.get(key).and_then(Value::as_u64).unwrap_or_default() +} + +/// A current record from its JSON text, as `listRecords`, a host, or a +/// package holds it. The record is checked as a complete current record. +#[uniffi::export] +pub fn current_record_from_json(json: Vec) -> Result { + Ok(CurrentRecord::from_value(&parse_json(&json)?)?) +} + +/// Current records from UTF-8 JSON: an array of current records, or an object +/// that holds that array under `records`, as the host's record list and +/// `ath records list --json` do. Every record is checked. +#[uniffi::export] +pub fn current_records_from_json(json: Vec) -> Result, AthleticStandardError> { + let mut list = parse_json(&json)?; + if let Value::Object(map) = &mut list { + if let Some(records @ Value::Array(_)) = map.remove("records") { + list = records; + } + } + let Value::Array(items) = list else { + return Err(AthleticStandardError::malformed("expected an array of current records".to_string())); + }; + Ok(items.iter().map(CurrentRecord::from_value).collect::>()?) +} + +/// One record with every retained revision, oldest first. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct RecordHistory { + pub record: CurrentRecord, + pub revisions: Vec, +} + +/// A record and its history from the host's UTF-8 JSON reply: +/// `{"record": {...}, "revisions": [...]}`. +#[uniffi::export] +pub fn record_history_from_json(json: Vec) -> Result { + let value = parse_json(&json)?; + let Some(Value::Array(revisions)) = value.get("revisions") else { + return Err(AthleticStandardError::malformed("expected a record and its revisions".to_string())); + }; + Ok(RecordHistory { + record: CurrentRecord::from_value(&value["record"])?, + revisions: revisions.iter().map(RecordRevision::from_value).collect::>()?, + }) +} + +/// The stored name of a record type, such as `workout_session`. +#[uniffi::export] +pub fn record_type_name(record_type: RecordType) -> String { + record_type.as_str().to_string() +} + +/// The record type a stored name names, or `None` for an unknown name. +#[uniffi::export] +pub fn record_type_from_name(name: String) -> Option { + RecordType::parse(&name) +} + +/// The record type of `data`. +#[uniffi::export] +pub fn record_type_of(data: RecordData) -> RecordType { + data.record_type() +} + +/// A current record as UTF-8 JSON, with its fields in published order. +#[uniffi::export] +pub fn current_record_to_json(record: CurrentRecord) -> Vec { + json::to_string(&record.to_value()).into_bytes() +} + +/// A retained revision from its JSON text. +#[uniffi::export] +pub fn record_revision_from_json(json: Vec) -> Result { + Ok(RecordRevision::from_value(&parse_json(&json)?)?) +} + +/// A retained revision as UTF-8 JSON. +#[uniffi::export] +pub fn record_revision_to_json(revision: RecordRevision) -> Vec { + json::to_string(&revision.to_value()).into_bytes() +} + +/// One record type's data from its JSON text, checked against the type's +/// shape and rules. +#[uniffi::export] +pub fn record_data_from_json(record_type: RecordType, json: Vec) -> Result { + Ok(RecordData::decode(record_type, &parse_json(&json)?)?) +} + +/// A record's data as UTF-8 JSON, with its fields in published order. +#[uniffi::export] +pub fn record_data_to_json(data: RecordData) -> Vec { + json::to_string(&data.to_value()).into_bytes() +} + +/// Check record data against its type's shape and rules without writing it, +/// for example while a person fills in a form. Throws `Invalid` with every +/// issue, as a write would. +#[uniffi::export] +pub fn check_record_data(data: RecordData) -> Result<(), AthleticStandardError> { + RecordData::decode(data.record_type(), &data.to_value())?; + Ok(()) +} + +/// A calculation result as the `ath apply --json` object in UTF-8 JSON. +#[uniffi::export] +pub fn apply_result_to_json(result: ApplyResult) -> Vec { + json::encode(&result).into_bytes() +} + +/// A range calculation's receipt as the `ath calculate --json` object in +/// UTF-8 JSON. +#[uniffi::export] +pub fn calculation_receipt_to_json(receipt: CalculationReceipt) -> Vec { + json::encode(&receipt).into_bytes() +} + +/// The JSON text an app stored under `key` in a record's extensions, or +/// `None` when the key is absent. Swift and Kotlin decode it into the app's +/// own type. +#[uniffi::export] +pub fn extension_json(extensions: Option, key: String) -> Result, AthleticStandardError> { + check_extension_key(&key)?; + Ok(extensions.and_then(|extensions| extensions.get(&key).cloned()).map(JsonValue)) +} + +/// The extensions with `value`, the JSON text of the app's own value, stored +/// under `key`. Other keys and their order stay. The key is a name of the +/// app's own domain written backwards, such as `com.example.myapp/notes`, and +/// the result is checked against the format's limits for extensions. +#[uniffi::export] +pub fn with_extension_json( + extensions: Option, + key: String, + value: JsonValue, +) -> Result { + check_extension_key(&key)?; + let mut extensions = extensions.unwrap_or_default(); + extensions.insert(key, value.0); + let checked = Value::Object(extensions.0.clone()); + model::extensions::record_extensions().validate(&checked)?; + Ok(extensions) +} + +fn check_extension_key(key: &str) -> Result<(), AthleticStandardError> { + model::extension_id().validate(&Value::String(key.to_string()))?; + Ok(()) +} diff --git a/mobile/src/store.rs b/mobile/src/store.rs index a9f96685..36645f5a 100644 --- a/mobile/src/store.rs +++ b/mobile/src/store.rs @@ -24,8 +24,15 @@ use athleticstandard::store::{CreateOptions, OpenOptions, Store}; use athleticstandard::Error; use sha2::{Digest, Sha256}; -use crate::calculate::{CalculationSkill, RangeRequest}; +use athleticstandard_core::calculate::{ApplyResult, CalculateOptions, CalculationReceipt}; +use athleticstandard_core::model::{CurrentRecord, RecordRevision, RecordType}; + +use crate::calculate::CalculationSkill; use crate::error::AthleticStandardError; +use crate::records::{ + records_of, whole, CorrectedRecord, DeleteRequest, DeletedRecord, ExpectedRevision, MigrationPreview, + MigrationResult, MigrationStepPreview, NewRecord, RecordChanges, RecordCorrection, WrittenRecords, +}; use crate::validate::parse_json; impl From for AthleticStandardError { @@ -36,10 +43,9 @@ impl From for AthleticStandardError { Error::NotFound(_) => AthleticStandardError::NotFound { detail }, Error::Stale(_) => AthleticStandardError::Stale { detail }, Error::Refused(_) => AthleticStandardError::Refused { detail }, - Error::MigrationRequired(preview) => AthleticStandardError::MigrationRequired { - detail, - preview: json::to_string(&json::to_value(preview.as_ref())).into_bytes(), - }, + Error::MigrationRequired(preview) => { + AthleticStandardError::MigrationRequired { detail, preview: preview.as_ref().into() } + } Error::Database(_) => AthleticStandardError::Database { detail }, Error::Io(_) => AthleticStandardError::Io { detail }, Error::Other(_) => AthleticStandardError::Failed { detail }, @@ -59,6 +65,28 @@ impl From for AthleticStandardError { } } +impl From<&athleticstandard::store::migrate::MigrationPreview> for MigrationPreview { + fn from(preview: &athleticstandard::store::migrate::MigrationPreview) -> Self { + MigrationPreview { + migration_needed: preview.migration_needed, + source_sql_schema_version: preview.source_sql_schema_version, + target_sql_schema_version: preview.target_sql_schema_version, + database_id: preview.database_id.clone(), + planned_steps: preview + .planned_steps + .iter() + .map(|step| MigrationStepPreview { + target_sql_schema_version: step.target_sql_schema_version, + migration_file: step.migration_file.clone(), + description: step.description.clone(), + }) + .collect(), + planned_backup_path: preview.planned_backup_path.clone(), + compatibility_effect: preview.compatibility_effect.clone(), + } + } +} + /// How to open a database. #[derive(Debug, Clone, uniffi::Record)] pub struct OpenDatabaseOptions { @@ -102,9 +130,9 @@ pub struct DatabaseInfo { /// Which current records to list. #[derive(Debug, Clone, uniffi::Record)] pub struct ListRecordsOptions { - /// A record type, such as `workout_session`. All types when absent. + /// One record type. All types when absent. #[uniffi(default = None)] - pub record_type: Option, + pub record_type: Option, #[uniffi(default = false)] pub include_deleted: bool, /// From 1 to 10,000. The desktop default, 100, when absent. @@ -218,16 +246,6 @@ impl Database { Ok(output) }) } - - fn json_operation(&self, name: &str, request: &[u8]) -> Result, AthleticStandardError> { - let input = parse_json(request)?; - Ok(json::to_string(&self.operation(name, input)?.output).into_bytes()) - } - - fn items_operation(&self, name: &str, input: Value) -> Result, AthleticStandardError> { - let output = self.operation(name, input)?; - Ok(json::to_string(&Value::Array(output.items)).into_bytes()) - } } #[uniffi::export] @@ -288,64 +306,108 @@ impl Database { }) } - /// The current record with this ID as UTF-8 JSON, or `None`. - pub fn get_record(&self, record_id: String) -> Result>, AthleticStandardError> { + /// The current record with this ID, or `None`. + pub fn get_record(&self, record_id: String) -> Result, AthleticStandardError> { let mut input = json::Map::new(); input.insert("record_id".into(), Value::String(record_id)); let output = self.operation("records.read", Value::Object(input))?.output; - Ok((!output.is_null()).then(|| json::to_string(&output).into_bytes())) + if output.is_null() { + return Ok(None); + } + Ok(Some(CurrentRecord::from_value(&output)?)) } - /// Current records in creation order, as a UTF-8 JSON array. - pub fn list_records(&self, options: ListRecordsOptions) -> Result, AthleticStandardError> { + /// Current records in creation order. + pub fn list_records(&self, options: ListRecordsOptions) -> Result, AthleticStandardError> { let mut input = json::Map::new(); if let Some(record_type) = options.record_type { - input.insert("record_type".into(), Value::String(record_type)); + input.insert("record_type".into(), Value::String(record_type.as_str().into())); } input.insert("include_deleted".into(), Value::Bool(options.include_deleted)); if let Some(limit) = options.limit { input.insert("limit".into(), Value::from(limit)); } - self.items_operation("records.list", Value::Object(input)) + let items = self.operation("records.list", Value::Object(input))?.items; + Ok(items.iter().map(CurrentRecord::from_value).collect::>()?) } - /// Every retained revision of a record, oldest first, as a UTF-8 JSON array. - pub fn record_revisions(&self, record_id: String) -> Result, AthleticStandardError> { + /// Every retained revision of a record, oldest first. + pub fn record_revisions(&self, record_id: String) -> Result, AthleticStandardError> { let mut input = json::Map::new(); input.insert("record_id".into(), Value::String(record_id)); - self.items_operation("records.revisions", Value::Object(input)) + let items = self.operation("records.revisions", Value::Object(input))?.items; + Ok(items.iter().map(RecordRevision::from_value).collect::>()?) } - /// Write new records in one change: the npm client's `writeRecords` input - /// and output, as UTF-8 JSON. - pub fn write_records(&self, request: Vec) -> Result, AthleticStandardError> { - self.json_operation("records.write", &request) + /// Write new records in one change, the npm client's `writeRecords`. A + /// record in `expected_current_revisions` at another revision refuses the + /// whole write with `Stale`. + #[uniffi::method(default(expected_current_revisions = []))] + pub fn write_records( + &self, + records: Vec, + expected_current_revisions: Vec, + ) -> Result { + let mut input = json::Map::new(); + input.insert("inputs".into(), Value::Array(records.iter().map(NewRecord::to_input).collect())); + input.insert( + "expected_current_revisions".into(), + Value::Array(expected_current_revisions.iter().map(ExpectedRevision::to_input).collect()), + ); + let output = self.operation("records.write", Value::Object(input))?.output; + Ok(WrittenRecords { + records: records_of(&output["records"])?, + database_revision: whole(&output, "database_revision"), + }) } - /// Corrections and new records in one change: `writeRecordChanges`. - pub fn write_record_changes(&self, request: Vec) -> Result, AthleticStandardError> { - self.json_operation("records.write_changes", &request) + /// Corrections and new records in one change, the npm client's + /// `writeRecordChanges`. A correction here keeps the record's extensions. + pub fn write_record_changes(&self, changes: RecordChanges) -> Result { + let mut input = json::Map::new(); + input.insert( + "corrections".into(), + Value::Array(changes.corrections.iter().map(RecordCorrection::to_input).collect()), + ); + input.insert("records".into(), Value::Array(changes.records.iter().map(NewRecord::to_input).collect())); + input.insert( + "expected_current_revisions".into(), + Value::Array(changes.expected_current_revisions.iter().map(ExpectedRevision::to_input).collect()), + ); + let output = self.operation("records.write_changes", Value::Object(input))?.output; + Ok(WrittenRecords { + records: records_of(&output["records"])?, + database_revision: whole(&output, "database_revision"), + }) } - /// A new revision of one record: `correctRecord`. A correction whose - /// `expected_revision` is not current is refused with `Stale`. - pub fn correct_record(&self, request: Vec) -> Result, AthleticStandardError> { - self.json_operation("records.correct", &request) + /// A new revision of one record, the npm client's `correctRecord`. A + /// correction whose `expected_revision` is not current is refused with + /// `Stale` and changes nothing. + pub fn correct_record(&self, correction: RecordCorrection) -> Result { + let output = self.operation("records.correct", correction.to_input())?.output; + Ok(CorrectedRecord { + record: CurrentRecord::from_value(&output["record"])?, + database_revision: whole(&output, "database_revision"), + }) } - /// A normal deletion that keeps history: `deleteRecord`. - pub fn delete_record(&self, request: Vec) -> Result, AthleticStandardError> { - self.json_operation("records.delete", &request) + /// A normal deletion that keeps history, the npm client's `deleteRecord`. + pub fn delete_record(&self, deletion: DeleteRequest) -> Result { + let output = self.operation("records.delete", deletion.to_input())?.output; + Ok(DeletedRecord { + record_id: output["record_id"].as_str().unwrap_or_default().to_string(), + record_revision: whole(&output, "record_revision"), + database_revision: whole(&output, "database_revision"), + }) } /// Run a calculation skill on one current record of this file, inside one - /// read snapshot: the `ath apply --json` object as UTF-8 JSON. - pub fn apply(&self, record_id: String, skill: CalculationSkill) -> Result, AthleticStandardError> { + /// read snapshot. The result is the `ath apply --json` object. + pub fn apply(&self, record_id: String, skill: CalculationSkill) -> Result { let text = skill.text()?; self.with_store(|store| { - let result = - athleticstandard::calculate::apply_text(store.as_ref().expect("checked open"), &text, &record_id)?; - Ok(json::encode(&result).into_bytes()) + Ok(athleticstandard::calculate::apply_text(store.as_ref().expect("checked open"), &text, &record_id)?) }) } @@ -358,28 +420,24 @@ impl Database { record_id: Option, skill: CalculationSkill, parameters: HashMap, - ) -> Result, AthleticStandardError> { + ) -> Result { let text = skill.text()?; let parameters = crate::calculate::parameters(parameters); self.with_store(|store| { - let result = athleticstandard::calculate::apply_text_with( + Ok(athleticstandard::calculate::apply_text_with( store.as_ref().expect("checked open"), &text, record_id.as_deref(), ¶meters, - )?; - Ok(json::encode(&result).into_bytes()) + )?) }) } - /// Run a named range calculation on this file, inside one read snapshot: - /// the `ath calculate --json` receipt as UTF-8 JSON. - pub fn calculate(&self, request: RangeRequest) -> Result, AthleticStandardError> { - let options = request.options()?; + /// Run a named range calculation on this file, inside one read snapshot. + /// The receipt is the `ath calculate --json` object. + pub fn calculate(&self, request: CalculateOptions) -> Result { self.with_store(|store| { - let receipt = - athleticstandard::calculate::calculate_range(store.as_ref().expect("checked open"), &options)?; - Ok(json::encode(&receipt).into_bytes()) + Ok(athleticstandard::calculate::calculate_range(store.as_ref().expect("checked open"), &request)?) }) } @@ -399,20 +457,20 @@ impl Database { }) } - /// The migration this database needs, as the desktop preview in UTF-8 - /// JSON. Open with `allow_outdated_schema` to read it. - pub fn migration_preview(&self) -> Result, AthleticStandardError> { + /// The migration this database needs, as the desktop previews it. Open + /// with `allow_outdated_schema` to read it. + pub fn migration_preview(&self) -> Result { self.with_store(|store| { let preview = athleticstandard::store::migrate::migration_preview(store.as_ref().expect("checked open"), None)?; - Ok(json::to_string(&json::to_value(&preview)).into_bytes()) + Ok((&preview).into()) }) } /// Make a verified backup at `backup_path`, then apply every pending /// migration step in one transaction. The desktop rules apply: no backup, /// no migration. - pub fn migrate(&self, backup_path: String) -> Result, AthleticStandardError> { + pub fn migrate(&self, backup_path: String) -> Result { self.with_store(|store| { let store = store.as_mut().expect("checked open"); let options = athleticstandard::store::migrate::MigrationOptions { @@ -420,7 +478,11 @@ impl Database { now_millis: None, }; let result = athleticstandard::store::migrate::execute_confirmed_migration(store, &options)?; - Ok(json::to_string(&json::to_value(&result)).into_bytes()) + Ok(MigrationResult { + backup_path: result.backup_path.clone(), + migrated: result.migrated, + preview: (&result.preview).into(), + }) }) } diff --git a/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift b/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift index bcdf3808..671f8b0a 100644 --- a/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift +++ b/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift @@ -39,22 +39,30 @@ final class Example: ObservableObject { : try Database.create(path: file.path, options: CreateDatabaseOptions()) defer { try? database.close() } if !exists { - let source = #"{"inputs":[{"record_type":"source","data":{"source_type":"manual","data_writer":"Athletic Standard example","data_route":"manual_entry"},"changed_by":{"author_type":"athlete"}}]}"# - _ = try database.writeRecords(request: Data(source.utf8)) + let source = SourceData( + sourceType: .manual, dataWriter: "Athletic Standard example", dataRoute: "manual_entry") + _ = try database.writeRecords(records: [NewRecord(data: .source(source), changedBy: .athlete)]) } - let sources = try JSONSerialization.jsonObject( - with: try database.listRecords(options: ListRecordsOptions(recordType: "source"))) as? [[String: Any]] - let sourceID = sources?.first?["record_id"] as? String ?? "" + let sourceID = try database.listRecords(options: ListRecordsOptions(recordType: .source)).first?.recordId ?? "" let now = ISO8601DateFormatter.withMilliseconds().string(from: Date()) - let reading = #"{"inputs":[{"record_type":"point_measurement","data":{"source_id":"\#(sourceID)","received_at":"\#(now)","received_at_basis":"local_write_time","quantity":"hrv_rmssd","recorded_at":"\#(now)","input_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"value":{"standard_value":\#(50 + Int.random(in: 0..<15)),"standard_unit":"ms","input_value_missing_reason":"not_provided_by_source","input_unit_missing_reason":"not_provided_by_source"}},"changed_by":{"author_type":"athlete"}}]}"# - let written = try JSONSerialization.jsonObject(with: try database.writeRecords(request: Data(reading.utf8))) - let recordID = ((written as? [String: Any])?["records"] as? [[String: Any]])?.first?["record_id"] as? String - let change = try database.apply(recordId: recordID ?? "", skill: .shipped(name: "hrv-change")) + let reading = PointMeasurementData( + sourceId: sourceID, receivedAt: now, receivedAtBasis: .localWriteTime, quantity: .hrvRmssd, + recordedAt: now, + inputTimestamp: InputTimestampReceipt( + timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource), + value: SourceValue( + standardValue: Double(50 + Int.random(in: 0..<15)), standardUnit: "ms", + inputValueMissingReason: .notProvidedBySource, inputUnitMissingReason: .notProvidedBySource)) + let written = try database.writeRecords(records: [ + NewRecord(data: .pointMeasurement(reading), changedBy: .athlete) + ]) + let recordID = written.records.first?.recordId ?? "" + let change = try database.apply(recordId: recordID, skill: .shipped(name: "hrv-change")) output = """ Athletic Standard \(libraryVersion()) \(file.path) database revision \(try database.info().databaseRevision) - hrv-change: \(String(decoding: change, as: UTF8.self)) + hrv-change: \(String(decoding: applyResultToJson(result: change), as: UTF8.self)) """ } catch { output = "Could not work on the local file: \(error)" @@ -92,10 +100,10 @@ final class Example: ObservableObject { } else { athlete = try await host.createAthlete(displayName: "Example athlete").athleteID } - let records = try JSONSerialization.jsonObject(with: try await host.recordsJSON(athleteID: athlete)) - let count = ((records as? [String: Any])?["records"] as? [Any])?.count ?? 0 - let source = Data(#"{"source_type":"manual","data_writer":"Athletic Standard example","data_route":"manual_entry"}"#.utf8) - let write = try host.prepareRecordCreation(athleteID: athlete, recordType: "source", data: source) + let count = try await host.records(athleteID: athlete).count + let source = SourceData( + sourceType: .manual, dataWriter: "Athletic Standard example", dataRoute: "manual_entry") + let write = try host.prepareRecordCreation(athleteID: athlete, data: .source(source)) let saved = try await host.send(write) output = """ Signed in to \(hostURL.absoluteString) diff --git a/mobile/swift/Package.swift b/mobile/swift/Package.swift index 48d7820e..f4d55bf2 100644 --- a/mobile/swift/Package.swift +++ b/mobile/swift/Package.swift @@ -21,15 +21,15 @@ let package = Package( dependencies: ["AthleticStandardFFI"], linkerSettings: [.linkedFramework("CoreFoundation"), .linkedLibrary("iconv")] ), - // The optional client for ath-host, with browser sign-in (D330). It needs no - // native library, and local files never need it. - .target(name: "AthleticStandardHost"), + // The optional client for ath-host, with browser sign-in (D330). Local files + // never need it. It reads and writes the generated record types. + .target(name: "AthleticStandardHost", dependencies: ["AthleticStandard"]), // The runnable example (`swift run AthleticStandardExample` on a Mac). Releases // do not carry it. .executableTarget( name: "AthleticStandardExample", dependencies: ["AthleticStandard", "AthleticStandardHost"], path: "Examples/AthleticStandardExample"), .testTarget(name: "AthleticStandardTests", dependencies: ["AthleticStandard"]), - .testTarget(name: "AthleticStandardHostTests", dependencies: ["AthleticStandardHost"]), + .testTarget(name: "AthleticStandardHostTests", dependencies: ["AthleticStandard", "AthleticStandardHost"]), ] ) diff --git a/mobile/swift/Sources/AthleticStandard/RecordExtensions.swift b/mobile/swift/Sources/AthleticStandard/RecordExtensions.swift new file mode 100644 index 00000000..08efc67c --- /dev/null +++ b/mobile/swift/Sources/AthleticStandard/RecordExtensions.swift @@ -0,0 +1,72 @@ +import Foundation + +/// An app's own values on a record, read and written with the app's own `Codable` +/// types (D329). +/// +/// An extension is stored on a record under a key the app owns: its domain name +/// written backwards, then a name, such as `com.example.myapp/notes`. The library +/// checks the key and the format's limits for extensions when a value is set, and +/// again when the record is written. The app's type decides what the value holds. +/// +/// ```swift +/// struct Notes: Codable { var mood: String } +/// +/// var record = NewRecord(data: data, changedBy: .athlete) +/// try record.setExtension(Notes(mood: "rested"), forKey: "com.example.myapp/notes") +/// +/// let notes = try current.extensionValue(Notes.self, forKey: "com.example.myapp/notes") +/// ``` +public enum RecordExtensions { + /// The value stored under `key`, decoded as `type`, or `nil` when the key is + /// absent. Throws `AthleticStandardError.invalid` for a key that is not an + /// extension key, and the decoder's error when the value does not fit `type`. + public static func value( + _ type: T.Type, forKey key: String, in extensions: JsonObject?, decoder: JSONDecoder = JSONDecoder() + ) throws -> T? { + guard let text = try extensionJson(extensions: extensions, key: key) else { return nil } + return try decoder.decode(T.self, from: Data(text.utf8)) + } + + /// `extensions` with `value` stored under `key`. Other keys keep their values + /// and order. Throws `AthleticStandardError.invalid` when the key or the result + /// breaks the format's rules for extensions. + public static func setting( + _ value: T, forKey key: String, in extensions: JsonObject?, encoder: JSONEncoder = JSONEncoder() + ) throws -> JsonObject { + let text = String(decoding: try encoder.encode(value), as: UTF8.self) + return try withExtensionJson(extensions: extensions, key: key, value: text) + } +} + +extension CurrentRecord { + /// The app's value stored under `key` on this record, or `nil` when the key is + /// absent. See `RecordExtensions`. + public func extensionValue(_ type: T.Type, forKey key: String) throws -> T? { + try RecordExtensions.value(type, forKey: key, in: extensions) + } +} + +extension RecordRevision { + /// The app's value stored under `key` on this revision, or `nil` when the key is + /// absent. See `RecordExtensions`. + public func extensionValue(_ type: T.Type, forKey key: String) throws -> T? { + try RecordExtensions.value(type, forKey: key, in: extensions) + } +} + +extension NewRecord { + /// Store the app's `value` under `key` on the record to be written. See + /// `RecordExtensions`. + public mutating func setExtension(_ value: T, forKey key: String) throws { + extensions = try RecordExtensions.setting(value, forKey: key, in: extensions) + } +} + +extension RecordCorrection { + /// Store the app's `value` under `key` on the corrected record. Start from the + /// current record's extensions to keep its other keys. A correction without + /// extensions keeps the record's extensions as they are. See `RecordExtensions`. + public mutating func setExtension(_ value: T, forKey key: String) throws { + extensions = try RecordExtensions.setting(value, forKey: key, in: extensions) + } +} diff --git a/mobile/swift/Sources/AthleticStandardHost/TypedRecords.swift b/mobile/swift/Sources/AthleticStandardHost/TypedRecords.swift new file mode 100644 index 00000000..f0ea2b7c --- /dev/null +++ b/mobile/swift/Sources/AthleticStandardHost/TypedRecords.swift @@ -0,0 +1,43 @@ +import AthleticStandard +import Foundation + +/// Reads and writes with the generated record types (D329). Each call sends the +/// same request as its JSON form, and checks the host's reply as complete records. +extension HostClient { + /// Current records, oldest first. The host caps `limit` at its page size. + public func records(athleteID: String, recordType: RecordType? = nil, limit: Int? = nil) async throws + -> [CurrentRecord] + { + let name = recordType.map { recordTypeName(recordType: $0) } + return try currentRecordsFromJson(json: try await recordsJSON(athleteID: athleteID, recordType: name, limit: limit)) + } + + /// One record and every retained revision, oldest first. + public func record(athleteID: String, recordID: String) async throws -> RecordHistory { + try recordHistoryFromJson(json: try await recordJSON(athleteID: athleteID, recordID: recordID)) + } + + /// A new record. The case of `data` names the record type. Keep the returned + /// write until the host answers, and send it again unchanged after a lost + /// reply (D261). + public func prepareRecordCreation( + athleteID: String, data: RecordData, recordID: String? = nil, attachments: [String] = [], + idempotencyKey: String = UUID().uuidString + ) throws -> PreparedWrite { + try prepareRecordCreation( + athleteID: athleteID, recordType: recordTypeName(recordType: recordTypeOf(data: data)), + data: recordDataToJson(data: data), recordID: recordID, attachments: attachments, + idempotencyKey: idempotencyKey) + } + + /// A correction of `record`: the complete new data, at the revision the person + /// edited. If the record changed since, the host answers `stale` and writes + /// nothing; keep the person's edit for review. + public func prepareCorrection( + athleteID: String, record: CurrentRecord, data: RecordData, idempotencyKey: String = UUID().uuidString + ) throws -> PreparedWrite { + try prepareCorrection( + athleteID: athleteID, recordID: record.recordId, expectedRevision: Int(record.currentRevision), + data: recordDataToJson(data: data), idempotencyKey: idempotencyKey) + } +} diff --git a/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift b/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift index 8f97636a..d216b2ad 100644 --- a/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift +++ b/mobile/swift/Tests/AthleticStandardHostTests/HostTests.swift @@ -1,3 +1,4 @@ +import AthleticStandard import AthleticStandardHost import Foundation import Testing @@ -112,8 +113,29 @@ struct HostTests { let records = try JSONSerialization.jsonObject(with: try await client.recordsJSON(athleteID: created.athleteID)) #expect(((records as? [String: Any])?["records"] as? [Any])?.count == 1) + + // The same reads and writes with the generated record types. + let current = try #require(try await client.records(athleteID: created.athleteID).first) + #expect(current.recordId == sourceID) + guard case var .source(source) = current.data else { + Issue.record("expected a source") + return + } + #expect(source.dataWriter == "Example Band 2") + source.dataWriter = "Example Band 3" + let typed = try client.prepareCorrection(athleteID: created.athleteID, record: current, data: .source(source)) + #expect(try await client.send(typed).records.first?.revision == 3) + let history = try await client.record(athleteID: created.athleteID, recordID: sourceID) + #expect(history.record.currentRevision == 3) + #expect(history.revisions.map(\.revision) == [1, 2, 3]) + let manual = RecordData.source( + SourceData(sourceType: .manual, dataWriter: "Example app", dataRoute: "manual_entry")) + let added = try await client.send(try client.prepareRecordCreation(athleteID: created.athleteID, data: manual)) + let sources = try await client.records(athleteID: created.athleteID, recordType: .source) + #expect(sources.map(\.recordId) == [sourceID, try #require(added.records.first?.recordID)]) + let changes = try await client.changes(athleteID: created.athleteID, since: 0) - #expect(changes.changes.count == 2) + #expect(changes.changes.count == 4) let export = try await client.export(athleteID: created.athleteID) #expect(export.zip.starts(with: [0x50, 0x4b])) } diff --git a/mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift b/mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift index 286471e2..9b3e9098 100644 --- a/mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift +++ b/mobile/swift/Tests/AthleticStandardTests/CalculationTests.swift @@ -8,7 +8,7 @@ import Testing /// device recordings, so the snapshot must give exactly that refusal. @Suite(.serialized) struct CalculationTests { - static func operation(_ name: String) -> RangeOperation { + static func operation(_ name: String) -> CalculationOperation { switch name { case "summary": .summary case "baseline": .baseline @@ -21,7 +21,7 @@ struct CalculationTests { } } - static func recordKind(_ name: String) -> RangeRecordKind { + static func recordKind(_ name: String) -> CalculationRecordKind { switch name { case "measurement": .measurement case "provider-score": .providerScore @@ -30,7 +30,7 @@ struct CalculationTests { } } - static func group(_ name: String) -> RangeGroup { + static func group(_ name: String) -> CalculationGroup { switch name { case "none": .ungrouped case "day": .day @@ -39,15 +39,28 @@ struct CalculationTests { } } + static func periodType(_ name: String?) -> ProviderReportingPeriodType? { + switch name { + case nil: nil + case "whoop_physiological_cycle": .whoopPhysiologicalCycle + case "oura_activity_day": .ouraActivityDay + case "oura_sleep_day": .ouraSleepDay + case "oura_calendar_day": .ouraCalendarDay + case "oura_day_unspecified": .ouraDayUnspecified + default: .appleActivitySummaryDay + } + } + static func rangeRequest(_ fields: [String: Any]) -> RangeRequest { RangeRequest( operation: operation(fields["operation"] as! String), quantity: fields["quantity"] as! String, - recordKind: recordKind(fields["record_kind"] as! String), group: group(fields["group"] as! String), - from: fields["from"] as? String, to: fields["to"] as? String, timeZone: fields["time_zone"] as? String, + recordKind: recordKind(fields["record_kind"] as! String), + providerPeriodType: periodType(fields["provider_period_type"] as? String), sourceId: fields["source_id"] as? String, compareSourceId: fields["compare_source_id"] as? String, otherQuantity: fields["other_quantity"] as? String, - workoutSessionId: fields["workout_session_id"] as? String, - providerPeriodType: fields["provider_period_type"] as? String) + workoutSessionId: fields["workout_session_id"] as? String, from: fields["from"] as? String, + to: fields["to"] as? String, timeZone: fields["time_zone"] as? String, + group: group(fields["group"] as! String)) } /// `ok ` or `error ` from a bundle's expected outcome. @@ -59,10 +72,21 @@ struct CalculationTests { return "error \(error["code"]!) \(error["detail"]!)" } - /// `ok ` or `error `, the same for both entry points. - static func outcome(_ body: () throws -> Data) -> String { + /// `ok ` or `error `, the same for both entry points. The + /// typed answer is turned back into the desktop JSON, so the comparison is exact. + static func outcome(_ body: () throws -> ApplyResult) -> String { + do { + return "ok " + String(decoding: applyResultToJson(result: try body()), as: UTF8.self) + } catch let error as AthleticStandardError { + return "error \(error.code) \(error.detail)" + } catch { + return "unexpected \(error)" + } + } + + static func outcome(_ body: () throws -> CalculationReceipt) -> String { do { - return "ok " + String(decoding: try body(), as: UTF8.self) + return "ok " + String(decoding: calculationReceiptToJson(receipt: try body()), as: UTF8.self) } catch let error as AthleticStandardError { return "error \(error.code) \(error.detail)" } catch { @@ -82,7 +106,7 @@ struct CalculationTests { let name = item["name"] as! String let builder = RecordSnapshotBuilder() for batch in item["record_batches"] as! [String] { - _ = try builder.addRecords(records: Data(batch.utf8)) + _ = try builder.addRecordsJson(records: Data(batch.utf8)) } #expect(builder.recordCount() == UInt64(item["record_count"] as! Int)) let snapshot = try builder.finish() @@ -136,6 +160,34 @@ struct CalculationTests { #expect(failures.isEmpty, "\(failures.prefix(10).joined(separator: "\n"))") } + @Test func typedRecordsGiveTypedAnswers() throws { + let database = try StoreTests.create(try StoreTests.folder().appendingPathComponent("athlete.ath.sqlite")) + try StoreTests.writeWorkout(database) + func reading(_ value: Double, at time: String) -> NewRecord { + let data = PointMeasurementData( + sourceId: StoreTests.sourceID, receivedAt: time, receivedAtBasis: .importTime, quantity: .hrvRmssd, + recordedAt: time, inputTimestamp: StoreTests.notReported, + value: SourceValue( + standardValue: value, standardUnit: "ms", inputValueMissingReason: .notProvidedBySource, + inputUnitMissingReason: .notProvidedBySource)) + return NewRecord(data: .pointMeasurement(data), changedBy: .athlete) + } + _ = try database.writeRecords(records: [ + reading(50, at: "2026-01-03T06:00:00.000Z"), reading(60, at: "2026-01-04T06:00:00.000Z"), + ]) + let builder = RecordSnapshotBuilder() + #expect(try builder.addRecords(records: try database.listRecords(options: ListRecordsOptions())) == 4) + let snapshot = try builder.finish() + let request = RangeRequest( + operation: .summary, quantity: "hrv_rmssd", recordKind: .measurement, timeZone: "UTC", group: .ungrouped) + let memory = try snapshot.calculate(request: request) + let file = try database.calculate(request: request) + #expect(memory == file) + #expect(memory.operation == .summary) + #expect(memory.unit == "ms") + #expect(memory.input.recordCount == 2) + } + @Test func shippedSkillsAreListed() { let names = shippedCalculationNames() #expect(names.contains("hrv-change")) @@ -147,7 +199,7 @@ struct CalculationTests { @Test func aRefusedBatchLeavesTheBuilderAsItWas() throws { let builder = RecordSnapshotBuilder() do { - _ = try builder.addRecords(records: Data(#"[{"record_id":"x"}]"#.utf8)) + _ = try builder.addRecordsJson(records: Data(#"[{"record_id":"x"}]"#.utf8)) Issue.record("an invalid batch was accepted") } catch let error as AthleticStandardError { #expect(error.code == "invalid") diff --git a/mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift b/mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift index 54afbb34..01875510 100644 --- a/mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift +++ b/mobile/swift/Tests/AthleticStandardTests/DocumentTests.swift @@ -18,8 +18,7 @@ struct DocumentTests { } static func endAt(_ database: Database) throws -> String? { - let record = try StoreTests.object(try #require(try database.getRecord(recordId: StoreTests.workoutID))) - return (record["data"] as? [String: Any])?["end_at"] as? String + try StoreTests.endAt(database) } @Test func editSaveAndReopen() throws { diff --git a/mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift b/mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift index 1fae257c..77121f5c 100644 --- a/mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift +++ b/mobile/swift/Tests/AthleticStandardTests/RoundTripTests.swift @@ -13,7 +13,9 @@ import Testing struct RoundTripTests { @Test func desktopFileEditedOnThePhone() throws { let desktop = try FixtureBundle.file("roundtrip/desktop.ath.sqlite") - let facts = try StoreTests.object(try Data(contentsOf: try FixtureBundle.file("roundtrip/desktop.json"))) + let facts = try #require( + try JSONSerialization.jsonObject(with: Data(contentsOf: try FixtureBundle.file("roundtrip/desktop.json"))) + as? [String: Any]) let recordID = try #require(facts["record_id"] as? String) let databaseID = try #require(facts["database_id"] as? String) let out = try #require( @@ -28,25 +30,24 @@ struct RoundTripTests { let working = try StoreTests.folder() let picked = try PickedDocument.open(documentURL: document, workingFolder: working) #expect(try picked.database.info().databaseId == databaseID) - var record = try StoreTests.object(try #require(try picked.database.getRecord(recordId: recordID))) - #expect(record["current_revision"] as? Int == 1) - var data = try #require(record["data"] as? [String: Any]) - var value = try #require(data["value"] as? [String: Any]) - value["standard_value"] = 63 - value["input_value"] = 63 - data["value"] = value - let request: [String: Any] = [ - "record_id": recordID, "expected_revision": 1, "data": data, - "changed_by": ["author_type": "athlete"], - ] - _ = try picked.database.correctRecord(request: try JSONSerialization.data(withJSONObject: request)) + let record = try #require(try picked.database.getRecord(recordId: recordID)) + #expect(record.currentRevision == 1) + guard case var .pointMeasurement(measurement) = record.data else { + Issue.record("expected a point measurement") + return + } + measurement.value.standardValue = 63 + measurement.value.inputValue = 63 + _ = try picked.database.correctRecord( + correction: RecordCorrection( + recordId: recordID, expectedRevision: record.currentRevision, data: .pointMeasurement(measurement), + changedBy: .athlete)) // Close the working copy and resume it, as after the app restarts. let state = picked.state try picked.close(removingWorkingCopy: false) let resumed = try PickedDocument.resume(state) - record = try StoreTests.object(try #require(try resumed.database.getRecord(recordId: recordID))) - #expect(record["current_revision"] as? Int == 2) + #expect(try resumed.database.getRecord(recordId: recordID)?.currentRevision == 2) #expect(try resumed.hasUnsavedEdits()) let saved = try resumed.save() #expect(saved.sha256 == (try fileSha256(path: document.path))) diff --git a/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift b/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift index 2e2266f4..d027a450 100644 --- a/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift +++ b/mobile/swift/Tests/AthleticStandardTests/StoreTests.swift @@ -2,11 +2,13 @@ import AthleticStandard import Foundation import Testing -/// The storage steps mobile/tests/store.rs runs, through the Swift package (D327). +/// The storage steps mobile/tests/store.rs runs, through the Swift package, with +/// the generated record types (D327, D329). @Suite(.serialized) struct StoreTests { static let sourceID = "01890f3e-e7d3-7cc0-88c8-000000000003" static let workoutID = "01890f3e-e7d3-7cc0-88c8-000000000064" + static let createdAt = "2026-01-02T03:04:05.678Z" static func folder() throws -> URL { let url = FileManager.default.temporaryDirectory @@ -15,30 +17,52 @@ struct StoreTests { return url } - static func workoutData(endAt: String) -> String { - #"{"source_id":"\#(sourceID)","received_at":"2026-01-02T03:04:05.678Z","received_at_basis":"import_time","start_at":"2026-01-02T03:04:05.678Z","end_at":"\#(endAt)","input_start_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"input_end_timestamp":{"timestamp_missing_reason":"not_provided_by_source","utc_offset_missing_reason":"not_provided_by_source"},"source_reported_summaries":[]}"# + /// A timestamp the source did not report. + static let notReported = InputTimestampReceipt( + timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource) + + static func workoutData(endAt: String) -> RecordData { + .workoutSession( + WorkoutSessionData( + sourceId: sourceID, receivedAt: createdAt, receivedAtBasis: .importTime, startAt: createdAt, + endAt: endAt, inputStartTimestamp: notReported, inputEndTimestamp: notReported, + sourceReportedSummaries: [])) } static func create(_ url: URL) throws -> Database { try Database.create( path: url.path, - options: CreateDatabaseOptions( - databaseId: "01890f3e-e7d3-7cc0-88c8-0000000000aa", createdAt: "2026-01-02T03:04:05.678Z")) + options: CreateDatabaseOptions(databaseId: "01890f3e-e7d3-7cc0-88c8-0000000000aa", createdAt: createdAt)) } - static func writeWorkout(_ database: Database) throws { - let request = #"{"inputs":[{"record_id":"\#(sourceID)","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","data":{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"},"changed_by":{"author_type":"athlete"}},{"record_id":"\#(workoutID)","record_type":"workout_session","created_at":"2026-01-02T03:04:05.678Z","data":\#(workoutData(endAt: "2026-01-02T04:04:05.678Z")),"changed_by":{"author_type":"athlete"}}]}"# - _ = try database.writeRecords(request: Data(request.utf8)) + @discardableResult + static func writeWorkout(_ database: Database) throws -> WrittenRecords { + let source = RecordData.source( + SourceData(sourceType: .wearable, dataWriter: "Example Band", dataRoute: "provider_export")) + return try database.writeRecords(records: [ + NewRecord(data: source, changedBy: .athlete, recordId: sourceID, createdAt: createdAt), + NewRecord( + data: workoutData(endAt: "2026-01-02T04:04:05.678Z"), changedBy: .athlete, recordId: workoutID, + createdAt: createdAt), + ]) } @discardableResult - static func correctWorkout(_ database: Database, expectedRevision: Int, endAt: String) throws -> Data { - let request = #"{"record_id":"\#(workoutID)","expected_revision":\#(expectedRevision),"data":\#(workoutData(endAt: endAt)),"changed_by":{"author_type":"athlete"},"became_known_at":"2026-01-03T00:00:00.000Z"}"# - return try database.correctRecord(request: Data(request.utf8)) + static func correctWorkout(_ database: Database, expectedRevision: UInt64, endAt: String) throws + -> CorrectedRecord + { + try database.correctRecord( + correction: RecordCorrection( + recordId: workoutID, expectedRevision: expectedRevision, data: workoutData(endAt: endAt), + changedBy: .athlete, becameKnownAt: "2026-01-03T00:00:00.000Z")) } - static func object(_ data: Data) throws -> [String: Any] { - try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + /// The workout's end time, read through the typed record. + static func endAt(_ database: Database) throws -> String? { + guard case let .workoutSession(workout) = try database.getRecord(recordId: workoutID)?.data else { + return nil + } + return workout.endAt } @Test func createEditCloseAndReopen() throws { @@ -46,22 +70,51 @@ struct StoreTests { let database = try Self.create(url) #expect(try database.info().databaseRevision == 0) #expect(try database.info().writable) - try Self.writeWorkout(database) - try Self.correctWorkout(database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + let written = try Self.writeWorkout(database) + #expect(written.records.map(\.recordId) == [Self.sourceID, Self.workoutID]) + #expect(written.databaseRevision == 1) + let corrected = try Self.correctWorkout(database, expectedRevision: 1, endAt: "2026-01-02T04:30:05.678Z") + #expect(corrected.record.currentRevision == 2) #expect(try database.info().databaseRevision == 2) try database.close() #expect(database.isClosed()) #expect(throws: AthleticStandardError.self) { try database.info() } let reopened = try Database.open(path: url.path, options: OpenDatabaseOptions()) - let record = try Self.object(try #require(try reopened.getRecord(recordId: Self.workoutID))) - #expect(record["current_revision"] as? Int == 2) - #expect((record["data"] as? [String: Any])?["end_at"] as? String == "2026-01-02T04:30:05.678Z") - let revisions = try JSONSerialization.jsonObject(with: try reopened.recordRevisions(recordId: Self.workoutID)) - #expect((revisions as? [Any])?.count == 2) + let record = try #require(try reopened.getRecord(recordId: Self.workoutID)) + #expect(record.currentRevision == 2) + #expect(try Self.endAt(reopened) == "2026-01-02T04:30:05.678Z") + let revisions = try reopened.recordRevisions(recordId: Self.workoutID) + #expect(revisions.map(\.revision) == [1, 2]) + #expect(revisions.last?.becameKnownAt == "2026-01-03T00:00:00.000Z") + let sources = try reopened.listRecords(options: ListRecordsOptions(recordType: .source)) + #expect(sources.map(\.recordId) == [Self.sourceID]) try reopened.close() } + @Test func aRecordChangesThroughItsTypedFields() throws { + let database = try Self.create(try Self.folder().appendingPathComponent("athlete.ath.sqlite")) + try Self.writeWorkout(database) + let current = try #require(try database.getRecord(recordId: Self.workoutID)) + guard case var .workoutSession(workout) = current.data else { + Issue.record("expected a workout session") + return + } + workout.name = "Morning row" + workout.activityType = "rowing" + _ = try database.correctRecord( + correction: RecordCorrection( + recordId: current.recordId, expectedRevision: current.currentRevision, + data: .workoutSession(workout), changedBy: .athlete)) + guard case let .workoutSession(saved) = try database.getRecord(recordId: Self.workoutID)?.data else { + Issue.record("expected a workout session") + return + } + #expect(saved.name == "Morning row") + #expect(saved.activityType == "rowing") + #expect(saved.endAt == workout.endAt) + } + @Test func staleCorrectionIsRefused() throws { let database = try Self.create(try Self.folder().appendingPathComponent("athlete.ath.sqlite")) try Self.writeWorkout(database) @@ -76,6 +129,24 @@ struct StoreTests { #expect(try database.info().databaseRevision == 2) } + @Test func anInvalidEditReturnsTheDesktopIssues() throws { + let database = try Self.create(try Self.folder().appendingPathComponent("athlete.ath.sqlite")) + try Self.writeWorkout(database) + do { + try Self.correctWorkout(database, expectedRevision: 1, endAt: "2026-01-01T00:00:00.000Z") + Issue.record("a workout that ends before it starts was accepted") + } catch let error as AthleticStandardError { + #expect(error.code == "invalid") + #expect(error.detail == "data.end_at: Workout session end cannot precede its start") + #expect(error.issues.map(\.pathText) == ["data.end_at"]) + } + // The same check runs before a write, for a form that is still open. + #expect(throws: AthleticStandardError.self) { + try checkRecordData(data: Self.workoutData(endAt: "2026-01-01T00:00:00.000Z")) + } + try checkRecordData(data: Self.workoutData(endAt: "2026-01-02T04:04:05.678Z")) + } + @Test func readOnlyOpenRefusesWrites() throws { let url = try Self.folder().appendingPathComponent("athlete.ath.sqlite") let database = try Self.create(url) @@ -91,6 +162,19 @@ struct StoreTests { } } + @Test func aDeletionKeepsHistory() throws { + let database = try Self.create(try Self.folder().appendingPathComponent("athlete.ath.sqlite")) + try Self.writeWorkout(database) + let deleted = try database.deleteRecord( + deletion: DeleteRequest(recordId: Self.workoutID, expectedRevision: 1, deletedBy: .athlete)) + #expect(deleted.recordRevision == 1) + #expect(try database.getRecord(recordId: Self.workoutID)?.isDeleted == true) + #expect(try database.recordRevisions(recordId: Self.workoutID).first?.revision == 1) + #expect(try database.listRecords(options: ListRecordsOptions(recordType: .workoutSession)).isEmpty) + let all = try database.listRecords(options: ListRecordsOptions(recordType: .workoutSession, includeDeleted: true)) + #expect(all.map(\.recordId) == [Self.workoutID]) + } + @Test func outdatedFileNeedsMigrationWithBackup() throws { let fixture = try FixtureBundle.file("outdated-2-1-0.ath.sqlite") let folder = try Self.folder() @@ -101,11 +185,17 @@ struct StoreTests { Issue.record("an outdated database opened without a migration") } catch let error as AthleticStandardError { #expect(error.code == "migration_required") + guard case let .MigrationRequired(_, preview) = error else { return } + #expect(preview.migrationNeeded) + #expect(!preview.plannedSteps.isEmpty) } let outdated = try Database.open(path: url.path, options: OpenDatabaseOptions(allowOutdatedSchema: true)) + #expect(try outdated.migrationPreview().targetSqlSchemaVersion > 0) let backup = folder.appendingPathComponent("before-migration.ath.sqlite") - let result = try Self.object(try outdated.migrate(backupPath: backup.path)) - #expect(result["migrated"] as? Bool == true) + let result = try outdated.migrate(backupPath: backup.path) + #expect(result.migrated) + let backupPath = try #require(result.backupPath) + #expect(URL(fileURLWithPath: backupPath).resolvingSymlinksInPath() == backup.resolvingSymlinksInPath()) try outdated.close() #expect(FileManager.default.fileExists(atPath: backup.path)) let migrated = try Database.open(path: url.path, options: OpenDatabaseOptions()) @@ -125,7 +215,78 @@ struct StoreTests { #expect(saved.sha256 == (try fileSha256(path: saved.path))) #expect(!FileManager.default.fileExists(atPath: saved.path + "-wal")) let copy = try Database.open(path: saved.path, options: OpenDatabaseOptions(readOnly: true)) - let record = try Self.object(try #require(try copy.getRecord(recordId: Self.workoutID))) - #expect(record["current_revision"] as? Int == 2) + #expect(try copy.getRecord(recordId: Self.workoutID)?.currentRevision == 2) + } + + @Test func recordsConvertToAndFromTheirJson() throws { + let database = try Self.create(try Self.folder().appendingPathComponent("athlete.ath.sqlite")) + try Self.writeWorkout(database) + let record = try #require(try database.getRecord(recordId: Self.workoutID)) + let json = currentRecordToJson(record: record) + let object = try #require(try JSONSerialization.jsonObject(with: json) as? [String: Any]) + #expect(object["record_type"] as? String == "workout_session") + #expect(try currentRecordFromJson(json: json) == record) + let data = try recordDataFromJson(recordType: .workoutSession, json: recordDataToJson(data: record.data)) + #expect(data == record.data) + } +} + +/// An app's own values on a record (D329). +@Suite(.serialized) +struct ExtensionTests { + struct Notes: Codable, Equatable { + var mood: String + var hoursSlept: Double + } + + static let key = "com.example.myapp/notes" + + @Test func anAppValueIsWrittenAndReadBack() throws { + let database = try StoreTests.create(try StoreTests.folder().appendingPathComponent("athlete.ath.sqlite")) + try StoreTests.writeWorkout(database) + let current = try #require(try database.getRecord(recordId: StoreTests.workoutID)) + #expect(try current.extensionValue(Notes.self, forKey: Self.key) == nil) + + var correction = RecordCorrection( + recordId: current.recordId, expectedRevision: current.currentRevision, data: current.data, + changedBy: .athlete, extensions: current.extensions) + try correction.setExtension(Notes(mood: "rested", hoursSlept: 7.5), forKey: Self.key) + _ = try database.correctRecord(correction: correction) + + let saved = try #require(try database.getRecord(recordId: StoreTests.workoutID)) + #expect(try saved.extensionValue(Notes.self, forKey: Self.key) == Notes(mood: "rested", hoursSlept: 7.5)) + // A later correction without extensions keeps them. + _ = try database.correctRecord( + correction: RecordCorrection( + recordId: saved.recordId, expectedRevision: saved.currentRevision, data: saved.data, + changedBy: .athlete)) + let kept = try #require(try database.getRecord(recordId: StoreTests.workoutID)) + #expect(try kept.extensionValue(Notes.self, forKey: Self.key)?.mood == "rested") + } + + @Test func aNewRecordCarriesAnAppValue() throws { + let database = try StoreTests.create(try StoreTests.folder().appendingPathComponent("athlete.ath.sqlite")) + var record = NewRecord( + data: .source(SourceData(sourceType: .manual, dataWriter: "Example", dataRoute: "manual_entry")), + changedBy: .athlete) + try record.setExtension(["colour": "blue"], forKey: "com.example.myapp/display") + let written = try database.writeRecords(records: [record]) + let stored = try #require(written.records.first) + #expect(try stored.extensionValue([String: String].self, forKey: "com.example.myapp/display") == ["colour": "blue"]) + } + + @Test func aKeyOutsideTheAppsOwnNameIsRefused() { + var record = NewRecord( + data: .source(SourceData(sourceType: .manual, dataWriter: "Example", dataRoute: "manual_entry")), + changedBy: .athlete) + do { + try record.setExtension("value", forKey: "notes") + Issue.record("a key without a domain was accepted") + } catch let error as AthleticStandardError { + #expect(error.code == "invalid") + } catch { + Issue.record("unexpected error \(error)") + } + #expect(record.extensions == nil) } } diff --git a/mobile/tests/fixtures.rs b/mobile/tests/fixtures.rs index 14aabf3d..516d386f 100644 --- a/mobile/tests/fixtures.rs +++ b/mobile/tests/fixtures.rs @@ -9,9 +9,14 @@ //! skipped with their documented reason, and the counts. A phone run must skip //! exactly the listed cases and match every other one. +// The library's error type is large because a migration failure carries the +// whole preview (see the note in src/lib.rs). +#![allow(clippy::result_large_err)] + use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; +use athleticstandard_core::calculate::{ApplyResult, CalculateOptions, CalculationReceipt}; use athleticstandard_core::json::{self, Map, Value}; use athleticstandard_mobile::{validate, AthleticStandardError, PathSegment}; @@ -265,20 +270,23 @@ fn memory_refusal(request: &Value) -> Option<(String, String)> { )) } -/// Run a phone request through a binding entry point. -/// A request without parameters on one record runs through `apply`; any -/// other runs through `apply_with`. +/// Run a phone request through a binding entry point, and give the result as +/// the desktop JSON text. A request without parameters on one record runs +/// through `apply`; any other runs through `apply_with`. fn calculation_outcome( request: &Value, - apply: impl Fn(String, athleticstandard_mobile::CalculationSkill) -> Result, AthleticStandardError>, + apply: impl Fn(String, athleticstandard_mobile::CalculationSkill) -> Result, apply_with: impl Fn( Option, athleticstandard_mobile::CalculationSkill, HashMap, - ) -> Result, AthleticStandardError>, - calculate: impl Fn(athleticstandard_mobile::RangeRequest) -> Result, AthleticStandardError>, + ) -> Result, + calculate: impl Fn(CalculateOptions) -> Result, ) -> Result { - use athleticstandard_mobile::{CalculationSkill, RangeGroup, RangeOperation, RangeRecordKind, RangeRequest}; + use athleticstandard_core::calculate::{Group, Operation, RecordKind}; + use athleticstandard_core::model::ProviderReportingPeriodType; + use athleticstandard_mobile::CalculationSkill; + let text_of = |bytes: Vec| String::from_utf8(bytes).unwrap(); let result = if request["kind"].as_str() == Some("apply") { let skill = match request["skill"].get("shipped").and_then(Value::as_str) { Some(name) => CalculationSkill::Shipped { name: name.into() }, @@ -295,49 +303,28 @@ fn calculation_outcome( Some(record_id) if parameters.is_empty() => apply(record_id, skill), record_id => apply_with(record_id, skill, parameters), } + .map(|result| text_of(athleticstandard_mobile::apply_result_to_json(result))) } else { let fields = &request["request"]; let text = |key: &str| fields[key].as_str().map(str::to_string); - let operation = match fields["operation"].as_str().unwrap() { - "summary" => RangeOperation::Summary, - "baseline" => RangeOperation::Baseline, - "trend" => RangeOperation::Trend, - "coverage" => RangeOperation::Coverage, - "compare-sources" => RangeOperation::CompareSources, - "correlation" => RangeOperation::Correlation, - "workout-drift" => RangeOperation::WorkoutDrift, - _ => RangeOperation::ProviderPeriodSummary, - }; - let record_kind = match fields["record_kind"].as_str().unwrap() { - "measurement" => RangeRecordKind::Measurement, - "provider-score" => RangeRecordKind::ProviderScore, - "provider-summary" => RangeRecordKind::ProviderSummary, - _ => RangeRecordKind::SessionSummary, - }; - let group = match fields["group"].as_str().unwrap() { - "none" => RangeGroup::Ungrouped, - "day" => RangeGroup::Day, - "week" => RangeGroup::Week, - _ => RangeGroup::Month, - }; - calculate(RangeRequest { - operation, + calculate(CalculateOptions { + operation: Operation::parse(fields["operation"].as_str().unwrap()).unwrap(), quantity: text("quantity").unwrap(), - record_kind, - group, - from: text("from"), - to: text("to"), - time_zone: text("time_zone"), + record_kind: RecordKind::parse(fields["record_kind"].as_str().unwrap()).unwrap(), + provider_period_type: text("provider_period_type") + .map(|name| ProviderReportingPeriodType::parse(&name).unwrap()), source_id: text("source_id"), compare_source_id: text("compare_source_id"), other_quantity: text("other_quantity"), workout_session_id: text("workout_session_id"), - provider_period_type: text("provider_period_type"), + from: text("from"), + to: text("to"), + time_zone: text("time_zone"), + group: Group::parse(fields["group"].as_str().unwrap()).unwrap(), }) + .map(|receipt| text_of(athleticstandard_mobile::calculation_receipt_to_json(receipt))) }; - result - .map(|bytes| String::from_utf8(bytes).unwrap()) - .map_err(|error| (error.code().to_string(), error.detail().to_string())) + result.map_err(|error| (error.code().to_string(), error.detail().to_string())) } /// `{"output": }` or `{"error": {"code", "detail"}}`. @@ -421,7 +408,7 @@ fn every_calculation_case_runs_through_the_binding() { json::to_string(&Value::Array(items[half..].to_vec())), ]; for batch in &batches { - builder.add_records(batch.clone().into_bytes()).unwrap(); + builder.add_records_json(batch.clone().into_bytes()).unwrap(); } let snapshot = builder.finish().unwrap(); let database = Database::open( diff --git a/mobile/tests/store.rs b/mobile/tests/store.rs index 464d6990..47c47642 100644 --- a/mobile/tests/store.rs +++ b/mobile/tests/store.rs @@ -2,12 +2,17 @@ //! //! The Swift and Kotlin tests run the same steps through the packages. +// The library's error type is large because a migration failure carries the +// whole preview (see the note in src/lib.rs). +#![allow(clippy::result_large_err)] + use std::path::{Path, PathBuf}; use athleticstandard::store::{OpenOptions, Store, SQL_SCHEMA_VERSION}; -use athleticstandard_core::json::{self, Value}; +use athleticstandard_core::model::{RecordActor, RecordData, RecordType}; use athleticstandard_mobile::{ - AthleticStandardError, CreateDatabaseOptions, Database, ListRecordsOptions, OpenDatabaseOptions, + AthleticStandardError, CorrectedRecord, CreateDatabaseOptions, Database, ListRecordsOptions, NewRecord, + OpenDatabaseOptions, RecordCorrection, WrittenRecords, }; const SOURCE_ID: &str = "01890f3e-e7d3-7cc0-88c8-000000000003"; @@ -30,29 +35,52 @@ fn workout_data(end_at: &str) -> String { ) } +/// Record data built without a check, as a Swift or Kotlin app builds a typed +/// value. The library checks it when it is written. +fn data(record_type: RecordType, text: &str) -> RecordData { + match record_type { + RecordType::Source => RecordData::Source(serde_json::from_str(text).unwrap()), + RecordType::WorkoutSession => RecordData::WorkoutSession(serde_json::from_str(text).unwrap()), + other => panic!("no test data for {other}"), + } +} + +fn new_record(record_id: &str, data: RecordData) -> NewRecord { + NewRecord { + data, + changed_by: RecordActor::Athlete, + extensions: None, + record_id: Some(record_id.into()), + created_at: Some("2026-01-02T03:04:05.678Z".into()), + became_known_at: None, + became_known_at_basis: None, + } +} + /// A source and one workout from it, written in one change. -fn write_workout(database: &Database) -> Value { - let request = format!( - r#"{{"inputs":[{{"record_id":"{SOURCE_ID}","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","data":{{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"}},"changed_by":{{"author_type":"athlete"}}}},{{"record_id":"{WORKOUT_ID}","record_type":"workout_session","created_at":"2026-01-02T03:04:05.678Z","data":{},"changed_by":{{"author_type":"athlete"}}}}]}}"#, - workout_data("2026-01-02T04:04:05.678Z") +fn write_workout(database: &Database) -> WrittenRecords { + let source = data( + RecordType::Source, + r#"{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"}"#, ); - parse(database.write_records(request.into_bytes()).unwrap()) + let workout = data(RecordType::WorkoutSession, &workout_data("2026-01-02T04:04:05.678Z")); + database.write_records(vec![new_record(SOURCE_ID, source), new_record(WORKOUT_ID, workout)], Vec::new()).unwrap() } fn correct_workout( database: &Database, expected_revision: u64, end_at: &str, -) -> Result, AthleticStandardError> { - let request = format!( - r#"{{"record_id":"{WORKOUT_ID}","expected_revision":{expected_revision},"data":{},"changed_by":{{"author_type":"athlete"}},"became_known_at":"2026-01-03T00:00:00.000Z"}}"#, - workout_data(end_at) - ); - database.correct_record(request.into_bytes()) -} - -fn parse(bytes: Vec) -> Value { - json::parse(std::str::from_utf8(&bytes).unwrap()).unwrap() +) -> Result { + database.correct_record(RecordCorrection { + record_id: WORKOUT_ID.into(), + expected_revision, + data: data(RecordType::WorkoutSession, &workout_data(end_at)), + changed_by: RecordActor::Athlete, + extensions: None, + became_known_at: Some("2026-01-03T00:00:00.000Z".into()), + became_known_at_basis: None, + }) } /// A path in the test's folder. The folder is resolved, as the desktop store @@ -72,30 +100,33 @@ fn create_edit_close_and_reopen() { assert!(info.writable); let written = write_workout(&database); - assert_eq!(written["database_revision"], Value::from(1)); - let corrected = parse(correct_workout(&database, 1, "2026-01-02T04:30:05.678Z").unwrap()); - assert_eq!(corrected["record"]["current_revision"], Value::from(2)); + assert_eq!(written.database_revision, 1); + assert_eq!( + written.records.iter().map(|record| record.record_id.as_str()).collect::>(), + [SOURCE_ID, WORKOUT_ID] + ); + let corrected = correct_workout(&database, 1, "2026-01-02T04:30:05.678Z").unwrap(); + assert_eq!(corrected.record.current_revision, 2); assert_eq!(database.info().unwrap().database_revision, 2); database.close().unwrap(); assert!(database.is_closed()); assert!(matches!(database.info(), Err(AthleticStandardError::Closed { .. }))); let reopened = Database::open(path.clone(), open_options()).unwrap(); - let record = parse(reopened.get_record(WORKOUT_ID.into()).unwrap().unwrap()); - assert_eq!(record["current_revision"], Value::from(2)); - assert_eq!(record["data"]["end_at"], Value::from("2026-01-02T04:30:05.678Z")); - let revisions = parse(reopened.record_revisions(WORKOUT_ID.into()).unwrap()); - assert_eq!(revisions.as_array().unwrap().len(), 2); - let listed = parse( - reopened - .list_records(ListRecordsOptions { - record_type: Some("workout_session".into()), - include_deleted: false, - limit: None, - }) - .unwrap(), - ); - assert_eq!(listed.as_array().unwrap().len(), 1); + let record = reopened.get_record(WORKOUT_ID.into()).unwrap().unwrap(); + assert_eq!(record.current_revision, 2); + let RecordData::WorkoutSession(workout) = &record.data else { panic!("expected a workout") }; + assert_eq!(workout.end_at, "2026-01-02T04:30:05.678Z"); + let revisions = reopened.record_revisions(WORKOUT_ID.into()).unwrap(); + assert_eq!(revisions.iter().map(|revision| revision.revision).collect::>(), [1, 2]); + let listed = reopened + .list_records(ListRecordsOptions { + record_type: Some(RecordType::WorkoutSession), + include_deleted: false, + limit: None, + }) + .unwrap(); + assert_eq!(listed.len(), 1); assert_eq!(reopened.get_record("01890f3e-e7d3-7cc0-88c8-0000000000ff".into()).unwrap(), None); reopened.close().unwrap(); @@ -176,18 +207,17 @@ fn an_outdated_file_needs_a_migration_with_a_verified_backup() { let path = outdated_copy(folder.path()); let error = Database::open(path.clone(), open_options()).err().unwrap(); let AthleticStandardError::MigrationRequired { preview, .. } = error else { panic!("expected a migration") }; - let preview = parse(preview); - assert_eq!(preview["target_sql_schema_version"], Value::from(SQL_SCHEMA_VERSION)); + assert_eq!(preview.target_sql_schema_version, SQL_SCHEMA_VERSION); let outdated = Database::open(path.clone(), OpenDatabaseOptions { allow_outdated_schema: true, ..open_options() }).unwrap(); - let preview = parse(outdated.migration_preview().unwrap()); - assert!(preview["source_sql_schema_version"].as_u64().unwrap() < u64::from(SQL_SCHEMA_VERSION)); + let preview = outdated.migration_preview().unwrap(); + assert!(preview.source_sql_schema_version < SQL_SCHEMA_VERSION); let backup = path_in(folder.path(), "before-migration.ath.sqlite"); - let result = parse(outdated.migrate(backup.clone()).unwrap()); - assert_eq!(result["migrated"], Value::Bool(true), "{result:?}"); + let result = outdated.migrate(backup.clone()).unwrap(); + assert!(result.migrated, "{result:?}"); // Compare the file name, so the check holds with either path separator. - let backup_path = Path::new(result["backup_path"].as_str().unwrap()); + let backup_path = Path::new(result.backup_path.as_deref().unwrap()); assert_eq!(backup_path.file_name(), Some(std::ffi::OsStr::new("before-migration.ath.sqlite")), "{result:?}"); outdated.close().unwrap(); assert!(Path::new(&backup).exists()); diff --git a/mobile/uniffi.toml b/mobile/uniffi.toml index b7e5aafd..e13de774 100644 --- a/mobile/uniffi.toml +++ b/mobile/uniffi.toml @@ -5,7 +5,10 @@ module_name = "AthleticStandard" ffi_module_name = "AthleticStandardFFI" ffi_module_filename = "AthleticStandardFFI" -generate_immutable_records = true +# Swift records keep `var` fields, so app code can change one field of a copy. +# Kotlin records are read-only; change a field with `copy(...)`. +# Lists of allowed values list their cases, for pickers. +generate_case_iterable_conformance = true [bindings.kotlin] package_name = "ai.athleticstandard" diff --git a/src/calculate/mod.rs b/src/calculate/mod.rs index 2e90c3ca..23caf45e 100644 --- a/src/calculate/mod.rs +++ b/src/calculate/mod.rs @@ -102,7 +102,7 @@ pub fn result_record(result: &ApplyResult, file_text: &str) -> Result { let mut numbers = Vec::new(); - flatten("", &outcome.result, &mut numbers); + flatten("", &crate::json::to_value(&outcome.result), &mut numbers); if let Some(labels) = &outcome.labels { flatten("", &crate::json::to_value(labels), &mut numbers); } diff --git a/src/calculate/window.rs b/src/calculate/window.rs index 31307fe6..a0aedd79 100644 --- a/src/calculate/window.rs +++ b/src/calculate/window.rs @@ -29,7 +29,8 @@ use crate::model::{time, EvidenceReference, ReadingValue, RecordingQuantity}; use rusqlite::Connection; pub use athleticstandard_core::calculate::window::{ - is_threshold_operation, needs_record, ReferenceToSave, ThresholdOutcome, ThresholdRequest, ThresholdRun, + is_threshold_operation, needs_record, ReferenceToSave, ThresholdOutcome, ThresholdRequest, ThresholdResult, + ThresholdRun, }; fn serialized(value: &T) -> Value { @@ -183,10 +184,10 @@ fn run_inner( }; return Ok(Ok(ThresholdOutcome { operation: operation.into(), - parameters: params.used, + parameters: params.used.into_iter().collect(), period_start: None, period_end: Some(end_date.clone()), - result: serialized(&outcome), + result: outcome.clone().into(), efforts: Vec::new(), labels: None, confirm_before_saving: vec![ @@ -227,19 +228,20 @@ fn run_inner( evidence.push(workout.reference.clone()); evidence.extend(workout.recordings.iter().map(|recording| recording.reference.clone())); } - let base = |references: Vec, result: Value, efforts: Vec, labels, confirm| { - ThresholdOutcome { - operation: operation.into(), - parameters: BTreeMap::new(), - period_start: Some(period_start.clone()), - period_end: Some(end_date.clone()), - result, - efforts, - labels, - confirm_before_saving: confirm, - references_to_save: references, - } - }; + let base = + |references: Vec, result: ThresholdResult, efforts: Vec, labels, confirm| { + ThresholdOutcome { + operation: operation.into(), + parameters: Default::default(), + period_start: Some(period_start.clone()), + period_end: Some(end_date.clone()), + result, + efforts, + labels, + confirm_before_saving: confirm, + references_to_save: references, + } + }; let reference = |quantity: &str, value: f64, unit: &str, basis: &str, references: Vec| ReferenceToSave { quantity: quantity.into(), @@ -276,7 +278,7 @@ fn run_inner( } else { t::best_5_second_power(&inputs) }); - let (workout, recording) = recordings[found.recording_index]; + let (workout, recording) = recordings[found.recording_index as usize]; let mut outcome = base( vec![reference( "peak_power", @@ -285,12 +287,12 @@ fn run_inner( "recorded", vec![workout.reference.clone(), recording.reference.clone()], )], - serialized(&found), + found.clone().into(), Vec::new(), None, vec!["The effort was a full sprint, not a burst inside a ride.".into()], ); - outcome.parameters = params.used; + outcome.parameters = params.used.into_iter().collect(); return Ok(Ok(outcome)); } let durations: Vec = match params.text("durations_s") { @@ -341,10 +343,10 @@ fn run_inner( let best_mean = efforts.first().map(|effort| effort.effort.mean); let (value, result) = if operation == t::FRACTION_OF_BEST_20_MINUTE_POWER { let result = refuse!(t::fraction_of_best_20_minute_power(best_mean, fraction)); - (result.threshold_power, serialized(&result)) + (result.threshold_power, result.clone().into()) } else { let result = refuse!(t::fraction_of_best_8_minute_power(best_mean, fraction)); - (result.threshold_power, serialized(&result)) + (result.threshold_power, result.clone().into()) }; base( vec![reference("threshold_power", value, "W", "model", effort_evidence)], @@ -358,7 +360,7 @@ fn run_inner( let (threshold, capacity, acceptable, result) = match op { t::CRITICAL_POWER_THREE_PARAMETER => { let r = refuse!(t::critical_power_three_parameter(&best)); - (r.threshold_power, r.work_capacity_above_threshold, r.fit_acceptable, serialized(&r)) + (r.threshold_power, r.work_capacity_above_threshold, r.fit_acceptable, r.clone().into()) } _ => { let r = refuse!(match op { @@ -366,7 +368,7 @@ fn run_inner( t::CRITICAL_POWER_LINEAR_INVERSE_TIME => t::critical_power_linear_inverse_time(&best), _ => t::critical_power_hyperbolic(&best), }); - (r.threshold_power, r.work_capacity_above_threshold, r.fit_acceptable, serialized(&r)) + (r.threshold_power, r.work_capacity_above_threshold, r.fit_acceptable, r.clone().into()) } }; // A fit that is not acceptable is not offered for saving (main study 5.1). @@ -389,7 +391,7 @@ fn run_inner( let (speed, distance, acceptable, result) = match op { t::CRITICAL_SPEED_THREE_PARAMETER => { let r = refuse!(t::critical_speed_three_parameter(&best)); - (r.threshold_speed, r.distance_above_threshold, r.fit_acceptable, serialized(&r)) + (r.threshold_speed, r.distance_above_threshold, r.fit_acceptable, r.clone().into()) } _ => { let r = refuse!(match op { @@ -397,7 +399,7 @@ fn run_inner( t::CRITICAL_SPEED_LINEAR_INVERSE_TIME => t::critical_speed_linear_inverse_time(&best), _ => t::critical_speed_hyperbolic(&best), }); - (r.threshold_speed, r.distance_above_threshold, r.fit_acceptable, serialized(&r)) + (r.threshold_speed, r.distance_above_threshold, r.fit_acceptable, r.clone().into()) } }; let references = if acceptable { @@ -411,7 +413,7 @@ fn run_inner( base(references, result, efforts, Some(labels), confirm_fit) } }; - outcome.parameters = params.used; + outcome.parameters = params.used.into_iter().collect(); Ok(Ok(outcome)) } @@ -524,19 +526,20 @@ fn run_test( "The effort was all out from the start, with no pacing, for the full 180 s.".to_string(), "Only a warm-up came before it.".into(), ]; - let outcome = |result: Value, references: Vec, confirm: Vec, params: &mut Params<'_>| { - ThresholdOutcome { - operation: operation.into(), - parameters: std::mem::take(&mut params.used), - period_start: Some(date.clone()), - period_end: Some(date.clone()), - result, - efforts: Vec::new(), - labels: None, - confirm_before_saving: confirm, - references_to_save: references, - } - }; + let outcome = + |result: ThresholdResult, references: Vec, confirm: Vec, params: &mut Params<'_>| { + ThresholdOutcome { + operation: operation.into(), + parameters: std::mem::take(&mut params.used).into_iter().collect(), + period_start: Some(date.clone()), + period_end: Some(date.clone()), + result, + efforts: Vec::new(), + labels: None, + confirm_before_saving: confirm, + references_to_save: references, + } + }; Ok(Ok(match operation { t::THREE_MINUTE_ALL_OUT_CYCLING_TEST => { let power = refuse!(readings_of(RecordingQuantity::Power, evidence)?); @@ -545,7 +548,7 @@ fn run_test( let mut confirm = confirm_all_out; confirm.push("The resistance mode of the trainer.".into()); outcome( - serialized(&result), + result.clone().into(), vec![ reference("threshold_power", result.threshold_power, "W", false), reference("work_capacity_above_threshold", result.work_capacity_above_threshold, "kJ", true), @@ -558,7 +561,7 @@ fn run_test( let power = refuse!(readings_of(RecordingQuantity::Power, evidence)?); let result = refuse!(t::three_minute_all_out_rowing_test(&power, interval_ms(&power))); outcome( - serialized(&result), + result.clone().into(), vec![reference("threshold_power", result.threshold_power, "W", false)], confirm_all_out, params, @@ -568,7 +571,7 @@ fn run_test( let distance = refuse!(readings_of(RecordingQuantity::Distance, evidence)?); let result = refuse!(t::three_minute_all_out_running_test(&distance, interval_ms(&distance))); outcome( - serialized(&result), + result.clone().into(), vec![ reference("threshold_speed", result.threshold_speed, "m/s", false), reference("distance_capacity_above_threshold", result.distance_above_threshold, "m", true), @@ -587,7 +590,7 @@ fn run_test( interval_ms(&heart_rate) )); outcome( - serialized(&result), + result.clone().into(), vec![ reference("threshold_speed", result.threshold_speed, "m/s", false), reference("threshold_heart_rate", result.threshold_heart_rate, "bpm", false), @@ -625,7 +628,7 @@ fn run_test( refuse!(swim(&second, &label_200)) )); outcome( - serialized(&result), + result.clone().into(), vec![reference("threshold_speed", result.threshold_speed, "m/s", false)], vec!["Both swims were maximal, front crawl, and in the same pool length.".into()], params, @@ -732,10 +735,10 @@ fn held_heart_rate( let _ = period_start; Ok(Ok(ThresholdOutcome { operation: operation.into(), - parameters: std::mem::take(&mut params.used), - period_start: Some(result.period_start.format("%Y-%m-%d").to_string()), + parameters: std::mem::take(&mut params.used).into_iter().collect(), + period_start: Some(result.period_start.clone()), period_end: Some(end_date.to_string()), - result: serialized(&result), + result: result.clone().into(), efforts: Vec::new(), labels: None, confirm_before_saving: vec![ From cc3b475b65bcfa2baf632b26d65a6ea5b8dda6eb Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Sun, 29 Nov 2026 23:42:33 -0600 Subject: [PATCH 20/30] Serve the Swift package from this repository. Apps add https://github.com/mwhitham/ath by version. The root Package.swift builds the package from mobile/swift/. On main its binary target is the XCFramework that build-apple.sh writes. A release from main tags one commit on top of the tested commit that names the zip on the GitHub release by address and checksum and adds the generated Swift, so Swift Package Manager installs the tested bytes (D332). stage-apple.sh stages that commit in a tagged clone of this repository and installs it by version. The release workflow builds the commit through the GitHub API, tags it, and adds the zip to the release. The separate package repository, its token, and its templates are gone. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release-cross-platform.yml | 109 ++++++++++++------ .github/workflows/release-mobile-packages.yml | 70 ++++------- .github/workflows/validate.yml | 11 +- .gitignore | 5 + Package.swift | 44 +++++++ build-history/v3.1.0/decisions.md | 32 +++-- mobile/README.md | 39 +++---- mobile/scripts/stage-apple.sh | 72 +++++++----- mobile/scripts/swift-package-release.sh | 33 ++++++ mobile/scripts/swift-package-repository.sh | 31 ----- mobile/scripts/test-apple.sh | 4 +- mobile/swift/Package.swift | 35 ------ mobile/swift/release/Package.swift.in | 24 ---- mobile/swift/release/README.md.in | 17 --- 14 files changed, 269 insertions(+), 257 deletions(-) create mode 100644 Package.swift create mode 100755 mobile/scripts/swift-package-release.sh delete mode 100755 mobile/scripts/swift-package-repository.sh delete mode 100644 mobile/swift/Package.swift delete mode 100644 mobile/swift/release/Package.swift.in delete mode 100644 mobile/swift/release/README.md.in diff --git a/.github/workflows/release-cross-platform.yml b/.github/workflows/release-cross-platform.yml index 69b730d1..022a20d0 100644 --- a/.github/workflows/release-cross-platform.yml +++ b/.github/workflows/release-cross-platform.yml @@ -11,8 +11,13 @@ # - Actions > Release cross-platform > Run workflow on `main`, with `publish` # set, from the website or GitHub Mobile; # - pushing a version tag, such as v2.1.2. -# A release from `main` tags the tested commit with the version in -# packages/npm/package.json, after every check has passed. +# A release from `main` tags the version in packages/npm/package.json after +# every check has passed. The tag names one commit on top of the tested commit: +# it points the root Package.swift at the tested XCFramework on the GitHub +# release, by address and checksum, and adds the generated Swift, so Swift +# Package Manager installs the iPhone package by version (D332). A release from +# a pushed tag cannot add that commit, so its iPhone package cannot be installed +# by version; the run says so. # # The tarball is staged on npm, not published (D251). npm's trusted publishing # lets this job stage it with a short-lived identity token from GitHub, so no @@ -98,8 +103,12 @@ jobs: elif [ "$GITHUB_REF" = refs/heads/main ]; then existing="$(tag_commit "$tag")" if [ -n "$existing" ] && [ "$existing" != "$GITHUB_SHA" ]; then - echo "::error::$tag already names commit $existing. Raise the version in packages/npm/package.json to release $GITHUB_SHA." - exit 1 + # The tag may name this commit's Swift package release commit. + parent="$(gh api "repos/$GITHUB_REPOSITORY/commits/$existing" --jq '.parents[0].sha')" + if [ "$parent" != "$GITHUB_SHA" ]; then + echo "::error::$tag already names commit $existing. Raise the version in packages/npm/package.json to release $GITHUB_SHA." + exit 1 + fi fi else echo "::error::A release starts only from main or a version tag, not $GITHUB_REF." @@ -138,6 +147,23 @@ jobs: pattern: archive-* path: archives merge-multiple: true + - uses: actions/download-artifact@v4 + with: + name: mobile-apple + path: apple + - name: Check the iPhone package is the tested one + run: | + version="${TAG#v}" + zip="apple/AthleticStandardFFI-$version.xcframework.zip" + checksum="$(sha256sum "$zip" | cut -d ' ' -f 1)" + [ "$(jq -r .version apple/apple-report.json)" = "$version" ] || + { echo "::error::apple-report.json is not version $version"; exit 1; } + [ "$(jq -r .asset_sha256 apple/apple-report.json)" = "$checksum" ] || + { echo "::error::the zip is not the tested one"; exit 1; } + [ "$(jq -r .commit apple/apple-report.json)" = "$GITHUB_SHA" ] || + { echo "::error::the iPhone package was staged from another commit"; exit 1; } + grep -qF "checksum: \"$checksum\"" apple/swift-package/Package.swift || + { echo "::error::the staged Package.swift does not name the tested checksum"; exit 1; } - name: Check the archives and the tarball agree run: | version="${TAG#v}" @@ -174,7 +200,7 @@ jobs: run: npm stage publish "./npm-tarball/$(node -p "require('./npm-tarball/pack-summary.json').tarball")" # Tag only after the package is staged. A failed staging then leaves no # tag, so a fixed workflow can release the same version from a new commit. - - name: Tag the tested commit + - name: Tag the Swift package release commit if: github.ref_type != 'tag' env: GH_TOKEN: ${{ github.token }} @@ -199,26 +225,51 @@ jobs: fi } existing="$(tag_commit "$TAG")" - if [ -z "$existing" ]; then - gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$GITHUB_SHA" --silent - echo "Tagged $GITHUB_SHA as $TAG." - elif [ "$existing" != "$GITHUB_SHA" ]; then - echo "::error::$TAG already names commit $existing." - exit 1 + if [ -n "$existing" ]; then + parent="$(gh api "repos/$GITHUB_REPOSITORY/commits/$existing" --jq '.parents[0].sha')" + [ "$parent" = "$GITHUB_SHA" ] || { echo "::error::$TAG already names commit $existing."; exit 1; } + echo "$TAG already names the Swift package release commit $existing." + exit 0 fi + # One commit on top of the tested commit: the release Package.swift and + # the generated Swift that the iPhone package job tested (D332). The + # files go through `--input`, because a command-line argument cannot + # hold the generated Swift. + version="${TAG#v}" + entries=() + while IFS= read -r -d '' file; do + path="${file#apple/swift-package/}" + jq -n --rawfile content "$file" '{content: $content, encoding: "utf-8"}' > blob.json + blob="$(gh api "repos/$GITHUB_REPOSITORY/git/blobs" --input blob.json --jq .sha)" + entries+=("$(jq -nc --arg path "$path" --arg sha "$blob" '{path: $path, mode: "100644", type: "blob", sha: $sha}')") + done < <(find apple/swift-package -type f -print0 | sort -z) + base="$(gh api "repos/$GITHUB_REPOSITORY/git/commits/$GITHUB_SHA" --jq .tree.sha)" + printf '%s\n' "${entries[@]}" | jq -s --arg base "$base" '{base_tree: $base, tree: .}' > tree.json + tree="$(gh api "repos/$GITHUB_REPOSITORY/git/trees" --input tree.json --jq .sha)" + jq -n --arg tree "$tree" --arg parent "$GITHUB_SHA" --arg message "Athletic Standard $version for Swift Package Manager" \ + '{message: $message, tree: $tree, parents: [$parent]}' > commit.json + commit="$(gh api "repos/$GITHUB_REPOSITORY/git/commits" --input commit.json --jq .sha)" + gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$commit" --silent + echo "Tagged $commit, on top of $GITHUB_SHA, as $TAG." + - name: Say the iPhone package needs a release from main + if: github.ref_type == 'tag' + run: | + echo "::warning::$TAG was pushed, so it names a commit without the Swift package release files. The XCFramework joins the release, but Swift Package Manager cannot install $TAG. Release from main to install the iPhone package by version." - name: Publish the checked archives as the GitHub release env: GH_TOKEN: ${{ github.token }} - run: gh release create "$TAG" archives/* --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" + run: | + version="${TAG#v}" + gh release create "$TAG" archives/* "apple/AthleticStandardFFI-$version.xcframework.zip" apple/apple-report.json \ + --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" - # The iPhone and Android packages (D332). The tested XCFramework zip and both - # reports join the GitHub release. The tested Maven bundle is uploaded to Maven - # Central as a deployment the maintainer must publish there; until then nothing - # can resolve it. A missing Central credential skips that upload and says so. - # The Swift package repository is tagged later, by the maintainer, with - # release-mobile-packages.yml. + # The Android library (D332). Its report joins the GitHub release. The tested + # Maven bundle is uploaded to Maven Central as a deployment the maintainer must + # publish there; until then nothing can resolve it. A missing Central credential + # skips that upload and says so. The iPhone package is already released: the + # publish job tagged its release commit and added the XCFramework. publish-mobile: - name: Stage the iPhone and Android packages + name: Stage the Android library needs: [version, validate, publish] if: needs.version.outputs.release == 'true' runs-on: ubuntu-latest @@ -251,18 +302,8 @@ jobs: zip="apple/AthleticStandardFFI-$version.xcframework.zip" [ "$(sha256sum "$zip" | cut -d ' ' -f 1)" = "$(jq -r .asset_sha256 apple/apple-report.json)" ] || { echo "::error::the zip is not the tested one"; exit 1; } - - name: Add the tested XCFramework and the reports to the GitHub release - run: | - version="${TAG#v}" - zip="apple/AthleticStandardFFI-$version.xcframework.zip" - tested="$(sha256sum "$zip" | cut -d ' ' -f 1)" - if gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "$(basename "$zip")" --dir published 2> /dev/null; then - [ "$(sha256sum "published/$(basename "$zip")" | cut -d ' ' -f 1)" = "$tested" ] || - { echo "::error::$TAG already holds a different $(basename "$zip")"; exit 1; } - echo "The release already holds the tested zip." - else - gh release upload "$TAG" "$zip" apple/apple-report.json android/android-report.json --repo "$GITHUB_REPOSITORY" - fi + - name: Add the Android report to the GitHub release + run: gh release upload "$TAG" android/android-report.json --clobber --repo "$GITHUB_REPOSITORY" - name: Upload the tested Maven bundle for the maintainer to publish run: | version="${TAG#v}" @@ -296,9 +337,9 @@ jobs: { echo "### iPhone and Android packages for $TAG" echo - echo "- XCFramework: \`$(jq -r .asset_sha256 apple/apple-report.json)\` on the GitHub release." + echo "- XCFramework: \`$(jq -r .asset_sha256 apple/apple-report.json)\` on the GitHub release; \`$TAG\` names the Swift package release commit." echo "- Android archive: \`$(jq -r .aar_sha256 android/android-report.json)\`, uploaded to Maven Central for approval when a credential is set." - echo "- Next: publish the Maven deployment, then run release-mobile-packages.yml for $TAG to tag the Swift package and check both public installs." + echo "- Next: publish the Maven deployment, then run release-mobile-packages.yml for $TAG to check both public installs." } >> "$GITHUB_STEP_SUMMARY" report: @@ -329,7 +370,7 @@ jobs: IFS= read -r -d '' body <<'EOF' || true **@TAG@ is staged on npm and waiting for your approval.** - The full check passed. `@TAG@` now names the tested commit, and the [GitHub release](@SERVER@/@REPO@/releases/tag/@TAG@) holds the native archives. Nobody can install @TAG@ from npm until you approve it. + The full check passed. `@TAG@` now names one commit on top of the tested commit, which adds the Swift package files, and the [GitHub release](@SERVER@/@REPO@/releases/tag/@TAG@) holds the native archives and the iPhone XCFramework. Nobody can install @TAG@ from npm until you approve it. Approve it in one of two ways. Both ask for your two-factor code. diff --git a/.github/workflows/release-mobile-packages.yml b/.github/workflows/release-mobile-packages.yml index 218de151..4379dd76 100644 --- a/.github/workflows/release-mobile-packages.yml +++ b/.github/workflows/release-mobile-packages.yml @@ -2,11 +2,10 @@ # hand after release-cross-platform.yml finished for a version and the Maven # Central deployment was published. # -# swift-package writes the Swift package repository for the tag from the tagged -# sources and the tested XCFramework on the GitHub release, after checking that -# the zip is the one the release tested. It tags the repository with the version -# and then installs the package from its public address. A tag that already names -# the same checksum is kept; a tag with another checksum stops the run. +# swift-package checks that the tag names the Swift package release commit: its +# Package.swift names the XCFramework on the GitHub release with the tested +# checksum, and that zip has that checksum. Then it installs the package from +# this repository by version, as an app does, and runs it offline. # # maven-check installs `ai.athleticstandard:athleticstandard` from Maven Central # in the consumer app and runs the library's tests on an emulator, offline from @@ -26,55 +25,32 @@ permissions: jobs: swift-package: - name: Tag the Swift package and install it from its public address + name: Install the Swift package from this repository by version runs-on: macos-15 - environment: release env: TAG: ${{ inputs.tag }} GH_TOKEN: ${{ github.token }} - PACKAGE_REPOSITORY: mwhitham/athleticstandard-swift - PACKAGE_TOKEN: ${{ secrets.SWIFT_PACKAGE_REPOSITORY_TOKEN }} steps: - uses: actions/checkout@v5 with: ref: ${{ inputs.tag }} - - name: Download the tested XCFramework and its report + # The tag's commit and the tested commit under it. + fetch-depth: 2 + - name: Check the tag names the tested XCFramework run: | version="${TAG#v}" - gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "AthleticStandardFFI-$version.xcframework.zip" \ - --pattern apple-report.json --dir released + zip="AthleticStandardFFI-$version.xcframework.zip" + gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "$zip" --pattern apple-report.json --dir released tested="$(jq -r .asset_sha256 released/apple-report.json)" - found="$(shasum -a 256 "released/AthleticStandardFFI-$version.xcframework.zip" | cut -d ' ' -f 1)" + found="$(shasum -a 256 "released/$zip" | cut -d ' ' -f 1)" [ "$found" = "$tested" ] || { echo "::error::the released zip is $found; the release tested $tested"; exit 1; } - [ "$(jq -r .commit released/apple-report.json)" = "$(git rev-parse HEAD)" ] || - { echo "::error::the report names another commit than $TAG"; exit 1; } - echo "CHECKSUM=$tested" >> "$GITHUB_ENV" - - name: Write, commit, and tag the package repository - run: | - if [ -z "$PACKAGE_TOKEN" ]; then - echo "::error::SWIFT_PACKAGE_REPOSITORY_TOKEN is not set; nothing was published." - exit 1 - fi - version="${TAG#v}" - git clone -q "https://x-access-token:$PACKAGE_TOKEN@github.com/$PACKAGE_REPOSITORY.git" package - if git -C package rev-parse -q --verify "refs/tags/$version" > /dev/null; then - if git -C package show "$version:Package.swift" | grep -q "checksum: \"$CHECKSUM\""; then - echo "$PACKAGE_REPOSITORY already tags $version with the tested checksum." - exit 0 - fi - echo "::error::$PACKAGE_REPOSITORY already tags $version with another checksum." - exit 1 - fi - url="https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG/AthleticStandardFFI-$version.xcframework.zip" - mobile/scripts/swift-package-repository.sh package "$version" "$(git rev-parse HEAD)" "$CHECKSUM" \ - ".binaryTarget(name: \"AthleticStandardFFI\", url: \"$url\", checksum: \"$CHECKSUM\")" - cd package - git add -A - git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ - commit -q -m "Athletic Standard $version" - git tag "$version" - git push -q origin HEAD "refs/tags/$version" - - name: Install from the public address and run offline + [ "$(jq -r .commit released/apple-report.json)" = "$(git rev-parse HEAD^)" ] || + { echo "::error::$TAG does not name a release commit on top of the tested commit"; exit 1; } + url="https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG/$zip" + grep -qF ".binaryTarget(name: \"AthleticStandardFFI\", url: \"$url\", checksum: \"$tested\")" Package.swift || + { echo "::error::Package.swift at $TAG does not name $url with checksum $tested"; exit 1; } + echo "$TAG names the tested XCFramework, $tested." + - name: Install from this repository by version and run offline run: | version="${TAG#v}" mkdir -p check/Sources/check @@ -83,19 +59,19 @@ jobs: import PackageDescription let package = Package( name: "check", platforms: [.macOS(.v14)], - dependencies: [.package(url: "https://github.com/$PACKAGE_REPOSITORY", exact: "$version")], - targets: [.executableTarget(name: "check", dependencies: [.product(name: "AthleticStandard", package: "athleticstandard-swift")])]) + dependencies: [.package(url: "https://github.com/$GITHUB_REPOSITORY", exact: "$version")], + targets: [.executableTarget(name: "check", dependencies: [.product(name: "AthleticStandard", package: "ath")])]) MANIFEST cat > check/Sources/check/main.swift <<'SOURCE' import AthleticStandard import Foundation - let record = #"{"record_id":"01890f3e-e7d3-7cc0-88c8-000000000064","record_type":"source","created_at":"2026-01-02T03:04:05.678Z","current_revision":1,"is_deleted":false,"data":{"source_type":"wearable","data_writer":"Example Band","data_route":"provider_export"}}"# - _ = try validateCurrentRecord(json: Data(record.utf8)) + let source = RecordData.source(SourceData(sourceType: .wearable, dataWriter: "Example Band", dataRoute: "provider_export")) + try checkRecordData(data: source) print(libraryVersion()) SOURCE printed="$(cd check && swift run -q check)" [ "$printed" = "$version" ] || { echo "::error::the public package reports $printed, not $version"; exit 1; } - echo "The public Swift package $version resolves, runs offline, and reports $printed." + echo "The Swift package $version installs from $GITHUB_REPOSITORY, runs offline, and reports $printed." maven-check: name: Install the Android library from Maven Central diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 07d3a241..79644b1e 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -288,10 +288,11 @@ jobs: shell: bash run: node packages/npm/scripts/smoke.mjs npm-tarball/athleticstandard-*.tgz - # The iPhone package (D331, D332). Builds the XCFramework, stages the Swift - # package repository, installs it by version in a consumer package, and runs the - # package tests on this Mac and on an iPhone simulator, with the desktop round - # trip and a real ath-host with the test sign-in provider. Nothing is published. + # The iPhone package (D331, D332). Builds the XCFramework, writes the files of + # the Swift package release commit, stages that commit in a tagged clone of this + # repository, installs it by version in a consumer package, and runs the package + # tests on this Mac and on an iPhone simulator, with the desktop round trip and a + # real ath-host with the test sign-in provider. Nothing is published. mobile-apple: name: iPhone package runs-on: macos-15 @@ -307,7 +308,7 @@ jobs: name: mobile-apple path: | mobile-release/apple/AthleticStandardFFI-*.xcframework.zip - mobile-release/apple/athleticstandard-swift + mobile-release/apple/swift-package mobile-release/apple/apple-report.json if-no-files-found: error diff --git a/.gitignore b/.gitignore index 2bfcc77e..3e8948d7 100644 --- a/.gitignore +++ b/.gitignore @@ -80,6 +80,11 @@ validation-data/ # Rust build output. /target/ +# Swift Package Manager output for the root Package.swift. +/.build/ +/.swiftpm/ +/Package.resolved + # The npm package build copies these in; pack.mjs removes them after packing. packages/npm/native/ packages/npm/core/ diff --git a/Package.swift b/Package.swift new file mode 100644 index 00000000..3419432f --- /dev/null +++ b/Package.swift @@ -0,0 +1,44 @@ +// swift-tools-version: 6.0 +// Athletic Standard for iPhone apps (D325, D331, D332). +// +// Apps add this repository by version, such as 3.1.0. A release's tag names a commit +// whose binary target below is the XCFramework on the GitHub release, by address and +// checksum, and which adds the generated Swift. On every other commit the binary +// target is the XCFramework that mobile/scripts/build-apple.sh writes, for +// development and tests. The release changes only that line. + +import PackageDescription + +let package = Package( + name: "AthleticStandard", + platforms: [.iOS(.v17), .macOS(.v14)], + products: [ + .library(name: "AthleticStandard", targets: ["AthleticStandard"]), + .library(name: "AthleticStandardHost", targets: ["AthleticStandardHost"]), + ], + targets: [ + .binaryTarget(name: "AthleticStandardFFI", path: "mobile/swift/build/AthleticStandardFFI.xcframework"), + .target( + name: "AthleticStandard", + dependencies: ["AthleticStandardFFI"], + path: "mobile/swift/Sources/AthleticStandard", + linkerSettings: [.linkedFramework("CoreFoundation"), .linkedLibrary("iconv")] + ), + // The optional client for ath-host, with browser sign-in (D330). Local files + // never need it. It reads and writes the generated record types. + .target( + name: "AthleticStandardHost", dependencies: ["AthleticStandard"], + path: "mobile/swift/Sources/AthleticStandardHost"), + // The runnable example (`swift run AthleticStandardExample` on a Mac). An app + // that adds this package never builds it. + .executableTarget( + name: "AthleticStandardExample", dependencies: ["AthleticStandard", "AthleticStandardHost"], + path: "mobile/swift/Examples/AthleticStandardExample"), + .testTarget( + name: "AthleticStandardTests", dependencies: ["AthleticStandard"], + path: "mobile/swift/Tests/AthleticStandardTests"), + .testTarget( + name: "AthleticStandardHostTests", dependencies: ["AthleticStandard", "AthleticStandardHost"], + path: "mobile/swift/Tests/AthleticStandardHostTests"), + ] +) diff --git a/build-history/v3.1.0/decisions.md b/build-history/v3.1.0/decisions.md index 0d4205fa..49ff61c6 100644 --- a/build-history/v3.1.0/decisions.md +++ b/build-history/v3.1.0/decisions.md @@ -263,30 +263,42 @@ Rejected alternatives: ## D332. How the packages are released -- **Swift.** The release builds the XCFramework, zips it, and records its SHA-256 - checksum. A separate Swift package repository holds a `Package.swift` that names the - release asset by address and checksum, with the generated Swift sources. Its version - tag points at the commit that names the tested checksum. The proposed repository is - `mwhitham/athleticstandard-swift`. The maintainer creates it. +- **Swift.** The Swift package is this repository, through a `Package.swift` at its + root. Apps add `https://github.com/mwhitham/ath` by version. The release builds the + XCFramework, zips it with fixed file times, and records its SHA-256 checksum. A + release from `main` then makes one commit on top of the tested commit, changing two + things: the binary target line of `Package.swift`, which names the zip on the GitHub + release by address and checksum, and the generated Swift, added. The version tag + names that commit, so Swift Package Manager installs the tested bytes. On every other + commit the binary target is the XCFramework that `mobile/scripts/build-apple.sh` + writes, for development and tests. A release from a pushed tag cannot add the commit, + so its Swift package cannot be installed by version, and the release says so. - **Android.** The release builds an Android archive with the generated Kotlin, both native libraries, a POM that declares the pinned JNA runtime, and sources and documentation jars. It is published to Maven Central as `ai.athleticstandard:athleticstandard`. The `ai.athleticstandard` namespace must be verified by the maintainer, through the `athleticstandard.ai` domain that already names the published schemas, before the coordinate is promised. -- A branch run builds both packages, installs them from a temporary Swift package - repository and a local Maven repository, and tests them, without publisher - credentials. The release job requires those tests. It uploads the tested archive, - publishes the checked Maven bundle, tags the tested Swift manifest, and then installs - from both public locations. +- A branch run builds both packages and tests them as installed: the Swift package from + a clone of this repository with the release commit staged and tagged, and the Android + library from a local Maven repository. It needs no publisher credentials. The release + job requires those tests. It tags the Swift package release commit, adds the tested + zip to the GitHub release, and uploads the checked Maven bundle. A last workflow then + installs both from their public locations. - A retry reuses the staged files. It skips an artifact already published with the same bytes and stops on a published version with different bytes. A missing registry credential blocks only publication. Publication stays with the maintainer. Rejected alternatives: +- Keep the Swift package in a separate repository, such as + `mwhitham/athleticstandard-swift`. Rejected because it is a second repository to + create, protect, and keep in step, with its own token, while this repository is + small enough for Swift Package Manager to fetch. - Commit the XCFramework to this repository. Rejected because Swift Package Manager fetches the whole repository, and binary files would stay in its history. +- Commit the generated Swift on `main`. Rejected because generated files are build + output (D327); only the release commit, which `main` never merges, holds them. - Build the Rust code from source inside Swift Package Manager. Rejected because a Swift package cannot run Cargo. - Publish through JitPack. Rejected because it builds on its own servers, so the diff --git a/mobile/README.md b/mobile/README.md index 1490271e..46e69d64 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -9,7 +9,7 @@ gets the same record checks, messages, and results as the desktop `ath` program. |---|---| | `src/` | The `athleticstandard-mobile` Rust crate: the functions and types the bindings expose. | | `bindgen/` | `uniffi-bindgen`, built from the same locked UniFFI version. | -| `swift/` | The Swift package `AthleticStandard` for iOS 17 and later, and macOS 14 and later for tests. | +| `swift/` | The sources, tests, and example of the Swift package `AthleticStandard` for iOS 17 and later, and macOS 14 and later for tests. Its manifest is `Package.swift` at the repository root. | | `android/` | The Android library `ai.athleticstandard:athleticstandard` for API 24 and later. | | `scripts/` | Build and test scripts for both platforms. | | `tests/` | Rust tests of the binding, and the exporter that writes the phone test bundle. | @@ -250,12 +250,12 @@ Both packages ship with each release and carry its version Publication stays with the maintainer. - `mobile/scripts/stage-apple.sh ` builds the release XCFramework, zips it with - fixed file times, and writes two copies of the Swift package repository: one whose - manifest names the release asset by address and checksum, and one, tagged with the - version, whose manifest points at the zip inside it. They differ only in that line. - A consumer package resolves the tagged copy by version and runs the package tests on - this Mac and on an iPhone simulator. `apple-report.json` records the hashes, slices, - and tool versions. + fixed file times, and writes the files of the Swift package release commit: the root + `Package.swift` naming the release asset by address and checksum, and the generated + Swift. It stages the same commit, pointing at the zip instead, in a clone of this + repository tagged with the version. A consumer package resolves the clone by version + and runs the package tests on this Mac and on an iPhone simulator. + `apple-report.json` records the hashes, slices, and tool versions. - `mobile/scripts/stage-android.sh ` publishes the Android library to a local Maven repository and checks that its POM declares the JNA runtime. The consumer app in `android/consumer/` resolves the library by coordinate from there, builds a shrunk @@ -263,22 +263,21 @@ Publication stays with the maintainer. runs the library's tests through the installed copy in a debug and a shrunk release build on every connected device. `android-report.json` records the results. - The `mobile-apple` and `mobile-android` jobs in `.github/workflows/validate.yml` run - both scripts for every release check. The release job then adds the tested zip and - both reports to the GitHub release, and uploads the tested Maven bundle to Maven + both scripts for every release check. A release from `main` then tags one commit on + top of the tested commit with the Swift package release files, adds the tested zip + and both reports to the GitHub release, and uploads the tested Maven bundle to Maven Central as a deployment that the maintainer publishes there. With no Central credential, it skips that upload and says the release is partial. - After that, the maintainer runs `.github/workflows/release-mobile-packages.yml` for - the tag. It writes the Swift package repository from the tagged sources, checks the - zip on the release against the tested checksum, tags the repository, and installs - both packages from their public locations. A version already published with the - same bytes is kept; one with different bytes stops the run. - -The proposed public coordinates are `ai.athleticstandard:athleticstandard` on Maven -Central and the Swift package repository `mwhitham/athleticstandard-swift`. Before the -first release, the maintainer verifies the `ai.athleticstandard` namespace on Maven -Central, creates the Swift package repository, and adds the `MAVEN_CENTRAL_USERNAME`, -`MAVEN_CENTRAL_PASSWORD`, `MAVEN_SIGNING_KEY`, `MAVEN_SIGNING_PASSPHRASE`, and -`SWIFT_PACKAGE_REPOSITORY_TOKEN` secrets to the `release` environment. + the tag. It checks that the tag's `Package.swift` names the tested zip, and installs + both packages from their public locations. + +Apps add the Swift package with `https://github.com/mwhitham/ath` by version, and the +Android library as `ai.athleticstandard:athleticstandard` from Maven Central. Before +the first release, the maintainer verifies the `ai.athleticstandard` namespace on Maven +Central and adds the `MAVEN_CENTRAL_USERNAME`, `MAVEN_CENTRAL_PASSWORD`, +`MAVEN_SIGNING_KEY`, and `MAVEN_SIGNING_PASSPHRASE` secrets to the `release` +environment. An Android app that uses the library should keep only the two ABIs it ships, because JNA carries more: diff --git a/mobile/scripts/stage-apple.sh b/mobile/scripts/stage-apple.sh index 096983d6..18b263f8 100755 --- a/mobile/scripts/stage-apple.sh +++ b/mobile/scripts/stage-apple.sh @@ -6,19 +6,22 @@ # Writes to the output folder: # AthleticStandardFFI-.xcframework.zip the release asset, with fixed file # times so equal input gives equal bytes -# athleticstandard-swift/ the Swift package repository as -# released: its manifest names the asset -# by address and checksum -# athleticstandard-swift-staged/ the same repository, its manifest +# swift-package/ the files the release commit adds or +# changes: Package.swift naming the asset +# by address and checksum, and the +# generated Swift +# ath/ a clone of this repository with the +# same commit on top of HEAD, its manifest # pointing at the zip inside it, tagged -# with the version -# consumer/ a package that resolves the staged -# repository by version and runs the -# package tests against it +# v +# consumer/ a package that resolves the clone by +# version and runs the package tests +# against it # apple-report.json hashes, targets, versions, test results # -# The two manifests differ only in the binary target line; the script checks that. -# Nothing is published. --mac-only leaves out the iPhone simulator run. +# The manifests differ from the root Package.swift only in the binary target line; +# swift-package-release.sh checks that. Nothing is published. --mac-only leaves out +# the iPhone simulator run. set -euo pipefail @@ -46,28 +49,28 @@ CHECKSUM="$(shasum -a 256 "$OUT/$ZIP" | cut -d ' ' -f 1)" computed="$(cd "$OUT" && swift package compute-checksum "$ZIP")" [ "$computed" = "$CHECKSUM" ] || { echo "swift computes $computed, not $CHECKSUM" >&2; exit 1; } -package_repository() { - rm -rf "${1:?}" - "$ROOT/mobile/scripts/swift-package-repository.sh" "$1" "$VERSION" "$COMMIT" "$CHECKSUM" "$2" -} - ASSET_URL="https://github.com/mwhitham/ath/releases/download/v$VERSION/$ZIP" -package_repository "$OUT/athleticstandard-swift" \ +rm -rf "${OUT:?}/swift-package" +"$ROOT/mobile/scripts/swift-package-release.sh" "$OUT/swift-package" \ ".binaryTarget(name: \"AthleticStandardFFI\", url: \"$ASSET_URL\", checksum: \"$CHECKSUM\")" -package_repository "$OUT/athleticstandard-swift-staged" \ - ".binaryTarget(name: \"AthleticStandardFFI\", path: \"$ZIP\")" -cp "$OUT/$ZIP" "$OUT/athleticstandard-swift-staged/$ZIP" -differences="$(diff "$OUT/athleticstandard-swift/Package.swift" "$OUT/athleticstandard-swift-staged/Package.swift" | grep -c '^[<>]' || true)" -[ "$differences" = 2 ] || { echo "the manifests differ in more than the binary target line" >&2; exit 1; } + +# The release commit on top of HEAD, in a clone, with the zip inside it in place of +# the address. Swift Package Manager accepts the `v` in front of the version. +STAGED="$OUT/ath" +rm -rf "${STAGED:?}" +git clone -q "$ROOT" "$STAGED" +git -C "$STAGED" checkout -q --detach "$COMMIT" +"$ROOT/mobile/scripts/swift-package-release.sh" "$STAGED" ".binaryTarget(name: \"AthleticStandardFFI\", path: \"$ZIP\")" +cp "$OUT/$ZIP" "$STAGED/$ZIP" ( - cd "$OUT/athleticstandard-swift-staged" - git init -q - git add -A - git -c user.name="Athletic Standard staging" -c user.email="staging@localhost" commit -q -m "Athletic Standard $VERSION" - git tag "$VERSION" + cd "$STAGED" + git add -f Package.swift "$ZIP" mobile/swift/Sources/AthleticStandard/Generated + git -c user.name="Athletic Standard staging" -c user.email="staging@localhost" commit -q \ + -m "Athletic Standard $VERSION for Swift Package Manager" + git tag -f "v$VERSION" > /dev/null ) -# An app's view: a package that depends on the staged repository by version. +# An app's view: a package that depends on the staged clone by version. CONSUMER="$OUT/consumer" rm -rf "${CONSUMER:?}" mkdir -p "$CONSUMER/Tests" @@ -79,14 +82,16 @@ import PackageDescription let package = Package( name: "AthleticStandardConsumer", platforms: [.iOS(.v17), .macOS(.v14)], - dependencies: [.package(url: "file://$OUT/athleticstandard-swift-staged", exact: "$VERSION")], + dependencies: [.package(url: "file://$STAGED", exact: "$VERSION")], targets: [ .testTarget( name: "AthleticStandardTests", - dependencies: [.product(name: "AthleticStandard", package: "athleticstandard-swift-staged")]), + dependencies: [.product(name: "AthleticStandard", package: "ath")]), .testTarget( name: "AthleticStandardHostTests", - dependencies: [.product(name: "AthleticStandardHost", package: "athleticstandard-swift-staged")]), + dependencies: [ + .product(name: "AthleticStandard", package: "ath"), .product(name: "AthleticStandardHost", package: "ath"), + ]), ] ) MANIFEST @@ -144,7 +149,7 @@ slice_report() { printf '{"identifier":"%s","architectures":"%s","sha256":"%s"}' "$1" "$(lipo -archs "$library")" \ "$(shasum -a 256 "$library" | cut -d ' ' -f 1)" } -GENERATED="$ROOT/mobile/swift/Sources/AthleticStandard/Generated/AthleticStandard.swift" +GENERATED="$ROOT/mobile/swift/Sources/AthleticStandard/Generated" cat > "$OUT/apple-report.json" < "$OUT/apple-report.json" <&1 | head -n 1 | sed 's/"/\\"/g')", diff --git a/mobile/scripts/swift-package-release.sh b/mobile/scripts/swift-package-release.sh new file mode 100755 index 00000000..d21bf629 --- /dev/null +++ b/mobile/scripts/swift-package-release.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Write the files a Swift package release commit adds or changes (D332). +# +# Usage: mobile/scripts/swift-package-release.sh +# +# replaces the binary target in the root Package.swift, such as +# `.binaryTarget(name: "AthleticStandardFFI", url: "...", checksum: "...")`. The +# folder gets that Package.swift and the generated Swift that +# mobile/scripts/build-apple.sh wrote, at their paths in the repository. The +# script checks that the manifest differs from the root one in that line only. +# stage-apple.sh and the release use it, so the staged and released commits hold +# the same files. + +set -euo pipefail + +FOLDER="${1:?folder}" +BINARY="${2:?binary target line}" +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +GENERATED=mobile/swift/Sources/AthleticStandard/Generated +DEVELOPMENT=' .binaryTarget(name: "AthleticStandardFFI", path: "mobile/swift/build/AthleticStandardFFI.xcframework"),' + +[ "$(grep -cxF "$DEVELOPMENT" "$ROOT/Package.swift")" = 1 ] || + { echo "Package.swift does not have the development binary target line" >&2; exit 1; } +for file in AthleticStandard.swift AthleticStandardCore.swift; do + [ -f "$ROOT/$GENERATED/$file" ] || { echo "no $GENERATED/$file; run build-apple.sh first" >&2; exit 1; } +done + +mkdir -p "$FOLDER/$GENERATED" +awk -v development="$DEVELOPMENT" -v binary=" $BINARY," '$0 == development { print binary; next } { print }' \ + "$ROOT/Package.swift" > "$FOLDER/Package.swift" +changed="$(diff "$ROOT/Package.swift" "$FOLDER/Package.swift" | grep -c '^[<>]' || true)" +[ "$changed" = 2 ] || { echo "the release manifest differs in more than the binary target line" >&2; exit 1; } +cp "$ROOT/$GENERATED/AthleticStandard.swift" "$ROOT/$GENERATED/AthleticStandardCore.swift" "$FOLDER/$GENERATED/" diff --git a/mobile/scripts/swift-package-repository.sh b/mobile/scripts/swift-package-repository.sh deleted file mode 100755 index 026891c8..00000000 --- a/mobile/scripts/swift-package-repository.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -# Write the Swift package repository's files for one release (D332). -# -# Usage: mobile/scripts/swift-package-repository.sh -# -# is the manifest's binary target line, such as -# `.binaryTarget(name: "AthleticStandardFFI", url: "...", checksum: "...")`. -# stage-apple.sh and release-mobile-packages.yml both call this, so the staged and -# the released repositories are written the same way. - -set -euo pipefail - -FOLDER="${1:?folder}" -VERSION="${2:?version}" -COMMIT="${3:?commit}" -CHECKSUM="${4:?checksum}" -BINARY="${5:?binary target line}" -ROOT="$(cd "$(dirname "$0")/../.." && pwd)" - -render() { - sed -e "s|@VERSION@|$VERSION|g" -e "s|@COMMIT@|$COMMIT|g" -e "s|@CHECKSUM@|$CHECKSUM|g" \ - -e "s|@BINARY_TARGET@|$BINARY|" "$1" -} - -mkdir -p "$FOLDER" -rm -rf "${FOLDER:?}/Sources" -mkdir -p "$FOLDER/Sources" -cp -R "$ROOT/mobile/swift/Sources/AthleticStandard" "$ROOT/mobile/swift/Sources/AthleticStandardHost" "$FOLDER/Sources/" -render "$ROOT/mobile/swift/release/Package.swift.in" > "$FOLDER/Package.swift" -render "$ROOT/mobile/swift/release/README.md.in" > "$FOLDER/README.md" -cp "$ROOT/LICENSE" "$FOLDER/LICENSE" diff --git a/mobile/scripts/test-apple.sh b/mobile/scripts/test-apple.sh index 62fbe36e..89c59788 100755 --- a/mobile/scripts/test-apple.sh +++ b/mobile/scripts/test-apple.sh @@ -43,7 +43,7 @@ set -a source "$HOST_ENV/env" set +a -cd "$ROOT/mobile/swift" +cd "$ROOT" # Some Command Line Tools releases leave the Swift Testing macro plugin out of # the search path; naming its folder is harmless when it is already found. SWIFT_TEST_FLAGS=() @@ -74,6 +74,6 @@ fi TEST_RUNNER_ATH_MOBILE_FIXTURES="$FIXTURES" TEST_RUNNER_ATH_MOBILE_ROUNDTRIP_OUT="$ROUNDTRIP_OUT/simulator" \ TEST_RUNNER_ATH_TEST_HOST_URL="$ATH_TEST_HOST_URL" TEST_RUNNER_ATH_TEST_ISSUER="$ATH_TEST_ISSUER" \ xcodebuild test -scheme AthleticStandard \ - -destination "platform=iOS Simulator,id=$SIMULATOR" -derivedDataPath "$ROOT/mobile/swift/.build/xcode" \ + -destination "platform=iOS Simulator,id=$SIMULATOR" -derivedDataPath "$ROOT/.build/xcode" \ | tail -n 40 "$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$ROUNDTRIP_OUT/simulator/phone-edited.ath.sqlite" diff --git a/mobile/swift/Package.swift b/mobile/swift/Package.swift deleted file mode 100644 index f4d55bf2..00000000 --- a/mobile/swift/Package.swift +++ /dev/null @@ -1,35 +0,0 @@ -// swift-tools-version: 6.0 -// Athletic Standard for iPhone apps (D325, D331). -// -// This manifest builds against the XCFramework that mobile/scripts/build-apple.sh -// writes to build/. Released versions come from a separate package repository whose -// manifest names the release asset by address and checksum (D332). - -import PackageDescription - -let package = Package( - name: "AthleticStandard", - platforms: [.iOS(.v17), .macOS(.v14)], - products: [ - .library(name: "AthleticStandard", targets: ["AthleticStandard"]), - .library(name: "AthleticStandardHost", targets: ["AthleticStandardHost"]), - ], - targets: [ - .binaryTarget(name: "AthleticStandardFFI", path: "build/AthleticStandardFFI.xcframework"), - .target( - name: "AthleticStandard", - dependencies: ["AthleticStandardFFI"], - linkerSettings: [.linkedFramework("CoreFoundation"), .linkedLibrary("iconv")] - ), - // The optional client for ath-host, with browser sign-in (D330). Local files - // never need it. It reads and writes the generated record types. - .target(name: "AthleticStandardHost", dependencies: ["AthleticStandard"]), - // The runnable example (`swift run AthleticStandardExample` on a Mac). Releases - // do not carry it. - .executableTarget( - name: "AthleticStandardExample", dependencies: ["AthleticStandard", "AthleticStandardHost"], - path: "Examples/AthleticStandardExample"), - .testTarget(name: "AthleticStandardTests", dependencies: ["AthleticStandard"]), - .testTarget(name: "AthleticStandardHostTests", dependencies: ["AthleticStandard", "AthleticStandardHost"]), - ] -) diff --git a/mobile/swift/release/Package.swift.in b/mobile/swift/release/Package.swift.in deleted file mode 100644 index a0bb36cd..00000000 --- a/mobile/swift/release/Package.swift.in +++ /dev/null @@ -1,24 +0,0 @@ -// swift-tools-version: 6.0 -// Athletic Standard @VERSION@ for iPhone apps (D325, D332). -// Built from commit @COMMIT@ of https://github.com/mwhitham/ath by -// mobile/scripts/stage-apple.sh. Do not edit; the next release replaces it. - -import PackageDescription - -let package = Package( - name: "AthleticStandard", - platforms: [.iOS(.v17), .macOS(.v14)], - products: [ - .library(name: "AthleticStandard", targets: ["AthleticStandard"]), - .library(name: "AthleticStandardHost", targets: ["AthleticStandardHost"]), - ], - targets: [ - @BINARY_TARGET@, - .target( - name: "AthleticStandard", - dependencies: ["AthleticStandardFFI"], - linkerSettings: [.linkedFramework("CoreFoundation"), .linkedLibrary("iconv")] - ), - .target(name: "AthleticStandardHost"), - ] -) diff --git a/mobile/swift/release/README.md.in b/mobile/swift/release/README.md.in deleted file mode 100644 index e8e16f25..00000000 --- a/mobile/swift/release/README.md.in +++ /dev/null @@ -1,17 +0,0 @@ -# Athletic Standard for iPhone apps - -Version @VERSION@, built from commit @COMMIT@ of -[mwhitham/ath](https://github.com/mwhitham/ath). This repository holds only what Swift -Package Manager needs. The source, the documentation, and the issue tracker are in -`mwhitham/ath`; see `mobile/README.md` there. - -```swift -.package(url: "https://github.com/mwhitham/athleticstandard-swift", exact: "@VERSION@") -``` - -- `AthleticStandard`: record checks, calculations, and `.ath.sqlite` files, through the - same Rust library as the desktop `ath` program. iOS 17 and later. -- `AthleticStandardHost`: the optional client for `ath-host`, with browser sign-in. - -The native library is `AthleticStandardFFI-@VERSION@.xcframework.zip` in the release -`v@VERSION@` of mwhitham/ath, with SHA-256 `@CHECKSUM@`. MIT license. From e95e347e37ff389145d1f9eb55271e44c9205ff7 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 00:02:38 -0600 Subject: [PATCH 21/30] Describe every phone library call, type, field, and case. UniFFI copies Rust doc comments into the Swift and Kotlin that Xcode and Android Studio show. The phone crate now denies missing documentation, so every call, and every type, field, and case it defines, has a description. Every call is in this crate. Co-Authored-By: Claude Opus 5.5 --- mobile/src/calculate.rs | 11 +++++-- mobile/src/error.rs | 73 +++++++++++++++++++++++++++++++++-------- mobile/src/lib.rs | 3 ++ mobile/src/records.rs | 26 +++++++++++++++ mobile/src/store.rs | 12 +++++++ 5 files changed, 110 insertions(+), 15 deletions(-) diff --git a/mobile/src/calculate.rs b/mobile/src/calculate.rs index 182fc189..1a241f88 100644 --- a/mobile/src/calculate.rs +++ b/mobile/src/calculate.rs @@ -38,9 +38,15 @@ impl From for AthleticStandardError { pub enum CalculationSkill { /// A skill shipped with this library, such as `hrv-change`, named as /// `ath apply` names it. - Shipped { name: String }, + Shipped { + /// The skill's name. + name: String, + }, /// The complete text of a skill file, such as an edited copy. - Text { text: String }, + Text { + /// The skill file's text. + text: String, + }, } /// The `--set name=value` parameters of `ath apply`, in a fixed order. @@ -78,6 +84,7 @@ impl RecordSnapshotBuilder { #[uniffi::export] impl RecordSnapshotBuilder { + /// An empty builder. #[uniffi::constructor] pub fn new() -> Arc { Arc::new(RecordSnapshotBuilder { builder: Mutex::new(Some(calculate::SnapshotBuilder::new())) }) diff --git a/mobile/src/error.rs b/mobile/src/error.rs index c6dea0bb..a2e7ba3c 100644 --- a/mobile/src/error.rs +++ b/mobile/src/error.rs @@ -11,29 +11,66 @@ use athleticstandard_core::model::{self, ValidationError}; #[derive(Debug, Clone, PartialEq, uniffi::Error)] pub enum AthleticStandardError { /// The bytes are not UTF-8 JSON text the library's reader accepts. - MalformedJson { detail: String }, + MalformedJson { + /// The desktop message. + detail: String, + }, /// No published shape has this name. - UnknownShape { detail: String }, + UnknownShape { + /// The desktop message. + detail: String, + }, /// The value does not match its shape. `issues` are in the desktop order; /// `detail` is the first one as a person reads it. - Invalid { detail: String, issues: Vec }, + Invalid { + /// The desktop message. + detail: String, + /// Every issue, in the desktop order. + issues: Vec, + }, /// A named record, file, or setting does not exist. - NotFound { detail: String }, + NotFound { + /// The desktop message. + detail: String, + }, /// The database changed, or an expected revision is not current. - Stale { detail: String }, + Stale { + /// The desktop message. + detail: String, + }, /// The operation is refused to protect data or files. - Refused { detail: String }, + Refused { + /// The desktop message. + detail: String, + }, /// The database needs a migration first. `preview` says what the /// migration would do. - MigrationRequired { detail: String, preview: crate::records::MigrationPreview }, + MigrationRequired { + /// The desktop message. + detail: String, + /// The migration the database needs. + preview: crate::records::MigrationPreview, + }, /// SQLite reported an error. - Database { detail: String }, + Database { + /// The desktop message. + detail: String, + }, /// A file operation failed. - Io { detail: String }, + Io { + /// The desktop message. + detail: String, + }, /// Any other failure, with the desktop message (desktop code `error`). - Failed { detail: String }, + Failed { + /// The desktop message. + detail: String, + }, /// The database handle was closed. - Closed { detail: String }, + Closed { + /// The desktop message. + detail: String, + }, } impl AthleticStandardError { @@ -103,16 +140,26 @@ impl From for AthleticStandardError { /// stay distinct, so field `"0"` and position 0 are different paths. #[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] pub enum PathSegment { - Field { name: String }, - Position { index: u64 }, + /// A field of an object. + Field { + /// The field's name. + name: String, + }, + /// A position in a list, from 0. + Position { + /// The position. + index: u64, + }, } /// One validation issue, as the desktop validator reports it. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct ValidationIssue { + /// Where the issue is, from the top of the checked value. pub path: Vec, /// The issue code, such as `invalid_type` or `custom`. pub code: String, + /// The desktop message, such as `Invalid input: expected string`. pub message: String, /// The path as the desktop prints it, such as `data.value.standard_unit`, /// or `record` for the top level. diff --git a/mobile/src/lib.rs b/mobile/src/lib.rs index b59345a9..9f3aaf6d 100644 --- a/mobile/src/lib.rs +++ b/mobile/src/lib.rs @@ -15,6 +15,9 @@ // type large. Errors cross to Swift or Kotlin once and are rare, so its size // does not matter here. #![allow(clippy::result_large_err)] +// Every exported call, type, field, and case needs a description: UniFFI copies +// it into the Swift and Kotlin that Xcode and Android Studio show. +#![deny(missing_docs)] uniffi::setup_scaffolding!(); diff --git a/mobile/src/records.rs b/mobile/src/records.rs index db1c5c44..669181d3 100644 --- a/mobile/src/records.rs +++ b/mobile/src/records.rs @@ -46,19 +46,23 @@ pub struct NewRecord { /// revision refuses the whole write with `Stale`. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct ExpectedRevision { + /// The record. pub record_id: String, + /// The revision it must be at. pub revision: u64, } /// A new revision of one record. The record keeps its type and ID. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct RecordCorrection { + /// The record to correct. pub record_id: String, /// The revision the person edited. Another current revision refuses the /// correction with `Stale` and changes nothing. pub expected_revision: u64, /// The complete new data, of the record's own type. pub data: RecordData, + /// Who made the change. pub changed_by: RecordActor, /// New extensions for the record. The current ones are kept when absent. /// `write_record_changes` always keeps them. @@ -75,10 +79,12 @@ pub struct RecordCorrection { /// A normal deletion. The record's history stays. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct DeleteRequest { + /// The record to delete. pub record_id: String, /// The revision the person saw. Another current revision refuses the /// deletion with `Stale`. pub expected_revision: u64, + /// Who deleted it. pub deleted_by: RecordActor, /// When it was deleted. Now when absent. #[uniffi(default = None)] @@ -88,10 +94,14 @@ pub struct DeleteRequest { /// Corrections and new records written in one change. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct RecordChanges { + /// New revisions of existing records. #[uniffi(default = [])] pub corrections: Vec, + /// New records. #[uniffi(default = [])] pub records: Vec, + /// Other records the change expects at a revision. One at another + /// revision refuses the whole change with `Stale`. #[uniffi(default = [])] pub expected_current_revisions: Vec, } @@ -108,34 +118,46 @@ pub struct WrittenRecords { /// The record a correction wrote. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct CorrectedRecord { + /// The record at its new revision. pub record: CurrentRecord, + /// The database revision after the change. pub database_revision: u64, } /// What a deletion changed. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct DeletedRecord { + /// The deleted record. pub record_id: String, /// The revision that was deleted. pub record_revision: u64, + /// The database revision after the deletion. pub database_revision: u64, } /// One step a migration runs. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct MigrationStepPreview { + /// The SQL schema version the step produces. pub target_sql_schema_version: u32, + /// The step's SQL file, relative to `spec/sql/`, such as `migrations/001-initial.sql`. pub migration_file: String, + /// What the step changes, as a person reads it. pub description: String, } /// What a migration would do. Reading it changes nothing. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct MigrationPreview { + /// False when the database is already current. pub migration_needed: bool, + /// The SQL schema version the database has now. pub source_sql_schema_version: u32, + /// The SQL schema version after the migration. pub target_sql_schema_version: u32, + /// The database's ID. pub database_id: String, + /// Every step the migration runs, in order. pub planned_steps: Vec, /// Where the verified backup would go, when a migration can run. pub planned_backup_path: Option, @@ -148,7 +170,9 @@ pub struct MigrationPreview { pub struct MigrationResult { /// The verified backup, or `None` when no migration was needed. pub backup_path: Option, + /// True when a migration ran. pub migrated: bool, + /// The migration that was planned. pub preview: MigrationPreview, } @@ -266,7 +290,9 @@ pub fn current_records_from_json(json: Vec) -> Result, At /// One record with every retained revision, oldest first. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct RecordHistory { + /// The current record. pub record: CurrentRecord, + /// Every retained revision, oldest first. pub revisions: Vec, } diff --git a/mobile/src/store.rs b/mobile/src/store.rs index 36645f5a..68fc70a1 100644 --- a/mobile/src/store.rs +++ b/mobile/src/store.rs @@ -105,8 +105,10 @@ pub struct OpenDatabaseOptions { /// Options for a new database. Both are chosen by the library when absent. #[derive(Debug, Clone, uniffi::Record)] pub struct CreateDatabaseOptions { + /// The new database's ID, a UUIDv7. #[uniffi(default = None)] pub database_id: Option, + /// When the database was created. #[uniffi(default = None)] pub created_at: Option, } @@ -114,12 +116,17 @@ pub struct CreateDatabaseOptions { /// What an open handle holds. #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct DatabaseInfo { + /// The file's path, with system links resolved. pub path: String, + /// The database's ID. pub database_id: String, /// Advances once with every committed change. pub database_revision: u64, + /// The Athletic Standard version the database records, such as `3.1.0`. pub athleticstandard_version: String, + /// The SQL schema version: the last migration step applied. pub sql_schema_version: u32, + /// When the database was created. pub created_at: String, /// False for a read-only open. Writes are refused. pub writable: bool, @@ -133,6 +140,7 @@ pub struct ListRecordsOptions { /// One record type. All types when absent. #[uniffi(default = None)] pub record_type: Option, + /// Include deleted records. #[uniffi(default = false)] pub include_deleted: bool, /// From 1 to 10,000. The desktop default, 100, when absent. @@ -143,13 +151,17 @@ pub struct ListRecordsOptions { /// A verified single-file copy of the database (D328). #[derive(Debug, Clone, PartialEq, uniffi::Record)] pub struct SavedCopy { + /// The copy's path. pub path: String, + /// The database's ID, the same as the original's. pub database_id: String, /// The revision the copy holds. pub database_revision: u64, + /// The number of records in the copy. pub record_count: u64, /// The SHA-256 of the copy's bytes, as lowercase hexadecimal. pub sha256: String, + /// The copy's size in bytes. pub byte_count: u64, } From c1cc8e0069d5a523f84fd7eb136b2a899a1a5c2d Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 00:03:06 -0600 Subject: [PATCH 22/30] Add app guides and starting-point examples for iPhone and Android. mobile/README.md walks an app developer through eight steps, from looking around and choosing where the athlete's data lives to shipping, staying current, and asking for what is missing. The Swift and Android guides show each call with code from the example apps. mobile/tests/guides.rs checks that every sample is a marked region of an example file, unchanged, and that every region is shown. Each example is split by task: records, calculations, the app's own values, picked files, and the host. Each has a README that says how to start an app from it. Their tests run the guide's code on a Mac and on the emulators. The Android consumer app is now mobile/android/example. mobile/CONTRIBUTING.md holds the build, test, and release notes, and the main README gains a "Build an app" section. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release-mobile-packages.yml | 4 +- .github/workflows/validate.yml | 2 +- .gitignore | 6 +- Package.swift | 4 + README.md | 14 + docs/architecture.md | 2 +- docs/hosting.md | 4 +- mobile/CONTRIBUTING.md | 133 +++++ mobile/README.md | 421 +++++--------- mobile/android/.gitignore | 8 +- mobile/android/README.md | 512 ++++++++++++++++++ .../athleticstandard/consumer/MainActivity.kt | 197 ------- mobile/android/example/README.md | 55 ++ .../app/build.gradle.kts | 11 +- .../app/instrumented-release-rules.pro | 3 + .../athleticstandard/example/ExampleTest.kt | 95 ++++ .../app/src/main/AndroidManifest.xml | 6 +- .../ai/athleticstandard/example/AppValues.kt | 44 ++ .../athleticstandard/example/Calculations.kt | 70 +++ .../ai/athleticstandard/example/Documents.kt | 31 ++ .../example/HostConnection.kt | 46 ++ .../athleticstandard/example/MainActivity.kt | 153 ++++++ .../ai/athleticstandard/example/Records.kt | 191 +++++++ .../app/src/main/res/values/strings.xml | 0 .../main/res/xml/network_security_config.xml | 0 .../{consumer => example}/app/test-rules.pro | 0 .../{consumer => example}/build.gradle.kts | 0 .../{consumer => example}/gradle.properties | 0 .../{consumer => example}/settings.gradle.kts | 2 +- mobile/scripts/stage-android.sh | 18 +- .../AthleticStandardExample/AppValues.swift | 31 ++ .../Calculations.swift | 46 ++ .../AthleticStandardExample/Documents.swift | 26 + .../AthleticStandardExample/ExampleApp.swift | 124 ++--- .../HostConnection.swift | 46 ++ .../AthleticStandardExample/README.md | 47 ++ .../AthleticStandardExample/Records.swift | 159 ++++++ mobile/swift/README.md | 451 +++++++++++++++ .../ExampleTests.swift | 83 +++ mobile/tests/guides.rs | 151 ++++++ mobile/tests/versions.rs | 2 +- tools/public-data-allowlist.json | 8 +- 42 files changed, 2613 insertions(+), 593 deletions(-) create mode 100644 mobile/CONTRIBUTING.md create mode 100644 mobile/android/README.md delete mode 100644 mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt create mode 100644 mobile/android/example/README.md rename mobile/android/{consumer => example}/app/build.gradle.kts (87%) rename mobile/android/{consumer => example}/app/instrumented-release-rules.pro (66%) create mode 100644 mobile/android/example/app/src/androidTest/kotlin/ai/athleticstandard/example/ExampleTest.kt rename mobile/android/{consumer => example}/app/src/main/AndroidManifest.xml (85%) create mode 100644 mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/AppValues.kt create mode 100644 mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Calculations.kt create mode 100644 mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Documents.kt create mode 100644 mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/HostConnection.kt create mode 100644 mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/MainActivity.kt create mode 100644 mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Records.kt rename mobile/android/{consumer => example}/app/src/main/res/values/strings.xml (100%) rename mobile/android/{consumer => example}/app/src/main/res/xml/network_security_config.xml (100%) rename mobile/android/{consumer => example}/app/test-rules.pro (100%) rename mobile/android/{consumer => example}/build.gradle.kts (100%) rename mobile/android/{consumer => example}/gradle.properties (100%) rename mobile/android/{consumer => example}/settings.gradle.kts (94%) create mode 100644 mobile/swift/Examples/AthleticStandardExample/AppValues.swift create mode 100644 mobile/swift/Examples/AthleticStandardExample/Calculations.swift create mode 100644 mobile/swift/Examples/AthleticStandardExample/Documents.swift create mode 100644 mobile/swift/Examples/AthleticStandardExample/HostConnection.swift create mode 100644 mobile/swift/Examples/AthleticStandardExample/README.md create mode 100644 mobile/swift/Examples/AthleticStandardExample/Records.swift create mode 100644 mobile/swift/README.md create mode 100644 mobile/swift/Tests/AthleticStandardExampleTests/ExampleTests.swift create mode 100644 mobile/tests/guides.rs diff --git a/.github/workflows/release-mobile-packages.yml b/.github/workflows/release-mobile-packages.yml index 4379dd76..2af94cc1 100644 --- a/.github/workflows/release-mobile-packages.yml +++ b/.github/workflows/release-mobile-packages.yml @@ -8,7 +8,7 @@ # this repository by version, as an app does, and runs it offline. # # maven-check installs `ai.athleticstandard:athleticstandard` from Maven Central -# in the consumer app and runs the library's tests on an emulator, offline from +# in the example app and runs the library's tests on an emulator, offline from # any host except the local test host. name: Release iPhone and Android packages @@ -110,7 +110,7 @@ jobs: adb reverse "tcp:$ATH_TEST_HOST_PORT" "tcp:$ATH_TEST_HOST_PORT" adb reverse "tcp:$ATH_TEST_ISSUER_PORT" "tcp:$ATH_TEST_ISSUER_PORT" cd mobile/android - ./gradlew --no-daemon -p consumer :app:connectedDebugAndroidTest \ + ./gradlew --no-daemon -p example :app:connectedDebugAndroidTest \ -Pathleticstandard.repository=https://repo1.maven.org/maven2 -Pathleticstandard.fixtures="$fixtures" \ -Pandroid.testInstrumentationRunnerArguments.hostUrl="$ATH_TEST_HOST_URL" \ -Pandroid.testInstrumentationRunnerArguments.issuer="$ATH_TEST_ISSUER" diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 79644b1e..3faca342 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -313,7 +313,7 @@ jobs: if-no-files-found: error # The Android library (D331, D332). Publishes it to a local Maven repository, - # builds a consumer app that resolves it by coordinate, checks 16 KB alignment + # builds the example app that resolves it by coordinate, checks 16 KB alignment # of every native library in the shrunk release APK, and runs the library's # tests through the installed copy on an emulator, in a debug and a shrunk # release build. GitHub's Linux runners have no 16 KB x86_64 emulator image, diff --git a/.gitignore b/.gitignore index 3e8948d7..17e87080 100644 --- a/.gitignore +++ b/.gitignore @@ -69,9 +69,9 @@ validation-data/ # in tools/public-data-allowlist.json like the fixtures above. !mobile/android/athleticstandard/src/androidTest/AndroidManifest.xml !mobile/android/athleticstandard/src/main/AndroidManifest.xml -!mobile/android/consumer/app/src/main/AndroidManifest.xml -!mobile/android/consumer/app/src/main/res/values/strings.xml -!mobile/android/consumer/app/src/main/res/xml/network_security_config.xml +!mobile/android/example/app/src/main/AndroidManifest.xml +!mobile/android/example/app/src/main/res/values/strings.xml +!mobile/android/example/app/src/main/res/xml/network_security_config.xml # Large deterministic release fixtures are generated locally or in the release job. /performance/generated/ diff --git a/Package.swift b/Package.swift index 3419432f..7b70fbc5 100644 --- a/Package.swift +++ b/Package.swift @@ -40,5 +40,9 @@ let package = Package( .testTarget( name: "AthleticStandardHostTests", dependencies: ["AthleticStandard", "AthleticStandardHost"], path: "mobile/swift/Tests/AthleticStandardHostTests"), + // Runs the example's code, which the Swift guide shows. + .testTarget( + name: "AthleticStandardExampleTests", dependencies: ["AthleticStandard", "AthleticStandardExample"], + path: "mobile/swift/Tests/AthleticStandardExampleTests"), ] ) diff --git a/README.md b/README.md index cf6eb38a..af2a9c65 100644 --- a/README.md +++ b/README.md @@ -396,6 +396,20 @@ The athlete can export the complete record at any time, and it opens in ordinary [`docs/hosting.md`](docs/hosting.md) explains how to run a host and how apps call it. `ath-host` is not in the release archives or the npm package. Build it from source. +## Build an app + +iPhone and Android apps use the same Rust library as `ath`, so they get the same +record checks, messages, calculations, and file handling. Every record type and every +calculation answer is a Swift and a Kotlin type. + +- **iPhone:** add the Swift package `https://github.com/mwhitham/ath` by version. +- **Android:** add `ai.athleticstandard:athleticstandard` from Maven Central. + +[`mobile/README.md`](mobile/README.md) walks through building an app, from choosing +where the athlete's data lives to shipping it. The [Swift guide](mobile/swift/README.md) +and the [Android guide](mobile/android/README.md) show the calls, with code from +tested example apps that are starting points for your own. + ## Predict and grade Inside an agent harness, ask the database for prediction evidence: diff --git a/docs/architecture.md b/docs/architecture.md index b8cd323c..8483930d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -40,7 +40,7 @@ Paths below are relative to the repository root. | The npm loader for the WebAssembly core (`athleticstandard/core`) | `packages/npm/src/core.ts` | the WebAssembly core | | Hosting many athletes' records: sign-in checks, grants, the HTTPS API, write receipts, working copies, attachment buckets | `host/` (`ath-host`) | the library with its `changesets` feature | | The npm host connection (`connectHost`) | `packages/npm/src/host.ts` | the host API | -| iPhone and Android bindings: the UniFFI crate, the Swift package, the Android library, their build and test scripts | `mobile/` ([README](../mobile/README.md)) | the core | +| iPhone and Android bindings: the UniFFI crate, the Swift package (manifest: root `Package.swift`), the Android library, the example apps, their build and test scripts | `mobile/` ([app guide](../mobile/README.md), [contributing](../mobile/CONTRIBUTING.md)) | the core, with its `uniffi` feature | Rules that keep this table true: diff --git a/docs/hosting.md b/docs/hosting.md index 60cf6791..9bb256f5 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -782,8 +782,8 @@ npm package `athleticstandard`. [`examples/host-starter/`](../examples/host-star runs a coach's steps with it, and [`examples/host-mcp/`](../examples/host-mcp/) is an MCP server built on it. [`examples/host-swift/`](../examples/host-swift/) is a Swift client for macOS and iOS apps that runs the same coach steps. The iPhone and Android -packages in [`mobile/`](../mobile/README.md#connect-to-a-host) include a client with -browser sign-in for owners and coaches (D330). +packages in [`mobile/`](../mobile/README.md#5-if-you-chose-a-host) include a client +with browser sign-in for owners and coaches (D330). ### 7.1 Conventions diff --git a/mobile/CONTRIBUTING.md b/mobile/CONTRIBUTING.md new file mode 100644 index 00000000..da121a46 --- /dev/null +++ b/mobile/CONTRIBUTING.md @@ -0,0 +1,133 @@ +# Working on the phone library + +This page is for changing the library itself. To build an app with it, read +[Build an iPhone or Android app](README.md). + +| Folder | What it holds | +|---|---| +| `src/` | The `athleticstandard-mobile` Rust crate: the calls and types the bindings expose. | +| `bindgen/` | `uniffi-bindgen`, built from the same locked UniFFI version. | +| `swift/` | The Swift package's sources, tests, and example. Its manifest is `Package.swift` at the repository root. | +| `android/` | The Android library `ai.athleticstandard:athleticstandard`, and the example app in `android/example/`. | +| `scripts/` | Build, test, and release scripts for both platforms. | +| `tests/` | Rust tests of the binding, the exporter that writes the phone test bundle, and the guide check. | + +## How the bindings are made + +UniFFI generates Swift and Kotlin from two crates +([D325](../build-history/v3.1.0/decisions.md#d325-phones-get-the-library-through-uniffi-in-version-310), +[D329](../build-history/v3.1.0/decisions.md#d329-records-and-results-are-generated-swift-and-kotlin-types)): + +- `athleticstandard-core` marks its record and result types under its `uniffi` + feature. Only this crate turns the feature on. `core/uniffi.toml` names them: in + Swift they join the `AthleticStandard` module, and in Kotlin they are in + `ai.athleticstandard.core`. +- `athleticstandard-mobile` holds the calls: `Database`, `RecordSnapshot`, the + converters, and the extension calls. `mobile/uniffi.toml` names them. + +A Rust doc comment becomes the Swift or Kotlin documentation that Xcode and Android +Studio show. The phone crate denies missing documentation (`#![deny(missing_docs)]` +in `src/lib.rs`), so every call, and every type, field, and case it defines, has one. +Every call is in this crate. Of the record and result types from the core, about +half have a description, and few of their fields and cases do; SPEC.md describes +the record fields. The generated Swift and Kotlin, the XCFramework, and the native Android +libraries are build output and are not committed +([D327](../build-history/v3.1.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). + +A phone write builds the npm client's JSON request and runs the same protocol +operation as the desktop, so a rule changes in one place. + +## Build + +You need the Rust toolchain from `rust-toolchain.toml` with these targets: + +```sh +rustup target add aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios \ + aarch64-apple-darwin x86_64-apple-darwin aarch64-linux-android x86_64-linux-android +``` + +**Swift.** `mobile/scripts/build-apple.sh [debug|release]` builds the static +libraries, generates the Swift, and writes +`mobile/swift/build/AthleticStandardFFI.xcframework`. The root `Package.swift` uses it +on every commit except a release's. It needs Xcode's iPhone SDKs. It does not need +Xcode's command-line license, because it assembles the XCFramework itself. + +**Android.** `mobile/android/gradlew :athleticstandard:assembleRelease` runs +`mobile/scripts/build-android.sh`, which builds `libathleticstandard_mobile.so` for +arm64-v8a and x86_64 with NDK 29.0.14206865 and checks that every library is aligned +for 16 KB memory pages. Set `ANDROID_HOME` to the SDK and `JAVA_HOME` to JDK 17 or +later. Pass `-Pathleticstandard.rustProfile=debug` for a faster local build. + +## Test + +The tests run one shared bundle of cases that the desktop library writes +([D333](../build-history/v3.1.0/decisions.md#d333-one-fixture-bundle-tests-every-platform)). +`mobile/tests/fixtures.rs` runs every case through the binding's Rust functions during +`cargo test`, and writes the bundle when `ATH_MOBILE_FIXTURES` names a folder. Each +suite file lists its cases, the expected outcome of each, and the skipped cases with +their documented reasons. A phone run must skip exactly those. + +```sh +mobile/scripts/test-apple.sh # this Mac, then an iPhone simulator +mobile/scripts/test-apple.sh --mac-only # this Mac only +mobile/scripts/test-android.sh # a running emulator or a connected phone +``` + +Both scripts also run the desktop round trip. `mobile/scripts/roundtrip.sh create` has +the desktop `ath` create a file with one reading. The phone tests open it as a picked +document, correct the reading, close and resume it, and save it. Then +`roundtrip.sh verify` has the desktop `ath` check the saved file: the same database +ID, the reading at revision 2, revision 1 kept, and `ath check` passing. + +`test-apple.sh` needs a full Xcode whose license has been accepted for the simulator +run. On a Mac it runs `swift test` from the repository root, including the example's +tests. + +**The guides.** `mobile/tests/guides.rs` checks that every code sample in the Swift +and Android guides is a marked region of an example file, unchanged. To change a +sample, change the example between its `// guide: ` and `// end guide` lines, +then copy the region into the guide. + +**The host client.** `mobile/scripts/host-test-env.sh` starts a real `ath-host` and +`host/examples/test-sign-in-provider.rs`, a test-only provider that answers like the +WorkOS recipe and signs with the fixed test key. The tests sign in through a stand-in +browser, write with retries, refresh and rotate tokens, and check a stale correction, a +key reused for another request, a cancelled and a foreign callback, a revoked coach, +and a disconnected app. They do not run the system browser or a real WorkOS account; +that check belongs with [issue 57](https://github.com/mwhitham/ath/issues/57). + +## Release + +Both packages ship with each release and carry its version +([D332](../build-history/v3.1.0/decisions.md#d332-how-the-packages-are-released)). +Publication stays with the maintainer. + +- `mobile/scripts/stage-apple.sh ` builds the release XCFramework, zips it with + fixed file times, and writes the files of the Swift package release commit: the root + `Package.swift` naming the release asset by address and checksum, and the generated + Swift. It stages the same commit, pointing at the zip instead, in a clone of this + repository tagged with the version. A test package resolves the clone by version and + runs the package tests on this Mac and on an iPhone simulator. `apple-report.json` + records the hashes, slices, and tool versions. +- `mobile/scripts/stage-android.sh ` publishes the Android library to a local + Maven repository and checks that its POM declares the JNA runtime. The example app + in `android/example/` resolves the library by coordinate from there, builds a shrunk + release APK, checks that every native library in it is aligned for 16 KB pages, and + runs the library's tests and its own through the installed copy, in a debug and a + shrunk release build, on every connected device. `android-report.json` records the + results. +- The `mobile-apple` and `mobile-android` jobs in `.github/workflows/validate.yml` run + both scripts for every release check. A release from `main` then tags one commit on + top of the tested commit with the Swift package release files, adds the tested zip + and both reports to the GitHub release, and uploads the tested Maven bundle to Maven + Central as a deployment that the maintainer publishes there. With no Central + credential, it skips that upload and says the release is partial. A release from a + pushed tag cannot add the Swift package commit, and says so. +- After that, the maintainer runs `.github/workflows/release-mobile-packages.yml` for + the tag. It checks that the tag's `Package.swift` names the tested zip, and installs + both packages from their public locations. + +Before the first release, the maintainer verifies the `ai.athleticstandard` namespace +on Maven Central and adds the `MAVEN_CENTRAL_USERNAME`, `MAVEN_CENTRAL_PASSWORD`, +`MAVEN_SIGNING_KEY`, and `MAVEN_SIGNING_PASSPHRASE` secrets to the `release` +environment. diff --git a/mobile/README.md b/mobile/README.md index 46e69d64..5428007c 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -1,288 +1,137 @@ -# Athletic Standard for iPhone and Android +# Build an iPhone or Android app -This folder builds the Athletic Standard library for iPhone and Android apps +The Athletic Standard library runs inside iPhone and Android apps. It is the same Rust +library as the desktop `ath` program, so an app gets the same record checks, messages, +calculations, and file handling ([D325](../build-history/v3.1.0/decisions.md#d325-phones-get-the-library-through-uniffi-in-version-310)). -The rules stay in Rust. UniFFI generates the Swift and Kotlin bindings, so an app -gets the same record checks, messages, and results as the desktop `ath` program. - -| Folder | What it holds | -|---|---| -| `src/` | The `athleticstandard-mobile` Rust crate: the functions and types the bindings expose. | -| `bindgen/` | `uniffi-bindgen`, built from the same locked UniFFI version. | -| `swift/` | The sources, tests, and example of the Swift package `AthleticStandard` for iOS 17 and later, and macOS 14 and later for tests. Its manifest is `Package.swift` at the repository root. | -| `android/` | The Android library `ai.athleticstandard:athleticstandard` for API 24 and later. | -| `scripts/` | Build and test scripts for both platforms. | -| `tests/` | Rust tests of the binding, and the exporter that writes the phone test bundle. | - -The generated Swift and Kotlin, the XCFramework, and the native Android libraries are -build output. They are not committed -([D327](../build-history/v3.1.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). - -## What an app can call - -- `libraryVersion()`: the version this library writes and reports, such as `3.1.0`. -- `validate(shape:json:)`: check UTF-8 JSON against a published shape, such as - `CurrentRecord` or `WorkoutSessionData`. It returns the checked JSON, or throws - `AthleticStandardError.Invalid` with every issue in the desktop order. -- `validateCurrentRecord(json:)`: check one complete current record, including the - rule that an athlete report never names a source. - -Record bodies and results cross as UTF-8 JSON bytes: `Data` in Swift and `ByteArray` -in Kotlin -([D329](../build-history/v3.1.0/decisions.md#d329-values-cross-the-boundary-as-json-text-and-failures-are-typed)). -Every failure is `AthleticStandardError` in Swift and `AthleticStandardException` in -Kotlin. Each has a `code` that matches the desktop error code, a `detail` with the -desktop message, and, for an invalid value, `issues`. An issue's `path` keeps field -names and list positions apart. - -## Real athlete files - -`Database` opens one `.ath.sqlite` file through the desktop store -([D327](../build-history/v3.1.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). -Edits run the same record operations the npm client runs, with the same inputs and -outputs as UTF-8 JSON, so they get the same checks and messages: - -| Call | What it does | -|---|---| -| `Database.create(path, options)` / `Database.open(path, options)` | Create a new file, or open one. Options: `readOnly`, `allowOutdatedSchema`, `expectedDatabaseId`. An outdated file is refused with `MigrationRequired`, which carries the desktop migration preview. | -| `info()` | The database ID, revision, versions, and whether it takes writes. | -| `getRecord`, `listRecords`, `recordRevisions` | Read current records and history as JSON. | -| `writeRecords`, `writeRecordChanges`, `correctRecord`, `deleteRecord` | Edit records. A correction carries the revision the person edited; a stale one is refused with `Stale` and changes nothing. | -| `runOperation(name, input)` | Any other listed record, query, view, or calculation operation of the npm client. | -| `migrationPreview()`, `migrate(backupPath)` | Preview a migration, then run it after a verified backup. | -| `saveCopy(destination)` | Write a verified single-file copy, including edits still in SQLite's companion log, with its SHA-256. | -| `close()` | Close the file. In Kotlin this is `closeDatabase()`, because Kotlin's `close()` frees the native object. | - -A handle runs one call at a time. Calls do file and SQLite work on the calling -thread, so call them away from the main thread. The binding resolves the system links -in front of app folders (`/var` on iOS, `/data/user/0` on Android) before it opens a -file. The desktop store refuses a path through a symbolic link. - -## Calculations - -Calculations run the desktop methods on records from memory or from a file -([D326](../build-history/v3.1.0/decisions.md#d326-calculations-ask-for-their-data-through-one-reader-interface)). -Both entry points give the desktop JSON: the `ath apply --json` object and the -`ath calculate --json` receipt. - -- **From memory.** `RecordSnapshotBuilder` takes batches of current records as a JSON - array, the shape `listRecords` returns. Supply the sources, the athlete profile, and - the samples the calculation reads; deleted records may be included. A batch with an - invalid record or a repeated ID is refused and leaves the builder as it was. - `finish()` gives a `RecordSnapshot`, which cannot change and can be shared between - threads. The records supplied are all the data a calculation sees: a range input - whose source is missing is left out, and a missing profile means no saved timezone. -- **From a file.** `Database.apply` and `Database.calculate` read the file inside one - read snapshot. -- `apply(recordId, skill)` runs one calculation skill on one record. `skill` is - `CalculationSkill.Shipped(name)` for a skill shipped with the library, or - `CalculationSkill.Text(text)` for an edited copy. A coaching skill or a range - calculation is refused with the command that runs it. -- `applyWith(recordId, skill, parameters)` takes the options of `ath apply --set`. A - threshold method may run without a record and takes `name=value` parameters, such - as `operation` and `end_date`. Every other skill needs a record and takes none. -- A `RecordSnapshot` does not hold device recordings yet. The 3.0.0 methods that read - recordings or the intensity reference in effect, such as `heart-rate-zones`, - `training-load-heart-rate`, and the threshold methods, are refused from memory with a - message that says to run them on a database. Run them on a `Database`. -- `calculate(request)` runs one of the eight range calculations. `RangeRequest` has the - options `ath calculate` takes; `RangeGroup.Ungrouped` is the desktop's `none`. -- `shippedCalculationNames()` and `shippedSkillText(name)` read the shipped skills. - -Calendar days use the bundled timezone data, never the phone's own timezone, so the -same request gives the same answer on every device. - -### Where to keep the file - -Recommend local storage, and keep iCloud Drive and other locations selectable -([D328](../build-history/v3.1.0/decisions.md#d328-where-a-phone-keeps-the-file)). -`FileLocationAdvice.recommendation` holds the suggested wording: "We recommend -keeping your working file on this device. Editing the same file on two devices -through iCloud Drive can cause sync conflicts." - -- A file in the app's own folder (`FileLocationAdvice.localFolder`) opens in place with - `Database.open`. An edit is saved when it commits. -- A document picked from another location opens with `PickedDocument.open`. It copies - the document into a working folder (with file coordination on iOS, through the - content URI on Android) and records its SHA-256. Edits commit to the working copy. - `save()` writes a verified copy and replaces the document only if it still has the - recorded content. Otherwise it throws `DocumentChangedElsewhere` (Swift) or - `DocumentChangedElsewhereException` (Kotlin), and `saveCopy(to:)` writes a new - document instead. A failed save keeps every local edit. -- `hasUnsavedEdits()` tells the two facts apart: the edit committed locally, and the - picked document received it. -- `state` and `PickedDocument.resume` reopen the working copy after the app restarts. - On Android, take a persistable permission for the document's URI. -- A single-file save does not carry attachment files. Use a package export for them. - -## Connect to a host - -Local files need no account and no network. Connecting to an `ath-host` is optional -([D330](../build-history/v3.1.0/decisions.md#d330-the-packages-include-a-host-client-with-browser-sign-in)). -The Swift module `AthleticStandardHost` and the Kotlin package `ai.athleticstandard.host` -hold the same client. It needs no native library. - -Give it the host's address, the app's registered public client ID, and its registered -callback address, then sign in. The client reads the host's protected-resource -metadata and the sign-in provider's discovery document, opens the provider in the -system browser with the authorization code flow and S256 PKCE, checks that the -callback carries this sign-in's `state`, and asks for a token for the host's resource. -It refreshes the token before it expires. - -```swift -import AthleticStandardHost - -let configuration = HostSignInConfiguration( - hostURL: URL(string: "https://records.example.org")!, clientID: "client_01EXAMPLE", - redirectURI: URL(string: "org.example.athlete:/oauth/callback")!) -let signIn = HostSignIn(configuration: configuration, store: KeychainTokenStore(configuration: configuration)) -try await signIn.signIn(browser: SystemBrowser { window }) // ASWebAuthenticationSession -let host = signIn.client() -let me = try await host.me() // the records this person owns -``` - -```kotlin -val configuration = HostSignInConfiguration( - hostUrl = "https://records.example.org", clientId = "client_01EXAMPLE", - redirectUri = "org.example.athlete:/oauth/callback", -) -val signIn = HostSignIn(configuration, KeystoreTokenStore(context)) -signIn.signIn(CustomTabsBrowser(activity)) // away from the main thread -val host = signIn.client() -``` - -On Android, add the `INTERNET` permission, and route the callback address to the -library's redirect activity in the app's manifest. The library declares neither, so -an app that only uses local files gets neither: - -```xml - - - - - - - - - -``` - -Call `CustomTabsBrowser.cancelPendingSignIn()` from the activity's `onResume` when the -person comes back without signing in. - -Tokens stay in the iOS Keychain (`KeychainTokenStore`) or in a private file encrypted -with an Android Keystore key (`KeystoreTokenStore`), never in an athlete file or -export. `signOut()` forgets them. An app that already has a session for this host and -app can skip `HostSignIn` and give `HostClient` a function that returns a current -access token. - -**Writes.** `prepareRecordCreation`, `prepareCorrection`, and `prepareDeletion` build a -`PreparedWrite`: the exact request bytes and a new `Idempotency-Key`. Keep it with the -unsent edit, and send the same `PreparedWrite` again after a lost reply; the host -returns the first answer and writes nothing new. A correction carries the revision the -person edited. If the record changed since, the host answers `stale`; keep the -person's edit for review. Connecting never links a local file or uploads it. Keeping a -local copy in step with a host is [issue 58](https://github.com/mwhitham/ath/issues/58). - -**Setting up WorkOS.** Follow [docs/hosting.md section 6.5](../docs/hosting.md#65-recipe-workos-authkit). -Register each app as a public OAuth application under Connect, and register its -callback address exactly. iOS and Android apps with different client IDs are different -apps to the host: a coach grant names one client ID, so each needs its own grant. Set -the host's public address as the Resource Indicator and the host's `audience`. - -**Tests.** `mobile/scripts/host-test-env.sh` starts a real `ath-host` and -`host/examples/test-sign-in-provider.rs`, a test-only provider that answers like the -WorkOS recipe and signs with the fixed test key. The tests sign in through a stand-in -browser, write with retries, refresh and rotate tokens, and check a stale correction, a -key reused for another request, a cancelled and a foreign callback, a revoked coach, -and a disconnected app. They do not run the system browser or a real WorkOS account; -that check belongs with [issue 57](https://github.com/mwhitham/ath/issues/57). - -## Build - -You need the Rust toolchain from `rust-toolchain.toml` with these targets: - -```sh -rustup target add aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios \ - aarch64-apple-darwin x86_64-apple-darwin aarch64-linux-android x86_64-linux-android -``` - -**Swift.** `mobile/scripts/build-apple.sh [debug|release]` builds the static libraries, -generates the Swift bindings, and writes `mobile/swift/build/AthleticStandardFFI.xcframework`. -It needs Xcode's iPhone SDKs. It does not need Xcode's command-line license, because it -assembles the XCFramework itself. - -**Android.** `mobile/android/gradlew :athleticstandard:assembleRelease` runs -`mobile/scripts/build-android.sh`, which builds `libathleticstandard_mobile.so` for -arm64-v8a and x86_64 with NDK 29.0.14206865 and checks that every library is aligned for -16 KB memory pages. Set `ANDROID_HOME` to the SDK and `JAVA_HOME` to JDK 17 or later. -Pass `-Pathleticstandard.rustProfile=debug` for a faster local build. - -## Test - -The tests run one shared bundle of cases that the desktop library writes -([D333](../build-history/v3.1.0/decisions.md#d333-one-fixture-bundle-tests-every-platform)). -`mobile/tests/fixtures.rs` runs every case through the binding's Rust functions during -`cargo test`, and writes the bundle when `ATH_MOBILE_FIXTURES` names a folder. Each -suite file lists its cases, the expected outcome of each, and the skipped cases with -their documented reasons. A phone run must skip exactly those. - -```sh -mobile/scripts/test-apple.sh # this Mac, then an iPhone simulator -mobile/scripts/test-apple.sh --mac-only # this Mac only -mobile/scripts/test-android.sh # a running emulator or a connected phone -``` - -Both scripts also run the desktop round trip. `mobile/scripts/roundtrip.sh create` has -the desktop `ath` create a file with one reading. The phone tests open it as a picked -document, correct the reading, close and resume it, and save it. Then -`roundtrip.sh verify` has the desktop `ath` check the saved file: the same database ID, -the reading at revision 2, revision 1 kept, and `ath check` passing. - -`test-apple.sh` needs a full Xcode whose license has been accepted for the simulator -run. On this Mac it uses `swift test`. - -## Release - -Both packages ship with each release and carry its version -([D332](../build-history/v3.1.0/decisions.md#d332-how-the-packages-are-released)). -Publication stays with the maintainer. - -- `mobile/scripts/stage-apple.sh ` builds the release XCFramework, zips it with - fixed file times, and writes the files of the Swift package release commit: the root - `Package.swift` naming the release asset by address and checksum, and the generated - Swift. It stages the same commit, pointing at the zip instead, in a clone of this - repository tagged with the version. A consumer package resolves the clone by version - and runs the package tests on this Mac and on an iPhone simulator. - `apple-report.json` records the hashes, slices, and tool versions. -- `mobile/scripts/stage-android.sh ` publishes the Android library to a local - Maven repository and checks that its POM declares the JNA runtime. The consumer app - in `android/consumer/` resolves the library by coordinate from there, builds a shrunk - release APK, checks that every native library in it is aligned for 16 KB pages, and - runs the library's tests through the installed copy in a debug and a shrunk release - build on every connected device. `android-report.json` records the results. -- The `mobile-apple` and `mobile-android` jobs in `.github/workflows/validate.yml` run - both scripts for every release check. A release from `main` then tags one commit on - top of the tested commit with the Swift package release files, adds the tested zip - and both reports to the GitHub release, and uploads the tested Maven bundle to Maven - Central as a deployment that the maintainer publishes there. With no Central - credential, it skips that upload and says the release is partial. -- After that, the maintainer runs `.github/workflows/release-mobile-packages.yml` for - the tag. It checks that the tag's `Package.swift` names the tested zip, and installs - both packages from their public locations. - -Apps add the Swift package with `https://github.com/mwhitham/ath` by version, and the -Android library as `ai.athleticstandard:athleticstandard` from Maven Central. Before -the first release, the maintainer verifies the `ai.athleticstandard` namespace on Maven -Central and adds the `MAVEN_CENTRAL_USERNAME`, `MAVEN_CENTRAL_PASSWORD`, -`MAVEN_SIGNING_KEY`, and `MAVEN_SIGNING_PASSPHRASE` secrets to the `release` -environment. - -An Android app that uses the library should keep only the two ABIs it ships, because -JNA carries more: - -```kotlin -android { defaultConfig { ndk { abiFilters += setOf("arm64-v8a", "x86_64") } } } -``` - +The library is the record and its rules. The app is yours: its screens, its flows, +and the data it adds. + +- **iPhone:** the Swift package in this repository. Read the [Swift guide](swift/README.md). +- **Android:** the Android library `ai.athleticstandard:athleticstandard`. Read the + [Android guide](android/README.md). + +Both guides follow the steps below and show code from the example apps, which are +tested. Each example is a starting point: copy it, rename it, and change it. + +## 1. Look around + +Run an example app. It creates a file, adds a reading and a workout, edits the +workout, stores the app's own value on it, and runs two calculations. + +- iPhone: [Examples/AthleticStandardExample](swift/Examples/AthleticStandardExample/README.md). + `swift run AthleticStandardExample` runs it on a Mac. +- Android: [example](android/example/README.md). Open `mobile/android/example` in + Android Studio. + +Read [what goes in the record](../docs/what-goes-in-the-record.md) and the field +reference, [SPEC.md](../SPEC.md). Two rules shape every app: + +- **Measured records and athlete reports never mix.** A measured record, such as a + reading or a workout, names the source it came from. An athlete report, such as how + the athlete felt, cannot name one. The library refuses a record that breaks this. +- **Sources stay apart.** Each device, export, or form the app writes from is its own + source. Calculations never pool two sources, and values typed in by hand never enter + a device calculation. + +## 2. Choose where the athlete's data lives + +| Choice | What it means | What it needs | +|---|---|---| +| **On the phone** | The record is one `.ath.sqlite` file in the app's storage. It works offline. The athlete can save a copy to iCloud Drive or another location, or export a package. | Nothing else. | +| **On a host you run** | The record lives on an `ath-host` server. The athlete can share it with a coach and use it from several devices. | A server running `ath-host`, and a sign-in provider ([docs/hosting.md](../docs/hosting.md)). | +| **Both, kept in step** | Not available on phones yet ([issue 58](https://github.com/mwhitham/ath/issues/58)). | — | + +An app can offer both of the first two. They stay separate: connecting to a host never +uploads the phone's file. + +Where to keep the file on the phone +([D328](../build-history/v3.1.0/decisions.md#d328-where-a-phone-keeps-the-file)): +recommend the app's own storage, and keep other locations selectable. +`FileLocationAdvice.recommendation` holds the suggested wording. A file in the app's +storage opens in place. A file the person picks from another location is edited +through a private copy and saved back only if nobody changed it meanwhile, so a sync +service cannot lose an edit. + +## 3. Start the project + +Create the app in Xcode or Android Studio, then add the library: + +- iPhone: add the package `https://github.com/mwhitham/ath` by version. +- Android: add `implementation("ai.athleticstandard:athleticstandard:3.1.0")`. + +Each guide lists the rest of the setup, such as the Android manifest entries a host +connection needs. + +## 4. Write the app + +Every record type, every part of a record, every list of allowed values, and every +calculation answer is a Swift and a Kotlin type +([D329](../build-history/v3.1.0/decisions.md#d329-records-and-results-are-generated-swift-and-kotlin-types)). +The guides cover, in order: + +1. Open the athlete's file, and migrate a file an older version wrote. +2. Add sources, readings, and workouts. +3. Read records. +4. Change and delete records. An edit names the revision the person edited, so an + edit made on a copy that changed since is refused, and nothing is lost. +5. Check a form before saving it. +6. Keep the app's own values on a record. +7. Run calculations on the file or on records in memory. +8. Let the person pick a file from another location. +9. Connect to a host. + +**The app's own values.** Data the format does not define, such as how the athlete +felt during a workout in the app's own words, goes in the record's `extensions`, under +a key of the app's domain written backwards, such as `com.example.myapp/feeling`. The +app writes its own Swift or Kotlin type for the value. The library checks the key and +the size limits. If a value would be useful to every app, propose it as a record +field instead ([docs/what-goes-in-the-record.md](../docs/what-goes-in-the-record.md)). + +**The app's own calculation settings.** A calculation skill is a text file whose +`ath-calculation` block names one of the library's methods and its settings, such as +`window_days: 28` for `hrv-change` ([docs/skills.md](../docs/skills.md)). To run a +method with other settings, pass an edited copy of the skill's text as +`CalculationSkill.Text`; `shippedSkillText` gives the original. A new method is new +arithmetic in the library +([docs/contributing-a-calculation.md](../docs/contributing-a-calculation.md)). + +**Threads.** Database calls do file and SQLite work on the calling thread, so call +them away from the main thread. A `Database` runs one call at a time. A finished +`RecordSnapshot` cannot change and can be shared between threads. + +## 5. If you chose a host + +1. Run `ath-host`, from the Docker image or from source + ([docs/hosting.md](../docs/hosting.md)). +2. Set up sign-in with the WorkOS recipe + ([docs/hosting.md section 6.5](../docs/hosting.md#65-recipe-workos-authkit)) or + another provider that meets the guide's rules. +3. Register the app with the provider as a public application, with its exact + callback address. iPhone and Android apps with different client IDs are different + apps to the host: a coach grant names one client ID, so each needs its own grant. +4. Use the host client in the app: `AthleticStandardHost` in Swift and + `ai.athleticstandard.host` in Kotlin + ([D330](../build-history/v3.1.0/decisions.md#d330-the-packages-include-a-host-client-with-browser-sign-in)). + It signs in through the system browser and keeps the token in the Keychain or in + storage encrypted with an Android Keystore key, never in an athlete file. + +## 6. Ship the app + +The library is under the MIT license ([LICENSE](../LICENSE)). It can go into any app, +as long as the app keeps the license notice, such as on its acknowledgements screen. + +## 7. Stay current + +Each release raises the version of both packages with the desktop program. Change the +version in Xcode or in Gradle, and read the release notes on the +[GitHub release](https://github.com/mwhitham/ath/releases). A release that changes the +database adds a migration step; the app migrates a file after a backup, as step 4 +shows. + +## 8. Ask for what is missing + +Open an issue or a pull request on [mwhitham/ath](https://github.com/mwhitham/ath) +rather than changing a copy of the library. A copy must build and host its own native +library and merge every later release by hand. [CONTRIBUTING.md](CONTRIBUTING.md) +says how to build and test the library itself. diff --git a/mobile/android/.gitignore b/mobile/android/.gitignore index 01208e97..61bdf79c 100644 --- a/mobile/android/.gitignore +++ b/mobile/android/.gitignore @@ -1,7 +1,9 @@ /build/ /.gradle/ /athleticstandard/build/ -/consumer/build/ -/consumer/app/build/ -/consumer/.gradle/ +/example/build/ +/example/app/build/ +/example/.gradle/ local.properties +# The Kotlin compiler daemon's session files. +.kotlin/ diff --git a/mobile/android/README.md b/mobile/android/README.md new file mode 100644 index 00000000..b649ab52 --- /dev/null +++ b/mobile/android/README.md @@ -0,0 +1,512 @@ +# Android guide + +This guide shows how an Android app uses the Athletic Standard library. Read +[Build an iPhone or Android app](../README.md) first: it covers the choices this guide +assumes. The code below comes from the [example app](example/README.md), which is +built and tested with the library; `mobile/tests/guides.rs` checks that the two agree. + +The library supports Android 7.0 (API 24) and later, on arm64-v8a phones and x86_64 +emulators. It needs JDK 17 or later to build. + +## Add the library + +Add Maven Central to the app's repositories, and the library to its dependencies: + + +```kotlin +dependencies { + implementation("ai.athleticstandard:athleticstandard:3.1.0") +} +``` + +The library's POM brings JNA, which the generated Kotlin uses to call the native +library. JNA carries native code for more ABIs than the library ships, so keep only +the library's two: + + +```kotlin +// The library ships these two ABIs. JNA carries more, which the app leaves out. +ndk { abiFilters += setOf("arm64-v8a", "x86_64") } +``` + +The library carries its own shrinker rules, so a release build with R8 needs no +extra rule for it. + +## How records look in Kotlin + +Every record type and every part of a record is a Kotlin class +([D329](../../build-history/v3.1.0/decisions.md#d329-records-and-results-are-generated-swift-and-kotlin-types)). +The record types are in the package `ai.athleticstandard.core`; the library's calls +and its write requests are in `ai.athleticstandard`. + +- `CurrentRecord` is one record as stored: `recordId`, `createdAt`, `currentRevision`, + `isDeleted`, `extensions`, and `data`. +- `RecordData` is a sealed class with one subclass for each record type. Its `v1` + holds that type's data, such as `WorkoutSessionData`. Read it with `when` or `as?`. +- Lists of allowed values are enum classes, such as `SourceType` and + `PointMeasurementType`. `entries` lists them, for pickers. +- Records are data classes with `val` fields. Change one with `copy(...)`. +- Whole numbers that cannot be negative, such as revisions, are `ULong`. +- Times are text in the stored UTC form, such as `2026-11-28T16:05:07.123Z`. +- A field that holds any JSON, such as `extensions` or `suppliedFields`, is + `JsonObject`: JSON text in a `String`. + +Field names follow Kotlin style: `end_at` is `endAt`. [SPEC.md](../../SPEC.md) +describes every field. `currentRecordToJson` and `currentRecordFromJson` turn a +record into its stored JSON and back. + +Native objects, such as `Database` and `RecordSnapshot`, hold memory outside the Java +heap. They are `AutoCloseable`: `close()` frees one, and `use { }` frees it at the end +of a block. `Database.closeDatabase()` closes the file itself. + +## Open the athlete's file + + +```kotlin +/** Open the athlete's file in [folder], or create it the first time. */ +fun openFile(folder: File): Database { + val file = File(folder, "athlete.ath.sqlite") + if (file.exists()) return Database.open(file.path, OpenDatabaseOptions()) + return Database.create(file.path, CreateDatabaseOptions()) +} +``` + +`FileLocationAdvice.localFolder(context)` gives a folder in the app's own storage. + +### A file from an older version + +A newer library refuses to open a file an older version wrote, with +`AthleticStandardException.MigrationRequired`. It carries the migration preview, +including what the migration means for older programs. Migrating makes a verified +backup first. + + +```kotlin +/** + * Open a file an older version wrote. The library refuses to open it until it is + * migrated, and migrates only after it makes a verified backup. + */ +fun openOlderFile(path: String, backupFolder: File): Database { + try { + return Database.open(path, OpenDatabaseOptions()) + } catch (error: AthleticStandardException.MigrationRequired) { + // Show `error.preview.compatibilityEffect` and ask the person before going on. + val outdated = Database.open(path, OpenDatabaseOptions(allowOutdatedSchema = true)) + val backup = File(backupFolder, "before-step-${error.preview.targetSqlSchemaVersion}.ath.sqlite") + outdated.migrate(backup.path) + outdated.closeDatabase() + return Database.open(path, OpenDatabaseOptions()) + } +} +``` + +## Add sources, readings, and workouts + +A measured record names its source, so the app writes its sources first. + + +```kotlin +// Every measured record names the source it came from. Readings the app takes +// from a heart rate strap and workouts the person types in have different +// sources, and calculations keep them apart: values typed in never enter a +// device calculation. +val strap = SourceData(sourceType = SourceType.WEARABLE, dataWriter = "Example app", dataRoute = "bluetooth_strap") +val typedIn = SourceData(sourceType = SourceType.MANUAL, dataWriter = "Example app", dataRoute = "manual_entry") + +/** The ID of [source] in the file. It is written the first time it is needed. */ +fun sourceId(database: Database, source: SourceData): String { + for (record in database.listRecords(ListRecordsOptions(recordType = RecordType.SOURCE))) { + if ((record.data as? RecordData.Source)?.v1 == source) return record.recordId + } + val written = database.writeRecords(listOf(NewRecord(data = RecordData.Source(source), changedBy = RecordActor.Athlete))) + return written.records.first().recordId +} +``` + +A reading records when the app received it (`receivedAt`), when it was measured +(`recordedAt`), and the value in its stored unit. `inputTimestamp` keeps the time +text the source itself gave; this strap gives none. + + +```kotlin +/** A morning heart rate variability reading from the strap, in milliseconds. */ +fun addReading(database: Database, sourceId: String, milliseconds: Double, at: String): CurrentRecord { + val reading = PointMeasurementData( + sourceId = sourceId, + receivedAt = at, + receivedAtBasis = ReceivedAtBasis.LOCAL_WRITE_TIME, + quantity = PointMeasurementType.HRV_RMSSD, + recordedAt = at, + inputTimestamp = InputTimestampReceipt( + timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ), + value = SourceValue(standardValue = milliseconds, standardUnit = "ms", inputValue = milliseconds, inputUnit = "ms"), + ) + val written = database.writeRecords( + listOf(NewRecord(data = RecordData.PointMeasurement(reading), changedBy = RecordActor.Athlete)), + ) + return written.records.first() +} +``` + + +```kotlin +/** A workout the person logged, from its start and end times. */ +fun addWorkout(database: Database, sourceId: String, name: String, start: String, end: String): CurrentRecord { + val notReported = InputTimestampReceipt( + timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ) + val workout = WorkoutSessionData( + sourceId = sourceId, + receivedAt = end, + receivedAtBasis = ReceivedAtBasis.LOCAL_WRITE_TIME, + startAt = start, + endAt = end, + inputStartTimestamp = notReported, + inputEndTimestamp = notReported, + name = name, + sourceReportedSummaries = emptyList(), + ) + val written = database.writeRecords( + listOf(NewRecord(data = RecordData.WorkoutSession(workout), changedBy = RecordActor.Athlete)), + ) + return written.records.first() +} +``` + +`writeRecords` writes every record in one change, or none of them. A record the +library refuses throws `AthleticStandardException.Invalid` with every issue. + +## Read records + + +```kotlin +/** Every reading's value, oldest first. A list holds 100 records unless `limit` asks for up to 10,000. */ +fun readings(database: Database): List> = + database.listRecords(ListRecordsOptions(recordType = RecordType.POINT_MEASUREMENT, limit = 10_000u)) + .mapNotNull { record -> + val reading = (record.data as? RecordData.PointMeasurement)?.v1 ?: return@mapNotNull null + record.recordId to reading.value.standardValue + } +``` + +`getRecord(recordId)` reads one record, or gives `null`. `listRecords` leaves out +deleted records unless `includeDeleted` is set. + +## Change and delete records + +A correction is the complete new data, with the revision the person edited. If the +record changed after the person opened it, such as on another device, the library +refuses the correction with `Stale` and changes nothing. + + +```kotlin +/** + * Rename a workout. [record] is the copy the person edited. When the file changed + * after they opened it, the library refuses the edit and changes nothing. + */ +fun rename(database: Database, record: CurrentRecord, name: String): CurrentRecord? { + val workout = (record.data as? RecordData.WorkoutSession)?.v1 ?: return null + val correction = RecordCorrection( + recordId = record.recordId, + expectedRevision = record.currentRevision, + data = RecordData.WorkoutSession(workout.copy(name = name)), + changedBy = RecordActor.Athlete, + ) + return try { + database.correctRecord(correction).record + } catch (error: AthleticStandardException.Stale) { + // Read the record again and show the person both versions. + null + } +} +``` + + +```kotlin +/** Delete a record. Its earlier revisions stay in the file. */ +fun delete(database: Database, record: CurrentRecord) { + database.deleteRecord(DeleteRequest(record.recordId, record.currentRevision, RecordActor.Athlete)) +} +``` + + +```kotlin +/** Every revision of a record, oldest first. */ +fun history(database: Database, recordId: String): List = + database.recordRevisions(recordId).map { "revision ${it.revision}, known from ${it.becameKnownAt}" } +``` + +`writeRecordChanges` writes corrections and new records in one change. + +## Check a form before saving + +`checkRecordData` runs the same checks as a write, without writing. Each issue has a +path to the field it is about, the desktop's code, and its message. + + +```kotlin +/** The problems with a form before it is saved, each with the field it is about. */ +fun problems(data: RecordData): List = try { + checkRecordData(data) + emptyList() +} catch (error: AthleticStandardException) { + error.issues.map { "${it.pathText}: ${it.message}" } +} +``` + +## Keep the app's own values + +The app's own values go in a record's extensions, under a key of the app's domain +written backwards. The app writes its own type and turns it into JSON text with any +JSON library; the example uses Android's `org.json`. `withExtension` and `extension` +store and read the text, and the library checks the key and the size limits. + + +```kotlin +/** How the person felt during a workout. The app owns this type; the format does not. */ +data class WorkoutFeeling(val mood: String, val soreness: Int) { + fun toJson(): String = JSONObject().put("mood", mood).put("soreness", soreness).toString() + + companion object { + fun fromJson(text: String): WorkoutFeeling = JSONObject(text).let { + WorkoutFeeling(it.getString("mood"), it.getInt("soreness")) + } + } +} + +object AppValues { + /** The key is the app's domain name written backwards, then a name. */ + const val FEELING_KEY = "com.example.athlete/workout-feeling" + + /** Store the feeling on a workout, keeping the record's other app values. */ + fun saveFeeling(feeling: WorkoutFeeling, record: CurrentRecord, database: Database) { + val correction = RecordCorrection( + recordId = record.recordId, + expectedRevision = record.currentRevision, + data = record.data, + changedBy = RecordActor.Athlete, + extensions = record.extensions, + ).withExtension(FEELING_KEY, feeling.toJson()) + database.correctRecord(correction) + } + + /** The feeling stored on a workout, or null when there is none. */ + fun feeling(record: CurrentRecord): WorkoutFeeling? = record.extension(FEELING_KEY) { WorkoutFeeling.fromJson(it) } +} +``` + +With kotlinx.serialization, the same calls are +`withExtension(key, Json.encodeToString(feeling))` and +`extension(key) { Json.decodeFromString(it) }`. A correction without +extensions keeps the record's extensions as they are. + +## Run calculations + +`apply` runs one calculation skill on one record. Its answer names the method, every +field it read, and the result. + + +```kotlin +/** + * How one reading compares with the athlete's recent readings, with the shipped + * `hrv-change` method. The answer names every field it read. + */ +fun hrvChange(database: Database, readingId: String): Double? { + val answer = database.apply(readingId, CalculationSkill.Shipped("hrv-change")) + return (answer.result as? OneRecordResult.QuantityChange)?.change +} +``` + +`calculate` runs one of the eight range calculations, such as a summary, a baseline, +or a trend. `RangeRequest` takes the options `ath calculate` takes. + + +```kotlin +/** + * The weekly mean of every reading, for each source. Weeks follow the time zone + * given here, never the phone's own setting. + */ +fun weeklyMeans(database: Database, timeZone: String): List> { + val request = RangeRequest( + operation = CalculationOperation.SUMMARY, + quantity = "hrv_rmssd", + recordKind = CalculationRecordKind.MEASUREMENT, + timeZone = timeZone, + group = CalculationGroup.WEEK, + ) + val sources = (database.calculate(request).result as? CalculationResult.Summaries)?.v1 ?: return emptyList() + return sources.filterIsInstance().flatMap { source -> + source.groups.map { it.period to it.summary.mean } + } +} +``` + +The same calculations run on records the app holds in memory, through a +`RecordSnapshot`. A snapshot cannot change, so several threads can calculate on it. + + +```kotlin +/** + * The same calculation on records the app holds, such as records read from a + * host. Give it the sources and the athlete profile too. + */ +fun weeklyMeans(records: List, timeZone: String): CalculationReceipt { + val request = RangeRequest( + operation = CalculationOperation.SUMMARY, + quantity = "hrv_rmssd", + recordKind = CalculationRecordKind.MEASUREMENT, + timeZone = timeZone, + group = CalculationGroup.WEEK, + ) + return RecordSnapshotBuilder().use { builder -> + builder.addRecords(records) + builder.finish().use { snapshot -> snapshot.calculate(request) } + } +} +``` + +- `shippedCalculationNames()` lists the shipped calculation skills, and + `shippedSkillText(name)` gives one's text. `CalculationSkill.Text(text)` runs an + edited copy. +- `applyWith(recordId, skill, parameters)` takes the options of `ath apply --set`, + such as a threshold method's `operation` and `end_date`. +- A snapshot does not hold device recordings. A method that reads them, such as + `heart-rate-zones` or a threshold method, is refused from memory with a message that + says to run it on a `Database`. +- `applyResultToJson` and `calculationReceiptToJson` give the desktop's JSON. + +## Let the person pick a file + +A file the person picks with `ACTION_OPEN_DOCUMENT`, such as one on Google Drive, +opens through `PickedDocument`. It copies the file into the app's storage, and +`save()` replaces the picked file only if it still holds what was copied. + + +```kotlin +/** + * Add a reading to a file the person picked, then save it back. The library edits + * a private copy, and saves only if nobody changed the file meanwhile. Take a + * persistable permission for [uri] first. + */ +fun addReading(context: Context, uri: Uri, milliseconds: Double): String = + PickedDocument.open(context, uri).use { picked -> + val sourceId = Records.sourceId(picked.database, Records.strap) + Records.addReading(picked.database, sourceId, milliseconds, Clock.now()) + try { + picked.save() + "Saved to $uri." + } catch (error: DocumentChangedElsewhereException) { + // Keep the person's edit: offer to save it as a new file instead. + "$uri changed on another device. Your reading is kept on this device." + } + } +``` + +- `saveCopy(target)` writes the edits to a new file, such as one the person names + with `ACTION_CREATE_DOCUMENT`. +- `hasUnsavedEdits()` says whether the picked file has every local edit. +- `state` and `PickedDocument.resume(context, state)` reopen the private copy, with + its unsaved edits, after the app restarts. Keep `state` with the app's settings. +- A single-file save does not carry attachment files. Use a package export for them. + +## Connect to a host + +The `ai.athleticstandard.host` package signs in through a Custom Tab and keeps the +token in a private file encrypted with an Android Keystore key. It needs the host's +address, the app's registered client ID, and its registered callback address. + +The library declares no permission and no activity, so an app that only uses local +files gets neither. An app that connects adds the network permission: + + +```xml + + +``` + +and routes its callback address to the library's redirect activity: + + +```xml + + + + + + + + + +``` + +Call `CustomTabsBrowser.cancelPendingSignIn()` from the activity's `onResume`, for a +person who comes back without signing in. + + +```kotlin +/** + * Sign in through a Custom Tab, once. Later launches reuse the saved session. + * Call it away from the main thread. + */ +fun signIn(activity: Activity, hostUrl: String, clientId: String, redirectUri: String): HostClient { + val configuration = HostSignInConfiguration(hostUrl, clientId, redirectUri) + val signIn = HostSignIn(configuration, KeystoreTokenStore(activity)) + if (!signIn.isSignedIn()) signIn.signIn(CustomTabsBrowser(activity)) + return signIn.client() +} +``` + +Reads and writes take the same record types as the file. + + +```kotlin +/** Read the person's record on the host, and add a source to it. */ +fun addSource(host: HostClient): String { + val athleteId = host.athletes().firstOrNull()?.athleteId + ?: host.createAthlete("Example athlete").athleteId + val count = host.records(athleteId).size + val source = SourceData(sourceType = SourceType.MANUAL, dataWriter = "Example app", dataRoute = "manual_entry") + // Keep `write` with the unsent edit. After a lost reply, send the same write + // again: the host answers with the first result and writes nothing new. + val write = host.prepareRecordCreation(athleteId, RecordData.Source(source)) + val saved = host.send(write) + return "$count records; saved ${saved.records.first().recordId} at revision ${saved.databaseRevision}" +} +``` + +- `prepareCorrection(athleteId, record, data)` corrects a record at the revision the + person edited. A stale correction fails with the host code `stale`; keep the + person's edit for review. +- `PreparedWrite.toJson()` and `PreparedWrite.fromJson` keep an unsent write across a + restart. +- `signOut()` forgets the tokens. An app that already has a session for this host can + give `HostClient` a function that returns a current access token instead. +- [docs/hosting.md](../../docs/hosting.md) covers running a host and setting up + sign-in. + +## Errors + +Every library call throws `AthleticStandardException`. Its `code` matches the +desktop's error code, and `detail` holds the desktop's message. Each code is its own +subclass, so `catch` can name one, such as `AthleticStandardException.Stale`. + +| `code` | Meaning | +|---|---| +| `invalid` | A record or value breaks the format's rules. `issues` lists each one. | +| `not_found` | No record or file with that ID or path. | +| `stale` | The record changed since the revision the edit names. Nothing changed. | +| `refused` | The call is not allowed here, such as a write to a file opened read-only. | +| `migration_required` | The file needs a migration before it opens. | +| `database`, `io` | SQLite or the file system failed. | +| `error` | Any other desktop failure. | +| `malformed_json`, `unknown_shape`, `closed` | JSON that is not JSON, an unknown shape name, or a call after `closeDatabase()`. | + +The host client throws `HostException` with the host's own codes, such as `stale`. + +## Start an app from the example + +[example](example/README.md) says how. diff --git a/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt b/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt deleted file mode 100644 index faf0bfc7..00000000 --- a/mobile/android/consumer/app/src/main/kotlin/ai/athleticstandard/consumer/MainActivity.kt +++ /dev/null @@ -1,197 +0,0 @@ -package ai.athleticstandard.consumer - -import ai.athleticstandard.CalculationSkill -import ai.athleticstandard.CreateDatabaseOptions -import ai.athleticstandard.Database -import ai.athleticstandard.FileLocationAdvice -import ai.athleticstandard.ListRecordsOptions -import ai.athleticstandard.NewRecord -import ai.athleticstandard.OpenDatabaseOptions -import ai.athleticstandard.PickedDocument -import ai.athleticstandard.applyResultToJson -import ai.athleticstandard.core.InputTimestampReceipt -import ai.athleticstandard.core.MissingReason -import ai.athleticstandard.core.PointMeasurementData -import ai.athleticstandard.core.PointMeasurementType -import ai.athleticstandard.core.ReceivedAtBasis -import ai.athleticstandard.core.RecordActor -import ai.athleticstandard.core.RecordData -import ai.athleticstandard.core.RecordType -import ai.athleticstandard.core.SourceData -import ai.athleticstandard.core.SourceType -import ai.athleticstandard.core.SourceValue -import ai.athleticstandard.host.CustomTabsBrowser -import ai.athleticstandard.host.HostSignIn -import ai.athleticstandard.host.HostSignInConfiguration -import ai.athleticstandard.host.KeystoreTokenStore -import ai.athleticstandard.libraryVersion -import android.app.Activity -import android.content.Intent -import android.os.Bundle -import android.widget.Button -import android.widget.EditText -import android.widget.LinearLayout -import android.widget.ScrollView -import android.widget.TextView -import java.io.File -import kotlin.concurrent.thread - -/** - * The runnable Android example. It works offline on a file in the app's own storage, - * opens a document the person picks, and, when asked, connects to an `ath-host`: - * signs in through a Custom Tab, picks an owned record, reads it, and saves an edit. - * - * The client ID and callback below are placeholders. Register your own with the host's - * sign-in provider (mobile/README.md). - */ -class MainActivity : Activity() { - private lateinit var output: TextView - private lateinit var hostAddress: EditText - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - output = TextView(this) - hostAddress = EditText(this).apply { hint = "https://records.example.org" } - val layout = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setPadding(32, 32, 32, 32) - addView(TextView(context).apply { text = FileLocationAdvice.RECOMMENDATION }) - addView(Button(context).apply { text = "Open a file"; setOnClickListener { pickDocument() } }) - addView(hostAddress) - addView(Button(context).apply { text = "Connect to a host"; setOnClickListener { connect() } }) - addView(output) - } - setContentView(ScrollView(this).apply { addView(layout) }) - thread { show(workOffline()) } - } - - override fun onResume() { - super.onResume() - // The person came back from the sign-in tab without finishing. - CustomTabsBrowser.cancelPendingSignIn() - } - - private fun show(text: String) = runOnUiThread { output.text = text } - - /** A local file: create it once, add a reading, and run a shipped calculation. */ - private fun workOffline(): String { - val file = File(FileLocationAdvice.localFolder(this), "example.ath.sqlite") - val database = if (file.exists()) { - Database.open(file.path, OpenDatabaseOptions()) - } else { - Database.create(file.path, CreateDatabaseOptions()).also { addSource(it) } - } - try { - val sourceId = database.listRecords(ListRecordsOptions(recordType = RecordType.SOURCE)).first().recordId - val at = Clock.now() - val reading = PointMeasurementData( - sourceId = sourceId, - receivedAt = at, - receivedAtBasis = ReceivedAtBasis.LOCAL_WRITE_TIME, - quantity = PointMeasurementType.HRV_RMSSD, - recordedAt = at, - inputTimestamp = InputTimestampReceipt( - timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, - utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, - ), - value = SourceValue( - standardValue = 50.0 + (System.currentTimeMillis() / 1000) % 15, - standardUnit = "ms", - inputValueMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, - inputUnitMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, - ), - ) - val written = database.writeRecords( - listOf(NewRecord(data = RecordData.PointMeasurement(reading), changedBy = RecordActor.Athlete)), - ) - val readings = database.listRecords(ListRecordsOptions(recordType = RecordType.POINT_MEASUREMENT)) - val change = database.apply(written.records.first().recordId, CalculationSkill.Shipped("hrv-change")) - val info = database.info() - return "Athletic Standard ${libraryVersion()}\n${file.path}\n" + - "database revision ${info.databaseRevision}, ${readings.size} readings\n" + - "hrv-change on the newest reading: ${applyResultToJson(change).decodeToString()}" - } finally { - database.closeDatabase() - } - } - - private fun addSource(database: Database) { - val source = SourceData( - sourceType = SourceType.MANUAL, - dataWriter = "Athletic Standard example", - dataRoute = "manual_entry", - ) - database.writeRecords(listOf(NewRecord(data = RecordData.Source(source), changedBy = RecordActor.Athlete))) - } - - private fun pickDocument() { - startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { - addCategory(Intent.CATEGORY_OPENABLE) - type = "*/*" - }, PICK) - } - - @Deprecated("The example uses the platform result callback to avoid extra dependencies.") - override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { - super.onActivityResult(requestCode, resultCode, data) - val uri = data?.data ?: return - if (requestCode != PICK || resultCode != RESULT_OK) return - contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or - Intent.FLAG_GRANT_WRITE_URI_PERMISSION) - thread { - show(try { - PickedDocument.open(this, uri).use { picked -> - val info = picked.database.info() - "Opened a working copy of $uri\ndatabase ${info.databaseId}, revision ${info.databaseRevision}" - } - } catch (error: Exception) { - "Could not open the document: ${error.message}" - }) - } - } - - /** Sign in, pick the first owned record, read it, and save an edit. */ - private fun connect() { - val address = hostAddress.text.toString().trim() - if (address.isEmpty()) return show("Enter the host's address first.") - thread { - show(try { - val configuration = HostSignInConfiguration(address, CLIENT_ID, "$REDIRECT_SCHEME:/oauth/callback") - val signIn = HostSignIn(configuration, KeystoreTokenStore(this)) - if (!signIn.isSignedIn()) signIn.signIn(CustomTabsBrowser(this)) - val host = signIn.client() - val operator = host.capabilities().operatorDisclosure - val athlete = host.athletes().firstOrNull() ?: host.createAthlete("Example athlete").let { - host.athletes().first() - } - val records = host.records(athlete.athleteId) - val source = SourceData( - sourceType = SourceType.MANUAL, - dataWriter = "Athletic Standard example", - dataRoute = "manual_entry", - ) - val write = host.prepareRecordCreation(athlete.athleteId, RecordData.Source(source)) - val saved = host.send(write) - "Signed in to $address\n$operator\nrecord ${athlete.athleteId}: ${records.size} records\n" + - "saved record ${saved.records.first().recordId} at database revision ${saved.databaseRevision}" - } catch (error: Exception) { - "Could not connect: ${error.message}" - }) - } - } - - companion object { - private const val PICK = 1 - private const val CLIENT_ID = "client_EXAMPLE" - private const val REDIRECT_SCHEME = "ai.athleticstandard.consumer" - } -} - -/** The current instant in the stored UTC form, such as `2026-11-28T16:05:07.123Z`. */ -internal object Clock { - fun now(): String { - val format = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.ROOT) - format.timeZone = java.util.TimeZone.getTimeZone("UTC") - return format.format(java.util.Date()) - } -} diff --git a/mobile/android/example/README.md b/mobile/android/example/README.md new file mode 100644 index 00000000..f9f519ee --- /dev/null +++ b/mobile/android/example/README.md @@ -0,0 +1,55 @@ +# Android example + +A small Android app that uses the Athletic Standard library. It is a starting point: +copy it and change it. The [Android guide](../README.md) explains each part, with the +same code. + +| File in `app/src/main/kotlin/ai/athleticstandard/example/` | What it does | +|---|---| +| `Records.kt` | Opens the athlete's file, migrates an older one, adds sources, readings, and workouts, reads, renames, and deletes records, and checks a form. | +| `Calculations.kt` | Runs `hrv-change` on one reading, and weekly means on the file and on records in memory. | +| `AppValues.kt` | Stores the app's own value on a workout, as JSON text. | +| `Documents.kt` | Adds a reading to a file the person picked, and saves it back. | +| `HostConnection.kt` | Signs in to an `ath-host` and adds a source there. | +| `MainActivity.kt` | The screen that runs them. | + +The app installs the library by its coordinate, as any app does. It also runs the +library's own instrumented tests against that installed copy, with +`app/src/androidTest/.../ExampleTest.kt`, which runs this code. + +## Run it + +The example resolves the library from a local repository, so build the library first. +From `mobile/android`, with `ANDROID_HOME` and `JAVA_HOME` set: + +```sh +./gradlew :athleticstandard:publishReleasePublicationToStagingRepository +./gradlew -p example :app:installDebug +``` + +Or open `mobile/android/example` in Android Studio after the first command. +`mobile/scripts/stage-android.sh` builds it, checks its release build, and runs its +tests on every connected device. + +## Start an app from it + +1. Copy this folder, and the Gradle wrapper from `mobile/android`, to a new + repository. +2. In `settings.gradle.kts`, remove the `athleticstandard` repository: Maven Central + has the library. +3. In `app/build.gradle.kts`: + - name the version, such as + `implementation("ai.athleticstandard:athleticstandard:3.1.0")`; + - remove the `androidTest` source set lines that add the library's tests and + fixtures, and the `instrumentedBuild` setting; + - change `namespace`, `applicationId`, and `redirectScheme` to the app's own; + - keep the ABI filter. +4. Move the Kotlin files to the app's package, and change the names that belong to the + example: + - the sources' `dataWriter`, `"Example app"`, to the app's name; + - the extension key, `com.example.athlete/workout-feeling`, to a key of your own + domain written backwards; + - for a host, the client ID and callback address, to the ones you registered with + the sign-in provider. +5. Replace the heart rate strap source with the app's real sources, one for each + device, export, or form the app writes from. diff --git a/mobile/android/consumer/app/build.gradle.kts b/mobile/android/example/app/build.gradle.kts similarity index 87% rename from mobile/android/consumer/app/build.gradle.kts rename to mobile/android/example/app/build.gradle.kts index 3ea98da1..7bdbffef 100644 --- a/mobile/android/consumer/app/build.gradle.kts +++ b/mobile/android/example/app/build.gradle.kts @@ -6,25 +6,27 @@ val athleticStandardVersion = providers.gradleProperty("athleticstandard.version val library = rootDir.resolve("../athleticstandard") // The build type the instrumented tests run against: `debug`, or `release` to check // the library inside a shrunk app. -val instrumentedBuild = providers.gradleProperty("consumer.testBuildType").getOrElse("debug") +val instrumentedBuild = providers.gradleProperty("example.testBuildType").getOrElse("debug") // The fixture bundle that mobile/tests/fixtures.rs writes (D333). val fixtures = providers.gradleProperty("athleticstandard.fixtures") .getOrElse(rootDir.resolve("../../../target/mobile-fixtures").path) android { - namespace = "ai.athleticstandard.consumer" + namespace = "ai.athleticstandard.example" compileSdk = 36 defaultConfig { - applicationId = "ai.athleticstandard.consumer" + applicationId = "ai.athleticstandard.example" minSdk = 24 targetSdk = 36 versionCode = 1 versionName = athleticStandardVersion testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - manifestPlaceholders["redirectScheme"] = "ai.athleticstandard.consumer" + manifestPlaceholders["redirectScheme"] = "ai.athleticstandard.example" + // guide: abi-filters // The library ships these two ABIs. JNA carries more, which the app leaves out. ndk { abiFilters += setOf("arm64-v8a", "x86_64") } + // end guide } buildTypes { @@ -61,6 +63,7 @@ android { } dependencies { + // An app names the version, such as "ai.athleticstandard:athleticstandard:3.1.0". implementation("ai.athleticstandard:athleticstandard:$athleticStandardVersion") androidTestImplementation("androidx.test:runner:1.7.0") androidTestImplementation("androidx.test.ext:junit:1.3.0") diff --git a/mobile/android/consumer/app/instrumented-release-rules.pro b/mobile/android/example/app/instrumented-release-rules.pro similarity index 66% rename from mobile/android/consumer/app/instrumented-release-rules.pro rename to mobile/android/example/app/instrumented-release-rules.pro index fdf7c6a7..bef03ad1 100644 --- a/mobile/android/consumer/app/instrumented-release-rules.pro +++ b/mobile/android/example/app/instrumented-release-rules.pro @@ -5,3 +5,6 @@ # build checks. -keep class kotlin.** { *; } -keep class androidx.tracing.** { *; } +# The example test calls example code the app's screen does not use, such as +# Records.problems, so the example's own classes are kept whole too. +-keep class ai.athleticstandard.example.** { *; } diff --git a/mobile/android/example/app/src/androidTest/kotlin/ai/athleticstandard/example/ExampleTest.kt b/mobile/android/example/app/src/androidTest/kotlin/ai/athleticstandard/example/ExampleTest.kt new file mode 100644 index 00000000..0661fc27 --- /dev/null +++ b/mobile/android/example/app/src/androidTest/kotlin/ai/athleticstandard/example/ExampleTest.kt @@ -0,0 +1,95 @@ +package ai.athleticstandard.example + +import ai.athleticstandard.Database +import ai.athleticstandard.OpenDatabaseOptions +import ai.athleticstandard.StoreTest +import ai.athleticstandard.core.InputTimestampReceipt +import ai.athleticstandard.core.MissingReason +import ai.athleticstandard.core.ReceivedAtBasis +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.WorkoutSessionData +import android.net.Uri +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +/** The example's code, which the Android guide shows, run on a temporary folder. */ +@RunWith(AndroidJUnit4::class) +class ExampleTest { + @Test + fun theOfflineWorkRunsTwiceOnTheSameFile() { + val folder = StoreTest.folder() + val first = MainActivity.offlineSummary(folder) + assertTrue(first, first.contains("1 readings, 2 sources")) + assertTrue(first, first.contains("feeling: rested")) + assertTrue(first, first.contains("revision 1, known from")) + val second = MainActivity.offlineSummary(folder) + assertTrue(second, second.contains("2 readings, 2 sources")) + } + + @Test + fun aStaleRenameChangesNothing() { + val database = Records.openFile(StoreTest.folder()) + val sourceId = Records.sourceId(database, Records.typedIn) + val workout = Records.addWorkout(database, sourceId, "Row", "2026-01-02T06:00:00.000Z", "2026-01-02T07:00:00.000Z") + assertNotNull(Records.rename(database, workout, "Morning row")) + // The same, older copy again: the file changed since, so it is refused. + assertNull(Records.rename(database, workout, "Evening row")) + val saved = (database.getRecord(workout.recordId)!!.data as RecordData.WorkoutSession).v1 + assertEquals("Morning row", saved.name) + Records.delete(database, database.getRecord(workout.recordId)!!) + assertTrue(database.getRecord(workout.recordId)!!.isDeleted) + database.closeDatabase() + } + + @Test + fun aFormThatEndsBeforeItStartsHasAProblem() { + val notReported = InputTimestampReceipt( + timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ) + val workout = WorkoutSessionData( + sourceId = "01890f3e-e7d3-7cc0-88c8-000000000003", + receivedAt = "2026-01-02T06:00:00.000Z", + receivedAtBasis = ReceivedAtBasis.LOCAL_WRITE_TIME, + startAt = "2026-01-02T06:00:00.000Z", + endAt = "2026-01-02T05:00:00.000Z", + inputStartTimestamp = notReported, + inputEndTimestamp = notReported, + sourceReportedSummaries = emptyList(), + ) + assertEquals( + listOf("end_at: Workout session end cannot precede its start"), + Records.problems(RecordData.WorkoutSession(workout)), + ) + } + + @Test + fun anOlderFileIsMigratedAfterABackup() { + val folder = StoreTest.folder() + val file = StoreTest.fixture("outdated-2-1-0.ath.sqlite", folder) + val database = Records.openOlderFile(file.path, folder) + assertTrue(database.info().writable) + database.closeDatabase() + assertEquals(1, folder.list()!!.count { it.startsWith("before-step-") }) + } + + @Test + fun aPickedFileGetsTheReading() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val provider = StoreTest.folder() + Records.openFile(provider).closeDatabase() + val document = File(provider, "athlete.ath.sqlite") + val uri = Uri.fromFile(document) + assertEquals("Saved to $uri.", Documents.addReading(context, uri, 58.0)) + val database = Database.open(document.path, OpenDatabaseOptions(readOnly = true)) + assertEquals(listOf(58.0), Records.readings(database).map { it.second }) + database.closeDatabase() + } +} diff --git a/mobile/android/consumer/app/src/main/AndroidManifest.xml b/mobile/android/example/app/src/main/AndroidManifest.xml similarity index 85% rename from mobile/android/consumer/app/src/main/AndroidManifest.xml rename to mobile/android/example/app/src/main/AndroidManifest.xml index e5f25eae..bd4aa807 100644 --- a/mobile/android/consumer/app/src/main/AndroidManifest.xml +++ b/mobile/android/example/app/src/main/AndroidManifest.xml @@ -1,7 +1,9 @@ + + @@ -11,7 +13,8 @@ - + + @@ -21,5 +24,6 @@ + diff --git a/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/AppValues.kt b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/AppValues.kt new file mode 100644 index 00000000..29dc7c7a --- /dev/null +++ b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/AppValues.kt @@ -0,0 +1,44 @@ +// The app's own values on a record. The Android guide shows the `guide:` region. + +package ai.athleticstandard.example + +import ai.athleticstandard.Database +import ai.athleticstandard.RecordCorrection +import ai.athleticstandard.core.CurrentRecord +import ai.athleticstandard.core.RecordActor +import ai.athleticstandard.extension +import ai.athleticstandard.withExtension +import org.json.JSONObject + +// guide: app-values +/** How the person felt during a workout. The app owns this type; the format does not. */ +data class WorkoutFeeling(val mood: String, val soreness: Int) { + fun toJson(): String = JSONObject().put("mood", mood).put("soreness", soreness).toString() + + companion object { + fun fromJson(text: String): WorkoutFeeling = JSONObject(text).let { + WorkoutFeeling(it.getString("mood"), it.getInt("soreness")) + } + } +} + +object AppValues { + /** The key is the app's domain name written backwards, then a name. */ + const val FEELING_KEY = "com.example.athlete/workout-feeling" + + /** Store the feeling on a workout, keeping the record's other app values. */ + fun saveFeeling(feeling: WorkoutFeeling, record: CurrentRecord, database: Database) { + val correction = RecordCorrection( + recordId = record.recordId, + expectedRevision = record.currentRevision, + data = record.data, + changedBy = RecordActor.Athlete, + extensions = record.extensions, + ).withExtension(FEELING_KEY, feeling.toJson()) + database.correctRecord(correction) + } + + /** The feeling stored on a workout, or null when there is none. */ + fun feeling(record: CurrentRecord): WorkoutFeeling? = record.extension(FEELING_KEY) { WorkoutFeeling.fromJson(it) } +} +// end guide diff --git a/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Calculations.kt b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Calculations.kt new file mode 100644 index 00000000..db37f3e6 --- /dev/null +++ b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Calculations.kt @@ -0,0 +1,70 @@ +// Calculations on the athlete's file and on records in memory. The Android guide +// shows each `guide:` region. + +package ai.athleticstandard.example + +import ai.athleticstandard.CalculationSkill +import ai.athleticstandard.Database +import ai.athleticstandard.RecordSnapshotBuilder +import ai.athleticstandard.core.CalculationGroup +import ai.athleticstandard.core.CalculationOperation +import ai.athleticstandard.core.CalculationReceipt +import ai.athleticstandard.core.CalculationRecordKind +import ai.athleticstandard.core.CalculationResult +import ai.athleticstandard.core.CurrentRecord +import ai.athleticstandard.core.OneRecordResult +import ai.athleticstandard.core.RangeRequest +import ai.athleticstandard.core.SourceSummary + +object Calculations { + // guide: apply + /** + * How one reading compares with the athlete's recent readings, with the shipped + * `hrv-change` method. The answer names every field it read. + */ + fun hrvChange(database: Database, readingId: String): Double? { + val answer = database.apply(readingId, CalculationSkill.Shipped("hrv-change")) + return (answer.result as? OneRecordResult.QuantityChange)?.change + } + // end guide + + // guide: range + /** + * The weekly mean of every reading, for each source. Weeks follow the time zone + * given here, never the phone's own setting. + */ + fun weeklyMeans(database: Database, timeZone: String): List> { + val request = RangeRequest( + operation = CalculationOperation.SUMMARY, + quantity = "hrv_rmssd", + recordKind = CalculationRecordKind.MEASUREMENT, + timeZone = timeZone, + group = CalculationGroup.WEEK, + ) + val sources = (database.calculate(request).result as? CalculationResult.Summaries)?.v1 ?: return emptyList() + return sources.filterIsInstance().flatMap { source -> + source.groups.map { it.period to it.summary.mean } + } + } + // end guide + + // guide: memory + /** + * The same calculation on records the app holds, such as records read from a + * host. Give it the sources and the athlete profile too. + */ + fun weeklyMeans(records: List, timeZone: String): CalculationReceipt { + val request = RangeRequest( + operation = CalculationOperation.SUMMARY, + quantity = "hrv_rmssd", + recordKind = CalculationRecordKind.MEASUREMENT, + timeZone = timeZone, + group = CalculationGroup.WEEK, + ) + return RecordSnapshotBuilder().use { builder -> + builder.addRecords(records) + builder.finish().use { snapshot -> snapshot.calculate(request) } + } + } + // end guide +} diff --git a/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Documents.kt b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Documents.kt new file mode 100644 index 00000000..a901c176 --- /dev/null +++ b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Documents.kt @@ -0,0 +1,31 @@ +// A file the person picked from another location, such as Google Drive. The +// Android guide shows the `guide:` region. + +package ai.athleticstandard.example + +import ai.athleticstandard.DocumentChangedElsewhereException +import ai.athleticstandard.PickedDocument +import android.content.Context +import android.net.Uri + +object Documents { + // guide: picked-document + /** + * Add a reading to a file the person picked, then save it back. The library edits + * a private copy, and saves only if nobody changed the file meanwhile. Take a + * persistable permission for [uri] first. + */ + fun addReading(context: Context, uri: Uri, milliseconds: Double): String = + PickedDocument.open(context, uri).use { picked -> + val sourceId = Records.sourceId(picked.database, Records.strap) + Records.addReading(picked.database, sourceId, milliseconds, Clock.now()) + try { + picked.save() + "Saved to $uri." + } catch (error: DocumentChangedElsewhereException) { + // Keep the person's edit: offer to save it as a new file instead. + "$uri changed on another device. Your reading is kept on this device." + } + } + // end guide +} diff --git a/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/HostConnection.kt b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/HostConnection.kt new file mode 100644 index 00000000..30064122 --- /dev/null +++ b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/HostConnection.kt @@ -0,0 +1,46 @@ +// Connecting to an ath-host. The Android guide shows each `guide:` region. +// +// The client ID and callback are placeholders. Register your own with the host's +// sign-in provider (mobile/README.md). + +package ai.athleticstandard.example + +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.SourceData +import ai.athleticstandard.core.SourceType +import ai.athleticstandard.host.CustomTabsBrowser +import ai.athleticstandard.host.HostClient +import ai.athleticstandard.host.HostSignIn +import ai.athleticstandard.host.HostSignInConfiguration +import ai.athleticstandard.host.KeystoreTokenStore +import android.app.Activity + +object HostConnection { + // guide: host-sign-in + /** + * Sign in through a Custom Tab, once. Later launches reuse the saved session. + * Call it away from the main thread. + */ + fun signIn(activity: Activity, hostUrl: String, clientId: String, redirectUri: String): HostClient { + val configuration = HostSignInConfiguration(hostUrl, clientId, redirectUri) + val signIn = HostSignIn(configuration, KeystoreTokenStore(activity)) + if (!signIn.isSignedIn()) signIn.signIn(CustomTabsBrowser(activity)) + return signIn.client() + } + // end guide + + // guide: host-records + /** Read the person's record on the host, and add a source to it. */ + fun addSource(host: HostClient): String { + val athleteId = host.athletes().firstOrNull()?.athleteId + ?: host.createAthlete("Example athlete").athleteId + val count = host.records(athleteId).size + val source = SourceData(sourceType = SourceType.MANUAL, dataWriter = "Example app", dataRoute = "manual_entry") + // Keep `write` with the unsent edit. After a lost reply, send the same write + // again: the host answers with the first result and writes nothing new. + val write = host.prepareRecordCreation(athleteId, RecordData.Source(source)) + val saved = host.send(write) + return "$count records; saved ${saved.records.first().recordId} at revision ${saved.databaseRevision}" + } + // end guide +} diff --git a/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/MainActivity.kt b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/MainActivity.kt new file mode 100644 index 00000000..dcbad743 --- /dev/null +++ b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/MainActivity.kt @@ -0,0 +1,153 @@ +package ai.athleticstandard.example + +import ai.athleticstandard.FileLocationAdvice +import ai.athleticstandard.ListRecordsOptions +import ai.athleticstandard.core.RecordType +import ai.athleticstandard.host.CustomTabsBrowser +import ai.athleticstandard.libraryVersion +import android.app.Activity +import android.content.Intent +import android.os.Bundle +import android.widget.Button +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import java.io.File +import kotlin.concurrent.thread + +/** + * The runnable Android example, a starting point for an app. It works offline on a + * file in the app's own storage, adds a reading to a file the person picks, and, when + * asked, connects to an `ath-host`. README.md in this folder says how to start an app + * from it. + * + * The work itself is in Records.kt, Calculations.kt, AppValues.kt, Documents.kt, and + * HostConnection.kt. The client ID and callback below are placeholders. Register your + * own with the host's sign-in provider. + */ +class MainActivity : Activity() { + private lateinit var output: TextView + private lateinit var hostAddress: EditText + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + output = TextView(this) + hostAddress = EditText(this).apply { hint = "https://records.example.org" } + val layout = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(32, 32, 32, 32) + addView(TextView(context).apply { text = FileLocationAdvice.RECOMMENDATION }) + addView(Button(context).apply { text = "Add a reading to a file I pick"; setOnClickListener { pickDocument() } }) + addView(hostAddress) + addView(Button(context).apply { text = "Connect to a host"; setOnClickListener { connect() } }) + addView(output) + } + setContentView(ScrollView(this).apply { addView(layout) }) + thread { + show( + try { + offlineSummary(FileLocationAdvice.localFolder(this)) + } catch (error: Exception) { + "Could not work on the local file: ${error.message}" + }, + ) + } + } + + override fun onResume() { + super.onResume() + // The person came back from the sign-in tab without finishing. + CustomTabsBrowser.cancelPendingSignIn() + } + + private fun show(text: String) = runOnUiThread { output.text = text } + + private fun pickDocument() { + startActivityForResult( + Intent(Intent.ACTION_OPEN_DOCUMENT).apply { + addCategory(Intent.CATEGORY_OPENABLE) + type = "*/*" + }, + PICK, + ) + } + + @Deprecated("The example uses the platform result callback to avoid extra dependencies.") + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + val uri = data?.data ?: return + if (requestCode != PICK || resultCode != RESULT_OK) return + contentResolver.takePersistableUriPermission( + uri, + Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION, + ) + thread { + show( + try { + Documents.addReading(this, uri, 58.0) + } catch (error: Exception) { + "Could not open the file: ${error.message}" + }, + ) + } + } + + private fun connect() { + val address = hostAddress.text.toString().trim() + if (address.isEmpty()) return show("Enter the host's address first.") + thread { + show( + try { + val host = HostConnection.signIn(this, address, CLIENT_ID, "$REDIRECT_SCHEME:/oauth/callback") + "Signed in to $address\n${host.capabilities().operatorDisclosure}\n${HostConnection.addSource(host)}" + } catch (error: Exception) { + "Could not connect: ${error.message}" + }, + ) + } + } + + companion object { + private const val PICK = 1 + private const val CLIENT_ID = "client_EXAMPLE" + private const val REDIRECT_SCHEME = "ai.athleticstandard.example" + + /** Open the file in [folder], add a reading and a workout, and calculate on them. */ + fun offlineSummary(folder: File): String { + val database = Records.openFile(folder) + try { + val now = System.currentTimeMillis() + val reading = Records.addReading( + database, + Records.sourceId(database, Records.strap), + 50.0 + (now / 1000) % 15, + Clock.at(now), + ) + val workout = Records.addWorkout( + database, + Records.sourceId(database, Records.typedIn), + "Row", + Clock.at(now - 3_600_000), + Clock.at(now), + ) + Records.rename(database, workout, "Morning row") + val renamed = database.getRecord(workout.recordId) ?: workout + AppValues.saveFeeling(WorkoutFeeling("rested", 2), renamed, database) + val feeling = database.getRecord(workout.recordId)?.let(AppValues::feeling) + val change = Calculations.hrvChange(database, reading.recordId) + val weeks = Calculations.weeklyMeans(database, "UTC") + val sources = database.listRecords(ListRecordsOptions(recordType = RecordType.SOURCE)).size + return "Athletic Standard ${libraryVersion()}\n" + + "${Records.readings(database).size} readings, $sources sources, " + + "database revision ${database.info().databaseRevision}\n" + + "hrv-change on the newest reading: ${change ?: "not enough readings yet"}\n" + + "weekly means: ${weeks.joinToString { "${it.first} ${it.second}" }}\n" + + "workout history: ${Records.history(database, workout.recordId).joinToString("; ")}\n" + + "feeling: ${feeling?.mood ?: "none"}" + } finally { + database.closeDatabase() + } + } + } +} diff --git a/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Records.kt b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Records.kt new file mode 100644 index 00000000..251b8f27 --- /dev/null +++ b/mobile/android/example/app/src/main/kotlin/ai/athleticstandard/example/Records.kt @@ -0,0 +1,191 @@ +// Records on one file in the app's own storage. The Android guide +// (mobile/android/README.md) shows each `guide:` region; mobile/tests/guides.rs +// checks that the guide and this file agree. + +package ai.athleticstandard.example + +import ai.athleticstandard.AthleticStandardException +import ai.athleticstandard.CreateDatabaseOptions +import ai.athleticstandard.Database +import ai.athleticstandard.DeleteRequest +import ai.athleticstandard.ListRecordsOptions +import ai.athleticstandard.NewRecord +import ai.athleticstandard.OpenDatabaseOptions +import ai.athleticstandard.RecordCorrection +import ai.athleticstandard.checkRecordData +import ai.athleticstandard.core.CurrentRecord +import ai.athleticstandard.core.InputTimestampReceipt +import ai.athleticstandard.core.MissingReason +import ai.athleticstandard.core.PointMeasurementData +import ai.athleticstandard.core.PointMeasurementType +import ai.athleticstandard.core.ReceivedAtBasis +import ai.athleticstandard.core.RecordActor +import ai.athleticstandard.core.RecordData +import ai.athleticstandard.core.RecordType +import ai.athleticstandard.core.SourceData +import ai.athleticstandard.core.SourceType +import ai.athleticstandard.core.SourceValue +import ai.athleticstandard.core.WorkoutSessionData +import ai.athleticstandard.issues +import java.io.File + +object Records { + // guide: open-file + /** Open the athlete's file in [folder], or create it the first time. */ + fun openFile(folder: File): Database { + val file = File(folder, "athlete.ath.sqlite") + if (file.exists()) return Database.open(file.path, OpenDatabaseOptions()) + return Database.create(file.path, CreateDatabaseOptions()) + } + // end guide + + // guide: open-outdated + /** + * Open a file an older version wrote. The library refuses to open it until it is + * migrated, and migrates only after it makes a verified backup. + */ + fun openOlderFile(path: String, backupFolder: File): Database { + try { + return Database.open(path, OpenDatabaseOptions()) + } catch (error: AthleticStandardException.MigrationRequired) { + // Show `error.preview.compatibilityEffect` and ask the person before going on. + val outdated = Database.open(path, OpenDatabaseOptions(allowOutdatedSchema = true)) + val backup = File(backupFolder, "before-step-${error.preview.targetSqlSchemaVersion}.ath.sqlite") + outdated.migrate(backup.path) + outdated.closeDatabase() + return Database.open(path, OpenDatabaseOptions()) + } + } + // end guide + + // guide: add-source + // Every measured record names the source it came from. Readings the app takes + // from a heart rate strap and workouts the person types in have different + // sources, and calculations keep them apart: values typed in never enter a + // device calculation. + val strap = SourceData(sourceType = SourceType.WEARABLE, dataWriter = "Example app", dataRoute = "bluetooth_strap") + val typedIn = SourceData(sourceType = SourceType.MANUAL, dataWriter = "Example app", dataRoute = "manual_entry") + + /** The ID of [source] in the file. It is written the first time it is needed. */ + fun sourceId(database: Database, source: SourceData): String { + for (record in database.listRecords(ListRecordsOptions(recordType = RecordType.SOURCE))) { + if ((record.data as? RecordData.Source)?.v1 == source) return record.recordId + } + val written = database.writeRecords(listOf(NewRecord(data = RecordData.Source(source), changedBy = RecordActor.Athlete))) + return written.records.first().recordId + } + // end guide + + // guide: add-reading + /** A morning heart rate variability reading from the strap, in milliseconds. */ + fun addReading(database: Database, sourceId: String, milliseconds: Double, at: String): CurrentRecord { + val reading = PointMeasurementData( + sourceId = sourceId, + receivedAt = at, + receivedAtBasis = ReceivedAtBasis.LOCAL_WRITE_TIME, + quantity = PointMeasurementType.HRV_RMSSD, + recordedAt = at, + inputTimestamp = InputTimestampReceipt( + timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ), + value = SourceValue(standardValue = milliseconds, standardUnit = "ms", inputValue = milliseconds, inputUnit = "ms"), + ) + val written = database.writeRecords( + listOf(NewRecord(data = RecordData.PointMeasurement(reading), changedBy = RecordActor.Athlete)), + ) + return written.records.first() + } + // end guide + + // guide: add-workout + /** A workout the person logged, from its start and end times. */ + fun addWorkout(database: Database, sourceId: String, name: String, start: String, end: String): CurrentRecord { + val notReported = InputTimestampReceipt( + timestampMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + utcOffsetMissingReason = MissingReason.NOT_PROVIDED_BY_SOURCE, + ) + val workout = WorkoutSessionData( + sourceId = sourceId, + receivedAt = end, + receivedAtBasis = ReceivedAtBasis.LOCAL_WRITE_TIME, + startAt = start, + endAt = end, + inputStartTimestamp = notReported, + inputEndTimestamp = notReported, + name = name, + sourceReportedSummaries = emptyList(), + ) + val written = database.writeRecords( + listOf(NewRecord(data = RecordData.WorkoutSession(workout), changedBy = RecordActor.Athlete)), + ) + return written.records.first() + } + // end guide + + // guide: list-records + /** Every reading's value, oldest first. A list holds 100 records unless `limit` asks for up to 10,000. */ + fun readings(database: Database): List> = + database.listRecords(ListRecordsOptions(recordType = RecordType.POINT_MEASUREMENT, limit = 10_000u)) + .mapNotNull { record -> + val reading = (record.data as? RecordData.PointMeasurement)?.v1 ?: return@mapNotNull null + record.recordId to reading.value.standardValue + } + // end guide + + // guide: correct-record + /** + * Rename a workout. [record] is the copy the person edited. When the file changed + * after they opened it, the library refuses the edit and changes nothing. + */ + fun rename(database: Database, record: CurrentRecord, name: String): CurrentRecord? { + val workout = (record.data as? RecordData.WorkoutSession)?.v1 ?: return null + val correction = RecordCorrection( + recordId = record.recordId, + expectedRevision = record.currentRevision, + data = RecordData.WorkoutSession(workout.copy(name = name)), + changedBy = RecordActor.Athlete, + ) + return try { + database.correctRecord(correction).record + } catch (error: AthleticStandardException.Stale) { + // Read the record again and show the person both versions. + null + } + } + // end guide + + // guide: delete-record + /** Delete a record. Its earlier revisions stay in the file. */ + fun delete(database: Database, record: CurrentRecord) { + database.deleteRecord(DeleteRequest(record.recordId, record.currentRevision, RecordActor.Athlete)) + } + // end guide + + // guide: history + /** Every revision of a record, oldest first. */ + fun history(database: Database, recordId: String): List = + database.recordRevisions(recordId).map { "revision ${it.revision}, known from ${it.becameKnownAt}" } + // end guide + + // guide: check-form + /** The problems with a form before it is saved, each with the field it is about. */ + fun problems(data: RecordData): List = try { + checkRecordData(data) + emptyList() + } catch (error: AthleticStandardException) { + error.issues.map { "${it.pathText}: ${it.message}" } + } + // end guide +} + +/** The current instant in the stored UTC form, such as `2026-11-28T16:05:07.123Z`. */ +internal object Clock { + fun at(millis: Long): String { + val format = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.ROOT) + format.timeZone = java.util.TimeZone.getTimeZone("UTC") + return format.format(java.util.Date(millis)) + } + + fun now(): String = at(System.currentTimeMillis()) +} diff --git a/mobile/android/consumer/app/src/main/res/values/strings.xml b/mobile/android/example/app/src/main/res/values/strings.xml similarity index 100% rename from mobile/android/consumer/app/src/main/res/values/strings.xml rename to mobile/android/example/app/src/main/res/values/strings.xml diff --git a/mobile/android/consumer/app/src/main/res/xml/network_security_config.xml b/mobile/android/example/app/src/main/res/xml/network_security_config.xml similarity index 100% rename from mobile/android/consumer/app/src/main/res/xml/network_security_config.xml rename to mobile/android/example/app/src/main/res/xml/network_security_config.xml diff --git a/mobile/android/consumer/app/test-rules.pro b/mobile/android/example/app/test-rules.pro similarity index 100% rename from mobile/android/consumer/app/test-rules.pro rename to mobile/android/example/app/test-rules.pro diff --git a/mobile/android/consumer/build.gradle.kts b/mobile/android/example/build.gradle.kts similarity index 100% rename from mobile/android/consumer/build.gradle.kts rename to mobile/android/example/build.gradle.kts diff --git a/mobile/android/consumer/gradle.properties b/mobile/android/example/gradle.properties similarity index 100% rename from mobile/android/consumer/gradle.properties rename to mobile/android/example/gradle.properties diff --git a/mobile/android/consumer/settings.gradle.kts b/mobile/android/example/settings.gradle.kts similarity index 94% rename from mobile/android/consumer/settings.gradle.kts rename to mobile/android/example/settings.gradle.kts index 05e1d83b..b08e7f97 100644 --- a/mobile/android/consumer/settings.gradle.kts +++ b/mobile/android/example/settings.gradle.kts @@ -23,5 +23,5 @@ dependencyResolutionManagement { } } -rootProject.name = "athleticstandard-consumer" +rootProject.name = "athleticstandard-example" include(":app") diff --git a/mobile/scripts/stage-android.sh b/mobile/scripts/stage-android.sh index 1e530c74..dfabe158 100755 --- a/mobile/scripts/stage-android.sh +++ b/mobile/scripts/stage-android.sh @@ -5,7 +5,7 @@ # # Publishes `ai.athleticstandard:athleticstandard` to a local Maven repository, # copies it to /maven, and checks that its POM declares the JNA -# runtime. Then the consumer app in mobile/android/consumer resolves the library +# runtime. Then the example app in mobile/android/example resolves the library # by its coordinate from that repository and: # - builds a shrunk release APK and checks that every native library in it is # aligned for 16 KB pages; @@ -67,16 +67,16 @@ for device in $devices; do adb -s "$device" reverse "tcp:$ATH_TEST_ISSUER_PORT" "tcp:$ATH_TEST_ISSUER_PORT" > /dev/null done -consumer() { - (cd "$ANDROID" && ./gradlew --no-daemon -q -p consumer "$@" \ +example() { + (cd "$ANDROID" && ./gradlew --no-daemon -q -p example "$@" \ -Pathleticstandard.repository="$OUT/maven" -Pathleticstandard.fixtures="$FIXTURES" \ -Pandroid.testInstrumentationRunnerArguments.hostUrl="$ATH_TEST_HOST_URL" \ -Pandroid.testInstrumentationRunnerArguments.issuer="$ATH_TEST_ISSUER") } # 3. A shrunk release APK, and 16 KB alignment of every native library in it. -consumer :app:assembleRelease -APK="$ANDROID/consumer/app/build/outputs/apk/release/app-release.apk" +example :app:assembleRelease +APK="$ANDROID/example/app/build/outputs/apk/release/app-release.apk" "$BUILD_TOOLS/zipalign" -c -P 16 4 "$APK" || { echo "the APK is not aligned for 16 KB pages" >&2; exit 1; } UNPACKED="$OUT/apk-libraries" rm -rf "${UNPACKED:?}" @@ -100,11 +100,11 @@ fi # 4. The library's tests through the installed copy: debug, then the shrunk release build. results="" for build in debug release; do - rm -rf "${ANDROID:?}/consumer/app/build/outputs/connected_android_test_additional_output" + rm -rf "${ANDROID:?}/example/app/build/outputs/connected_android_test_additional_output" task="connectedDebugAndroidTest" [ "$build" = release ] && task="connectedReleaseAndroidTest" - consumer ":app:$task" -Pconsumer.testBuildType="$build" - for report in "$ANDROID"/consumer/app/build/outputs/androidTest-results/connected/"$build"/TEST-*.xml; do + example ":app:$task" -Pexample.testBuildType="$build" + for report in "$ANDROID"/example/app/build/outputs/androidTest-results/connected/"$build"/TEST-*.xml; do summary="$(grep -o ']*>' "$report" | grep -o 'tests="[0-9]*" failures="[0-9]*" errors="[0-9]*" skipped="[0-9]*"')" device="$(basename "$report" .xml)" echo "$build $device: $summary" @@ -116,7 +116,7 @@ for build in debug release; do done while IFS= read -r -d '' phone_file; do "$ROOT/mobile/scripts/roundtrip.sh" verify "$FIXTURES/roundtrip" "$phone_file" - done < <(find "$ANDROID/consumer/app/build/outputs/connected_android_test_additional_output" -name phone-edited.ath.sqlite -print0) + done < <(find "$ANDROID/example/app/build/outputs/connected_android_test_additional_output" -name phone-edited.ath.sqlite -print0) done sha() { shasum -a 256 "$1" | cut -d ' ' -f 1; } diff --git a/mobile/swift/Examples/AthleticStandardExample/AppValues.swift b/mobile/swift/Examples/AthleticStandardExample/AppValues.swift new file mode 100644 index 00000000..e67fe671 --- /dev/null +++ b/mobile/swift/Examples/AthleticStandardExample/AppValues.swift @@ -0,0 +1,31 @@ +// The app's own values on a record. The Swift guide shows the `guide:` region. + +import AthleticStandard +import Foundation + +// guide: app-values +/// How the person felt during a workout. The app owns this type; the format does not. +struct WorkoutFeeling: Codable, Equatable { + var mood: String + var soreness: Int +} + +enum AppValues { + /// The key is the app's domain name written backwards, then a name. + static let feelingKey = "com.example.athlete/workout-feeling" + + /// Store the feeling on a workout, keeping the record's other app values. + static func saveFeeling(_ feeling: WorkoutFeeling, on record: CurrentRecord, in database: Database) throws { + var correction = RecordCorrection( + recordId: record.recordId, expectedRevision: record.currentRevision, data: record.data, + changedBy: .athlete, extensions: record.extensions) + try correction.setExtension(feeling, forKey: feelingKey) + _ = try database.correctRecord(correction: correction) + } + + /// The feeling stored on a workout, or `nil` when there is none. + static func feeling(on record: CurrentRecord) throws -> WorkoutFeeling? { + try record.extensionValue(WorkoutFeeling.self, forKey: feelingKey) + } +} +// end guide diff --git a/mobile/swift/Examples/AthleticStandardExample/Calculations.swift b/mobile/swift/Examples/AthleticStandardExample/Calculations.swift new file mode 100644 index 00000000..22036a0c --- /dev/null +++ b/mobile/swift/Examples/AthleticStandardExample/Calculations.swift @@ -0,0 +1,46 @@ +// Calculations on the athlete's file and on records in memory. The Swift guide +// shows each `guide:` region. + +import AthleticStandard +import Foundation + +enum Calculations { + // guide: apply + /// How one reading compares with the athlete's recent readings, with the + /// shipped `hrv-change` method. The answer names every field it read. + static func hrvChange(_ database: Database, readingID: String) throws -> Double? { + let answer = try database.apply(recordId: readingID, skill: .shipped(name: "hrv-change")) + guard case let .quantityChange(_, change, _) = answer.result else { return nil } + return change + } + // end guide + + // guide: range + /// The weekly mean of every reading, for each source. Weeks follow the time + /// zone given here, never the phone's own setting. + static func weeklyMeans(_ database: Database, timeZone: String) throws -> [(week: String, mean: Double)] { + let request = RangeRequest( + operation: .summary, quantity: "hrv_rmssd", recordKind: .measurement, timeZone: timeZone, group: .week) + let receipt = try database.calculate(request: request) + guard case let .summaries(sources) = receipt.result else { return [] } + var weeks: [(week: String, mean: Double)] = [] + for case let .grouped(_, groups) in sources { + weeks += groups.map { ($0.period, $0.summary.mean) } + } + return weeks + } + // end guide + + // guide: memory + /// The same calculation on records the app holds, such as records read from a + /// host. Give it the sources and the athlete profile too. + static func weeklyMeans(of records: [CurrentRecord], timeZone: String) throws -> CalculationReceipt { + let builder = RecordSnapshotBuilder() + _ = try builder.addRecords(records: records) + let snapshot = try builder.finish() + let request = RangeRequest( + operation: .summary, quantity: "hrv_rmssd", recordKind: .measurement, timeZone: timeZone, group: .week) + return try snapshot.calculate(request: request) + } + // end guide +} diff --git a/mobile/swift/Examples/AthleticStandardExample/Documents.swift b/mobile/swift/Examples/AthleticStandardExample/Documents.swift new file mode 100644 index 00000000..923b7901 --- /dev/null +++ b/mobile/swift/Examples/AthleticStandardExample/Documents.swift @@ -0,0 +1,26 @@ +// A file the person picked from another location, such as iCloud Drive. The Swift +// guide shows the `guide:` region. + +import AthleticStandard +import Foundation + +enum Documents { + // guide: picked-document + /// Add a reading to a file the person picked, then save it back. The library + /// edits a private copy, and saves only if nobody changed the file meanwhile. + static func addReading(toPicked url: URL, milliseconds: Double) throws -> String { + let picked = try PickedDocument.open(documentURL: url) + defer { try? picked.close() } + let sourceID = try Records.sourceID(picked.database, for: Records.strap) + let now = ISO8601DateFormatter.withMilliseconds().string(from: Date()) + _ = try Records.addReading(picked.database, sourceID: sourceID, milliseconds: milliseconds, at: now) + do { + try picked.save() + return "Saved to \(url.lastPathComponent)." + } catch is DocumentChangedElsewhere { + // Keep the person's edit: offer to save it as a new file instead. + return "\(url.lastPathComponent) changed on another device. Your reading is kept on this device." + } + } + // end guide +} diff --git a/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift b/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift index 671f8b0a..ad88d7b3 100644 --- a/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift +++ b/mobile/swift/Examples/AthleticStandardExample/ExampleApp.swift @@ -1,11 +1,12 @@ -// The runnable Swift example (D330). It works offline on a file in the app's own -// storage, opens a document the person picks, and, when asked, connects to an -// `ath-host`: signs in through the system browser, picks an owned record, reads it, -// and saves an edit. `swift run AthleticStandardExample` runs it on a Mac; the same -// views run in an iPhone app. +// The runnable Swift example (D330), a starting point for an app. It works offline +// on a file in the app's own storage, adds a reading to a file the person picks, +// and, when asked, connects to an `ath-host`. `swift run AthleticStandardExample` +// runs it on a Mac; the same views run in an iPhone app. README.md in this folder +// says how to start an app from it. // -// The client ID and callback are placeholders. Register your own with the host's -// sign-in provider (mobile/README.md). +// The work itself is in Records.swift, Calculations.swift, AppValues.swift, +// Documents.swift, and HostConnection.swift. The client ID and callback are +// placeholders. Register your own with the host's sign-in provider. import AthleticStandard import AthleticStandardHost @@ -28,88 +29,64 @@ final class Example: ObservableObject { @Published var redirect = "ai.athleticstandard.example:/oauth/callback" @Published var picking = false - /// A local file: create it once, add a reading, and run a shipped calculation. + /// The local file: add a reading and show what the library knows about it. func workOffline() { do { - let file = try FileLocationAdvice.localFolder().appendingPathComponent("example.ath.sqlite") - let exists = FileManager.default.fileExists(atPath: file.path) - let database = - exists - ? try Database.open(path: file.path, options: OpenDatabaseOptions()) - : try Database.create(path: file.path, options: CreateDatabaseOptions()) - defer { try? database.close() } - if !exists { - let source = SourceData( - sourceType: .manual, dataWriter: "Athletic Standard example", dataRoute: "manual_entry") - _ = try database.writeRecords(records: [NewRecord(data: .source(source), changedBy: .athlete)]) - } - let sourceID = try database.listRecords(options: ListRecordsOptions(recordType: .source)).first?.recordId ?? "" - let now = ISO8601DateFormatter.withMilliseconds().string(from: Date()) - let reading = PointMeasurementData( - sourceId: sourceID, receivedAt: now, receivedAtBasis: .localWriteTime, quantity: .hrvRmssd, - recordedAt: now, - inputTimestamp: InputTimestampReceipt( - timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource), - value: SourceValue( - standardValue: Double(50 + Int.random(in: 0..<15)), standardUnit: "ms", - inputValueMissingReason: .notProvidedBySource, inputUnitMissingReason: .notProvidedBySource)) - let written = try database.writeRecords(records: [ - NewRecord(data: .pointMeasurement(reading), changedBy: .athlete) - ]) - let recordID = written.records.first?.recordId ?? "" - let change = try database.apply(recordId: recordID, skill: .shipped(name: "hrv-change")) - output = """ - Athletic Standard \(libraryVersion()) - \(file.path) - database revision \(try database.info().databaseRevision) - hrv-change: \(String(decoding: applyResultToJson(result: change), as: UTF8.self)) - """ + output = try Self.offlineSummary(in: try FileLocationAdvice.localFolder()) } catch { output = "Could not work on the local file: \(error)" } } - func open(_ url: URL) { + /// Open the file in `folder`, add a reading and a workout, and calculate on them. + nonisolated static func offlineSummary(in folder: URL) throws -> String { + let database = try Records.openFile(in: folder) + defer { try? database.close() } + let formatter = ISO8601DateFormatter.withMilliseconds() + let now = Date() + let reading = try Records.addReading( + database, sourceID: try Records.sourceID(database, for: Records.strap), + milliseconds: Double(50 + Int.random(in: 0..<15)), at: formatter.string(from: now)) + let workout = try Records.addWorkout( + database, sourceID: try Records.sourceID(database, for: Records.typedIn), name: "Row", + start: formatter.string(from: now.addingTimeInterval(-3600)), end: formatter.string(from: now)) + _ = try Records.rename(database, workout: workout, to: "Morning row") + let renamed = try database.getRecord(recordId: workout.recordId) ?? workout + try AppValues.saveFeeling(WorkoutFeeling(mood: "rested", soreness: 2), on: renamed, in: database) + let feeling = try database.getRecord(recordId: workout.recordId).flatMap(AppValues.feeling) + let change = try Calculations.hrvChange(database, readingID: reading.recordId) + let weeks = try Calculations.weeklyMeans(database, timeZone: "UTC") + return """ + Athletic Standard \(libraryVersion()) + \(try Records.readings(database).count) readings, database revision \(try database.info().databaseRevision) + hrv-change on the newest reading: \(change.map { String($0) } ?? "not enough readings yet") + weekly means: \(weeks.map { "\($0.week) \($0.mean)" }.joined(separator: ", ")) + workout history: \(try Records.history(database, recordID: workout.recordId).joined(separator: "; ")) + feeling: \(feeling?.mood ?? "none") + """ + } + + func addReading(toPicked url: URL) { do { - let picked = try PickedDocument.open(documentURL: url) - let info = try picked.database.info() - output = "Opened a working copy of \(url.lastPathComponent): database \(info.databaseId), revision \(info.databaseRevision)" - try picked.close() + output = try Documents.addReading(toPicked: url, milliseconds: 58) } catch { - output = "Could not open the document: \(error)" + output = "Could not open the file: \(error)" } } - /// Sign in, pick the first owned record, read it, and save an edit. func connect() async { guard let hostURL = URL(string: hostAddress), let redirectURI = URL(string: redirect) else { output = "Enter the host's address first." return } - let configuration = HostSignInConfiguration(hostURL: hostURL, clientID: clientID, redirectURI: redirectURI) - let signIn = HostSignIn(configuration: configuration, store: KeychainTokenStore(configuration: configuration)) do { - if try await !signIn.isSignedIn() { - try await signIn.signIn(browser: SystemBrowser(anchor: Self.window)) - } - let host = signIn.client() + let host = try await HostConnection.signIn( + hostURL: hostURL, clientID: clientID, redirectURI: redirectURI, anchor: Self.window) let capabilities = try await host.capabilities() - let athlete: String - if let first = try await host.athletes().first { - athlete = first.athleteID - } else { - athlete = try await host.createAthlete(displayName: "Example athlete").athleteID - } - let count = try await host.records(athleteID: athlete).count - let source = SourceData( - sourceType: .manual, dataWriter: "Athletic Standard example", dataRoute: "manual_entry") - let write = try host.prepareRecordCreation(athleteID: athlete, data: .source(source)) - let saved = try await host.send(write) output = """ Signed in to \(hostURL.absoluteString) \(capabilities.operatorDisclosure) - record \(athlete): \(count) records - saved record \(saved.records.first?.recordID ?? "") at database revision \(saved.databaseRevision) + \(try await HostConnection.addSource(host)) """ } catch { output = "Could not connect: \(error)" @@ -134,7 +111,7 @@ struct ContentView: View { Section("This device") { Text(FileLocationAdvice.recommendation) Button("Add a reading to the local file") { example.workOffline() } - Button("Open a file") { example.picking = true } + Button("Add a reading to a file I pick") { example.picking = true } } Section("Connect to a host") { TextField("https://records.example.org", text: $example.hostAddress) @@ -146,17 +123,8 @@ struct ContentView: View { } .padding() .fileImporter(isPresented: $example.picking, allowedContentTypes: [.data]) { result in - if case let .success(url) = result { example.open(url) } + if case let .success(url) = result { example.addReading(toPicked: url) } } .onAppear { example.workOffline() } } } - -extension ISO8601DateFormatter { - /// The stored UTC form, such as `2026-11-28T16:05:07.123Z`. - static func withMilliseconds() -> ISO8601DateFormatter { - let formatter = ISO8601DateFormatter() - formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] - return formatter - } -} diff --git a/mobile/swift/Examples/AthleticStandardExample/HostConnection.swift b/mobile/swift/Examples/AthleticStandardExample/HostConnection.swift new file mode 100644 index 00000000..518b5c40 --- /dev/null +++ b/mobile/swift/Examples/AthleticStandardExample/HostConnection.swift @@ -0,0 +1,46 @@ +// Connecting to an ath-host. The Swift guide shows each `guide:` region. +// +// The client ID and callback are placeholders. Register your own with the host's +// sign-in provider (mobile/README.md). + +import AthleticStandard +import AthleticStandardHost +import AuthenticationServices +import Foundation + +enum HostConnection { + // guide: host-sign-in + /// Sign in through the system browser, once. Later launches reuse the saved + /// session from the Keychain. + @MainActor + static func signIn(hostURL: URL, clientID: String, redirectURI: URL, anchor: @escaping () -> ASPresentationAnchor) + async throws -> HostClient + { + let configuration = HostSignInConfiguration(hostURL: hostURL, clientID: clientID, redirectURI: redirectURI) + let signIn = HostSignIn(configuration: configuration, store: KeychainTokenStore(configuration: configuration)) + if try await !signIn.isSignedIn() { + try await signIn.signIn(browser: SystemBrowser(anchor: anchor)) + } + return signIn.client() + } + // end guide + + // guide: host-records + /// Read the person's record on the host, and add a source to it. + static func addSource(_ host: HostClient) async throws -> String { + let athleteID: String + if let first = try await host.athletes().first { + athleteID = first.athleteID + } else { + athleteID = try await host.createAthlete(displayName: "Example athlete").athleteID + } + let count = try await host.records(athleteID: athleteID).count + let source = SourceData(sourceType: .manual, dataWriter: "Example app", dataRoute: "manual_entry") + // Keep `write` with the unsent edit. After a lost reply, send the same write + // again: the host answers with the first result and writes nothing new. + let write = try host.prepareRecordCreation(athleteID: athleteID, data: .source(source)) + let saved = try await host.send(write) + return "\(count) records; saved \(saved.records.first?.recordID ?? "") at revision \(saved.databaseRevision)" + } + // end guide +} diff --git a/mobile/swift/Examples/AthleticStandardExample/README.md b/mobile/swift/Examples/AthleticStandardExample/README.md new file mode 100644 index 00000000..1a61a8be --- /dev/null +++ b/mobile/swift/Examples/AthleticStandardExample/README.md @@ -0,0 +1,47 @@ +# Swift example + +A small SwiftUI app that uses the Athletic Standard library. It is a starting point: +copy its files into a new app and change them. The [Swift guide](../../README.md) +explains each part, with the same code. + +| File | What it does | +|---|---| +| `Records.swift` | Opens the athlete's file, migrates an older one, adds sources, readings, and workouts, reads, renames, and deletes records, and checks a form. | +| `Calculations.swift` | Runs `hrv-change` on one reading, and weekly means on the file and on records in memory. | +| `AppValues.swift` | Stores the app's own `Codable` value on a workout. | +| `Documents.swift` | Adds a reading to a file the person picked, and saves it back. | +| `HostConnection.swift` | Signs in to an `ath-host` and adds a source there. | +| `ExampleApp.swift` | The screen that runs them. | + +`mobile/swift/Tests/AthleticStandardExampleTests` runs this code on every test run. + +## Run it on a Mac + +From the repository root: + +```sh +mobile/scripts/build-apple.sh debug +swift run AthleticStandardExample +``` + +The first command builds the native library, which the package on `main` uses. An app +that adds a released version gets the prebuilt library instead. + +## Start an iPhone app from it + +1. In Xcode, create an iOS App project with SwiftUI. +2. Add the package `https://github.com/mwhitham/ath` by version, with the + `AthleticStandard` library, and `AthleticStandardHost` if the app connects to a + host. +3. Copy the Swift files from this folder into the app's target. In + `ExampleApp.swift`, delete the `ExampleApp` struct, because the new project has its + own `@main` app. Show `ContentView` from the app's own scene, or write your own + screen. +4. Change the names that belong to the example: + - the sources' `dataWriter`, `"Example app"`, to the app's name; + - the extension key, `com.example.athlete/workout-feeling`, to a key of your own + domain written backwards; + - for a host, the client ID and callback address, to the ones you registered with + the sign-in provider. +5. Replace the heart rate strap source with the app's real sources, one for each + device, export, or form the app writes from. diff --git a/mobile/swift/Examples/AthleticStandardExample/Records.swift b/mobile/swift/Examples/AthleticStandardExample/Records.swift new file mode 100644 index 00000000..7f255e9b --- /dev/null +++ b/mobile/swift/Examples/AthleticStandardExample/Records.swift @@ -0,0 +1,159 @@ +// Records on one file in the app's own storage. The Swift guide +// (mobile/swift/README.md) shows each `guide:` region; mobile/tests/guides.rs +// checks that the guide and this file agree. + +import AthleticStandard +import Foundation + +enum Records { + // guide: open-file + /// Open the athlete's file in `folder`, or create it the first time. + static func openFile(in folder: URL) throws -> Database { + let file = folder.appendingPathComponent("athlete.ath.sqlite") + if FileManager.default.fileExists(atPath: file.path) { + return try Database.open(path: file.path, options: OpenDatabaseOptions()) + } + return try Database.create(path: file.path, options: CreateDatabaseOptions()) + } + // end guide + + // guide: open-outdated + /// Open a file an older version wrote. The library refuses to open it until it is + /// migrated, and migrates only after it makes a verified backup. + static func openOlderFile(at path: String, backupFolder: URL) throws -> Database { + do { + return try Database.open(path: path, options: OpenDatabaseOptions()) + } catch AthleticStandardError.MigrationRequired(_, let preview) { + // Show `preview.compatibilityEffect` and ask the person before going on. + let outdated = try Database.open(path: path, options: OpenDatabaseOptions(allowOutdatedSchema: true)) + let backup = backupFolder.appendingPathComponent("before-step-\(preview.targetSqlSchemaVersion).ath.sqlite") + _ = try outdated.migrate(backupPath: backup.path) + try outdated.close() + return try Database.open(path: path, options: OpenDatabaseOptions()) + } + } + // end guide + + // guide: add-source + /// Every measured record names the source it came from. Readings the app takes + /// from a heart rate strap and workouts the person types in have different + /// sources, and calculations keep them apart: values typed in never enter a + /// device calculation. + static let strap = SourceData(sourceType: .wearable, dataWriter: "Example app", dataRoute: "bluetooth_strap") + static let typedIn = SourceData(sourceType: .manual, dataWriter: "Example app", dataRoute: "manual_entry") + + /// The ID of `source` in the file. It is written the first time it is needed. + static func sourceID(_ database: Database, for source: SourceData) throws -> String { + for record in try database.listRecords(options: ListRecordsOptions(recordType: .source)) { + if case let .source(existing) = record.data, existing == source { + return record.recordId + } + } + let written = try database.writeRecords(records: [NewRecord(data: .source(source), changedBy: .athlete)]) + return written.records[0].recordId + } + // end guide + + // guide: add-reading + /// A morning heart rate variability reading from the strap, in milliseconds. + static func addReading(_ database: Database, sourceID: String, milliseconds: Double, at time: String) throws + -> CurrentRecord + { + let reading = PointMeasurementData( + sourceId: sourceID, receivedAt: time, receivedAtBasis: .localWriteTime, quantity: .hrvRmssd, + recordedAt: time, + inputTimestamp: InputTimestampReceipt( + timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource), + value: SourceValue(standardValue: milliseconds, standardUnit: "ms", inputValue: milliseconds, inputUnit: "ms")) + let written = try database.writeRecords(records: [ + NewRecord(data: .pointMeasurement(reading), changedBy: .athlete) + ]) + return written.records[0] + } + // end guide + + // guide: add-workout + /// A workout the person logged, from its start and end times. + static func addWorkout(_ database: Database, sourceID: String, name: String, start: String, end: String) throws + -> CurrentRecord + { + let notReported = InputTimestampReceipt( + timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource) + let workout = WorkoutSessionData( + sourceId: sourceID, receivedAt: end, receivedAtBasis: .localWriteTime, startAt: start, endAt: end, + inputStartTimestamp: notReported, inputEndTimestamp: notReported, name: name, sourceReportedSummaries: []) + let written = try database.writeRecords(records: [NewRecord(data: .workoutSession(workout), changedBy: .athlete)]) + return written.records[0] + } + // end guide + + // guide: list-records + /// Every reading's value, oldest first. A list holds 100 records unless + /// `limit` asks for up to 10,000. + static func readings(_ database: Database) throws -> [(id: String, milliseconds: Double)] { + let records = try database.listRecords(options: ListRecordsOptions(recordType: .pointMeasurement, limit: 10_000)) + return records.compactMap { record in + guard case let .pointMeasurement(reading) = record.data else { return nil } + return (record.recordId, reading.value.standardValue) + } + } + // end guide + + // guide: correct-record + /// Rename a workout. `record` is the copy the person edited. When the file changed + /// after they opened it, the library refuses the edit and changes nothing. + static func rename(_ database: Database, workout record: CurrentRecord, to name: String) throws -> CurrentRecord? { + guard case var .workoutSession(workout) = record.data else { return nil } + workout.name = name + let correction = RecordCorrection( + recordId: record.recordId, expectedRevision: record.currentRevision, data: .workoutSession(workout), + changedBy: .athlete) + do { + return try database.correctRecord(correction: correction).record + } catch AthleticStandardError.Stale { + // Read the record again and show the person both versions. + return nil + } + } + // end guide + + // guide: delete-record + /// Delete a record. Its earlier revisions stay in the file. + static func delete(_ database: Database, _ record: CurrentRecord) throws { + _ = try database.deleteRecord( + deletion: DeleteRequest(recordId: record.recordId, expectedRevision: record.currentRevision, deletedBy: .athlete)) + } + // end guide + + // guide: history + /// Every revision of a record, oldest first. + static func history(_ database: Database, recordID: String) throws -> [String] { + try database.recordRevisions(recordId: recordID).map { revision in + "revision \(revision.revision), known from \(revision.becameKnownAt)" + } + } + // end guide + + // guide: check-form + /// The problems with a form before it is saved, each with the field it is about. + static func problems(with data: RecordData) -> [String] { + do { + try checkRecordData(data: data) + return [] + } catch let error as AthleticStandardError { + return error.issues.map { issue in "\(issue.pathText): \(issue.message)" } + } catch { + return ["\(error)"] + } + } + // end guide +} + +extension ISO8601DateFormatter { + /// The stored UTC form, such as `2026-11-28T16:05:07.123Z`. + static func withMilliseconds() -> ISO8601DateFormatter { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter + } +} diff --git a/mobile/swift/README.md b/mobile/swift/README.md new file mode 100644 index 00000000..6f88a536 --- /dev/null +++ b/mobile/swift/README.md @@ -0,0 +1,451 @@ +# Swift guide + +This guide shows how an iPhone app uses the Athletic Standard library. Read +[Build an iPhone or Android app](../README.md) first: it covers the choices this guide +assumes. The code below comes from the [example app](Examples/AthleticStandardExample/README.md), +which is built and tested with the library; `mobile/tests/guides.rs` checks that the +two agree. + +The package supports iOS 17 and later, and macOS 14 and later. It needs Xcode 16 or +later, for Swift 6. + +## Add the package + +In Xcode, choose **File > Add Package Dependencies**, enter +`https://github.com/mwhitham/ath`, and pick a version. Add the `AthleticStandard` +library to the app's target. Add `AthleticStandardHost` too if the app connects to a +host. In a `Package.swift`: + + +```swift +dependencies: [.package(url: "https://github.com/mwhitham/ath", from: "3.1.0")], +targets: [ + .target(name: "MyApp", dependencies: [.product(name: "AthleticStandard", package: "ath")]), +], +``` + +Swift Package Manager downloads this repository and the release's prebuilt native +library, and checks the library against the checksum in the release's `Package.swift` +([D332](../../build-history/v3.1.0/decisions.md#d332-how-the-packages-are-released)). +Nothing is compiled from Rust. + +## How records look in Swift + +Every record type and every part of a record is a Swift struct or enum +([D329](../../build-history/v3.1.0/decisions.md#d329-records-and-results-are-generated-swift-and-kotlin-types)): + +- `CurrentRecord` is one record as stored: `recordId`, `createdAt`, `currentRevision`, + `isDeleted`, `extensions`, and `data`. +- `RecordData` is an enum with one case for each record type. Its value is that + type's data, such as `WorkoutSessionData`. Read it with `switch` or `if case`. +- Lists of allowed values are enums, such as `SourceType` and `PointMeasurementType`. + They list their cases (`CaseIterable`), for pickers. +- Fields are `var`, so code changes one field of a copy and writes the copy. +- Times are text in the stored UTC form, such as `2026-11-28T16:05:07.123Z`. +- A field that holds any JSON, such as `extensions` or `suppliedFields`, is + `JsonObject`: JSON text in a `String`. + +Field names follow Swift style: `end_at` is `endAt`. [SPEC.md](../../SPEC.md) describes +every field. `currentRecordToJson` and `currentRecordFromJson` turn a record into its +stored JSON and back. + +## Open the athlete's file + + +```swift +/// Open the athlete's file in `folder`, or create it the first time. +static func openFile(in folder: URL) throws -> Database { + let file = folder.appendingPathComponent("athlete.ath.sqlite") + if FileManager.default.fileExists(atPath: file.path) { + return try Database.open(path: file.path, options: OpenDatabaseOptions()) + } + return try Database.create(path: file.path, options: CreateDatabaseOptions()) +} +``` + +`FileLocationAdvice.localFolder()` gives a folder in the app's own storage. Call +`close()` when the app is done with the file; committed edits are already in it. + +### A file from an older version + +A newer library refuses to open a file an older version wrote, with +`MigrationRequired`. The error carries the migration preview, including what the +migration means for older programs. Migrating makes a verified backup first. + + +```swift +/// Open a file an older version wrote. The library refuses to open it until it is +/// migrated, and migrates only after it makes a verified backup. +static func openOlderFile(at path: String, backupFolder: URL) throws -> Database { + do { + return try Database.open(path: path, options: OpenDatabaseOptions()) + } catch AthleticStandardError.MigrationRequired(_, let preview) { + // Show `preview.compatibilityEffect` and ask the person before going on. + let outdated = try Database.open(path: path, options: OpenDatabaseOptions(allowOutdatedSchema: true)) + let backup = backupFolder.appendingPathComponent("before-step-\(preview.targetSqlSchemaVersion).ath.sqlite") + _ = try outdated.migrate(backupPath: backup.path) + try outdated.close() + return try Database.open(path: path, options: OpenDatabaseOptions()) + } +} +``` + +## Add sources, readings, and workouts + +A measured record names its source, so the app writes its sources first. + + +```swift +/// Every measured record names the source it came from. Readings the app takes +/// from a heart rate strap and workouts the person types in have different +/// sources, and calculations keep them apart: values typed in never enter a +/// device calculation. +static let strap = SourceData(sourceType: .wearable, dataWriter: "Example app", dataRoute: "bluetooth_strap") +static let typedIn = SourceData(sourceType: .manual, dataWriter: "Example app", dataRoute: "manual_entry") + +/// The ID of `source` in the file. It is written the first time it is needed. +static func sourceID(_ database: Database, for source: SourceData) throws -> String { + for record in try database.listRecords(options: ListRecordsOptions(recordType: .source)) { + if case let .source(existing) = record.data, existing == source { + return record.recordId + } + } + let written = try database.writeRecords(records: [NewRecord(data: .source(source), changedBy: .athlete)]) + return written.records[0].recordId +} +``` + +A reading records when the app received it (`receivedAt`), when it was measured +(`recordedAt`), and the value in its stored unit. `inputTimestamp` keeps the time +text the source itself gave; this strap gives none. + + +```swift +/// A morning heart rate variability reading from the strap, in milliseconds. +static func addReading(_ database: Database, sourceID: String, milliseconds: Double, at time: String) throws + -> CurrentRecord +{ + let reading = PointMeasurementData( + sourceId: sourceID, receivedAt: time, receivedAtBasis: .localWriteTime, quantity: .hrvRmssd, + recordedAt: time, + inputTimestamp: InputTimestampReceipt( + timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource), + value: SourceValue(standardValue: milliseconds, standardUnit: "ms", inputValue: milliseconds, inputUnit: "ms")) + let written = try database.writeRecords(records: [ + NewRecord(data: .pointMeasurement(reading), changedBy: .athlete) + ]) + return written.records[0] +} +``` + + +```swift +/// A workout the person logged, from its start and end times. +static func addWorkout(_ database: Database, sourceID: String, name: String, start: String, end: String) throws + -> CurrentRecord +{ + let notReported = InputTimestampReceipt( + timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource) + let workout = WorkoutSessionData( + sourceId: sourceID, receivedAt: end, receivedAtBasis: .localWriteTime, startAt: start, endAt: end, + inputStartTimestamp: notReported, inputEndTimestamp: notReported, name: name, sourceReportedSummaries: []) + let written = try database.writeRecords(records: [NewRecord(data: .workoutSession(workout), changedBy: .athlete)]) + return written.records[0] +} +``` + +`writeRecords` writes every record in one change, or none of them. A record the +library refuses throws `AthleticStandardError.Invalid` with every issue. + +## Read records + + +```swift +/// Every reading's value, oldest first. A list holds 100 records unless +/// `limit` asks for up to 10,000. +static func readings(_ database: Database) throws -> [(id: String, milliseconds: Double)] { + let records = try database.listRecords(options: ListRecordsOptions(recordType: .pointMeasurement, limit: 10_000)) + return records.compactMap { record in + guard case let .pointMeasurement(reading) = record.data else { return nil } + return (record.recordId, reading.value.standardValue) + } +} +``` + +`getRecord(recordId:)` reads one record, or gives `nil`. `listRecords` leaves out +deleted records unless `includeDeleted` is set. + +## Change and delete records + +A correction is the complete new data, with the revision the person edited. If the +record changed after the person opened it, such as on another device, the library +refuses the correction with `Stale` and changes nothing. + + +```swift +/// Rename a workout. `record` is the copy the person edited. When the file changed +/// after they opened it, the library refuses the edit and changes nothing. +static func rename(_ database: Database, workout record: CurrentRecord, to name: String) throws -> CurrentRecord? { + guard case var .workoutSession(workout) = record.data else { return nil } + workout.name = name + let correction = RecordCorrection( + recordId: record.recordId, expectedRevision: record.currentRevision, data: .workoutSession(workout), + changedBy: .athlete) + do { + return try database.correctRecord(correction: correction).record + } catch AthleticStandardError.Stale { + // Read the record again and show the person both versions. + return nil + } +} +``` + + +```swift +/// Delete a record. Its earlier revisions stay in the file. +static func delete(_ database: Database, _ record: CurrentRecord) throws { + _ = try database.deleteRecord( + deletion: DeleteRequest(recordId: record.recordId, expectedRevision: record.currentRevision, deletedBy: .athlete)) +} +``` + + +```swift +/// Every revision of a record, oldest first. +static func history(_ database: Database, recordID: String) throws -> [String] { + try database.recordRevisions(recordId: recordID).map { revision in + "revision \(revision.revision), known from \(revision.becameKnownAt)" + } +} +``` + +`writeRecordChanges` writes corrections and new records in one change. + +## Check a form before saving + +`checkRecordData` runs the same checks as a write, without writing. Each issue has +a path to the field it is about, the desktop's code, and its message. + + +```swift +/// The problems with a form before it is saved, each with the field it is about. +static func problems(with data: RecordData) -> [String] { + do { + try checkRecordData(data: data) + return [] + } catch let error as AthleticStandardError { + return error.issues.map { issue in "\(issue.pathText): \(issue.message)" } + } catch { + return ["\(error)"] + } +} +``` + +## Keep the app's own values + +The app's own values go in a record's extensions, under a key of the app's domain +written backwards. The app writes its own `Codable` type. `setExtension` and +`extensionValue` encode and decode it, and the library checks the key and the size +limits. + + +```swift +/// How the person felt during a workout. The app owns this type; the format does not. +struct WorkoutFeeling: Codable, Equatable { + var mood: String + var soreness: Int +} + +enum AppValues { + /// The key is the app's domain name written backwards, then a name. + static let feelingKey = "com.example.athlete/workout-feeling" + + /// Store the feeling on a workout, keeping the record's other app values. + static func saveFeeling(_ feeling: WorkoutFeeling, on record: CurrentRecord, in database: Database) throws { + var correction = RecordCorrection( + recordId: record.recordId, expectedRevision: record.currentRevision, data: record.data, + changedBy: .athlete, extensions: record.extensions) + try correction.setExtension(feeling, forKey: feelingKey) + _ = try database.correctRecord(correction: correction) + } + + /// The feeling stored on a workout, or `nil` when there is none. + static func feeling(on record: CurrentRecord) throws -> WorkoutFeeling? { + try record.extensionValue(WorkoutFeeling.self, forKey: feelingKey) + } +} +``` + +A correction without extensions keeps the record's extensions as they are. + +## Run calculations + +`apply` runs one calculation skill on one record. Its answer names the method, every +field it read, and the result. + + +```swift +/// How one reading compares with the athlete's recent readings, with the +/// shipped `hrv-change` method. The answer names every field it read. +static func hrvChange(_ database: Database, readingID: String) throws -> Double? { + let answer = try database.apply(recordId: readingID, skill: .shipped(name: "hrv-change")) + guard case let .quantityChange(_, change, _) = answer.result else { return nil } + return change +} +``` + +`calculate` runs one of the eight range calculations, such as a summary, a baseline, +or a trend. `RangeRequest` takes the options `ath calculate` takes. + + +```swift +/// The weekly mean of every reading, for each source. Weeks follow the time +/// zone given here, never the phone's own setting. +static func weeklyMeans(_ database: Database, timeZone: String) throws -> [(week: String, mean: Double)] { + let request = RangeRequest( + operation: .summary, quantity: "hrv_rmssd", recordKind: .measurement, timeZone: timeZone, group: .week) + let receipt = try database.calculate(request: request) + guard case let .summaries(sources) = receipt.result else { return [] } + var weeks: [(week: String, mean: Double)] = [] + for case let .grouped(_, groups) in sources { + weeks += groups.map { ($0.period, $0.summary.mean) } + } + return weeks +} +``` + +The same calculations run on records the app holds in memory, through a +`RecordSnapshot`. A snapshot cannot change, so several threads can calculate on it. + + +```swift +/// The same calculation on records the app holds, such as records read from a +/// host. Give it the sources and the athlete profile too. +static func weeklyMeans(of records: [CurrentRecord], timeZone: String) throws -> CalculationReceipt { + let builder = RecordSnapshotBuilder() + _ = try builder.addRecords(records: records) + let snapshot = try builder.finish() + let request = RangeRequest( + operation: .summary, quantity: "hrv_rmssd", recordKind: .measurement, timeZone: timeZone, group: .week) + return try snapshot.calculate(request: request) +} +``` + +- `shippedCalculationNames()` lists the shipped calculation skills, and + `shippedSkillText(name:)` gives one's text. `CalculationSkill.text(text:)` runs an + edited copy. +- `applyWith(recordId:skill:parameters:)` takes the options of `ath apply --set`, such + as a threshold method's `operation` and `end_date`. +- A snapshot does not hold device recordings. A method that reads them, such as + `heart-rate-zones` or a threshold method, is refused from memory with a message that + says to run it on a `Database`. +- `applyResultToJson` and `calculationReceiptToJson` give the desktop's JSON. + +## Let the person pick a file + +A file the person picks from iCloud Drive or another location opens through +`PickedDocument`. It copies the file into the app's storage under file coordination, +and `save()` replaces the picked file only if it still holds what was copied. + + +```swift +/// Add a reading to a file the person picked, then save it back. The library +/// edits a private copy, and saves only if nobody changed the file meanwhile. +static func addReading(toPicked url: URL, milliseconds: Double) throws -> String { + let picked = try PickedDocument.open(documentURL: url) + defer { try? picked.close() } + let sourceID = try Records.sourceID(picked.database, for: Records.strap) + let now = ISO8601DateFormatter.withMilliseconds().string(from: Date()) + _ = try Records.addReading(picked.database, sourceID: sourceID, milliseconds: milliseconds, at: now) + do { + try picked.save() + return "Saved to \(url.lastPathComponent)." + } catch is DocumentChangedElsewhere { + // Keep the person's edit: offer to save it as a new file instead. + return "\(url.lastPathComponent) changed on another device. Your reading is kept on this device." + } +} +``` + +- `saveCopy(to:)` writes the edits to a new file, such as one the person names with + `UIDocumentPickerViewController(forExporting:)`. +- `hasUnsavedEdits()` says whether the picked file has every local edit. +- `state` and `PickedDocument.resume(_:)` reopen the private copy, with its unsaved + edits, after the app restarts. Keep `state` with the app's settings. +- A single-file save does not carry attachment files. Use a package export for them. + +## Connect to a host + +The `AthleticStandardHost` library signs in through the system browser +(`ASWebAuthenticationSession`) and keeps the token in the Keychain. It needs the +host's address, the app's registered client ID, and its registered callback address. +No `Info.plist` entry is needed: the sign-in sheet receives the callback. + + +```swift +/// Sign in through the system browser, once. Later launches reuse the saved +/// session from the Keychain. +@MainActor +static func signIn(hostURL: URL, clientID: String, redirectURI: URL, anchor: @escaping () -> ASPresentationAnchor) + async throws -> HostClient +{ + let configuration = HostSignInConfiguration(hostURL: hostURL, clientID: clientID, redirectURI: redirectURI) + let signIn = HostSignIn(configuration: configuration, store: KeychainTokenStore(configuration: configuration)) + if try await !signIn.isSignedIn() { + try await signIn.signIn(browser: SystemBrowser(anchor: anchor)) + } + return signIn.client() +} +``` + +Reads and writes take the same record types as the file. + + +```swift +/// Read the person's record on the host, and add a source to it. +static func addSource(_ host: HostClient) async throws -> String { + let athleteID: String + if let first = try await host.athletes().first { + athleteID = first.athleteID + } else { + athleteID = try await host.createAthlete(displayName: "Example athlete").athleteID + } + let count = try await host.records(athleteID: athleteID).count + let source = SourceData(sourceType: .manual, dataWriter: "Example app", dataRoute: "manual_entry") + // Keep `write` with the unsent edit. After a lost reply, send the same write + // again: the host answers with the first result and writes nothing new. + let write = try host.prepareRecordCreation(athleteID: athleteID, data: .source(source)) + let saved = try await host.send(write) + return "\(count) records; saved \(saved.records.first?.recordID ?? "") at revision \(saved.databaseRevision)" +} +``` + +- `prepareCorrection(athleteID:record:data:)` corrects a record at the revision the + person edited. A stale correction fails with the host code `stale`; keep the + person's edit for review. +- `signOut()` forgets the tokens. An app that already has a session for this host can + give `HostClient` a function that returns a current access token instead. +- [docs/hosting.md](../../docs/hosting.md) covers running a host and setting up + sign-in. + +## Errors + +Every library call throws `AthleticStandardError`. Its `code` matches the desktop's +error code, and `detail` holds the desktop's message. + +| `code` | Meaning | +|---|---| +| `invalid` | A record or value breaks the format's rules. `issues` lists each one. | +| `not_found` | No record or file with that ID or path. | +| `stale` | The record changed since the revision the edit names. Nothing changed. | +| `refused` | The call is not allowed here, such as a write to a file opened read-only. | +| `migration_required` | The file needs a migration before it opens. | +| `database`, `io` | SQLite or the file system failed. | +| `error` | Any other desktop failure. | +| `malformed_json`, `unknown_shape`, `closed` | JSON that is not JSON, an unknown shape name, or a call after `close()`. | + +The host client throws `HostError` with the host's own codes, such as `stale`. + +## Start an app from the example + +[Examples/AthleticStandardExample](Examples/AthleticStandardExample/README.md) says how. diff --git a/mobile/swift/Tests/AthleticStandardExampleTests/ExampleTests.swift b/mobile/swift/Tests/AthleticStandardExampleTests/ExampleTests.swift new file mode 100644 index 00000000..69ef9df7 --- /dev/null +++ b/mobile/swift/Tests/AthleticStandardExampleTests/ExampleTests.swift @@ -0,0 +1,83 @@ +import AthleticStandard +import Foundation +import Testing + +@testable import AthleticStandardExample + +/// The example's code, which the Swift guide shows, run on a temporary folder. +@Suite(.serialized) +struct ExampleTests { + static func folder() throws -> URL { + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("athleticstandard-example-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + @Test func theOfflineWorkRunsTwiceOnTheSameFile() throws { + let folder = try Self.folder() + let first = try Example.offlineSummary(in: folder) + #expect(first.contains("1 readings")) + #expect(first.contains("feeling: rested")) + #expect(first.contains("revision 1, known from")) + let second = try Example.offlineSummary(in: folder) + #expect(second.contains("2 readings")) + let database = try Records.openFile(in: folder) + #expect(try Records.readings(database).count == 2) + // One source for the strap's readings and one for typed-in workouts. + #expect(try database.listRecords(options: ListRecordsOptions(recordType: .source)).count == 2) + try database.close() + } + + @Test func aStaleRenameChangesNothing() throws { + let database = try Records.openFile(in: try Self.folder()) + let sourceID = try Records.sourceID(database, for: Records.typedIn) + let workout = try Records.addWorkout( + database, sourceID: sourceID, name: "Row", start: "2026-01-02T06:00:00.000Z", end: "2026-01-02T07:00:00.000Z") + #expect(try Records.rename(database, workout: workout, to: "Morning row") != nil) + // The same, older copy again: the file changed since, so it is refused. + #expect(try Records.rename(database, workout: workout, to: "Evening row") == nil) + guard case let .workoutSession(saved) = try database.getRecord(recordId: workout.recordId)?.data else { + Issue.record("expected a workout") + return + } + #expect(saved.name == "Morning row") + try Records.delete(database, try #require(try database.getRecord(recordId: workout.recordId))) + #expect(try database.getRecord(recordId: workout.recordId)?.isDeleted == true) + try database.close() + } + + @Test func aFormThatEndsBeforeItStartsHasAProblem() throws { + let notReported = InputTimestampReceipt( + timestampMissingReason: .notProvidedBySource, utcOffsetMissingReason: .notProvidedBySource) + let workout = WorkoutSessionData( + sourceId: "01890f3e-e7d3-7cc0-88c8-000000000003", receivedAt: "2026-01-02T06:00:00.000Z", + receivedAtBasis: .localWriteTime, startAt: "2026-01-02T06:00:00.000Z", endAt: "2026-01-02T05:00:00.000Z", + inputStartTimestamp: notReported, inputEndTimestamp: notReported, sourceReportedSummaries: []) + let problems = Records.problems(with: .workoutSession(workout)) + #expect(problems == ["end_at: Workout session end cannot precede its start"], "\(problems)") + } + + @Test func anOlderFileIsMigratedAfterABackup() throws { + let fixtures = try #require(ProcessInfo.processInfo.environment["ATH_MOBILE_FIXTURES"]) + let folder = try Self.folder() + let path = folder.appendingPathComponent("older.ath.sqlite").path + try FileManager.default.copyItem(atPath: fixtures + "/outdated-2-1-0.ath.sqlite", toPath: path) + let database = try Records.openOlderFile(at: path, backupFolder: folder) + #expect(try database.info().writable) + try database.close() + let backups = try FileManager.default.contentsOfDirectory(atPath: folder.path).filter { $0.hasPrefix("before-step-") } + #expect(backups.count == 1) + } + + @Test func aPickedFileGetsTheReading() throws { + let provider = try Self.folder() + let seed = try Records.openFile(in: provider) + try seed.close() + let document = provider.appendingPathComponent("athlete.ath.sqlite") + #expect(try Documents.addReading(toPicked: document, milliseconds: 58) == "Saved to athlete.ath.sqlite.") + let database = try Database.open(path: document.path, options: OpenDatabaseOptions(readOnly: true)) + #expect(try Records.readings(database).map(\.milliseconds) == [58]) + try database.close() + } +} diff --git a/mobile/tests/guides.rs b/mobile/tests/guides.rs new file mode 100644 index 00000000..ef6f08a9 --- /dev/null +++ b/mobile/tests/guides.rs @@ -0,0 +1,151 @@ +//! The app guides show the example apps' code, unchanged (D329, D333). +//! +//! A code sample in a guide follows a marker line. `` +//! names a region of an example file, between `// guide: ` and +//! `// end guide` (or the same words in an XML comment). The sample must be that +//! region with its shared indent removed. `` marks an +//! install sample, which must name the library's version. Every Swift, Kotlin, and +//! XML sample has one of the two markers, and every region is in a guide. The +//! examples themselves are built and tested by mobile/scripts/. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +const GUIDES: &[&str] = &["mobile/swift/README.md", "mobile/android/README.md"]; +const EXAMPLE_FOLDERS: &[&str] = &["mobile/swift/Examples", "mobile/android/example/app"]; + +fn repository() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..") +} + +fn read(path: &Path) -> String { + std::fs::read_to_string(path).unwrap_or_else(|error| panic!("{}: {error}", path.display())) +} + +fn start_marker(line: &str) -> Option<&str> { + let line = line.trim(); + line.strip_prefix("// guide: ") + .or_else(|| line.strip_prefix(""))) +} + +fn is_end_marker(line: &str) -> bool { + matches!(line.trim(), "// end guide" | "") +} + +/// The named region of an example file, with its shared indent removed. +fn region(path: &Path, name: &str) -> String { + let text = read(path); + let mut lines = Vec::new(); + let mut inside = false; + let mut found = 0; + for line in text.lines() { + if start_marker(line) == Some(name) { + inside = true; + found += 1; + } else if inside && is_end_marker(line) { + inside = false; + } else if inside { + lines.push(line); + } + } + assert_eq!(found, 1, "{} has {found} regions named {name}", path.display()); + assert!(!inside, "{} does not end region {name}", path.display()); + let indent = lines + .iter() + .filter(|line| !line.trim().is_empty()) + .map(|line| line.len() - line.trim_start_matches(' ').len()) + .min() + .unwrap_or(0); + lines.iter().map(|line| if line.trim().is_empty() { "" } else { &line[indent..] }).collect::>().join("\n") +} + +/// Each fenced sample in a guide: its language, its text, and the marker line +/// before it, if any. +fn samples(text: &str) -> Vec<(String, String, Option)> { + let mut found = Vec::new(); + let mut lines = text.lines(); + let mut previous: Option<&str> = None; + while let Some(line) = lines.next() { + if let Some(language) = line.strip_prefix("```") { + let body: Vec<&str> = lines.by_ref().take_while(|line| *line != "```").collect(); + let marker = previous.filter(|line| line.starts_with("")) { + let (file, name) = reference.split_once('#').unwrap(); + let source = folder.join(file); + let relative = source + .strip_prefix(repository()) + .map(|path| path.to_string_lossy().replace('\\', "/")) + .unwrap_or_default(); + used.insert(format!("{relative}#{name}")); + let expected = region(&source, name); + if body != expected { + failures.push(format!("{guide}: the sample {reference} differs from the example:\n{expected}")); + } + } else if marker == "" { + if !body.contains(&version) { + failures.push(format!("{guide}: an install sample does not name {version}:\n{body}")); + } + } else if matches!(language.as_str(), "swift" | "kotlin" | "xml") { + failures.push(format!("{guide}: a {language} sample has no marker:\n{body}")); + } + } + } + let mut regions = BTreeSet::new(); + for folder in EXAMPLE_FOLDERS { + regions_in(&repository().join(folder), &mut regions); + } + for region in regions.difference(&used) { + failures.push(format!("no guide shows the example region {region}")); + } + assert!(used.len() >= 30, "the guides show only {} regions", used.len()); + assert!(failures.is_empty(), "{}", failures.join("\n\n")); +} + +#[test] +fn the_overview_names_the_android_coordinate_and_version() { + let version = athleticstandard_mobile::library_version(); + let overview = read(&repository().join("mobile/README.md")); + assert!( + overview.contains(&format!("ai.athleticstandard:athleticstandard:{version}")), + "mobile/README.md names another Android version" + ); +} diff --git a/mobile/tests/versions.rs b/mobile/tests/versions.rs index 9e03e69b..0dc0d220 100644 --- a/mobile/tests/versions.rs +++ b/mobile/tests/versions.rs @@ -21,7 +21,7 @@ fn the_phone_builds_name_the_library_version() { ("mobile/Cargo.toml", "version = "), ("mobile/bindgen/Cargo.toml", "version = "), ("mobile/android/gradle.properties", "athleticstandard.version="), - ("mobile/android/consumer/gradle.properties", "athleticstandard.version="), + ("mobile/android/example/gradle.properties", "athleticstandard.version="), ("packages/npm/package.json", " \"version\": "), ] { let found = value_after(file, prefix); diff --git a/tools/public-data-allowlist.json b/tools/public-data-allowlist.json index daaaa932..8eccd3f6 100644 --- a/tools/public-data-allowlist.json +++ b/tools/public-data-allowlist.json @@ -242,15 +242,15 @@ "sha256": "c8fe08b06e479efc7e3d00476fffe693a3e943e2b874b3c6a1ba5156fc180751" }, { - "path": "mobile/android/consumer/app/src/main/AndroidManifest.xml", - "sha256": "f5d43a6546a6bb05cbf010423786f75886801af1d37f09ad141b096844a49bc2" + "path": "mobile/android/example/app/src/main/AndroidManifest.xml", + "sha256": "7dbe9a251f12b91cb83281eb0dbaf6156a9306af57c6b120213b735a3b8f39e1" }, { - "path": "mobile/android/consumer/app/src/main/res/values/strings.xml", + "path": "mobile/android/example/app/src/main/res/values/strings.xml", "sha256": "253b00c595747bc93f8de98e9b618bcc36a67742c368129523a22c71f5b41cae" }, { - "path": "mobile/android/consumer/app/src/main/res/xml/network_security_config.xml", + "path": "mobile/android/example/app/src/main/res/xml/network_security_config.xml", "sha256": "6046c8e28ecf4a1ec69097368769600506b61ff0cdf2005f0c907dc244ce49a8" } ] From 463dfeea23b69de496f364e8f345afb8f5decde7 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 00:10:41 -0600 Subject: [PATCH 23/30] Say whether a release's tag carries the Swift package. A release from a pushed tag names the tested commit, which Swift Package Manager cannot install. The pull request comment and the release summary now say so instead of naming a release commit that does not exist. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release-cross-platform.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release-cross-platform.yml b/.github/workflows/release-cross-platform.yml index 022a20d0..fa37b7a9 100644 --- a/.github/workflows/release-cross-platform.yml +++ b/.github/workflows/release-cross-platform.yml @@ -337,7 +337,7 @@ jobs: { echo "### iPhone and Android packages for $TAG" echo - echo "- XCFramework: \`$(jq -r .asset_sha256 apple/apple-report.json)\` on the GitHub release; \`$TAG\` names the Swift package release commit." + echo "- XCFramework: \`$(jq -r .asset_sha256 apple/apple-report.json)\` on the GitHub release. In a release from main, \`$TAG\` names the Swift package release commit." echo "- Android archive: \`$(jq -r .aar_sha256 android/android-report.json)\`, uploaded to Maven Central for approval when a credential is set." echo "- Next: publish the Maven deployment, then run release-mobile-packages.yml for $TAG to check both public installs." } >> "$GITHUB_STEP_SUMMARY" @@ -370,7 +370,7 @@ jobs: IFS= read -r -d '' body <<'EOF' || true **@TAG@ is staged on npm and waiting for your approval.** - The full check passed. `@TAG@` now names one commit on top of the tested commit, which adds the Swift package files, and the [GitHub release](@SERVER@/@REPO@/releases/tag/@TAG@) holds the native archives and the iPhone XCFramework. Nobody can install @TAG@ from npm until you approve it. + The full check passed. @TAGGED@ The [GitHub release](@SERVER@/@REPO@/releases/tag/@TAG@) holds the native archives and the iPhone XCFramework. Nobody can install @TAG@ from npm until you approve it. Approve it in one of two ways. Both ask for your two-factor code. @@ -388,6 +388,12 @@ jobs: Open the [release run](@RUN@) to see which step failed. Fix it in a new pull request, merge it, and comment `/release` on that pull request. EOF fi + if [ "$GITHUB_REF_TYPE" = tag ]; then + tagged="\`$TAG\` was pushed, so it names the tested commit, and Swift Package Manager cannot install it; release from main for the iPhone package." + else + tagged="\`$TAG\` now names one commit on top of the tested commit, which adds the Swift package files." + fi + body="${body//@TAGGED@/$tagged}" body="${body//@TAG@/$TAG}" body="${body//@VERSION@/${TAG#v}}" body="${body//@RUN@/$RUN_URL}" From 1a31e37ce42a4e6b37f1003211b3082bf2476d24 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 00:10:41 -0600 Subject: [PATCH 24/30] Record typed records, the in-repository Swift package, and the guides. Progress gains steps 8 to 10, the spec gains the guides as a release gate, and the evidence is gathered again from commit 797813b: 942 Rust tests, the Swift package installed by version from a tagged clone (33 tests), the Android library installed by coordinate in the example app (37 tests on each emulator, debug and shrunk release), two identical XCFramework zips, and the round trip on every platform. Co-Authored-By: Claude Opus 5.5 --- .../v3.1.0/appendix/release-evidence.md | 25 +++++--- build-history/v3.1.0/progress.md | 64 +++++++++++++++++-- build-history/v3.1.0/spec.md | 8 ++- 3 files changed, 82 insertions(+), 15 deletions(-) diff --git a/build-history/v3.1.0/appendix/release-evidence.md b/build-history/v3.1.0/appendix/release-evidence.md index fcf1f320..a662f40e 100644 --- a/build-history/v3.1.0/appendix/release-evidence.md +++ b/build-history/v3.1.0/appendix/release-evidence.md @@ -1,8 +1,10 @@ # Version 3.1.0 release evidence This is the evidence for the release gates of 3.1.0 ([spec](../spec.md) section 3). It -was gathered on 2026-11-29 on an Apple silicon Mac (arm64) with Rust 1.100.0, from -commit `fda0047` of the build, with synthetic data. No live provider account was used. +was gathered on 2026-11-30 on an Apple silicon Mac (arm64) with Rust 1.100.0 and Swift +6.4, from commit `797813b` of the build, with synthetic data. No live provider account +was used. An earlier run, from commit `fda0047` before the typed records (D329), gave +the same results for every check it shared with this one. Each staging run writes `apple-report.json` and `android-report.json` with the hashes, the source commit, the targets, and the tool versions; the release job adds both to the GitHub release. @@ -16,13 +18,17 @@ GitHub release. | Calculations through the database | 49 cases, 113 requests, 0 differences from the desktop | | Calculations through the memory snapshot | 99 requests match the desktop; 14 that read device recordings or intensity references get the documented refusal (D326) | | Both calculation readers on the desktop | 42 worked examples and 71 case requests: 30 and 69 match, 12 and 2 get the documented refusal; the 100,000-input limit holds on both | -| Swift package installed by version from a staged repository, on macOS | 25 tests passed: 20 package tests and 5 host tests | -| Android library installed by coordinate, API 36 (4 KB pages) and API 37.1 (16 KB pages) emulators | 25 tests passed on each, in a debug build and in a shrunk release build | +| Swift package installed by version from a tagged clone of this repository with the release commit staged, on macOS | 33 tests passed: 28 package tests and 5 host tests | +| Swift package from the repository root, on macOS | 38 tests passed: 28 package tests, 5 host tests, and 5 example tests | +| Android library installed by coordinate in the example app, API 36 (4 KB pages) and API 37.1 (16 KB pages) emulators | 37 tests passed on each, in a debug build and in a shrunk release build: the library's 32 and the example's 5 | +| Android library from source, the same two emulators | 32 tests passed on each | +| Guides | 37 code samples in the Swift and Android guides match the example apps' marked regions; every region is shown | | 16 KB alignment of every native library in the shrunk release APK | 4 of 4 libraries aligned (both ABIs of the library and of JNA) | | Desktop round trip | Passed on macOS and on both emulators: the desktop `ath` created the file, the phone library corrected a reading, and the desktop `ath` found the edit at revision 2, revision 1 kept, and a passing `ath check` | -| XCFramework zip | Two staging runs gave the same bytes for `AthleticStandardFFI-3.1.0.xcframework.zip` | +| XCFramework zip | Two staging runs gave the same bytes for `AthleticStandardFFI-3.1.0.xcframework.zip` (SHA-256 `4309b67e…912f`) | +| Swift package release commit | Differs from the root `Package.swift` only in the binary target line, and adds the two generated Swift files; the test package resolved version 3.1.0 to it | | Version | Each binding reports 3.1.0, and an outdated 2.1.0 file migrates to SQL step 9 on macOS and on both emulators | -| The whole workspace | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass, also without the `cli` feature for the library and the phone crate; `cargo test` (workspace) gives 940 passed, 0 failed, 18 ignored; npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (3.0.0 gate 5) passes | +| The whole workspace | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass, also without the `cli` feature for the library and the phone crate; `cargo test` (workspace) gives 942 passed, 0 failed, 18 ignored (the 7 terminal tests ran outside the sandbox); npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (3.0.0 gate 5) passes | ## 2. Found and fixed while gathering this evidence @@ -41,6 +47,7 @@ GitHub release. - The iCloud Drive picker on a signed-in device. - The system browser sheets with a person, and a live WorkOS environment (issue 57). - The CI jobs and the release workflows. They were written in this build but have not - run on GitHub. -- Publication. The Maven namespace, the Swift package repository, and the publishing - credentials belong to the maintainer. + run on GitHub. The step that builds the Swift package release commit ran only as a + dry run with a stand-in for `gh`. +- Publication. The Maven namespace and the publishing credentials belong to the + maintainer. diff --git a/build-history/v3.1.0/progress.md b/build-history/v3.1.0/progress.md index 518c9ca2..64619559 100644 --- a/build-history/v3.1.0/progress.md +++ b/build-history/v3.1.0/progress.md @@ -12,6 +12,9 @@ Status: **built; not released.** The plan is [spec.md](spec.md). Evidence: | 5 | Host client for Swift and Kotlin with browser sign-in | Mac and two Android emulators pass against a real host; live WorkOS not run | | 6 | Release packaging, phone test runs, release gate | staged and installed locally at 3.1.0; release CI jobs, simulator, and publication not run | | 7 | Version 3.1.0 and migration step 9 | done | +| 8 | Records and calculation answers as generated Swift and Kotlin types (D329) | Mac and two Android emulators pass; iPhone simulator not run | +| 9 | The Swift package served from this repository (D332) | staged and installed by version from a tagged clone; the release workflows not run | +| 10 | App guides, starting-point examples, and the contributor page | the guide check passes; both examples' tests pass on a Mac and on two Android emulators | The phone work was built on 3.0.0 as build steps 12 to 17, and moved here when 3.0.0 was released without it (D334). @@ -121,8 +124,9 @@ was released without it (D334). release packages, install them the way an app does, and run every phone test through the installed copy. Results are in [release-evidence.md](appendix/release-evidence.md). -- The Android consumer app keeps only the library's two ABIs, because JNA carries - more. Its shrunk release build needed two test-only rules, both in the consumer: the +- The Android example app (then named the consumer app) keeps only the library's two + ABIs, because JNA carries more. Its shrunk release build needed two test-only rules, + both in the example: the AndroidX test libraries name annotation classes they do not ship, and the test APK uses the app's copies of the Kotlin standard library and `androidx.tracing`. The library's own consumer rules needed no change. @@ -130,9 +134,8 @@ was released without it (D334). `publish-mobile` job in `release-cross-platform.yml`, and `release-mobile-packages.yml` are written but have not run on GitHub. The 16 KB emulator run is local only: GitHub's Linux runners have no 16 KB x86_64 image. -- Runnable examples: the consumer app is the Android example, and - `swift run AthleticStandardExample` is the Swift one. The Android example ran - offline on an emulator. The Swift example builds; its window was not opened. +- Runnable examples: the Android example app, and `swift run AthleticStandardExample`. + Step 10 split both by task and added tests that run their code. ## Step 7: version 3.1.0 and migration step 9 @@ -150,3 +153,54 @@ was released without it (D334). - The 31 calculation skills of 3.0.0 joined the list of released files, so `ath skill install` replaces an unedited 3.0.0 copy and keeps an edited one (D231). - `SPEC.md`, the README, the hosting guide, `AGENTS.md`, and every skill name 3.1.0. + +## Step 8: records and answers as Swift and Kotlin types + +- D329 changed: every record type, part of a record, list of allowed values, the + record wrapper, and every calculation answer is a generated Swift and Kotlin type. + The core marks them under an optional `uniffi` feature that only the phone crate + turns on, so the desktop program and the WebAssembly build are unchanged. +- Model fields that hold any JSON are the named types `JsonObject` and `JsonValue`, + which cross as JSON text. Result types that UniFFI cannot carry changed shape + without changing their JSON: counts are `u64`, fixed names are `String`, readings + around the best power are `(offset, value)` pairs, and a threshold answer is one + untagged enum. Every desktop JSON golden is unchanged. +- Phone writes take the types and run the npm client's request through the same + protocol operation. Reads check the stored JSON as a complete record. The + calculation bundle compares the typed answers, turned back into JSON, with the + desktop's bytes. +- An app keeps its own values as extensions: `extensionJson` and `withExtensionJson` + read and set one key, with the key and limit checks. The Swift package adds + `Codable` helpers, the Kotlin library adds helpers that take JSON text, and both + host clients read and write the typed records. +- In Swift both generated files compile into one module with one C module; records + have `var` fields and lists of allowed values are `CaseIterable`. In Kotlin the + core's types are in `ai.athleticstandard.core` and records change through `copy`. + +## Step 9: the Swift package in this repository + +- D332 changed: apps add `https://github.com/mwhitham/ath` by version. The root + `Package.swift` builds the package from `mobile/swift/`. On `main` its binary target + is the locally built XCFramework. +- A release from `main` tags one commit on top of the tested commit, which changes the + binary target line to the zip on the GitHub release, with its checksum, and adds + the generated Swift. The release workflow builds that commit through the GitHub API. + A release from a pushed tag cannot, and says so. +- `stage-apple.sh` stages the same commit in a clone of this repository, tagged + `v`, and a test package installs it by version. The separate package + repository, its token, and its templates are gone. + +## Step 10: app guides and examples + +- `mobile/README.md` follows the eight steps of building an app. The Swift guide + (`mobile/swift/README.md`) and the Android guide (`mobile/android/README.md`) show + each call. `mobile/tests/guides.rs` checks that each of their 37 code samples is a + marked region of an example file, unchanged, and that every region is shown. +- The examples are split by task (records, calculations, app values, picked files, + the host), each with a README that says how to start an app from it. Five tests in + each run the examples' code. The Android consumer app is now `mobile/android/example`. +- The phone crate denies missing documentation, so every call and every type, field, + and case it defines has a description in Xcode and Android Studio. Of the core's + record and result types, about half have one, and few of their fields and cases do. +- `mobile/CONTRIBUTING.md` holds the build, test, and release notes. The main README + has a "Build an app" section. diff --git a/build-history/v3.1.0/spec.md b/build-history/v3.1.0/spec.md index d3a84ddd..f3781039 100644 --- a/build-history/v3.1.0/spec.md +++ b/build-history/v3.1.0/spec.md @@ -29,7 +29,10 @@ In 3.1.0: interface. The settings, methods, and receipts move into the core (D326). - A host client with browser sign-in for Swift and Kotlin (D330). - A `cli` feature, on by default, that the phone build turns off (D327). -- Release packaging and one fixture bundle that tests every platform (D332, D333). +- Release packaging and one fixture bundle that tests every platform (D332, D333). The + Swift package is this repository, installed by version. +- App guides for Swift and Android, with tested examples that are starting points for + an app. - Version 3.1.0 and migration step 9 (section 2). Not in 3.1.0: @@ -72,3 +75,6 @@ Release gates (all must pass): 5. **Host client.** Both clients pass their tests against a real `ath-host` and the test sign-in provider. 6. **iPhone simulator.** The Swift tests pass on an iPhone simulator. +7. **Guides.** Every code sample in the Swift and Android guides is an unchanged + region of an example app, and the examples' tests pass on a Mac and on the Android + emulators. From 76f6e8d043015efb13c77dcefe15346dae6d5963 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 20:56:59 -0600 Subject: [PATCH 25/30] Describe every record and result type for Xcode and Android Studio. UniFFI copies Rust doc comments into the Swift and Kotlin that app developers read. The core now denies missing documentation, so every record type, part of a record, list of allowed values, calculation answer, field, and value has a description: about 1,700 new lines, from the code, SPEC.md, the skills, and the studies behind the methods. Each value of a list of allowed values also says how it is stored, such as "Stored as `import_time`.", with a line on what it means where its name says too little. Several existing descriptions that sat on one field but described a group, or that left out cases, were corrected. The generated Swift has a description on all 1,742 of its items. Co-Authored-By: Claude Opus 5.5 --- build-history/v3.1.0/progress.md | 6 +- core/build.rs | 1 + core/src/assets.rs | 3 + core/src/calculate/definition.rs | 196 +++++++++-- core/src/calculate/hyrox.rs | 38 +++ core/src/calculate/memory.rs | 3 + core/src/calculate/methods.rs | 121 ++++++- core/src/calculate/range.rs | 158 ++++++++- core/src/calculate/reader.rs | 68 +++- core/src/calculate/record.rs | 148 ++++++++- core/src/calculate/recorded.rs | 19 ++ core/src/calculate/window.rs | 56 +++- core/src/calculate/workout_ops.rs | 98 ++++++ core/src/calendar.rs | 13 + core/src/error.rs | 5 + core/src/json.rs | 2 + core/src/lib.rs | 4 + core/src/model/common.rs | 313 +++++++++++++++++- core/src/model/data.rs | 533 +++++++++++++++++++++++++++++- core/src/model/grade.rs | 7 + core/src/model/json_schema.rs | 2 + core/src/model/package.rs | 64 ++++ core/src/model/record.rs | 75 ++++- core/src/model/recording.rs | 72 ++++ core/src/model/schema.rs | 79 +++++ core/src/model/time.rs | 5 + core/src/model/training.rs | 325 +++++++++++++++++- core/src/save.rs | 12 + core/src/thresholds.rs | 329 ++++++++++++++---- mobile/CONTRIBUTING.md | 13 +- 30 files changed, 2631 insertions(+), 137 deletions(-) diff --git a/build-history/v3.1.0/progress.md b/build-history/v3.1.0/progress.md index 64619559..7a87a629 100644 --- a/build-history/v3.1.0/progress.md +++ b/build-history/v3.1.0/progress.md @@ -199,8 +199,8 @@ was released without it (D334). - The examples are split by task (records, calculations, app values, picked files, the host), each with a README that says how to start an app from it. Five tests in each run the examples' code. The Android consumer app is now `mobile/android/example`. -- The phone crate denies missing documentation, so every call and every type, field, - and case it defines has a description in Xcode and Android Studio. Of the core's - record and result types, about half have one, and few of their fields and cases do. +- The phone crate and the core deny missing documentation, so every call, type, + field, and case an app sees has a description in Xcode and Android Studio. Each + value of a list of allowed values also says how it is stored. - `mobile/CONTRIBUTING.md` holds the build, test, and release notes. The main README has a "Build an app" section. diff --git a/core/build.rs b/core/build.rs index 66d4cb7c..b56603f3 100644 --- a/core/build.rs +++ b/core/build.rs @@ -24,6 +24,7 @@ fn main() { collect(&root, &root, &mut files); files.sort(); let mut generated = String::from("// Generated by core/build.rs from skills/. Do not edit.\n\n"); + writeln!(generated, "/// Every file under `skills/`, sorted by path.").unwrap(); writeln!(generated, "pub static SKILL_FILES: &[EmbeddedFile] = &[").unwrap(); for relative in &files { let absolute = root.join(relative); diff --git a/core/src/assets.rs b/core/src/assets.rs index d8a581b2..222471b4 100644 --- a/core/src/assets.rs +++ b/core/src/assets.rs @@ -11,6 +11,7 @@ use std::collections::BTreeMap; pub struct EmbeddedFile { /// The path below `skills/` or `mappings/`, with `/` separators. pub path: &'static str, + /// The file's contents. pub bytes: &'static [u8], } @@ -67,7 +68,9 @@ pub fn shipped_calculation_names() -> Vec<&'static str> { /// A frontmatter value: text, or one nested level of `key: value` pairs. #[derive(Debug, Clone, PartialEq, Eq)] pub enum FrontmatterValue { + /// A `key: value` line's value, with one pair of surrounding quotes removed. Text(String), + /// The indented `key: value` pairs under a key that has no value of its own. Map(BTreeMap), } diff --git a/core/src/calculate/definition.rs b/core/src/calculate/definition.rs index b5fec2ff..b3cd3427 100644 --- a/core/src/calculate/definition.rs +++ b/core/src/calculate/definition.rs @@ -42,7 +42,9 @@ pub fn method_line(text: &str) -> String { /// in file order. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CalculationBlock { + /// The block's `name:` value. pub name: String, + /// Every setting by key, with its values in file order. pub settings: BTreeMap>, } @@ -89,31 +91,87 @@ pub fn parse_block(text: &str) -> Result { #[derive(Debug, Clone, PartialEq)] pub enum OneRecordCalculation { /// Seconds of heart-rate samples between fractions of the maximum. - TimeBetweenCuts { sample_field: String, maximum_field: String, cuts: Vec }, + TimeBetweenCuts { + /// The field with the heart-rate samples, `heart_rate_samples` by default. + sample_field: String, + /// The field with the maximum heart rate in bpm, `maximum_heart_rate_bpm` by default. + maximum_field: String, + /// Zone boundaries as fractions of the maximum heart rate, such as 0.6. + cuts: Vec, + }, /// Heart rate at the last sample minus the sample a fixed time later. - ValueAfterEnd { sample_field: String, later_offset_ms: i64 }, + ValueAfterEnd { + /// The field with the heart-rate samples, `heart_rate_samples` by default. + sample_field: String, + /// How long after the last sample to read the second heart rate, in milliseconds. + later_offset_ms: i64, + }, /// The lowest heart rate held without change for a span. - LowestHeld { sample_field: String, sustain_ms: i64 }, + LowestHeld { + /// The field with the heart-rate samples, `heart_rate_samples` by default. + sample_field: String, + /// How long the heart rate must stay the same, in milliseconds. + sustain_ms: i64, + }, /// Minutes weighted by the heart-rate reserve curve. - HeartRateReserveCurve { sample_field: String, rest_field: String, maximum_field: String, factor: f64 }, + HeartRateReserveCurve { + /// The field with the heart-rate samples, `heart_rate_samples` by default. + sample_field: String, + /// The field with the resting heart rate in bpm, `resting_heart_rate_bpm` by default. + rest_field: String, + /// The field with the maximum heart rate in bpm, `maximum_heart_rate_bpm` by default. + maximum_field: String, + /// The multiplier in the curve `reserve × e^(factor × reserve)`, 1.92 by default. + factor: f64, + }, /// Minutes multiplied by an effort rating. - Multiply { duration_field: String, effort_field: String }, + Multiply { + /// The field with the duration in seconds, `duration_seconds` by default. + duration_field: String, + /// The field with the effort rating, `rating` by default. + effort_field: String, + }, /// One numeric field. - Field { field: String }, + Field { + /// The field to read, such as `asleep_seconds`. + field: String, + }, /// Time asleep divided by time in bed. - Divide { asleep_field: String, in_bed_field: String }, + Divide { + /// The field with the time asleep in seconds, `asleep_seconds` by default. + asleep_field: String, + /// The field with the time in bed in seconds, `in_bed_seconds` by default. + in_bed_field: String, + }, /// Start time and the midpoint between start and end. - Midpoint { start_field: String, end_field: String }, + Midpoint { + /// The field with the start time, `start_at` by default. + start_field: String, + /// The field with the end time, `end_at` by default. + end_field: String, + }, /// Named numeric fields of an object and their total. - SumFields { field: String }, + SumFields { + /// The field with an object of stage names and minutes, `stage_minutes` by default. + field: String, + }, /// Minute-by-minute agreement of asleep windows on consecutive nights. - NightAgreement { minimum_nights: usize }, + NightAgreement { + /// The fewest nights, the target included, needed for a result. + minimum_nights: usize, + }, /// Repetitions times weight over every set. - RepsTimesWeight { field: String }, + RepsTimesWeight { + /// The field with the list of sets, `sets` by default. + field: String, + }, /// A point measurement minus the mean of the other values of its quantity. QuantityChange, /// A sleep field minus the mean of the other sessions' values. - SleepChange { field: String }, + SleepChange { + /// The sleep session field to compare, `asleep_seconds` by default. + field: String, + }, // ---- 2.1.2 operations (D230). The operations above keep their 2.1.1 // arithmetic so an edited file still gives the answer it gave before. @@ -123,44 +181,110 @@ pub enum OneRecordCalculation { /// The heart-rate drop from the end of effort to a fixed time later (D235). DropAfterEffortEnd(RecoverySettings), /// The Sleep Regularity Index on sleep periods (D236). - SleepRegularityIndex { window_days: u32, minimum_day_pairs: u32 }, + SleepRegularityIndex { + /// The number of 24-hour days, ending at the target session's end, that the index + /// covers. + window_days: u32, + /// The fewest pairs of consecutive observed days needed for a result. + minimum_day_pairs: u32, + }, /// Repetitions times load in kilograms, with load basis (D237). - VolumeLoad { field: String }, + VolumeLoad { + /// The field with the list of sets, `sets` by default. + field: String, + }, /// A session-effort rating times the minutes it covers (D238). - SessionEffortLoad { duration_field: String, effort_field: String }, + SessionEffortLoad { + /// The report field with the duration in seconds, `duration_seconds` by default. + duration_field: String, + /// The report field with the effort rating, `rating` by default. + effort_field: String, + }, /// Banister's TRIMP with sex-specific weighting and covered time only (D240). BanisterTrimp(TrimpSettings), /// Covered seconds between fractions of the maximum (D240). - TimeInZones { sample_field: String, maximum_field: String, cuts: Vec, max_gap_ms: i64 }, + TimeInZones { + /// The field with the heart-rate samples, `heart_rate_samples` by default. + sample_field: String, + /// The field with the maximum heart rate in bpm, `maximum_heart_rate_bpm` by default. + maximum_field: String, + /// Zone boundaries as fractions of the maximum heart rate, such as 0.6. + cuts: Vec, + /// The longest time one sample counts for, in milliseconds. Time past it is uncovered. + max_gap_ms: i64, + }, /// The lowest mean heart rate over a sustained window (D241). LowestRollingMean(RollingMeanSettings), /// Time asleep over time in bed, checked (D242). - SleepEfficiency { asleep_field: String, in_bed_field: String }, + SleepEfficiency { + /// The field with the time asleep in seconds, `asleep_seconds` by default. + asleep_field: String, + /// The field with the time in bed in seconds, `in_bed_seconds` by default. + in_bed_field: String, + }, /// Asleep and awake stage minutes apart, with stage shares (D242). - SleepStageSplit { field: String }, + SleepStageSplit { + /// The field with an object of stage names and minutes, `stage_minutes` by default. + field: String, + }, /// Start, midpoint, and end in the athlete's time zone (D242). - SleepClockTimes { start_field: String, end_field: String }, + SleepClockTimes { + /// The field with the start time, `start_at` by default. + start_field: String, + /// The field with the end time, `end_at` by default. + end_field: String, + }, /// A HYROX result divided into runs, stations, Roxzone, and penalties (D245). HyroxSplits, // ---- 3.0.0 operations (D309). They read the workout's device recordings // and the intensity references in effect, not fields on the workout. /// The best mean power and speed over each duration (D306). - BestMeanEfforts { durations_s: Vec, max_gap_s: u64 }, + BestMeanEfforts { + /// The effort durations, in seconds. + durations_s: Vec, + /// The longest time one reading holds its value, in seconds. + max_gap_s: u64, + }, /// Seconds in each zone of the threshold power in effect. - TimeInPowerZones { cuts: Vec, max_gap_s: u64 }, + TimeInPowerZones { + /// Zone boundaries as fractions of the threshold power, such as 0.55. + cuts: Vec, + /// The longest time one reading holds its value, in seconds. + max_gap_s: u64, + }, /// Heart-rate zones from the maximum heart rate in effect (D301). - TimeInZonesFromMaximumReference { cuts: Vec, max_gap_ms: i64 }, + TimeInZonesFromMaximumReference { + /// Zone boundaries as fractions of the maximum heart rate, such as 0.6. + cuts: Vec, + /// The longest time one sample counts for, in milliseconds. Time past it is uncovered. + max_gap_ms: i64, + }, /// Banister's TRIMP with the maximum in effect and the latest measured /// resting heart rate on or before the day. - BanisterTrimpFromReferences { max_gap_ms: i64, male: (f64, f64), female: (f64, f64) }, + BanisterTrimpFromReferences { + /// The longest time one sample counts for, in milliseconds. Time past it is uncovered. + max_gap_ms: i64, + /// The coefficient and exponent for men, 0.64 and 1.92 by default. + male: (f64, f64), + /// The coefficient and exponent for women, 0.86 and 1.67 by default. + female: (f64, f64), + }, /// The exponential model of work capacity above threshold (Skiba et al., 2012). - WorkCapacityBalance { max_gap_s: u64 }, + WorkCapacityBalance { + /// The longest time one reading holds its value, in seconds. + max_gap_s: u64, + }, /// Each planned block against the lap that carried it out. PlannedBlocksAgainstLaps, /// Threshold methods and maximum heart-rate estimates (D320, D322): the /// operations the file allows, the first being the default. - Thresholds { operations: Vec, max_gap_s: u64 }, + Thresholds { + /// The operations the file allows. The first is the default. + operations: Vec, + /// The longest time one reading holds its value, in seconds. + max_gap_s: u64, + }, /// A range calculation, which `ath apply` refuses (D243). Range(String), /// An operation this program does not have. @@ -173,7 +297,9 @@ pub struct WindowChangeSettings { /// A session field such as `asleep_seconds`. None reads a measurement's /// `value.standard_value`. pub field: Option, + /// How many days before the target's day to compare with, 28 by default. pub window_days: u32, + /// The fewest earlier days, or earlier main sleeps, needed for a result, 7 by default. pub minimum_days: u32, /// A sleep session shorter than this is a nap. pub main_sleep_hours: f64, @@ -182,30 +308,48 @@ pub struct WindowChangeSettings { /// Settings for `drop_after_effort_end`. #[derive(Debug, Clone, PartialEq)] pub struct RecoverySettings { + /// The field with the heart-rate samples, `heart_rate_samples` by default. pub sample_field: String, + /// How long after the end of effort to read the second heart rate, in milliseconds. pub later_offset_ms: i64, + /// How far the nearest sample may be from a wanted time, in milliseconds, when the + /// heart rate cannot be interpolated. pub tolerance_ms: i64, + /// The largest gap between two samples, in milliseconds, that a heart rate may be + /// interpolated across. pub max_interpolation_gap_ms: i64, + /// The workout segment label that marks the end of effort, in any letter case. pub recovery_label: String, } /// Settings for `banister_trimp`. #[derive(Debug, Clone, PartialEq)] pub struct TrimpSettings { + /// The field with the heart-rate samples, `heart_rate_samples` by default. pub sample_field: String, + /// The field with the resting heart rate in bpm, `resting_heart_rate_bpm` by default. pub rest_field: String, + /// The field with the maximum heart rate in bpm, `maximum_heart_rate_bpm` by default. pub maximum_field: String, + /// The longest time one sample counts for, in milliseconds. Time past it is uncovered. pub max_gap_ms: i64, + /// The coefficient and exponent for men, 0.64 and 1.92 by default. pub male: (f64, f64), + /// The coefficient and exponent for women, 0.86 and 1.67 by default. pub female: (f64, f64), } /// Settings for `lowest_rolling_mean`. #[derive(Debug, Clone, PartialEq)] pub struct RollingMeanSettings { + /// The field with the heart-rate samples, `heart_rate_samples` by default. pub sample_field: String, + /// The window's length, in milliseconds. pub window_ms: i64, + /// The fewest samples a window must hold to count. pub minimum_samples: usize, + /// The largest gap allowed between neighbouring samples in a window, and between + /// the last sample and the window's end, in milliseconds. pub max_gap_ms: i64, } @@ -303,7 +447,9 @@ impl OneRecordCalculation { /// A calculation file read into typed settings. #[derive(Debug, Clone, PartialEq)] pub struct CalculationFile { + /// The calculation's name, from the block's `name:` line. pub name: String, + /// The operation and its settings. pub calculation: OneRecordCalculation, } diff --git a/core/src/calculate/hyrox.rs b/core/src/calculate/hyrox.rs index bd5e2303..127bf9ed 100644 --- a/core/src/calculate/hyrox.rs +++ b/core/src/calculate/hyrox.rs @@ -21,28 +21,41 @@ pub const HYROX_EXTENSION: &str = "org.athleticstandard/hyrox-race"; pub const STATIONS: [&str; 8] = ["ski_erg", "sled_push", "sled_pull", "burpee_broad_jumps", "row", "farmers_carry", "sandbag_lunges", "wall_balls"]; +/// One run in a HYROX result. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct Split { + /// The run's segment label, `run_1` to `run_8`. pub label: String, + /// The run time, in seconds, as recorded. pub seconds: f64, } +/// One station in a HYROX result. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct StationSplit { + /// The station's segment label, such as `ski_erg` or `wall_balls`. pub label: String, + /// The station time, in seconds, as recorded. pub seconds: f64, + /// The station time as a percentage of the finish time, to one decimal place. pub share_percent: f64, } +/// How the runs of a HYROX result were paced. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RunSummary { + /// How many runs were recorded, up to 8. pub count: u64, + /// The mean run time, in seconds, to one decimal place. pub mean_seconds: f64, + /// The fastest run. pub fastest: Split, + /// The slowest run. pub slowest: Split, + /// The slowest run time minus the fastest, in seconds, to one decimal place. pub spread_seconds: f64, /// Run 1, which follows no station. #[serde(skip_serializing_if = "Option::is_none")] @@ -52,35 +65,60 @@ pub struct RunSummary { pub later_runs_mean_seconds: Option, } +/// Each part of a HYROX result as a percentage of the finish time, to one decimal place. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SharePercent { + /// All runs together. pub runs: f64, + /// All stations together. pub stations: f64, + /// All Roxzone time together. pub roxzone: f64, + /// All time penalties together. pub penalties: f64, + /// Finish time not covered by any part. pub unaccounted: f64, } +/// The result of `hyrox_splits`: one HYROX result divided into runs, stations, Roxzone, and +/// penalties, with no time counted twice. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct HyroxSplitsResult { + /// The finish time, in seconds, from the result's `score.duration_s`. pub total_seconds: f64, + /// All run time, in seconds, to one decimal place. pub runs_seconds: f64, + /// All station time, in seconds, to one decimal place. pub stations_seconds: f64, + /// All Roxzone time, in seconds, to one decimal place: the `roxzone` segment, or the sum + /// of the numbered `roxzone_N` segments. pub roxzone_seconds: f64, + /// All time penalties, in seconds, to one decimal place: from a `penalty` segment or the + /// race extension's `penalties_s`. pub penalties_seconds: f64, /// Finish time not covered by any part, such as Roxzone time that was not /// recorded. pub unaccounted_seconds: f64, + /// Each part's share of the finish time. pub share_percent: SharePercent, + /// Each recorded run, in race order. pub runs: Vec, + /// How the runs were paced. Absent when no run was recorded. pub run_summary: Option, + /// Each recorded station, in race order, with its share of the finish time. pub stations: Vec, + /// The rulebook season, such as `2026/27`, from the HYROX race extension. Absent when the + /// extension does not give it. #[serde(skip_serializing_if = "Option::is_none")] pub season: Option, + /// The race format, such as `singles`, `doubles`, or `relay`, from the HYROX race + /// extension. Absent when the extension does not give it. #[serde(skip_serializing_if = "Option::is_none")] pub format: Option, + /// The division, such as `open`, `pro`, or `adaptive`, from the HYROX race extension. + /// Absent when the extension does not give it. #[serde(skip_serializing_if = "Option::is_none")] pub division: Option, } diff --git a/core/src/calculate/memory.rs b/core/src/calculate/memory.rs index 4e4775b7..3928623a 100644 --- a/core/src/calculate/memory.rs +++ b/core/src/calculate/memory.rs @@ -149,6 +149,7 @@ pub struct SnapshotBuilder { } impl SnapshotBuilder { + /// An empty builder. pub fn new() -> Self { SnapshotBuilder::default() } @@ -158,6 +159,7 @@ impl SnapshotBuilder { self.entries.len() } + /// True when no record has been added. pub fn is_empty(&self) -> bool { self.entries.is_empty() } @@ -220,6 +222,7 @@ impl RecordSnapshot { self.entries.len() } + /// True when no record was supplied. pub fn is_empty(&self) -> bool { self.entries.is_empty() } diff --git a/core/src/calculate/methods.rs b/core/src/calculate/methods.rs index 3320e9bc..404c6dce 100644 --- a/core/src/calculate/methods.rs +++ b/core/src/calculate/methods.rs @@ -27,7 +27,10 @@ pub const POUND_IN_KG: f64 = 0.45359237; /// The athlete profile fields some methods read. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Profile { + /// The athlete profile's `default_time_zone`, an IANA time zone name such as + /// `Europe/London`. Absent when the profile has none. pub time_zone: Option, + /// The athlete profile's `sex`: `male` or `female`. Absent when the profile does not say. pub sex: Option, /// Read by the age formula only (D320). pub birth_year: Option, @@ -37,8 +40,11 @@ pub struct Profile { /// rate, and the record it came from. #[derive(Debug, Clone, PartialEq)] pub struct SeriesSample { + /// When the sample was taken, in milliseconds since 1970-01-01 UTC. pub at_ms: i64, + /// The heart rate, in beats per minute. pub bpm: f64, + /// The record and revision the sample came from. pub reference: EvidenceReference, } @@ -171,165 +177,276 @@ fn heart_rate_at(samples: &[(i64, f64)], at: i64, max_gap_ms: i64, tolerance_ms: #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct Comparison { + /// The mean of the compared values, to three decimal places. For a measurement, the + /// mean of the earlier daily means, so each day counts once. pub mean: f64, - /// The sample standard deviation (n − 1) of the compared values. + /// The sample standard deviation (n − 1) of the compared values. Absent with fewer + /// than two values. pub standard_deviation: Option, + /// How many earlier days were compared, for a measurement. Absent for a sleep session. #[serde(skip_serializing_if = "Option::is_none")] pub days: Option, + /// How many earlier main sleeps were compared, for a sleep session. Absent for a + /// measurement. #[serde(skip_serializing_if = "Option::is_none")] pub nights: Option, + /// The start of the compared window. For a measurement, a calendar day, `YYYY-MM-DD`, in + /// the result's time zone. For a sleep session, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. pub from: String, + /// The end of the compared window. For a measurement, the day before the target's day, + /// `YYYY-MM-DD`. For a sleep session, the UTC instant the target session started. pub to: String, } +/// The result of `earlier_window_change`: one day's reading, or one main sleep, against the +/// athlete's own earlier values from the same source. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct WindowChangeResult { + /// The quantity compared, such as `hrv_rmssd` or `resting_heart_rate`. Absent for a sleep + /// session. #[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option, + /// The sleep session field compared, such as `asleep_seconds`. Absent for a measurement. #[serde(skip_serializing_if = "Option::is_none")] pub field: Option, + /// The basis of the compared readings, from `field_basis.value`, such as `provider`, or + /// `unstated` when the reading names none. Absent for a sleep session. #[serde(skip_serializing_if = "Option::is_none")] pub basis: Option, /// The target value: the mean of the target's day so far, or the night. pub value: f64, + /// How many readings from the target's day, up to and including the target, made `value`. + /// Absent for a sleep session. #[serde(skip_serializing_if = "Option::is_none")] pub target_day_readings: Option, + /// `value` minus `comparison.mean`, in the unit of the value, to three decimal places. pub change: f64, + /// `change` as a percentage of `comparison.mean`, to one decimal place. Absent when the + /// mean is zero. pub change_percent: Option, - /// The change in standard deviations of the compared values. + /// The change in standard deviations of the compared values. Absent with fewer than + /// two compared values, or when their standard deviation is zero. pub standardized_change: Option, + /// The earlier values compared against. pub comparison: Comparison, + /// How many earlier records were compared. For a measurement this counts every reading, + /// so it can be more than `comparison.days`. pub compared_records: u64, + /// The time zone that set the days: the athlete profile's `default_time_zone`, or `UTC`. + /// Absent for a sleep session. #[serde(skip_serializing_if = "Option::is_none")] pub time_zone: Option, } +/// The result of `drop_after_effort_end`: how far heart rate fell in a set time after the +/// end of effort. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RecoveryResult { + /// `end_bpm` minus `later_bpm`, in beats per minute, to one decimal place. pub drop_bpm: f64, + /// The heart rate at the end of effort, in beats per minute, to one decimal place. pub end_bpm: f64, + /// The heart rate the set time after the end of effort (60 seconds by default), in beats + /// per minute, to one decimal place. pub later_bpm: f64, + /// When the effort ended, in milliseconds from the workout start. pub end_offset_ms: i64, + /// When `later_bpm` was read, in milliseconds from the workout start. pub later_offset_ms: i64, /// `recovery segment` or `workout end`. pub anchor: String, } +/// The result of `sleep_regularity_index`: how alike the athlete's sleep and wake times are +/// on consecutive days, from sleep sessions of one source. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RegularityResult { /// −100 (opposite states) to 100 (the same state 24 hours apart). pub index: f64, + /// How many pairs of consecutive days, both with a sleep session, were compared. pub day_pairs: u64, + /// How many days of the window had a sleep session. pub days_observed: u64, + /// The window's length in days. pub window_days: u32, + /// The window's start, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub window_from: String, + /// The window's end: the end of the target session, a UTC instant. pub window_to: String, + /// How many sleep sessions fall inside the window, including the target session. pub sessions: u64, } +/// Volume load for one movement in a `volume_load` result. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct MovementVolume { + /// The movement name, with spaces at either end removed. Absent for the sets that name + /// no movement. pub movement: Option, + /// Repetitions times load for this movement, in kilograms, to three decimal places. pub volume: f64, + /// How many sets of this movement. pub sets: u64, + /// How many repetitions of this movement, over every set. pub reps: f64, } +/// The result of `volume_load`: repetitions times load over every set, in kilograms. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct VolumeResult { + /// Repetitions times load over every set, in kilograms, to three decimal places. A pound + /// counts as 0.45359237 kg. pub volume: f64, + /// The unit of `volume`: always `kg`. pub weight_unit: String, + /// How many sets were read. pub sets: u64, + /// How many repetitions, over every set. pub reps: f64, + /// Volume, sets, and repetitions for each movement. Absent when no set names a movement. #[serde(skip_serializing_if = "Option::is_none")] pub by_movement: Option>, + /// How many sets state no `load_basis`, so their weight was counted as written. pub unstated_load_basis_sets: u64, } +/// The result of `session_effort_load`: a session-effort rating times the minutes it covers. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortLoadResult { + /// The rating times the minutes, in arbitrary units, to one decimal place. pub load: f64, + /// The unit of `load`: always `AU`, for arbitrary units. pub unit: String, + /// The athlete's effort rating, as reported. pub rating: f64, + /// The rating scale the report names, such as `0-10`, `CR10`, `1-10`, or `6-20`. pub rating_scale: String, /// `10-point` or `6-20`. Loads on different scales are never comparable. pub scale_family: String, + /// The minutes the rating covers, to one decimal place. pub duration_minutes: f64, /// `report` or `linked workout session`. pub duration_from: String, } +/// The result of `banister_trimp`: Banister's training impulse (TRIMP) from the heart-rate +/// samples, resting heart rate, and maximum heart rate fields on the workout. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct TrimpResult { + /// The training impulse, in arbitrary units, to one decimal place. pub load: f64, + /// The weighting used, `male` or `female`, chosen by the athlete profile's `sex`. pub weighting: String, + /// The weighting's coefficient. By default 0.64 for `male` and 0.86 for `female`. pub coefficient: f64, + /// The weighting's exponent. By default 1.92 for `male` and 1.67 for `female`. pub exponent: f64, + /// Minutes the heart-rate samples cover, to one decimal place. pub covered_minutes: f64, + /// Minutes with no sample close enough, which add no load, to one decimal place. pub uncovered_minutes: f64, } +/// The result of `time_in_zones`: seconds in each heart-rate zone, split at fractions of a +/// maximum heart rate field on the workout. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ZonesResult { + /// Seconds in each zone, lowest zone first, to three decimal places. pub seconds: Vec, + /// Seconds with no sample close enough, which are in no zone, to three decimal places. pub uncovered_seconds: f64, + /// The zone boundaries in beats per minute, lowest first, to one decimal place. A heart + /// rate on a boundary is in the zone above it. pub boundaries_bpm: Vec, + /// The maximum heart rate read from the workout, in beats per minute. pub maximum_heart_rate_bpm: f64, } +/// The result of `lowest_rolling_mean`: the lowest mean heart rate over a window of set +/// length (5 minutes by default). #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RestingResult { + /// The lowest window mean, in beats per minute, to one decimal place. pub bpm: f64, + /// Where the lowest window starts, in milliseconds from the start of the record's own + /// samples, such as a workout's `heart_rate_samples`. Absent for a sleep session. #[serde(skip_serializing_if = "Option::is_none")] pub window_start_offset_ms: Option, + /// Where the lowest window starts, a UTC instant such as `2026-01-02T03:04:05.678Z`. + /// Present only for a sleep session. #[serde(skip_serializing_if = "Option::is_none")] pub window_start_at: Option, + /// The window length, in minutes. pub window_minutes: f64, + /// How many samples made the lowest mean. pub samples_in_window: u64, + /// How many samples were read in all. pub samples_read: u64, } +/// The result of `sleep_efficiency`: the share of time in bed spent asleep. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EfficiencyResult { + /// Time asleep divided by time in bed, from 0 to 1, to four decimal places. pub efficiency: f64, + /// The same share as a percentage, to one decimal place. pub percent: f64, + /// The time asleep read, in seconds. pub asleep_seconds: f64, + /// The time in bed read, in seconds. pub in_bed_seconds: f64, } +/// The result of `sleep_stage_split`: sleep stage minutes with awake time kept apart. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct StageSplitResult { + /// Each stage name with its minutes, as the source supplied them. pub stages: crate::json::JsonObject, + /// Minutes in every stage except the one named `awake`. pub asleep_minutes: f64, + /// Minutes in the stage named `awake`, in any letter case. pub awake_minutes: f64, + /// Asleep and awake minutes together. pub total_minutes: f64, /// Each sleep stage as a percentage of asleep minutes. pub percent_of_asleep: crate::json::JsonObject, } +/// The result of `sleep_clock_times`: when a sleep session started, reached its midpoint, and +/// ended, in UTC and in local time. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ClockTimesResult { + /// The session start, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub start_at: String, + /// The instant halfway between start and end, in UTC. pub midpoint_at: String, + /// The session end, a UTC instant. pub end_at: String, + /// The start in local time with its UTC offset, such as `2026-01-01T23:30:00-05:00`. pub local_start: String, + /// The midpoint in local time with its UTC offset. pub local_midpoint: String, + /// The end in local time with its UTC offset. pub local_end: String, + /// The zone used for local times: an IANA name such as `Europe/London`, a fixed offset + /// such as `+01:00`, or `UTC`. pub time_zone: String, /// `athlete_profile.default_time_zone`, `source offset`, or `utc`. pub time_zone_basis: String, + /// Hours from start to end, to two decimal places. This includes time awake. pub duration_hours: f64, } diff --git a/core/src/calculate/range.rs b/core/src/calculate/range.rs index a01bf09d..e567dd9c 100644 --- a/core/src/calculate/range.rs +++ b/core/src/calculate/range.rs @@ -39,19 +39,24 @@ pub const MAX_RUNTIME_INPUTS: usize = 100_000; pub const MAX_RECEIPT_REFERENCES: usize = 1_000; macro_rules! named_enum { - ($(#[$meta:meta])* pub enum $name:ident { $($variant:ident = $text:literal),* $(,)? }) => { + ($(#[$meta:meta])* pub enum $name:ident { $($(#[$variant_meta:meta])* $variant:ident = $text:literal),* $(,)? }) => { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] $(#[$meta])* - pub enum $name { $($variant),* } + pub enum $name { + $($(#[$variant_meta])* $variant),* + } impl $name { + /// Every value, in published order. pub const ALL: &'static [$name] = &[$($name::$variant),*]; + /// The value's name, as `ath calculate` writes it. pub fn as_str(self) -> &'static str { match self { $($name::$variant => $text),* } } + /// The value with this name, or `None`. pub fn parse(text: &str) -> Option { match text { $($text => Some($name::$variant),)* _ => None } } @@ -74,13 +79,29 @@ named_enum! { /// A named range calculation. #[cfg_attr(feature = "uniffi", uniffi(name = "CalculationOperation"))] pub enum Operation { + /// Count, minimum, maximum, mean, sum, and standard deviation for each source. + /// Written as `summary`. Summary = "summary", + /// Mean and standard deviation for each source, with day means when a time zone is known. + /// Written as `baseline`. Baseline = "baseline", + /// The least-squares slope per day for each source. + /// Written as `trend`. Trend = "trend", + /// The calendar days with and without a reading, for each source. + /// Written as `coverage`. Coverage = "coverage", + /// Two sources' summaries and the difference between their means. + /// Written as `compare-sources`. CompareSources = "compare-sources", + /// The Pearson correlation of two quantities' same-day means. + /// Written as `correlation`. Correlation = "correlation", + /// The change in mean from the first half of one workout to the second half. + /// Written as `workout-drift`. WorkoutDrift = "workout-drift", + /// A summary for each exact provider reporting period, such as an Oura sleep day. + /// Written as `provider-period-summary`. ProviderPeriodSummary = "provider-period-summary", } } @@ -89,9 +110,17 @@ named_enum! { /// Which typed rows a calculation reads. #[cfg_attr(feature = "uniffi", uniffi(name = "CalculationRecordKind"))] pub enum RecordKind { + /// Point measurements and measurement samples. + /// Written as `measurement`. Measurement = "measurement", + /// A provider's composite scores, such as a recovery or readiness score. + /// Written as `provider-score`. ProviderScore = "provider-score", + /// A provider's reported totals or durations, such as active energy. + /// Written as `provider-summary`. ProviderSummary = "provider-summary", + /// Summaries a sleep or workout session reported, read only by `provider-period-summary`. + /// Written as `session-summary`. SessionSummary = "session-summary", } } @@ -100,9 +129,15 @@ named_enum! { /// Calendar grouping for summary and baseline. #[cfg_attr(feature = "uniffi", uniffi(name = "CalculationGroup"))] pub enum Group { + /// No grouping: one result for the whole window. + /// Written as `none`. None = "none", + /// Written as `day`. Day = "day", + /// Calendar weeks that start on Monday. + /// Written as `week`. Week = "week", + /// Written as `month`. Month = "month", } } @@ -112,31 +147,48 @@ named_enum! { #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] #[cfg_attr(feature = "uniffi", uniffi(name = "RangeRequest"))] pub struct CalculateOptions { + /// The calculation to run. pub operation: Operation, /// A measurement quantity, provider metric, or summary type. pub quantity: String, + /// Which kind of record to read. pub record_kind: RecordKind, + /// The provider reporting period type to group by, such as `oura_sleep_day`. + /// Required for `provider-period-summary` and refused for every other operation. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub provider_period_type: Option, + /// Read only this source, by its record ID. Required for `compare-sources`. + /// Absent reads every source that is not manual. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub source_id: Option, + /// The second source, by its record ID. Required for `compare-sources`. For + /// `correlation`, the source of `other_quantity`. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub compare_source_id: Option, + /// The second quantity. Required for `correlation`. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub other_quantity: Option, + /// The record ID of the workout session to read. Required for `workout-drift`. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub workout_session_id: Option, /// A calendar day (`YYYY-MM-DD`) or an exact UTC instant. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub from: Option, + /// The end of the window: a calendar day (`YYYY-MM-DD`) or an exact UTC instant. + /// Absent means no end. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub to: Option, + /// The IANA time zone name for calendar days, such as `Europe/London`. Absent + /// uses the athlete profile's default time zone. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub time_zone: Option, + /// The calendar grouping for `summary` and `baseline`. pub group: Group, } impl CalculateOptions { + /// A request for `operation` on `quantity` that reads measurements from every + /// source, with no dates, no time zone, and no grouping. pub fn new(operation: Operation, quantity: impl Into) -> Self { CalculateOptions { operation, @@ -159,10 +211,15 @@ impl CalculateOptions { #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReceiptRange { + /// The start of the window read, included: a calendar day (`YYYY-MM-DD`) or a UTC + /// instant. For `workout-drift`, the workout's start. Absent when the window has no start. #[serde(skip_serializing_if = "Option::is_none")] pub from: Option, + /// The end of the window read, included: a calendar day (`YYYY-MM-DD`) or a UTC + /// instant. For `workout-drift`, the workout's end. Absent when the window has no end. #[serde(skip_serializing_if = "Option::is_none")] pub to: Option, + /// The IANA time zone name used for calendar days. Absent when none was used. #[serde(skip_serializing_if = "Option::is_none")] pub time_zone: Option, } @@ -171,6 +228,7 @@ pub struct ReceiptRange { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReceiptInput { + /// The number of records used. pub record_count: u64, /// The exact record revisions used, in input order, at most 1,000. pub record_references: Vec, @@ -183,18 +241,28 @@ pub struct ReceiptInput { #[derive(Debug, Clone, Copy, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct NumericSummary { + /// The number of values. pub count: u64, + /// The smallest value, in the receipt's unit. pub minimum: f64, + /// The largest value, in the receipt's unit. pub maximum: f64, + /// The mean of the values. pub mean: f64, + /// The sum of the values. pub sum: f64, + /// The population standard deviation of the values. pub standard_deviation: f64, } +/// The summary of one calendar period, for `summary` or `baseline` with a grouping. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct GroupSummary { + /// The period: a day (`YYYY-MM-DD`), the Monday that starts a week (`YYYY-MM-DD`), + /// or a month (`YYYY-MM`). pub period: String, + /// The summary of the values in the period. #[serde(flatten)] pub summary: NumericSummary, } @@ -204,36 +272,55 @@ pub struct GroupSummary { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct DailySummary { + /// The IANA time zone name that set the calendar days. pub time_zone: String, + /// The number of calendar days with at least one value. pub days: u64, + /// The mean of the day means, rounded to four decimal places. pub mean: f64, + /// The population standard deviation of the day means, rounded to four decimal places. pub standard_deviation: f64, } +/// One source's result for `summary` or `baseline`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum SourceSummary { + /// One summary for the whole window, when the request has no grouping. Whole { + /// The source's record ID. source_id: String, + /// The summary with every value counted once. #[serde(flatten)] summary: NumericSummary, + /// The summary of calendar-day means. Present only for `baseline` when a time + /// zone is known. #[serde(skip_serializing_if = "Option::is_none")] daily: Option, }, + /// One summary for each calendar period, when the request names a grouping. Grouped { + /// The source's record ID. source_id: String, + /// The summaries, one for each period with a value, in date order. groups: Vec, }, } +/// One source's result for `trend`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SourceTrend { + /// The source's record ID. pub source_id: String, + /// The number of values the line is fitted to. pub count: u64, + /// The fitted change per day, in the receipt's unit, rounded to four decimal places. pub slope_per_day: f64, + /// The value of the earliest input. pub first_value: f64, + /// The value of the latest input. pub last_value: f64, /// Days from the first to the last input. pub days_spanned: f64, @@ -242,32 +329,47 @@ pub struct SourceTrend { pub slope_standard_error: Option, } +/// One source's result for `coverage`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SourceCoverage { + /// The source's record ID. pub source_id: String, + /// The first calendar day checked, `YYYY-MM-DD`. Absent when no day was checked. pub first_date: Option, + /// The last calendar day checked, `YYYY-MM-DD`. Absent when no day was checked. pub last_date: Option, + /// The number of calendar days checked. pub days_expected: u64, + /// The number of calendar days with at least one reading. pub days_present: u64, + /// The checked days with no reading, `YYYY-MM-DD`, in date order. pub missing_dates: Vec, /// `days_present / days_expected`. pub coverage_ratio: f64, } +/// One source's summary, for `compare-sources`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct NamedSummary { + /// The source's record ID. pub source_id: String, + /// The summary with every value of the source counted once. #[serde(flatten)] pub summary: NumericSummary, } +/// The result of `compare-sources`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CompareSourcesResult { + /// The summary of the first source, the request's `source_id`. pub source: NamedSummary, + /// The summary of the second source, the request's `compare_source_id`. pub comparison_source: NamedSummary, + /// The first source's mean minus the second source's mean, over all values, rounded + /// to four decimal places. The values are not paired by day. pub mean_difference: f64, /// The mean of daily differences on days both sources read, when a time /// zone is known (D244). @@ -275,69 +377,101 @@ pub struct CompareSourcesResult { pub paired: Option, } +/// The difference between two sources on the calendar days both have values. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PairedComparison { + /// The IANA time zone name that set the calendar days. pub time_zone: String, + /// The number of calendar days on which both sources have values. pub days: u64, /// Null when no day has both sources. pub mean_difference: Option, } +/// The result of `correlation`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CorrelationResult { + /// The second quantity, compared with the receipt's `quantity`. pub other_quantity: String, + /// The number of calendar days with values of both quantities. pub paired_day_count: u64, /// Null when fewer than three days pair or a side does not vary. pub correlation: Option, + /// The calendar days with values of both quantities, `YYYY-MM-DD`, in date order. pub paired_dates: Vec, /// Why the correlation is null. #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, } +/// One source's result for `workout-drift`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum SourceDrift { + /// Both halves of the workout have samples from this source. Available { + /// The source's record ID. source_id: String, + /// Always true. available: bool, + /// The mean of the samples in the first half, rounded to four decimal places. first_half_mean: f64, + /// The mean of the samples in the second half, rounded to four decimal places. second_half_mean: f64, + /// The second half's mean minus the first half's mean, rounded to four decimal + /// places. change: f64, + /// The change as a percentage of the first half's mean, rounded to four decimal + /// places. change_percentage: f64, + /// The number of samples in the first half. first_half_count: u64, + /// The number of samples in the second half. second_half_count: u64, }, + /// One half of the workout has no samples from this source. Unavailable { + /// The source's record ID. source_id: String, + /// Always false. available: bool, + /// Why there is no result, such as `one half has no samples`. reason: String, }, } +/// The result of `workout-drift`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct WorkoutDriftResult { + /// The record ID of the workout session read. pub workout_session_id: String, + /// One result for each source with samples inside the workout. pub sources: Vec, } +/// The summary of one provider reporting period. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PeriodSummary { /// The provider period exactly as stored. pub provider_period: crate::json::JsonValue, + /// The summary of the values in the period. #[serde(flatten)] pub summary: NumericSummary, } +/// One source's result for `provider-period-summary`. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct SourcePeriods { + /// The source's record ID. pub source_id: String, + /// One summary for each stored period, ordered by the period's provider date, else + /// its start, else its provider ID. pub periods: Vec, } @@ -346,12 +480,19 @@ pub struct SourcePeriods { #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum CalculationResult { + /// The results of `summary` or `baseline`, one for each source. Summaries(Vec), + /// The results of `trend`, one for each source. Trends(Vec), + /// The results of `coverage`, one for each source. Coverage(Vec), + /// The result of `compare-sources`. CompareSources(CompareSourcesResult), + /// The result of `correlation`. Correlation(CorrelationResult), + /// The result of `workout-drift`. WorkoutDrift(WorkoutDriftResult), + /// The results of `provider-period-summary`, one for each source. ProviderPeriods(Vec), } @@ -359,17 +500,30 @@ pub enum CalculationResult { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CalculationReceipt { + /// The version of the calculation rules that made the receipt, such as `ath-runtime-v2`. pub calculation_version: String, + /// The calculation that ran. pub operation: Operation, + /// The kind of record read. pub record_kind: RecordKind, + /// The method in words, such as `count, minimum, maximum, mean, and sum per source`. pub method: String, + /// The measurement quantity, provider metric, or summary type read. pub quantity: String, + /// The standard unit of the values read, such as `ms` or `bpm`. pub unit: String, + /// The window read, and the time zone used for calendar days. pub range: ReceiptRange, + /// The record IDs of the sources the inputs came from, sorted. pub sources: Vec, + /// How many records were used, and which revisions. pub input: ReceiptInput, + /// What the calculation left out, in words, such as `manual sources excluded`. pub exclusions: Vec, + /// The operation's own result. pub result: CalculationResult, + /// The provider reporting period type that `provider-period-summary` grouped by. + /// Absent for every other operation. #[serde(skip_serializing_if = "Option::is_none")] pub provider_period_type: Option, } diff --git a/core/src/calculate/reader.rs b/core/src/calculate/reader.rs index b47e5fed..9c8be5d5 100644 --- a/core/src/calculate/reader.rs +++ b/core/src/calculate/reader.rs @@ -18,14 +18,18 @@ use crate::model::ProviderReportingPeriodType; /// The table a session request reads. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SessionType { + /// Sleep sessions. Sleep, + /// Workout sessions. Workout, } /// The table a measurement request reads. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MeasurementType { + /// Point measurements. Point, + /// Measurement samples. Sample, } @@ -34,31 +38,56 @@ pub enum MeasurementType { pub enum RelatedRequest<'a> { /// Current point measurements of one source and quantity, ordered by /// `recorded_at` (records without one first) and then record ID. - PointsOfQuantity { source_id: &'a str, quantity: &'a str }, + PointsOfQuantity { + /// The source's record ID. + source_id: &'a str, + /// The measurement quantity, such as `hrv_rmssd`. + quantity: &'a str, + }, /// Current sessions of one source, ordered by creation time and then /// record ID. - SessionsOfSource { session_type: SessionType, source_id: &'a str }, + SessionsOfSource { + /// Sleep or workout sessions. + session_type: SessionType, + /// The source's record ID. + source_id: &'a str, + }, /// Current point measurements or samples of one source and quantity /// recorded from `from` to `to`, both included, ordered by `recorded_at` /// and then record ID. MeasurementsInWindow { + /// Point measurements or measurement samples. measurement_type: MeasurementType, + /// The source's record ID. source_id: &'a str, + /// The measurement quantity, such as `hrv_rmssd`. quantity: &'a str, + /// The earliest `recorded_at`, a UTC instant such as `2026-01-02T03:04:05.678Z`. from: &'a str, + /// The latest `recorded_at`, a UTC instant. to: &'a str, }, /// Current sleep sessions of one source that start from `from` to `to`, /// both included, ordered by start and then record ID. - SleepStartingInWindow { source_id: &'a str, from: &'a str, to: &'a str }, + SleepStartingInWindow { + /// The source's record ID. + source_id: &'a str, + /// The earliest start, a UTC instant such as `2026-01-02T03:04:05.678Z`. + from: &'a str, + /// The latest start, a UTC instant. + to: &'a str, + }, } /// Current heart-rate samples of one source recorded from `start_at` to /// `end_at`, both included, ordered by `recorded_at` and then record ID. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct HeartRateRequest<'a> { + /// The source's record ID. pub source_id: &'a str, + /// The earliest `recorded_at`, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub start_at: &'a str, + /// The latest `recorded_at`, a UTC instant. pub end_at: &'a str, } @@ -66,22 +95,31 @@ pub struct HeartRateRequest<'a> { /// not read as an instant is left out. #[derive(Debug, Clone, PartialEq)] pub struct SampleRow { + /// When the sample was recorded, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub recorded_at: String, + /// The heart rate in its standard unit, beats per minute. pub value: f64, + /// The sample's record ID. pub record_id: String, + /// The sample's current revision. pub revision: u64, } /// One accepted input row of a range calculation. #[derive(Debug, Clone, PartialEq)] pub struct RangeInput { + /// The input's record ID. pub record_id: String, + /// The input's current revision. pub revision: u64, + /// The record ID of the input's source. pub source_id: String, /// The instant. For a provider-period input the core sets it to the /// period's sort key, so a reader leaves it empty. pub recorded_at: String, + /// The value in its standard unit. pub value: f64, + /// The standard unit, such as `ms` or `bpm`. pub unit: String, /// The provider reporting period, for a provider-period input. pub period: Option, @@ -93,11 +131,19 @@ pub struct RangeInput { /// A reader returns at most `limit` rows; the caller refuses a full answer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct InputRequest<'a> { + /// Which kind of record to read. pub record_kind: RecordKind, + /// The measurement quantity, provider metric, or summary type. pub quantity: &'a str, + /// Read only this source, by its record ID. Absent reads every source. pub source_id: Option<&'a str>, + /// The earliest `recorded_at` to read, included. It is a UTC instant, or the + /// request's own `from` when the calculation needs no calendar days. Absent means no start. pub from: Option<&'a str>, + /// The latest `recorded_at` to read, included, in the same form as `from`. Absent + /// means no end. pub to: Option<&'a str>, + /// The most rows to return. pub limit: usize, } @@ -108,12 +154,19 @@ pub struct InputRequest<'a> { /// ID. A reader returns at most `limit` rows. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PeriodRequest<'a> { + /// Which kind of record to read. pub record_kind: RecordKind, + /// The measurement quantity, provider metric, or summary type. pub quantity: &'a str, + /// The provider reporting period type to read, such as `oura_sleep_day`. pub period_type: ProviderReportingPeriodType, + /// Read only this source, by its record ID. Absent reads every source. pub source_id: Option<&'a str>, + /// The earliest period date or start, included. Absent means no start. pub from: Option<&'a str>, + /// The latest period date or start, included. Absent means no end. pub to: Option<&'a str>, + /// The most rows to return. pub limit: usize, } @@ -126,19 +179,24 @@ pub trait CalculationReader { /// A current record that is not deleted, or `None`. fn current_record(&self, record_id: &str) -> Result, Self::Error>; + /// Other current records a one-record method compares with its target, in the order + /// the request names. fn related_records(&self, request: &RelatedRequest<'_>) -> Result, Self::Error>; + /// Current heart-rate samples of one source inside a time span, as the request names. fn heart_rate_samples(&self, request: &HeartRateRequest<'_>) -> Result, Self::Error>; - /// The time zone and sex of the first current athlete profile, ordered by - /// creation time and then record ID. Empty without a profile. + /// The time zone, sex, and birth year of the first current athlete profile, ordered + /// by creation time and then record ID. Empty without a profile. fn athlete_profile(&self) -> Result; /// The default time zone of a current athlete profile, for calendar days. fn saved_time_zone(&self) -> Result, Self::Error>; + /// The instant inputs of a range calculation, as the request names. fn range_inputs(&self, request: &InputRequest<'_>) -> Result, Self::Error>; + /// The provider-period inputs of a range calculation, as the request names. fn period_inputs(&self, request: &PeriodRequest<'_>) -> Result, Self::Error>; /// What a 3.0.0 workout operation reads besides its record (D302): the diff --git a/core/src/calculate/record.rs b/core/src/calculate/record.rs index dc71d2ba..489bd3d7 100644 --- a/core/src/calculate/record.rs +++ b/core/src/calculate/record.rs @@ -23,9 +23,13 @@ pub const UNKNOWN_OPERATION_HINT: &str = "this skill file may need a newer ath ( /// A record's current stored data. #[derive(Debug, Clone, PartialEq)] pub struct StoredRecord { + /// The record's ID. pub record_id: String, + /// The record type, such as `workout_session` or `sleep_session`. pub record_type: String, + /// The record's current revision number. pub revision: u64, + /// The record's data fields as JSON, without its extensions. pub data: Value, /// The record's namespaced extensions (D118), when it has any. pub extensions: Option, @@ -35,9 +39,14 @@ pub struct StoredRecord { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct FieldRead { + /// The name of the field read, such as `asleep_seconds` or `value.standard_value`. A few + /// entries name the input in words instead, such as `asleep window`. pub field: String, + /// True when the calculation found the field. pub present: bool, - /// The quantity read by a quantity change. + /// The text read, for a field that chooses how the calculation runs: the quantity a change + /// compares, the report type of a session effort, or the athlete's sex for Banister's + /// training impulse. Absent for every other field. #[serde(skip_serializing_if = "Option::is_none")] pub value: Option, } @@ -47,35 +56,132 @@ pub struct FieldRead { #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(untagged)] pub enum OneRecordResult { - Zones { seconds: Vec }, - HeartRate { bpm: f64 }, - Load { load: f64 }, - Value { value: f64 }, - Efficiency { efficiency: f64 }, - Timing { start_at: String, midpoint_at: Option }, - Stages { stages: crate::json::JsonObject, total_minutes: f64 }, - Regularity { nights: u64, regularity: f64 }, - Volume { volume: f64, weight_unit: Option }, - QuantityChange { quantity: String, change: f64, compared_records: u64 }, - Change { change: f64, compared_records: u64 }, + /// Seconds in each heart-rate zone, from the older operation `time_between_cuts`. The + /// zones are split at fractions of a maximum heart rate field on the record. + Zones { + /// Seconds in each zone, lowest zone first. + seconds: Vec, + }, + /// A heart rate from the older operations `value_after_end` and `lowest_held`. + HeartRate { + /// For `value_after_end`, the drop from the last sample to the sample a set time + /// later. For `lowest_held`, the lowest heart rate held without change for a set time. + /// In beats per minute. + bpm: f64, + }, + /// A training load from the older operations `heart_rate_reserve_curve` and `multiply`. + Load { + /// The load in arbitrary units. `heart_rate_reserve_curve` gives minutes weighted + /// by heart-rate reserve. `multiply` gives the duration field divided by 60, times + /// the effort rating: minutes times the rating when the duration is in seconds. + load: f64, + }, + /// One number field as the record stores it, from the operation `field`. + Value { + /// The field's value, in the field's own unit, such as seconds for `asleep_seconds`. + value: f64, + }, + /// Time asleep divided by time in bed, from the older operation `divide`. + Efficiency { + /// Time asleep divided by time in bed, as a fraction such as `0.857`. This older + /// operation does not check that time asleep is no more than time in bed. + efficiency: f64, + }, + /// A session's start and midpoint, from the older operation `midpoint`. + Timing { + /// The session start, as the record stores it. + start_at: String, + /// The UTC instant halfway between start and end, such as `2026-01-02T03:04:05.678Z`. + /// Absent when the start or end could not be read as a date and time. + midpoint_at: Option, + }, + /// Sleep stage minutes and their total, from the older operation `sum_fields`. + Stages { + /// Each stage name with its minutes, as the record stores them. + stages: crate::json::JsonObject, + /// The sum of every stage's minutes, including any awake stage. + total_minutes: f64, + }, + /// How alike the sleep times of consecutive nights are, from the older operation + /// `night_agreement`. + Regularity { + /// How many sleep sessions were compared, including this one. + nights: u64, + /// The mean share of minutes in the same state, asleep or awake, on consecutive + /// nights. From 0 to 1, to three decimal places. + regularity: f64, + }, + /// Repetitions times weight over every set, from the older operation `reps_times_weight`. + Volume { + /// Repetitions times weight over every set, each weight as written. This older + /// operation adds pounds and kilograms together. + volume: f64, + /// The weight unit of the first set, such as `kg` or `lb`. + weight_unit: Option, + }, + /// A point measurement against the mean of the other readings of its quantity, from the + /// older operation `subtract_earlier_mean`. + QuantityChange { + /// The quantity compared, such as `hrv_rmssd`. + quantity: String, + /// This reading's standard value minus the mean of the other readings from the same + /// source, to three decimal places. The mean includes later readings. + change: f64, + /// How many other readings made the mean. + compared_records: u64, + }, + /// A sleep session field against the mean of the same source's other sleep sessions, from + /// the older operation `subtract_earlier_mean`. + Change { + /// This session's value minus the mean of the other sessions' values, in the field's + /// unit. The mean includes later sessions. + change: f64, + /// How many other sessions made the mean. + compared_records: u64, + }, + /// The result of `earlier_window_change`: one day's reading, or one main sleep, against + /// earlier ones. WindowChange(methods::WindowChangeResult), + /// The result of `drop_after_effort_end`: how far heart rate fell after the end of effort. Recovery(methods::RecoveryResult), + /// The result of `sleep_regularity_index`: how alike sleep times are on consecutive days. SleepRegularity(methods::RegularityResult), + /// The result of `volume_load`: strength volume in kilograms. VolumeLoad(methods::VolumeResult), + /// The result of `session_effort_load`: a session-effort rating times its minutes. EffortLoad(methods::EffortLoadResult), + /// The result of `banister_trimp`: Banister's training impulse from fields on the workout. Trimp(methods::TrimpResult), + /// The result of `time_in_zones`: seconds in each heart-rate zone, from fields on the + /// workout. TimeInZones(methods::ZonesResult), + /// The result of `lowest_rolling_mean`: the lowest mean heart rate over a window. Resting(methods::RestingResult), + /// The result of `sleep_efficiency`: the share of time in bed spent asleep. SleepEfficiency(methods::EfficiencyResult), + /// The result of `sleep_stage_split`: sleep stage minutes with awake time kept apart. StageSplit(methods::StageSplitResult), + /// The result of `sleep_clock_times`: a sleep session's start, midpoint, and end. ClockTimes(methods::ClockTimesResult), + /// The result of `hyrox_splits`: one HYROX result divided into its parts. HyroxSplits(super::hyrox::HyroxSplitsResult), + /// The result of `best_mean_efforts`: the best mean power and speed over each duration. BestEfforts(super::workout_ops::BestEffortsResult), + /// The result of `time_in_power_zones`: seconds in each zone of threshold power. PowerZones(super::workout_ops::PowerZonesResult), + /// The result of `time_in_zones_from_maximum_reference`: seconds in each heart-rate zone + /// of the maximum heart rate in effect. ReferenceZones(super::workout_ops::ReferenceZonesResult), + /// The result of `banister_trimp_from_references`: Banister's training impulse from the + /// maximum heart rate in effect and a measured resting heart rate. ReferenceTrimp(super::workout_ops::ReferenceTrimpResult), + /// The result of `work_capacity_balance_exponential`: the work capacity above threshold + /// left over the workout. Balance(super::workout_ops::BalanceResult), + /// The result of `planned_blocks_against_laps`: a planned session against the laps of the + /// workout that carried it out. Plan(super::workout_ops::PlanAgainstResult), + /// The result of a threshold method or a maximum heart-rate estimate. Threshold(super::window::ThresholdOutcome), } @@ -83,15 +189,21 @@ pub enum OneRecordResult { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ApplyResult { + /// The calculation's name, from the `name:` line of its file, such as `hrv-change`. pub calculation: String, /// The operation the file named (`use:`), which carries the method (D230). pub operation: String, /// The record it ran on; none for a method that reads a window of records. #[serde(skip_serializing_if = "Option::is_none")] pub record_id: Option, + /// Each field the calculation looked for on the record, in the order it looked. pub fields_read: Vec, + /// Each input the calculation needed and did not find: a field name, or a sentence that + /// says what was missing. pub missing: Vec, - /// Null when an input is missing. + /// The answer. Absent when the calculation could not produce one, usually because + /// an input is missing. `missing` names every input the record lacked, even when an + /// answer is given. pub result: Option, /// The other records the method read, when it read any. #[serde(skip_serializing_if = "Option::is_none")] @@ -113,6 +225,7 @@ pub struct ApplyResult { pub struct MethodInputs { /// Other current records of the same source, as each method defines them. pub related: Vec, + /// The athlete profile fields some methods read. pub profile: Profile, /// The workout an athlete report links to. pub linked_workout: Option, @@ -127,12 +240,21 @@ pub struct MethodInputs { /// listed in the result's inputs. #[derive(Debug, Clone, Default)] pub struct RecordedInputs { + /// The workout's power recordings. pub power: Vec, + /// The workout's speed recordings. pub speed: Vec, + /// The workout's heart-rate recordings. pub heart_rate: Vec, + /// The maximum heart rate in effect on the workout's day, when the operation reads it. pub maximum: Option, + /// The threshold power in effect on the workout's day, when the operation reads it. pub threshold: Option, + /// The work capacity above threshold in effect on the workout's day, when the operation + /// reads it. pub capacity: Option, + /// The latest measured resting heart rate on or before the workout's day, when the + /// operation reads it. pub resting: Option, /// Why a reference or reading could not be found, in plain words. Any /// problem means no result. diff --git a/core/src/calculate/recorded.rs b/core/src/calculate/recorded.rs index cc0b683e..b6872b49 100644 --- a/core/src/calculate/recorded.rs +++ b/core/src/calculate/recorded.rs @@ -27,9 +27,13 @@ pub const DEFAULT_MAX_GAP_S: u64 = 5; /// One recording read for a calculation. #[derive(Debug, Clone)] pub struct ReadRecording { + /// The recording's record ID and revision. pub reference: EvidenceReference, + /// The recording's stored data. pub data: DeviceRecordingData, + /// The recording's `start_at`, in milliseconds since 1970-01-01 UTC. pub start_ms: i64, + /// The recording's readings. Each reading's time is an offset from the start. pub readings: Vec, } @@ -86,7 +90,9 @@ impl ReadRecording { /// The value held in each second of a recording. #[derive(Debug, Clone, PartialEq)] pub struct Grid { + /// The recording's start, in milliseconds since 1970-01-01 UTC. Second 0 begins here. pub start_ms: i64, + /// The value held in each second from the start. Empty for a second no reading holds. pub values: Vec>, } @@ -94,13 +100,18 @@ pub struct Grid { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct Effort { + /// The effort's length, in seconds. pub duration_s: u64, + /// The mean value over the effort, in the recording's unit, such as `W` or `m/s`. pub mean: f64, + /// When the effort began, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub start_at: String, + /// When the effort ended, `duration_s` seconds after `start_at`, a UTC instant. pub end_at: String, } impl Grid { + /// The number of seconds a reading holds. pub fn covered_seconds(&self) -> usize { self.values.iter().filter(|value| value.is_some()).count() } @@ -150,8 +161,11 @@ impl Grid { /// A workout read for a calculation over a window. #[derive(Debug, Clone)] pub struct WindowWorkout { + /// The workout's record ID and revision. pub reference: EvidenceReference, + /// The workout's start, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub start_at: String, + /// The workout's recordings of the quantity the method reads. pub recordings: Vec, } @@ -160,11 +174,16 @@ pub struct WindowWorkout { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct WindowEffort { + /// The effort's duration, mean, start, and end. #[serde(flatten)] pub effort: Effort, + /// The record ID of the recording the effort came from. pub recording_id: String, + /// The revision of that recording. pub recording_revision: u64, + /// The record ID of the workout the recording belongs to. pub workout_id: String, + /// The record ID of the source that made the recording. pub source_id: String, } diff --git a/core/src/calculate/window.rs b/core/src/calculate/window.rs index 6cb9f783..198dab29 100644 --- a/core/src/calculate/window.rs +++ b/core/src/calculate/window.rs @@ -20,19 +20,34 @@ use crate::thresholds::{self as t, EffortLabels}; #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceToSave { + /// The intensity reference quantity, such as `threshold_power` or `maximum_heart_rate`. pub quantity: String, + /// The value, in `unit`. pub value: f64, + /// The unit the quantity fixes: `W`, `bpm`, `m/s`, `kJ`, or `m`. pub unit: String, + /// The sport the value is for, such as `cycling`. Absent for a maximum heart rate + /// that no sport limits. #[serde(skip_serializing_if = "Option::is_none")] pub sport: Option, + /// The machine the value is for, such as `none` or `stationary_bike`. Absent for a + /// maximum heart rate. #[serde(skip_serializing_if = "Option::is_none")] pub machine: Option, + /// The calendar day the value takes effect, `YYYY-MM-DD`: the `end_date` parameter, + /// or the day of the test workout. pub effective_date: String, + /// How the value was found: `test`, `model`, or `recorded`. pub basis: String, + /// The operation that found the value, such as `critical_power_hyperbolic`. pub method: String, - /// The records a saved reference cites; a `model` value cites the saved - /// calculation result instead. + /// The records the saved reference cites: the test workout for a `test` value, the + /// workout and recording of a peak power, the recordings of the best efforts for the + /// two fraction rules, and the workout for a held heart rate. Empty for the fitted + /// methods and the age formula, whose value cites the saved calculation result. pub evidence: Vec, + /// A note to save with the value, such as `efforts not confirmed as maximal`. Absent + /// when there is none. #[serde(skip_serializing_if = "Option::is_none")] pub note: Option, /// Saved only when the person asks for it specifically (supplement 6). @@ -46,19 +61,35 @@ pub struct ReferenceToSave { #[serde(untagged)] #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] pub enum ThresholdResult { + /// The result of `critical_power_linear_work_time`, `critical_power_linear_inverse_time`, + /// or `critical_power_hyperbolic`. CriticalPower(t::CriticalPowerResult), + /// The result of `critical_power_three_parameter`. CriticalPowerThreeParameter(t::CriticalPowerThreeParameterResult), + /// The result of `critical_speed_linear_distance_time`, + /// `critical_speed_linear_inverse_time`, or `critical_speed_hyperbolic`. CriticalSpeed(t::CriticalSpeedResult), + /// The result of `critical_speed_three_parameter`. CriticalSpeedThreeParameter(t::CriticalSpeedThreeParameterResult), + /// The result of `fraction_of_best_20_minute_power`. FractionOf20Minute(t::FractionOf20MinuteResult), + /// The result of `fraction_of_best_8_minute_power`. FractionOf8Minute(t::FractionOf8MinuteResult), + /// The result of `three_minute_all_out_cycling_test`. ThreeMinuteCycling(t::ThreeMinuteCyclingResult), + /// The result of `three_minute_all_out_rowing_test`. ThreeMinuteRowing(t::ThreeMinuteRowingResult), + /// The result of `three_minute_all_out_running_test`. ThreeMinuteRunning(t::ThreeMinuteRunningResult), + /// The result of `critical_swim_speed_400_and_200_m`. CriticalSwimSpeed(t::CriticalSwimSpeedResult), + /// The result of `thirty_minute_running_time_trial`. ThirtyMinuteTimeTrial(t::ThirtyMinuteTimeTrialResult), + /// The result of `best_1_second_power` or `best_5_second_power`. PeakPower(t::PeakPowerResult), + /// The result of `age_formula_208_minus_0_7_age`. AgeFormula(t::AgeFormulaResult), + /// The result of `highest_heart_rate_held_5_s`. HeldHeartRate(t::HeldHeartRateResult), } @@ -150,34 +181,53 @@ impl From for ThresholdResult { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThresholdOutcome { + /// The threshold method or maximum heart-rate estimate that ran, such as + /// `critical_power_hyperbolic`. pub operation: String, + /// The parameters the method used, by name, with the defaults it filled in. pub parameters: crate::json::JsonObject, + /// The first calendar day the method read, `YYYY-MM-DD`. Absent for the age formula. #[serde(skip_serializing_if = "Option::is_none")] pub period_start: Option, + /// The last calendar day the method read, `YYYY-MM-DD`: the `end_date` parameter, or + /// the day of the test workout. #[serde(skip_serializing_if = "Option::is_none")] pub period_end: Option, /// The method's own result, with the names and units of its study. pub result: ThresholdResult, + /// The best efforts a fitted method or fraction rule used, with where each came + /// from. Empty for every other method. #[serde(skip_serializing_if = "Vec::is_empty")] pub efforts: Vec, + /// How many workouts, overlapping efforts, and sources the best efforts came from. + /// Present only for the fitted methods and fraction rules. #[serde(skip_serializing_if = "Option::is_none")] pub labels: Option, /// What a person must confirm before a value becomes the one in effect. pub confirm_before_saving: Vec, + /// The intensity references a person may save. Empty when a fit is not acceptable + /// or the method found no value. pub references_to_save: Vec, } /// What `ath apply` passed in. pub struct ThresholdRequest<'a> { + /// The threshold method or maximum heart-rate estimate to run, such as + /// `critical_power_hyperbolic`. pub operation: &'a str, + /// The test workout a field test reads. Absent for every other method. pub record: Option<&'a StoredRecord>, + /// The `name=value` parameters given with `--set`, without `operation`. pub parameters: &'a BTreeMap, + /// The longest time one reading holds its value, in seconds, from the calculation file. pub max_gap_s: u64, } /// The outcome, or the plain reason the method refused, and every record read. pub struct ThresholdRun { + /// What the method found, or the plain reason it refused. pub outcome: std::result::Result, + /// Every record and revision the method read. pub evidence: Vec, } @@ -190,7 +240,7 @@ const TESTS: [&str; 5] = [ t::THIRTY_MINUTE_RUNNING_TIME_TRIAL, ]; -/// Every operation a threshold skill may name. +/// True when `operation` is one a threshold skill may name. pub fn is_threshold_operation(operation: &str) -> bool { t::THRESHOLD_OPERATIONS.contains(&operation) || operation == t::AGE_FORMULA_208_MINUS_0_7_AGE diff --git a/core/src/calculate/workout_ops.rs b/core/src/calculate/workout_ops.rs index d9d8de9c..433e7edd 100644 --- a/core/src/calculate/workout_ops.rs +++ b/core/src/calculate/workout_ops.rs @@ -34,12 +34,19 @@ pub const DEFAULT_EFFORT_DURATIONS_S: [u64; 5] = [5, 60, 300, 1200, 3600]; #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceUsed { + /// The ID of the intensity reference record. pub record_id: String, + /// The revision of that record that was used. pub revision: u64, + /// The reference value, in `unit`. pub value: f64, + /// The unit of `value`, such as `W`, `bpm`, `m/s`, or `kJ`. pub unit: String, + /// How the value was found, such as from a test or set by a person. pub basis: IntensityBasis, + /// The name of the test or model the value came from, from an open list. pub method: String, + /// The day the value takes effect, `YYYY-MM-DD`. pub effective_date: String, /// The sport it applies to; none means every sport. #[serde(skip_serializing_if = "Option::is_none")] @@ -47,6 +54,7 @@ pub struct ReferenceUsed { } impl ReferenceUsed { + /// The reference as a result names it, from its record and revision and its data. pub fn new(reference: EvidenceReference, data: &IntensityReferenceData) -> ReferenceUsed { ReferenceUsed { record_id: reference.record_id, @@ -67,19 +75,31 @@ impl ReferenceUsed { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortFound { + /// `power` or `speed`. pub quantity: String, + /// The effort's length, in seconds. pub duration_s: u64, + /// The mean over the effort, in `unit`, to four decimal places. pub mean: f64, + /// `W` for power, or `m/s` for speed. pub unit: String, + /// When the effort started, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub start_at: String, + /// When the effort ended, a UTC instant. pub end_at: String, + /// The ID of the device recording the effort came from. pub recording_id: String, } +/// The result of `best_mean_efforts`: the highest mean power and speed the workout's +/// recordings held over each duration. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BestEffortsResult { + /// The longest time, in seconds, one reading holds its value. A second no reading holds + /// is uncovered, and an effort with an uncovered second does not count. pub max_gap_s: u64, + /// One best effort for each quantity and duration found. pub efforts: Vec, /// Durations with no fully held effort, such as `power 3600 s`. pub not_found: Vec, @@ -129,13 +149,23 @@ pub fn best_mean_efforts( // ---- time_in_power_zones ---------------------------------------------------------------------- +/// The result of `time_in_power_zones`: seconds in each zone of the threshold power in effect +/// on the workout's day. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PowerZonesResult { + /// Seconds in each power zone, lowest zone first. There is one more zone than there are + /// boundaries; seven by default. pub seconds: Vec, + /// Seconds no reading holds, which are in no zone. pub uncovered_seconds: f64, + /// The zone boundaries in watts, lowest first, to one decimal place. A value on a boundary + /// is in the zone above it. pub boundaries_w: Vec, + /// The threshold power reference used. pub threshold: ReferenceUsed, + /// The longest time, in seconds, one reading holds its value before a second is + /// uncovered. pub max_gap_s: u64, } @@ -191,13 +221,23 @@ fn workout_span_ms(workout: &Value) -> Option { Some(at("end_at")? - at("start_at")?) } +/// The result of `time_in_zones_from_maximum_reference`: seconds in each heart-rate zone, +/// split at fractions of the maximum heart rate in effect on the workout's day. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceZonesResult { + /// Seconds in each zone, lowest zone first, to three decimal places. pub seconds: Vec, + /// Seconds with no reading close enough, which are in no zone, to three decimal places. + /// This includes any time before the first reading. pub uncovered_seconds: f64, + /// The zone boundaries in beats per minute, lowest first, to one decimal place. A heart + /// rate on a boundary is in the zone above it. pub boundaries_bpm: Vec, + /// The maximum heart rate reference used. pub maximum: ReferenceUsed, + /// Where the heart rate came from: `heart_rate recording` or + /// `workout heart_rate_samples`. pub heart_rate_from: String, } @@ -235,23 +275,39 @@ pub fn time_in_zones_from_reference( #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RestingUsed { + /// The ID of the resting heart rate measurement. pub record_id: String, + /// The revision of that record that was used. pub revision: u64, + /// The resting heart rate, in beats per minute. pub bpm: f64, + /// When it was measured, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub recorded_at: String, } +/// The result of `banister_trimp_from_references`: Banister's training impulse (TRIMP) from +/// the maximum heart rate in effect and the latest measured resting heart rate. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReferenceTrimpResult { + /// The training impulse, in arbitrary units, to one decimal place. pub load: f64, + /// The weighting used, `male` or `female`, chosen by the athlete profile's `sex`. pub weighting: String, + /// The weighting's coefficient. By default 0.64 for `male` and 0.86 for `female`. pub coefficient: f64, + /// The weighting's exponent. By default 1.92 for `male` and 1.67 for `female`. pub exponent: f64, + /// Minutes the heart-rate readings cover, to one decimal place. pub covered_minutes: f64, + /// Minutes with no reading close enough, which add no load, to one decimal place. pub uncovered_minutes: f64, + /// The maximum heart rate reference used. pub maximum: ReferenceUsed, + /// The resting heart rate measurement used. pub resting: RestingUsed, + /// Where the heart rate came from: `heart_rate recording` or + /// `workout heart_rate_samples`. pub heart_rate_from: String, } @@ -300,18 +356,35 @@ pub fn banister_trimp( // ---- work_capacity_balance_exponential -------------------------------------------------------- +/// The result of `work_capacity_balance_exponential`: how much of the work capacity above +/// threshold power was left, second by second, in the exponential model (Skiba et al., 2012). #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BalanceResult { + /// The threshold power reference used. pub threshold: ReferenceUsed, + /// The work capacity above threshold reference used. pub capacity: ReferenceUsed, + /// The lowest balance, in kilojoules, to four decimal places. pub minimum_balance_kj: f64, + /// When the lowest balance came, a UTC instant such as `2026-01-02T03:04:05.678Z`. The + /// recording's start when the balance never fell. pub minimum_at: String, + /// The balance at the end of the recording, in kilojoules, to four decimal places. pub final_balance_kj: f64, + /// Seconds with a balance below zero, when more than the capacity in effect was spent. + /// This means the threshold or the capacity in effect is too low for the athlete. pub seconds_below_zero: u64, + /// How fast spent work recovers, in seconds: `546 × e^(−0.01 × shortfall) + 316`, to four + /// decimal places. pub time_constant_s: f64, + /// The mean of threshold power minus power over the seconds below threshold, in watts, to + /// four decimal places. Zero when no second was below threshold. pub mean_shortfall_below_threshold_w: f64, + /// Seconds no reading holds. They spend nothing, and recovery goes on through them. pub uncovered_seconds: u64, + /// The longest time, in seconds, one reading holds its value before a second is + /// uncovered. pub max_gap_s: u64, } @@ -373,9 +446,14 @@ pub fn work_capacity_balance( #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct TargetCompared { + /// The target's quantity, such as `power`, `heart_rate`, `speed`, or `cadence`. pub quantity: String, + /// The lowest value within the target, in `unit`. pub low: f64, + /// The highest value within the target, in `unit`. pub high: f64, + /// The unit of `low` and `high`. A percent target is turned into the reference's unit; + /// one with no reference in effect keeps `%`. pub unit: String, /// The lap's measured value, when the lap has one. pub actual: Option, @@ -386,26 +464,46 @@ pub struct TargetCompared { pub from_reference: Option, } +/// One planned step compared with the lap in the same place. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BlockCompared { + /// The planned block's title. Empty when the block has none. pub block: String, + /// The lap's label. Absent when no lap is in that place, or the lap has no label. pub lap: Option, + /// The block's planned duration, in seconds. Absent when the plan gives none. pub planned_duration_s: Option, + /// The lap's duration, in seconds, to three decimal places. Absent when no lap is in that + /// place, or the lap has no start or end offset. pub actual_duration_s: Option, + /// The block's planned distance, in metres. Absent when the plan gives none. pub planned_distance_m: Option, + /// The lap's distance, in metres, from its `distance` summary. Absent when the lap has + /// none. pub actual_distance_m: Option, + /// Each of the block's targets compared with the lap. pub targets: Vec, } +/// The result of `planned_blocks_against_laps`: each planned step of a planned session +/// against the lap in the same place in the workout that carried it out. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PlanAgainstResult { + /// The ID of the completed workout compared. pub workout_id: String, + /// One entry per planned step, in the order the steps are done. A rounds group repeats + /// its blocks once per round. pub blocks: Vec, + /// How many laps come after the last planned step. pub laps_without_block: u64, + /// How many targets the lap's value was within. pub targets_met: u64, + /// How many targets the lap's value was outside. pub targets_missed: u64, + /// How many targets had no lap value to compare, or were percent targets with no + /// reference to work them out from. pub targets_not_measured: u64, } diff --git a/core/src/calendar.rs b/core/src/calendar.rs index c25573d4..04c1c246 100644 --- a/core/src/calendar.rs +++ b/core/src/calendar.rs @@ -27,7 +27,9 @@ pub fn parse_utc_timestamp(text: &str) -> Result { /// accepts. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Zone { + /// A named IANA timezone, such as `America/Chicago`. Named(Tz), + /// A fixed UTC offset, such as `+05:30`. Fixed(FixedOffset), } @@ -144,8 +146,14 @@ pub fn calendar_date_in_zone(timestamp: &str, zone_name: &str) -> Result /// A requested time window: calendar days or exact UTC instants. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct CalendarRangeRequest { + /// The first calendar day, `YYYY-MM-DD`, or the first UTC instant, such as + /// `2026-01-02T03:04:05.678Z`. Absent for no lower bound. pub from: Option, + /// The last calendar day, `YYYY-MM-DD`, or the last UTC instant. A day includes its + /// whole length. Absent for no upper bound. pub to: Option, + /// The timezone for calendar days: an IANA name such as `America/Chicago`, or a fixed + /// UTC offset. Absent to use the athlete profile's default timezone. pub time_zone: Option, /// Raw sample reads need a timezone only for calendar-day bounds. pub raw: bool, @@ -154,10 +162,14 @@ pub struct CalendarRangeRequest { /// A resolved window in exact UTC instants, with the timezone used. #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)] pub struct InstantRange { + /// The first instant in the window, in the stored UTC form. Absent for no lower bound. #[serde(skip_serializing_if = "Option::is_none")] pub from: Option, + /// The last instant in the window, in the stored UTC form. Absent for no upper bound. #[serde(skip_serializing_if = "Option::is_none")] pub to: Option, + /// The timezone used for calendar days. Absent when the request gave none and none + /// was needed. #[serde(skip_serializing_if = "Option::is_none")] pub time_zone: Option, } @@ -211,6 +223,7 @@ pub fn resolve_calendar_range_with>( /// The cut-off for a historical read. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct AsOfTime { + /// The cut-off instant, in the stored UTC form such as `2026-01-02T03:04:05.678Z`. pub as_of: String, /// The timezone used when the request named a calendar day. #[serde(skip_serializing_if = "Option::is_none")] diff --git a/core/src/error.rs b/core/src/error.rs index 535fcfa2..cc477a09 100644 --- a/core/src/error.rs +++ b/core/src/error.rs @@ -6,6 +6,7 @@ use crate::model::ValidationError; +/// An error from a check or a calculation. #[derive(Debug, Clone, PartialEq)] pub enum Error { /// Input does not match the record format. @@ -18,17 +19,21 @@ pub enum Error { Other(String), } +/// A result whose error is the core's [`Error`] unless another is named. pub type Result = std::result::Result; impl Error { + /// An [`Error::Other`] with this message. pub fn other(message: impl Into) -> Self { Error::Other(message.into()) } + /// An [`Error::Refused`] with this message. pub fn refused(message: impl Into) -> Self { Error::Refused(message.into()) } + /// An [`Error::NotFound`] with this message. pub fn not_found(message: impl Into) -> Self { Error::NotFound(message.into()) } diff --git a/core/src/json.rs b/core/src/json.rs index 372fd8e4..a4d1fda4 100644 --- a/core/src/json.rs +++ b/core/src/json.rs @@ -33,6 +33,7 @@ pub struct JsonObject(pub Map); pub struct JsonValue(pub Value); impl JsonObject { + /// An empty object. pub fn new() -> Self { JsonObject(Map::new()) } @@ -113,6 +114,7 @@ impl From for Value { /// A JSON text could not be read. #[derive(Debug, Clone, PartialEq, Eq)] pub struct JsonError { + /// What was wrong with the text. pub message: String, } diff --git a/core/src/lib.rs b/core/src/lib.rs index 88b85a46..80ec8385 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -16,6 +16,10 @@ //! - `save`: the typed rows and child rows a record's current state is //! stored as, and the statements that store them. +// Every public item needs a description: UniFFI copies it into the Swift and +// Kotlin that Xcode and Android Studio show, and the desktop reads it too. +#![deny(missing_docs)] + pub mod assets; pub mod calculate; pub mod calendar; diff --git a/core/src/model/common.rs b/core/src/model/common.rs index 81d02f97..01ba78c7 100644 --- a/core/src/model/common.rs +++ b/core/src/model/common.rs @@ -12,11 +12,19 @@ use crate::{model_enum, model_object}; // ---- Checked strings ---------------------------------------------------- +/// The published pattern for a record ID: a lowercase UUID version 7. pub const RECORD_ID_PATTERN: &str = "^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"; +/// The published pattern for a lowercase UUID of any version, in the 8-4-4-4-12 form. pub const LOWERCASE_UUID_PATTERN: &str = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"; +/// The published pattern for a semantic version such as `1.2.3`. pub const SEMVER_PATTERN: &str = r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$"; +/// The published pattern for a SHA-256 hash: 64 lowercase hexadecimal digits. pub const SHA256_PATTERN: &str = "^[a-f0-9]{64}$"; +/// The published pattern for a benchmark key: lowercase letters, digits, hyphens, and +/// underscores, starting with a letter or digit. pub const BENCHMARK_KEY_PATTERN: &str = "^[a-z0-9][a-z0-9_-]*$"; +/// The published pattern for a path inside a package: not empty, not starting with `/`, +/// with no backslash and no `..` folder. pub const PACKAGE_RELATIVE_PATH_PATTERN: &str = r"^(?!\/)(?!.*\\)(?!.*(?:^|\/)\.\.(?:\/|$)).+$"; /// A lowercase RFC 9562 version 7 UUID. @@ -49,6 +57,8 @@ pub fn is_lowercase_uuid(text: &str) -> bool { }) } +/// Whether `text` is a semantic version such as `1.2.3`, with an optional `-` pre-release +/// part and an optional `+` build part. pub fn is_semver(text: &str) -> bool { let (core, rest) = match text.find(['-', '+']) { Some(index) => (&text[..index], &text[index..]), @@ -75,10 +85,13 @@ pub fn is_semver(text: &str) -> bool { } } +/// Whether `text` is a SHA-256 hash: 64 lowercase hexadecimal digits. pub fn is_sha256(text: &str) -> bool { text.len() == 64 && text.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) } +/// Whether `text` is a benchmark key: lowercase letters, digits, hyphens, and underscores, +/// starting with a letter or digit. pub fn is_benchmark_key(text: &str) -> bool { let bytes = text.as_bytes(); !bytes.is_empty() @@ -150,18 +163,24 @@ schema_fn!( .describe("Stable UUIDv7 record ID") ); schema_fn!( + /// The shape of a database ID: a lowercase UUID version 7 that never changes. database_id, string() .check(Check::Pattern { source: RECORD_ID_PATTERN, test: is_record_id, message: "lowercase UUIDv7" }) .describe("Stable UUIDv7 database ID") ); schema_fn!( + /// The shape of a UTC instant with milliseconds, such as `2026-01-02T03:04:05.678Z`. utc_timestamp, string() .check(Check::Format(StringFormat::DateTimeMillisUtc)) .describe("Normalized ISO 8601 timestamp in UTC with millisecond precision") ); -schema_fn!(calendar_date, string().check(Check::Format(StringFormat::Date)).describe("ISO 8601 calendar date")); +schema_fn!( + /// The shape of a calendar day, `YYYY-MM-DD`. + calendar_date, + string().check(Check::Format(StringFormat::Date)).describe("ISO 8601 calendar date") +); schema_fn!( /// A namespaced extension ID such as `org.example/widget`. extension_id, @@ -183,14 +202,18 @@ schema_fn!( }) ); schema_fn!( + /// The shape of a semantic version such as `1.2.3`. semver, string().check(Check::Pattern { source: SEMVER_PATTERN, test: is_semver, message: "semantic version" }) ); schema_fn!( + /// The shape of a SHA-256 hash: 64 lowercase hexadecimal digits. sha256, string().check(Check::Pattern { source: SHA256_PATTERN, test: is_sha256, message: "lowercase SHA-256 hex digest" }) ); schema_fn!( + /// The shape of a benchmark key: lowercase letters, digits, hyphens, and underscores, + /// starting with a letter or digit. benchmark_key, string().check(Check::Pattern { source: BENCHMARK_KEY_PATTERN, @@ -199,6 +222,8 @@ schema_fn!( }) ); schema_fn!( + /// The shape of a path inside a package: not empty, not starting with `/`, with no + /// backslash and no `..` folder. package_relative_path, string().check(Check::MinLength(1)).check(Check::Pattern { source: PACKAGE_RELATIVE_PATH_PATTERN, @@ -207,17 +232,39 @@ schema_fn!( }) ); schema_fn!( + /// The shape of a timezone for calendar calculations: an IANA name such as + /// `America/Chicago`, in any letter case, or a fixed UTC offset such as `+05:30`. iana_time_zone, string() .check(Check::MinLength(1)) .check(Check::StringRefine { test: is_iana_time_zone, message: "IANA timezone" }) .describe_first("IANA timezone for calendar calculations") ); -schema_fn!(revision_number, positive_int_schema()); -schema_fn!(previous_revision, Schema::new(Kind::Nullable(positive_int()))); -schema_fn!(sleep_stage_minutes, Schema::new(Kind::Record { key: text(), value: nonnegative() })); -schema_fn!(text_array, Schema::new(Kind::Array(text()))); -schema_fn!(record_id_array, Schema::new(Kind::Array(record_id()))); +schema_fn!( + /// The shape of a record revision number: a whole number from 1 up. + revision_number, + positive_int_schema() +); +schema_fn!( + /// The shape of `previous_revision`: `null`, or a whole number from 1 up. + previous_revision, + Schema::new(Kind::Nullable(positive_int())) +); +schema_fn!( + /// The shape of sleep stage minutes: an object from stage name to minutes, each 0 or more. + sleep_stage_minutes, + Schema::new(Kind::Record { key: text(), value: nonnegative() }) +); +schema_fn!( + /// The shape of a list of nonempty strings. + text_array, + Schema::new(Kind::Array(text())) +); +schema_fn!( + /// The shape of a list of record IDs. + record_id_array, + Schema::new(Kind::Array(record_id())) +); fn positive_int_schema() -> Schema { super::schema::integer().check(super::schema::above(0.0)) @@ -232,98 +279,218 @@ pub type StageMinutes = crate::json::JsonObject; // ---- Enums -------------------------------------------------------------- model_enum! { + /// The kind of a record. It selects the shape of the record's `data`. pub enum RecordType { + /// The athlete's profile: name, birth year, units, timezone, and preferences. + /// Stored as `athlete_profile`. AthleteProfile = "athlete_profile", + /// Where measured records came from: who wrote the data and by which route. + /// Stored as `source`. Source = "source", + /// A device behind a source's data, with its name, maker, and model. + /// Stored as `source_device`. SourceDevice = "source_device", + /// One measured value, such as resting heart rate or body weight. + /// Stored as `point_measurement`. PointMeasurement = "point_measurement", + /// One sample in a dense series, such as one heart-rate reading. + /// Stored as `measurement_sample`. MeasurementSample = "measurement_sample", + /// One sleep, with its start, end, and the totals the source reported. + /// Stored as `sleep_session`. SleepSession = "sleep_session", + /// One workout, with its start, end, and the totals the source reported. + /// Stored as `workout_session`. WorkoutSession = "workout_session", + /// The measured score of one attempt at a benchmark. + /// Stored as `benchmark_result`. BenchmarkResult = "benchmark_result", + /// A total or duration a source reported, such as Apple active energy. + /// Stored as `provider_summary`. ProviderSummary = "provider_summary", + /// A composite score from a provider, such as recovery, strain, or readiness. + /// Stored as `provider_score`. ProviderScore = "provider_score", + /// What the athlete said, such as sleep quality, soreness, effort, or an injury. + /// Stored as `athlete_report`. AthleteReport = "athlete_report", + /// What the athlete said they ate or drank, in their own words. + /// Stored as `nutrition_entry`. NutritionEntry = "nutrition_entry", + /// A file the athlete attached, such as a photo. The bytes are kept outside the data. + /// Stored as `attachment`. Attachment = "attachment", + /// A named test, and how its score is measured. + /// Stored as `benchmark_definition`. BenchmarkDefinition = "benchmark_definition", + /// A predicted score for a benchmark, with a confidence and the reasoning. + /// Stored as `prediction`. Prediction = "prediction", + /// Links an exact prediction revision to an exact benchmark result revision. + /// Stored as `prediction_result_link`. PredictionResultLink = "prediction_result_link", + /// A tool's grade of a prediction against its result. + /// Stored as `prediction_grade`. PredictionGrade = "prediction_grade", + /// Why a graded prediction missed, with evidence for each cause. + /// Stored as `prediction_error_analysis`. PredictionErrorAnalysis = "prediction_error_analysis", + /// A training plan with a title, an objective, and dates. + /// Stored as `training_plan`. TrainingPlan = "training_plan", + /// One planned training session, with its date and blocks. + /// Stored as `planned_session`. PlannedSession = "planned_session", + /// A coaching note, which may apply over a range of dates. + /// Stored as `coaching_note`. CoachingNote = "coaching_note", + /// A review of training over a range of dates, with a summary. + /// Stored as `saved_training_review`. SavedTrainingReview = "saved_training_review", + /// A goal, with an optional target date, target score, or event. + /// Stored as `goal`. Goal = "goal", + /// An authored reading of a nutrition entry as foods and nutrients. + /// Stored as `nutrition_model_interpretation`. NutritionModelInterpretation = "nutrition_model_interpretation", + /// One dated value that training intensity is set against, such as a threshold. + /// Stored as `intensity_reference`. IntensityReference = "intensity_reference", + /// A race or competition. + /// Stored as `event`. Event = "event", + /// The exact record versions a coach or the athlete approved. + /// Stored as `approval`. Approval = "approval", + /// One saved calculation result, with the record revisions it read. + /// Stored as `calculation_result`. CalculationResult = "calculation_result", + /// One device's recording of one quantity, such as a power meter's power. + /// Stored as `device_recording`. DeviceRecording = "device_recording", } } model_enum! { + /// Where an authored record stands, from draft to cancelled. pub enum AuthoredRecordStatus { + /// Still being decided. The athlete has not accepted it. + /// Stored as `draft`. Draft = "draft", + /// Accepted and in use. + /// Stored as `active`. Active = "active", + /// Stored as `completed`. Completed = "completed", + /// A newer version replaces it. + /// Stored as `superseded`. Superseded = "superseded", + /// Stored as `cancelled`. Cancelled = "cancelled", } } model_enum! { + /// Why a value the source could have given is absent. pub enum MissingReason { + /// The source did not supply the value. + /// Stored as `not_provided_by_source`. NotProvidedBySource = "not_provided_by_source", + /// The import route used does not expose the value, although the source may have it. + /// Stored as `not_exposed_by_route`. NotExposedByRoute = "not_exposed_by_route", + /// The value does not apply to this record. + /// Stored as `not_applicable`. NotApplicable = "not_applicable", } } model_enum! { + /// How the time text a source wrote was read as an instant. pub enum InputTimestampBasis { + /// The source wrote an exact instant, such as a UTC time ending in `Z`. + /// Stored as `source_instant`. SourceInstant = "source_instant", + /// The source wrote a time with a numeric UTC offset, such as `-04:00`. + /// Stored as `source_offset_timestamp`. SourceOffsetTimestamp = "source_offset_timestamp", + /// The source wrote a local time, placed by a separate documented offset, as WHOOP does. + /// Stored as `source_local_timestamp_with_documented_offset`. SourceLocalTimestampWithDocumentedOffset = "source_local_timestamp_with_documented_offset", + /// Worked out from the series start time. The source wrote no time for the sample. + /// Stored as `reconstructed_from_series_start`. ReconstructedFromSeriesStart = "reconstructed_from_series_start", } } model_enum! { + /// What a UTC offset written by a source means. pub enum UtcOffsetMeaning { + /// The source documents it as the offset where the data was recorded. + /// Stored as `documented_recording_offset`. DocumentedRecordingOffset = "documented_recording_offset", + /// The provider's offset for a whole cycle, such as a WHOOP cycle. + /// Stored as `provider_cycle_offset`. ProviderCycleOffset = "provider_cycle_offset", + /// The offset the import route used to print the time. + /// Stored as `route_rendering_offset`. RouteRenderingOffset = "route_rendering_offset", + /// The source does not say what the offset means. + /// Stored as `meaning_not_documented`. MeaningNotDocumented = "meaning_not_documented", } } model_enum! { + /// What a timezone name written by a source means. pub enum SourceTimeZoneMeaning { + /// Apple Health's `HKTimeZone`: the user's timezone when the HealthKit object was created. + /// Stored as `apple_health_object_creation_time_zone`. AppleHealthObjectCreationTimeZone = "apple_health_object_creation_time_zone", } } model_enum! { + /// What time a measured record's `received_at` holds. pub enum ReceivedAtBasis { + /// A time the provider supplied. + /// Stored as `provider_supplied`. ProviderSupplied = "provider_supplied", + /// When a connector, a program that fetches data from a service, received it. + /// Stored as `connector_received_time`. ConnectorReceivedTime = "connector_received_time", + /// When the imported file was last changed. + /// Stored as `file_modified_time`. FileModifiedTime = "file_modified_time", + /// When the import ran. + /// Stored as `import_time`. ImportTime = "import_time", + /// When this program wrote the record directly, as `ath log` does. + /// Stored as `local_write_time`. LocalWriteTime = "local_write_time", } } model_enum! { + /// A kind of period a provider assigns values to. It is kept apart from calendar days. pub enum ProviderReportingPeriodType { + /// A WHOOP physiological cycle. It does not follow calendar days. + /// Stored as `whoop_physiological_cycle`. WhoopPhysiologicalCycle = "whoop_physiological_cycle", + /// An Oura activity day, from 04:00 to 04:00. + /// Stored as `oura_activity_day`. OuraActivityDay = "oura_activity_day", + /// An Oura sleep day, from 18:00 to 18:00. + /// Stored as `oura_sleep_day`. OuraSleepDay = "oura_sleep_day", + /// An Oura calendar day, midnight to midnight in the phone's timezone. + /// Stored as `oura_calendar_day`. OuraCalendarDay = "oura_calendar_day", + /// An Oura day whose kind the import route does not state. + /// Stored as `oura_day_unspecified`. OuraDayUnspecified = "oura_day_unspecified", + /// An Apple activity summary day: the day as the user saw it. + /// Stored as `apple_activity_summary_day`. AppleActivitySummaryDay = "apple_activity_summary_day", } } @@ -331,11 +498,23 @@ model_enum! { model_enum! { /// Bases for a stored value (D185, D187, D192). pub enum ValueBasis { + /// The provider, or a service that passed the data on, computed it. Which one is unknown. + /// Stored as `provider_or_aggregator`. ProviderOrAggregator = "provider_or_aggregator", + /// The writer computed or recorded the value and gives it as its own. + /// Stored as `provider`. Provider = "provider", + /// The source documents the field as the mean RMSSD. + /// Stored as `hrv_mean_rmssd`. HrvMeanRmssd = "hrv_mean_rmssd", + /// The source says heart-rate variability, and WHOOP or Oura documents it as RMSSD. + /// Stored as `provider_documented_rmssd`. ProviderDocumentedRmssd = "provider_documented_rmssd", + /// This program calculated the value from the source's own samples. + /// Stored as `calculated_on_import`. CalculatedOnImport = "calculated_on_import", + /// A person entered the value, or an agent entered it through `ath log`. + /// Stored as `entered_by_hand`. EnteredByHand = "entered_by_hand", } } @@ -343,31 +522,52 @@ model_enum! { model_enum! { /// Where a workout's activity type came from (D185, D187, D192). pub enum ActivityTypeBasis { + /// A service that passed the data on, such as Open Wearables, chose the activity word. + /// Stored as `aggregator_normalized`. AggregatorNormalized = "aggregator_normalized", + /// The writer named the activity. This program may drop Apple's prefix or change the case. + /// Stored as `provider_label`. ProviderLabel = "provider_label", } } model_enum! { + /// How a workout's route summaries were made. pub enum RouteSummariesBasis { + /// Calculated on import from the workout's route file, such as elevation gain or splits. + /// Stored as `calculated_on_import`. CalculatedOnImport = "calculated_on_import", } } model_enum! { + /// How a revision became known to the database. pub enum BecameKnownAtBasis { + /// Written directly to this database. + /// Stored as `local_write`. LocalWrite = "local_write", + /// Imported from a provider's data. + /// Stored as `provider_import`. ProviderImport = "provider_import", + /// Restored from a JSON package. + /// Stored as `package_restore`. PackageRestore = "package_restore", + /// Written to settle a conflict while a package was merged into this database. + /// Stored as `package_merge`. PackageMerge = "package_merge", } } model_enum! { + /// Why a record was erased for privacy. pub enum ErasureReasonCode { + /// Stored as `athlete_request`. AthleteRequest = "athlete_request", + /// Stored as `legal_requirement`. LegalRequirement = "legal_requirement", + /// Stored as `recorded_in_error`. RecordedInError = "recorded_in_error", + /// Stored as `other`. Other = "other", } } @@ -377,7 +577,9 @@ model_enum! { model_object! { /// A record and the exact revision used. pub struct EvidenceReference { + /// The ID of the record used, a lowercase UUID version 7. record_id: String = record_id(), + /// The exact revision of that record used, a whole number from 1 up. revision: u64 = revision_number(), } } @@ -387,26 +589,37 @@ model_object! { #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(tag = "author_type", rename_all = "snake_case")] pub enum RecordActor { + /// The athlete made the change. Athlete, + /// An agent made the change. Agent { + /// The agent's name. agent: String, + /// The agent's version, a semantic version such as `1.2.3`. Absent when not given. #[serde(default, skip_serializing_if = "Option::is_none")] agent_version: Option, }, + /// A tool made the change. Tool { + /// The tool's name, such as `ath`. tool: String, + /// The tool's version, a semantic version such as `1.0.0`. tool_version: String, }, /// A human coach (D255): the name shown when the change was made and the /// ID the host that accepted it assigned. They are history, not /// credentials. Coach { + /// The coach's name as shown when the change was made. coach: String, + /// The ID the host that accepted the change gave the coach: a lowercase UUID in + /// the 8-4-4-4-12 form. It grants no access. coach_id: String, }, } impl RecordActor { + /// The stored `author_type` text: `athlete`, `agent`, `tool`, or `coach`. pub fn author_type(&self) -> &'static str { match self { RecordActor::Athlete => "athlete", @@ -416,6 +629,7 @@ impl RecordActor { } } + /// Whether the actor is a coach. pub fn is_coach(&self) -> bool { matches!(self, RecordActor::Coach { .. }) } @@ -426,28 +640,43 @@ impl RecordActor { #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[serde(tag = "author_type", rename_all = "snake_case")] pub enum AuthoredRecordAuthor { + /// The athlete wrote it. Athlete, + /// An agent wrote it with a model. Agent { + /// The agent's name. agent: String, + /// The agent's version, a semantic version such as `1.2.3`. Absent when not given. #[serde(default, skip_serializing_if = "Option::is_none")] agent_version: Option, + /// The name of the model the agent used. model: String, + /// The model's version, as nonempty text. Absent when not given. #[serde(default, skip_serializing_if = "Option::is_none")] model_version: Option, }, + /// A tool wrote it by running a calculation. Tool { + /// The tool's name, such as `ath`. tool: String, + /// The tool's version, a semantic version such as `1.0.0`. tool_version: String, + /// The name and version of the calculation the tool ran, such as + /// `prediction-grade-v1`. calculation_version: String, }, /// A human coach (D255), with the same fields as the coach actor. Coach { + /// The coach's name as shown when the record was written. coach: String, + /// The ID the host that accepted the record gave the coach: a lowercase UUID in + /// the 8-4-4-4-12 form. It grants no access. coach_id: String, }, } impl AuthoredRecordAuthor { + /// The stored `author_type` text: `athlete`, `agent`, `tool`, or `coach`. pub fn author_type(&self) -> &'static str { match self { AuthoredRecordAuthor::Athlete => "athlete", @@ -457,6 +686,7 @@ impl AuthoredRecordAuthor { } } + /// Whether the author is a coach. pub fn is_coach(&self) -> bool { matches!(self, AuthoredRecordAuthor::Coach { .. }) } @@ -580,10 +810,15 @@ impl Shape for AuthoredRecordAuthor { model_object! { /// Who wrote an authored record, when, from what evidence, and its status. pub struct AuthoredRecordMetadata { + /// Who wrote the record: the athlete, an agent, a tool, or a coach. author: AuthoredRecordAuthor, + /// When it was written, a UTC instant such as `2026-01-02T03:04:05.678Z`. authored_at: String = utc_timestamp(), + /// The exact record revisions the author used, in order. evidence: Vec, + /// The version of the authored content, a whole number from 1 up. content_version: u64 = positive_int(), + /// Where the record stands: draft, active, completed, superseded, or cancelled. status: AuthoredRecordStatus, } } @@ -593,13 +828,26 @@ model_object! { model_object! { /// The time text a source wrote, and how it was read. pub struct InputTimestampReceipt { + /// The time exactly as the source wrote it. Absent when the source gave none; + /// `timestamp_missing_reason` then says why. timestamp_text?: String, + /// The UTC offset exactly as the source wrote it, such as `-04:00`. Absent when + /// the source gave none; `utc_offset_missing_reason` then says why. utc_offset_text?: String, + /// What the offset means. Required with `utc_offset_text`, and allowed only with it. utc_offset_meaning?: UtcOffsetMeaning, + /// The timezone name the source wrote, such as Apple Health's `HKTimeZone`. + /// Present only together with `source_time_zone_meaning`. source_time_zone?: String, + /// What the source timezone name means. Present only with `source_time_zone`. source_time_zone_meaning?: SourceTimeZoneMeaning, + /// How the time text was read as an instant. Required with `timestamp_text`. timestamp_basis?: InputTimestampBasis, + /// Why there is no time text. Required when `timestamp_text` is absent, and not + /// allowed with it. timestamp_missing_reason?: MissingReason, + /// Why there is no offset text. Required when `utc_offset_text` is absent, and not + /// allowed with it. utc_offset_missing_reason?: MissingReason, } refine(refine_input_timestamp) @@ -647,15 +895,28 @@ fn refine_input_timestamp(value: &Value, issues: &mut Vec) { model_object! { /// A period a provider assigned to a value, such as a WHOOP cycle or an Oura day. pub struct ProviderReportingPeriod { + /// The kind of period, such as a WHOOP cycle or an Oura sleep day. period_type: ProviderReportingPeriodType, + /// The provider's own ID for the period. A period needs at least one of this ID, + /// `provider_date`, or `start_at`. provider_period_id?: String, + /// The day the provider assigned, `YYYY-MM-DD`. It is the provider's day, not a + /// calendar day in a timezone. provider_date?: String = calendar_date(), + /// When the period starts, a UTC instant such as `2026-01-02T03:04:05.678Z`. start_at?: String = utc_timestamp(), + /// When the period ends, a UTC instant. It cannot be before `start_at`. Absent + /// when the provider gave no end. end_at?: String = utc_timestamp(), + /// The start time as the provider wrote it, and how it was read. input_start_timestamp?: InputTimestampReceipt, + /// The end time as the provider wrote it, and how it was read. input_end_timestamp?: InputTimestampReceipt, + /// The UTC offset text the provider gave for the period, exactly as written. timezone_offset_text?: String, + /// What the offset means. Required with `timezone_offset_text`. timezone_offset_meaning?: UtcOffsetMeaning, + /// Why there is no offset text. Not allowed with `timezone_offset_text`. timezone_offset_missing_reason?: MissingReason, } refine(refine_reporting_period) @@ -715,11 +976,19 @@ pub fn end_not_before_start(value: &Value, start: &str, end: &str) -> bool { model_object! { /// A measured value in its standard unit, with the value and unit the source wrote. pub struct SourceValue { + /// The value in the standard unit for its quantity. standard_value: f64, + /// The standard unit, such as `bpm`, `ms`, or `kg`. standard_unit: String, + /// The value exactly as the source gave it. Absent when the source gave none; + /// `input_value_missing_reason` then says why. input_value?: f64, + /// The unit the source gave. Absent when the source gave none; + /// `input_unit_missing_reason` then says why. input_unit?: String, + /// Why there is no input value. Present exactly when `input_value` is absent. input_value_missing_reason?: MissingReason, + /// Why there is no input unit. Present exactly when `input_unit` is absent. input_unit_missing_reason?: MissingReason, } refine(refine_source_value) @@ -737,12 +1006,22 @@ fn refine_source_value(value: &Value, issues: &mut Vec) { model_object! { /// A summary value a source reported, such as a total distance. pub struct SourceReportedSummary { + /// The value in the standard unit for the summary. standard_value: f64, + /// The standard unit, such as `bpm` or `m`. standard_unit: String, + /// The value exactly as the source gave it. Absent when the source gave none; + /// `input_value_missing_reason` then says why. input_value?: f64, + /// The unit the source gave. Absent when the source gave none; + /// `input_unit_missing_reason` then says why. input_unit?: String, + /// Why there is no input value. Present exactly when `input_value` is absent. input_value_missing_reason?: MissingReason, + /// Why there is no input unit. Present exactly when `input_unit` is absent. input_unit_missing_reason?: MissingReason, + /// What the summary measures, such as `average_heart_rate`, `distance`, or + /// `sleep_duration`. summary_type: String, } refine(refine_source_value) @@ -751,8 +1030,13 @@ model_object! { model_object! { /// The basis this program assigns to a stored value. It is not a supplied field (D185, D187). pub struct FieldBasis { + /// Where a workout's activity type came from. activity_type?: ActivityTypeBasis, + /// On what basis the record's value was stored. Every measured record that an + /// import or `ath log` writes from 2.1.0 on has it. value?: ValueBasis, + /// How a workout's route summaries were made. The only value is + /// `calculated_on_import`. route_summaries?: RouteSummariesBasis = literal("calculated_on_import"), /// How a workout's machine was filled (D297). New in 3.0.0. machine?: MachineBasis, @@ -763,13 +1047,17 @@ model_enum! { /// Where a workout's machine came from (D297). pub enum MachineBasis { /// The source's own label. + /// Stored as `source`. Source = "source", /// The athlete said so. + /// Stored as `athlete`. Athlete = "athlete", /// The athlete's saved default for the sport. + /// Stored as `preference_default`. PreferenceDefault = "preference_default", /// An agent assumed it from context, because the athlete chose not to /// be asked (D298). + /// Stored as `assumed`. Assumed = "assumed", } } @@ -780,11 +1068,17 @@ model_object! { /// A benchmark score: time, repetitions, load, or, from 3.0.0, mean /// power, distance, or energy (D304). Zero is refused. pub struct Score { + /// A time, in seconds, above 0. duration_s?: f64 = positive(), + /// A repetition count, 1 or more. reps?: u64 = positive_int(), + /// A load, in kilograms, above 0. weight_kg?: f64 = positive(), + /// Mean power, in watts, above 0. New in 3.0.0. power_w?: f64 = positive(), + /// A distance, in metres, above 0. New in 3.0.0. distance_m?: f64 = positive(), + /// Energy, in kilocalories, above 0. New in 3.0.0. energy_kcal?: f64 = positive(), } refine(refine_score) @@ -797,7 +1091,8 @@ fn refine_score(value: &Value, issues: &mut Vec) { } impl Score { - /// The value for a benchmark score type: `time`, `reps`, or `load`. + /// The value for a benchmark score type: `time`, `reps`, `load`, `power`, `distance`, + /// or `energy`. `None` for another type or when the score lacks that value. pub fn value_for(&self, score_type: &str) -> Option { match score_type { "time" => self.duration_s, @@ -812,9 +1107,13 @@ impl Score { } model_enum! { + /// How sure the author of a prediction is. pub enum Confidence { + /// Stored as `low`. Low = "low", + /// Stored as `moderate`. Moderate = "moderate", + /// Stored as `high`. High = "high", } } diff --git a/core/src/model/data.rs b/core/src/model/data.rs index bb65a9e9..81e305c5 100644 --- a/core/src/model/data.rs +++ b/core/src/model/data.rs @@ -23,15 +23,21 @@ fn reporting_period_or_instant(value: &Value) -> bool { // ---- Athlete and sources ------------------------------------------------ model_enum! { + /// The athlete's sex. pub enum Sex { + /// Stored as `male`. Male = "male", + /// Stored as `female`. Female = "female", } } model_enum! { + /// The units an app shows numbers in. Stored values keep their standard units. pub enum DisplayUnits { + /// Stored as `metric`. Metric = "metric", + /// Stored as `imperial`. Imperial = "imperial", } } @@ -43,11 +49,18 @@ fn birth_year() -> SchemaRef { } model_object! { + /// Facts about the athlete and the athlete's own settings. pub struct AthleteProfileData { + /// The athlete's name. name?: String, + /// The year the athlete was born, from 1900 to 2100. birth_year?: u32 = birth_year(), + /// The athlete's sex. sex?: Sex, + /// The units an app shows numbers in. Stored values keep their standard units. display_units?: DisplayUnits, + /// The IANA time zone name, such as `America/Chicago`, that calendar calculations + /// use when no time zone is given. default_time_zone?: String = iana_time_zone(), /// The athlete's own preferences (D297). New in 3.0.0. preferences?: AthletePreferences, @@ -55,10 +68,21 @@ model_object! { } model_enum! { + /// The kind of route a source's data came by. pub enum SourceType { + /// A device the athlete wears. + /// Stored as `wearable`. Wearable = "wearable", + /// A file exported from a device maker's app or service, such as an Apple Health + /// export or a WHOOP export. + /// Stored as `export_file`. ExportFile = "export_file", + /// A program that fetches data from a device service automatically. + /// Stored as `connector`. Connector = "connector", + /// Values a person typed in. A manual source does not claim that a device + /// measured the value. + /// Stored as `manual`. Manual = "manual", } } @@ -66,26 +90,46 @@ model_enum! { model_object! { /// Where measured records came from: who wrote the data and by which route. pub struct SourceData { + /// The kind of route the data came by. source_type: SourceType, + /// The device, app, or service that wrote the data, such as `Apple Watch`. data_writer: String, + /// The path the data took into the record, such as `garmin_account_export` or + /// `manual_entry`. Two routes stay separate sources even when the writer is the same. data_route: String, + /// The company whose app, export, or service delivered the data, such as `garmin`. vendor?: String, + /// The sensor that measured the data, such as `ecg`, when the source names one. + /// The writer, route, and sensor together identify the source. sensor_type?: String, + /// A short description of the source, such as `WHOOP export folder`. detail?: String, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), } } model_object! { + /// One device that wrote data under a source, such as one particular watch. pub struct SourceDeviceData { + /// The record ID of the source this device wrote data under. source_id: String = record_id(), + /// The device's name, as the source gave it. name?: String, + /// The device's manufacturer, as the source gave it. manufacturer?: String, + /// The device's model, as the source gave it. model?: String, + /// The device's hardware identifier, as the source gave it, such as `Watch6,1`. hardware?: String, + /// The device's serial number, as the source gave it. serial_number?: String, + /// The first day the import saw data from this device, a calendar day `YYYY-MM-DD`. coverage_start_date?: String = calendar_date(), + /// The last day the import saw data from this device, a calendar day `YYYY-MM-DD`. coverage_end_date?: String = calendar_date(), + /// How many records the import stored from this device. Zero or more. accepted_record_count?: u64 = nonnegative_int(), } } @@ -95,28 +139,58 @@ model_object! { model_enum! { /// Single-value measurements. Each uses one standard unit. pub enum PointMeasurementType { + /// Heart rate variability as RMSSD, in milliseconds. Never compared with SDNN. + /// Stored as `hrv_rmssd`. HrvRmssd = "hrv_rmssd", + /// Heart rate variability as SDNN, in milliseconds. Never compared with RMSSD. + /// Stored as `hrv_sdnn`. HrvSdnn = "hrv_sdnn", + /// Stored as `resting_heart_rate`. RestingHeartRate = "resting_heart_rate", + /// Stored as `body_weight`. BodyWeight = "body_weight", + /// Stored as `respiratory_rate`. RespiratoryRate = "respiratory_rate", + /// VO2 max, the most oxygen the body can use, in ml/kg/min. + /// Stored as `vo2_max`. Vo2Max = "vo2_max", + /// Heart rate recovery: how far heart rate dropped in the first minute after + /// effort, in beats per minute. + /// Stored as `hr_recovery`. HrRecovery = "hr_recovery", + /// The average heart rate while walking, in beats per minute. It is not a resting + /// value. + /// Stored as `walking_heart_rate`. WalkingHeartRate = "walking_heart_rate", + /// Stored as `oxygen_saturation`. OxygenSaturation = "oxygen_saturation", + /// Stored as `body_temperature`. BodyTemperature = "body_temperature", + /// The temperature measured at the skin, such as by WHOOP, in °C. + /// Stored as `skin_temperature`. SkinTemperature = "skin_temperature", + /// Apple's overnight wrist temperature, in °C. + /// Stored as `wrist_temperature_sleeping`. WristTemperatureSleeping = "wrist_temperature_sleeping", + /// The difference from a device maker's own baseline, in °C. It is not a + /// temperature, and it may be zero or negative. + /// Stored as `temperature_deviation`. TemperatureDeviation = "temperature_deviation", + /// Stored as `height`. Height = "height", + /// Stored as `lean_body_mass`. LeanBodyMass = "lean_body_mass", + /// Stored as `body_fat_percentage`. BodyFatPercentage = "body_fat_percentage", + /// Stored as `blood_pressure_systolic`. BloodPressureSystolic = "blood_pressure_systolic", + /// Stored as `blood_pressure_diastolic`. BloodPressureDiastolic = "blood_pressure_diastolic", } } impl PointMeasurementType { + /// The standard unit of this quantity, such as `ms`, `bpm`, or `kg`. pub fn unit(self) -> &'static str { point_measurement_unit(self.as_str()).expect("every point quantity has a unit") } @@ -141,34 +215,72 @@ pub fn point_measurement_unit(quantity: &str) -> Option<&'static str> { model_enum! { /// Time-series sample quantities. Each uses one standard unit. pub enum SeriesQuantity { + /// Stored as `heart_rate`. HeartRate = "heart_rate", + /// The time between heartbeats from a heart rate variability reading, in + /// milliseconds. Kept apart from ECG beats. + /// Stored as `hrv_beats`. HrvBeats = "hrv_beats", + /// The time between heartbeats found in an ECG (electrocardiogram) recording, in + /// milliseconds. Kept apart from other heart rate variability beats. + /// Stored as `ecg_beats`. EcgBeats = "ecg_beats", + /// Heart rate variability as SDNN, in milliseconds. Never compared with RMSSD. + /// Stored as `hrv_sdnn`. HrvSdnn = "hrv_sdnn", + /// Stored as `respiratory_rate`. RespiratoryRate = "respiratory_rate", + /// Stored as `oxygen_saturation`. OxygenSaturation = "oxygen_saturation", + /// Stored as `steps`. Steps = "steps", + /// Energy burned by activity, in kilocalories. + /// Stored as `active_energy`. ActiveEnergy = "active_energy", + /// Stored as `distance_walking_running`. DistanceWalkingRunning = "distance_walking_running", + /// Stored as `distance_cycling`. DistanceCycling = "distance_cycling", + /// Stored as `distance_swimming`. DistanceSwimming = "distance_swimming", + /// Stored as `running_speed`. RunningSpeed = "running_speed", + /// Stored as `running_power`. RunningPower = "running_power", + /// Stored as `running_stride_length`. RunningStrideLength = "running_stride_length", + /// How far the body moves up and down with each running step, in centimetres. + /// Stored as `running_vertical_oscillation`. RunningVerticalOscillation = "running_vertical_oscillation", + /// How long a foot stays on the ground in each running step, in milliseconds. + /// Stored as `running_ground_contact_time`. RunningGroundContactTime = "running_ground_contact_time", + /// Apple's physical effort, in METs (metabolic equivalents). + /// Stored as `physical_effort`. PhysicalEffort = "physical_effort", + /// Energy the body burns at rest, in kilocalories. + /// Stored as `basal_energy`. BasalEnergy = "basal_energy", + /// Minutes of exercise, as the source counted them. + /// Stored as `exercise_time`. ExerciseTime = "exercise_time", + /// Stored as `flights_climbed`. FlightsClimbed = "flights_climbed", + /// Stored as `walking_speed`. WalkingSpeed = "walking_speed", + /// Stored as `walking_step_length`. WalkingStepLength = "walking_step_length", + /// The percentage of walking steps in which one foot moves at a different speed + /// from the other. + /// Stored as `walking_asymmetry_percentage`. WalkingAsymmetryPercentage = "walking_asymmetry_percentage", + /// Stored as `time_in_daylight`. TimeInDaylight = "time_in_daylight", } } impl SeriesQuantity { + /// The standard unit of this quantity, such as `bpm`, `ms`, or `m`. pub fn unit(self) -> &'static str { series_quantity_unit(self.as_str()).expect("every series quantity has a unit") } @@ -200,31 +312,64 @@ pub fn series_quantity_unit(quantity: &str) -> Option<&'static str> { // ---- Measured records --------------------------------------------------- model_object! { + /// How the software calculated a point measurement from other data, such as RMSSD + /// from the time between heartbeats. pub struct PointMeasurementCalculation { + /// The quantity the value was calculated from, such as `hrv_beats` or `ecg_beats`. from_quantity: String, + /// The name of the calculation, such as `rmssd`. method: String, + /// The version of the calculation, such as `provider-parser-v1`. calculation_version: String, + /// How much data the calculation covered, in seconds. Greater than zero. window_s?: f64 = positive(), + /// How many samples the calculation used, such as heartbeat intervals. usable_sample_count?: u64 = positive_int(), + /// How many samples the calculation left out as implausible, such as heartbeat + /// intervals outside a believable range. dropped_sample_count?: u64 = nonnegative_int(), + /// A signal quality number the calculation reports, zero or more. For an ECG it + /// says how far the beats stood above background noise. signal_quality?: f64 = nonnegative(), + /// The records the calculation read, each at its exact revision. Empty when the + /// inputs were not stored as records. input_records: Vec, } } model_object! { + /// One measured value at one time, such as a resting heart rate or a body weight. pub struct PointMeasurementData { + /// The record ID of the source this value came from. source_id: String = record_id(), + /// The source's own ID for this value. Absent when the source gave none. provider_record_id?: String, + /// The periods the provider assigned this value to, such as a WHOOP cycle or an + /// Oura day. provider_reporting_periods?: Vec, + /// When this value reached the software, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which clock gave it. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as the provider's own time or the import time. received_at_basis: ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), + /// The basis on which the software stored the values, such as calculated on import + /// or entered by hand. The source did not send it. field_basis?: FieldBasis, + /// What was measured. It sets the standard unit of `value`. quantity: PointMeasurementType, + /// When the value was measured, a UTC instant such as `2026-01-02T03:04:05.678Z`. + /// Absent when the source tied the value only to a provider reporting period. recorded_at?: String = utc_timestamp(), + /// The time text the source wrote for this value, and how it was read. input_timestamp: InputTimestampReceipt, + /// The value in the quantity's standard unit, with the value and unit the source + /// wrote. Greater than zero, except for `temperature_deviation`. value: SourceValue, + /// How the software calculated the value from other data. Absent when the source + /// reported the value itself. calculations?: Vec, } refine(refine_point_measurement) @@ -247,20 +392,44 @@ fn refine_point_measurement(value: &Value, issues: &mut Vec) { } model_object! { + /// One reading in a time series, such as a heart rate sample or a step count. pub struct MeasurementSampleData { + /// The record ID of the source this reading came from. source_id: String = record_id(), + /// The source's own ID for this reading. Absent when the source gave none. provider_record_id?: String, + /// The periods the provider assigned this reading to, such as a WHOOP cycle or an + /// Oura day. provider_reporting_periods?: Vec, + /// When this reading reached the software, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which clock gave it. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as the provider's own time or the import time. received_at_basis: ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), + /// The basis on which the software stored the values, such as calculated on import + /// or entered by hand. The source did not send it. field_basis?: FieldBasis, + /// What was measured. It sets the standard unit of `value`. quantity: SeriesQuantity, + /// When the reading was taken, or when its span began, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. recorded_at: String = utc_timestamp(), + /// The time text the source wrote for this reading, and how it was read. input_timestamp: InputTimestampReceipt, + /// The reading in the quantity's standard unit, with the value and unit the source + /// wrote. value: SourceValue, + /// How long the reading covers from `recorded_at`, in milliseconds. Zero or more. duration_ms?: u64 = nonnegative_int(), + /// The series start time text the source wrote, from which this reading's time was + /// rebuilt. Present only when `input_timestamp.timestamp_basis` is + /// `reconstructed_from_series_start`. timestamp_base_text?: String, + /// The name of the method that rebuilt this reading's time, such as + /// `series_start_plus_offset_ms_v1`. Present only with `timestamp_base_text`. timestamp_reconstruction_method?: String, } refine(refine_measurement_sample) @@ -290,22 +459,44 @@ fn stage_minutes() -> SchemaRef { } model_object! { + /// One period of sleep a source measured, with its start, end, and totals. pub struct SleepSessionData { + /// The record ID of the source this sleep came from. source_id: String = record_id(), + /// The source's own ID for this sleep. Absent when the source gave none. provider_record_id?: String, + /// The periods the provider assigned this sleep to, such as a WHOOP cycle or an + /// Oura sleep day. provider_reporting_periods?: Vec, + /// When this sleep reached the software, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which clock gave it. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as the provider's own time or the import time. received_at_basis: ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), + /// The basis on which the software stored the values, such as calculated on import + /// or entered by hand. The source did not send it. field_basis?: FieldBasis, + /// When the sleep began, a UTC instant such as `2026-01-02T03:04:05.678Z`. start_at: String = utc_timestamp(), + /// When the sleep ended, a UTC instant. It cannot be before `start_at`. end_at: String = utc_timestamp(), + /// The start time text the source wrote, and how it was read. input_start_timestamp: InputTimestampReceipt, + /// The end time text the source wrote, and how it was read. input_end_timestamp: InputTimestampReceipt, + /// Totals the source reported for this sleep. May be empty. source_reported_summaries: Vec, + /// Time asleep, in seconds. Zero or more. asleep_seconds?: f64 = nonnegative(), + /// Time in bed, in seconds. Zero or more. in_bed_seconds?: f64 = nonnegative(), + /// How many times sleep was interrupted, as the source counted them. interruptions?: u64 = nonnegative_int(), + /// Minutes in each sleep stage, keyed by stage name, such as `awake`, `light`, + /// `deep`, and `rem`. Each value is zero or more. stage_minutes?: StageMinutes = stage_minutes(), } refine(refine_sleep_session) @@ -318,8 +509,11 @@ fn refine_sleep_session(value: &Value, issues: &mut Vec) { } model_object! { + /// One heart rate reading during a workout. pub struct HeartRateSample { + /// The time of the reading, in milliseconds from the workout's `start_at`. offset_ms: u64 = nonnegative_int(), + /// The heart rate, in beats per minute. Greater than zero. bpm: f64 = positive(), } } @@ -328,19 +522,28 @@ model_enum! { /// What a strength set's `weight` measures (D239). pub enum LoadBasis { /// The whole load moved, such as a loaded barbell. + /// Stored as `total`. Total = "total", /// The load of each implement, such as one of two dumbbells. + /// Stored as `per_implement`. PerImplement = "per_implement", } } model_object! { + /// One set of a strength exercise: how many repetitions, with what load. pub struct StrengthSet { + /// How many repetitions. Greater than zero. reps: f64 = positive(), + /// The load, in `weight_unit`. Greater than zero. With a `per_implement` + /// `load_basis`, it is the load of each implement. weight: f64 = positive(), + /// The unit of `weight` as written, such as `kg` or `lb`. weight_unit: String, /// The exercise, such as `back squat`. movement?: String, + /// What `weight` measures: the whole load, or the load of each implement. Absent + /// when the set states no basis; calculations then count `weight` as written. load_basis?: LoadBasis, /// How many implements carried `weight` each. Only with `per_implement`. implement_count?: u64 = positive_int(), @@ -371,54 +574,103 @@ fn longitude() -> SchemaRef { } model_object! { + /// One point on a workout's route: a position and the time it was reached. pub struct RoutePoint { + /// When the athlete was at this point, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. recorded_at: String = utc_timestamp(), + /// The latitude, in degrees, from -90 to 90. latitude_deg: f64 = latitude(), + /// The longitude, in degrees, from -180 to 180. longitude_deg: f64 = longitude(), - /// The time the source wrote, including its UTC offset. `recorded_at` is that instant in UTC. + /// The time the source wrote, including its UTC offset. `recorded_at` is that + /// instant in UTC. input_timestamp?: InputTimestampReceipt, + /// Other values the source sent for this point, kept under the names they arrived + /// with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), } } model_object! { + /// One part of a workout, such as a lap, with its own totals. pub struct WorkoutSessionSegment { + /// The name of the part, such as `lap 1`. label: String, + /// When the part began, in milliseconds from the workout's `start_at`. start_offset_ms?: u64 = nonnegative_int(), + /// When the part ended, in milliseconds from the workout's `start_at`. end_offset_ms?: u64 = nonnegative_int(), + /// Totals the source reported for this part, such as distance or average power. + /// May be empty. source_reported_summaries: Vec, } } model_object! { + /// One workout a source recorded, or the athlete logged, with its times and results. pub struct WorkoutSessionData { + /// The record ID of the source this workout came from. source_id: String = record_id(), + /// The source's own ID for this workout. Absent when the source gave none. provider_record_id?: String, + /// The periods the provider assigned this workout to, such as a WHOOP cycle. provider_reporting_periods?: Vec, + /// When this workout reached the software, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which clock gave it. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as the provider's own time or the import time. received_at_basis: ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), + /// The basis on which the software stored the values, such as the source's own + /// activity label or a machine the athlete named. The source did not send it. field_basis?: FieldBasis, + /// When the workout began, a UTC instant such as `2026-01-02T03:04:05.678Z`. start_at: String = utc_timestamp(), + /// When the workout ended, a UTC instant. It cannot be before `start_at`. end_at: String = utc_timestamp(), + /// The start time text the source wrote, and how it was read. input_start_timestamp: InputTimestampReceipt, + /// The end time text the source wrote, and how it was read. input_end_timestamp: InputTimestampReceipt, + /// The kind of activity as the source named it, such as `Running`. activity_type?: String, + /// The workout's title, as the source or the athlete gave it. name?: String, + /// A description of the workout, as the source gave it. description?: String, + /// The result or notes as free text, such as the words the athlete logged. A + /// workout logged only as text has no `sets`. text_result?: String, + /// Retired: new writes refuse it from 3.0.0. The athlete's maximum heart rate, in + /// beats per minute. It is not the workout's peak, which is the `max_heart_rate` + /// summary. The athlete's maximum heart rate is now an intensity reference. maximum_heart_rate_bpm?: f64 = positive(), + /// Retired: new writes refuse it from 3.0.0. The athlete's resting heart rate, in + /// beats per minute. Resting heart rate now comes from measured readings. resting_heart_rate_bpm?: f64 = positive(), + /// Heart rate readings during the workout, each timed from `start_at`. heart_rate_samples?: Vec, + /// The strength sets done in the workout. sets?: Vec, + /// The points of the route the workout followed. route?: Vec, + /// Totals the source reported for the whole workout, such as distance or average + /// power. May be empty. source_reported_summaries: Vec, + /// The parts of the workout, such as laps, each with its own totals. segments?: Vec, - /// What the body was doing and the machine that produced the numbers - /// (D295). New in 3.0.0. + /// What the body was doing, such as running or rowing (D295). New in 3.0.0. sport?: Sport, + /// The machine that produced the numbers, such as a treadmill, or `none` (D295). + /// Required when `sport` is present. New in 3.0.0. machine?: Machine, + /// The machine's manufacturer and model. New in 3.0.0. machine_details?: MachineDetails, + /// The surroundings during the workout, such as altitude, temperature, humidity, + /// or whether it was indoors. New in 3.0.0. environment?: Environment, /// The fingerprint of the file the workout came from (D307). original_file?: OriginalFile, @@ -477,51 +729,96 @@ fn refine_workout_session(value: &Value, issues: &mut Vec) { } model_object! { + /// One part of a benchmark result, such as one round, with its own score. pub struct BenchmarkResultSegment { + /// The name of the part, such as `21` for a round of 21 repetitions. label: String, + /// The score for this part. Absent when the part has no score of its own. score?: Score, } } model_enum! { + /// Whether a benchmark was done as written or changed to suit the athlete. pub enum Scaling { + /// Done as prescribed: the workout as written. + /// Stored as `rx`. Rx = "rx", + /// Stored as `scaled`. Scaled = "scaled", } } model_object! { + /// One attempt at a benchmark and its score. pub struct BenchmarkResultData { + /// The record ID of the source this result came from. A result the athlete typed + /// in uses the `manual` source. source_id: String = record_id(), + /// The source's own ID for this result. Absent when the source gave none. provider_record_id?: String, + /// The periods the provider assigned this result to. provider_reporting_periods?: Vec, + /// When this result reached the software, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which clock gave it. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as the provider's own time or the import time. received_at_basis: ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), + /// The basis on which the software stored the values, such as entered by hand. + /// The source did not send it. field_basis?: FieldBasis, + /// The record ID of the benchmark definition this result is for. benchmark_definition_id: String = record_id(), + /// When the attempt happened, a UTC instant such as `2026-01-02T03:04:05.678Z`. recorded_at: String = utc_timestamp(), + /// The time text the source wrote for the attempt, and how it was read. input_timestamp: InputTimestampReceipt, + /// The score. The benchmark's score type says which field of the score counts. score: Score, + /// The score as the source wrote it, such as `4:41`. input_score_text?: String, + /// Whether the workout was done as prescribed or scaled. Absent when not stated. scaling?: Scaling, + /// The record ID of the workout in which the attempt happened. workout_session_id?: String = record_id(), + /// The parts of the result in order, such as rounds, each with its own score. segments?: Vec, } } model_object! { + /// A total or duration a source reported, such as a day's active energy. It is not a + /// single reading or a composite score. pub struct ProviderSummaryData { + /// The record ID of the source this total came from. source_id: String = record_id(), + /// The source's own ID for this total. Absent when the source gave none. provider_record_id?: String, + /// The periods the provider assigned this total to, such as an Apple activity day. + /// A summary needs this or `recorded_at`. provider_reporting_periods?: Vec, + /// When this total reached the software, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which clock gave it. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as the provider's own time or the import time. received_at_basis: ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), + /// The basis on which the software stored the values, such as the provider's own + /// number. The source did not send it. field_basis?: FieldBasis, + /// The name of the total, such as `active_energy_burned`. summary_type: String, + /// The total in its standard unit, with the value and unit the source wrote. value: SourceValue, + /// When the total applies, a UTC instant such as `2026-01-02T03:04:05.678Z`. A + /// summary needs this or at least one provider reporting period. recorded_at?: String = utc_timestamp(), + /// The time text the source wrote for this total, and how it was read. input_timestamp: InputTimestampReceipt, } refine(refine_provider_summary) @@ -538,18 +835,37 @@ fn refine_provider_summary(value: &Value, issues: &mut Vec) { } model_object! { + /// A score a provider calculated, such as recovery, strain, readiness, or a sleep + /// score. It is not a sensor reading. pub struct ProviderScoreData { + /// The record ID of the source this score came from. source_id: String = record_id(), + /// The source's own ID for this score. Absent when the source gave none. provider_record_id?: String, + /// The periods the provider assigned this score to, such as a WHOOP cycle or an + /// Oura day. A score needs this or `recorded_at`. provider_reporting_periods?: Vec, + /// When this score reached the software, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which clock gave it. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as the provider's own time or the import time. received_at_basis: ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names they + /// arrived with. supplied_fields?: SuppliedFields = super::schema::supplied_fields(), + /// The basis on which the software stored the values, such as the provider's own + /// score. The source did not send it. field_basis?: FieldBasis, + /// The provider's name for the score, such as `readiness` or `sleep_score`. metric: String, + /// The score, with the value the source wrote. value: SourceValue, + /// The scale of the score, such as `0-100`. scale: String, + /// When the score applies, a UTC instant such as `2026-01-02T03:04:05.678Z`. A + /// score needs this or at least one provider reporting period. recorded_at?: String = utc_timestamp(), + /// The time text the source wrote for this score, and how it was read. input_timestamp: InputTimestampReceipt, } refine(refine_provider_score) @@ -568,50 +884,90 @@ fn refine_provider_score(value: &Value, issues: &mut Vec) { // ---- Athlete reports ---------------------------------------------------- model_enum! { + /// What an athlete report is about. pub enum AthleteReportType { + /// Stored as `sleep_quality`. SleepQuality = "sleep_quality", + /// Stored as `soreness`. Soreness = "soreness", + /// Stored as `stress`. Stress = "stress", + /// Stored as `mood`. Mood = "mood", + /// Stored as `energy`. Energy = "energy", + /// Stored as `note`. Note = "note", /// The athlete's rating of a whole session, such as a session RPE (D238). + /// Stored as `session_effort`. SessionEffort = "session_effort", /// An injury or pain the athlete reports (D310). Not a diagnosis. + /// Stored as `injury`. Injury = "injury", /// An illness the athlete reports (D310). Not a diagnosis. + /// Stored as `illness`. Illness = "illness", } } model_enum! { + /// How the athlete gave a report or a nutrition entry. pub enum ReportedVia { + /// Stored as `text`. Text = "text", + /// Stored as `voice`. Voice = "voice", + /// Stored as `photo`. Photo = "photo", } } model_object! { + /// Something the athlete said about themselves, such as soreness, mood, or the effort + /// of a session. It has no source: no device measured it. pub struct AthleteReportData { + /// What the report is about. report_type: AthleteReportType, + /// When the athlete made the report, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. reported_at: String = utc_timestamp(), + /// The time text given for `reported_at`, and how it was read. input_reported_at: InputTimestampReceipt, + /// How the athlete gave the report: text, voice, or photo. reported_via: ReportedVia, + /// The athlete's rating, on the scale in `rating_scale`. Required for a + /// `session_effort` report. rating?: f64, + /// The scale of `rating`, such as `0-10` or `1-5`. Required when `rating` is present. rating_scale?: String, + /// The part of the body the report is about, such as `knee`. body_region?: String, + /// The athlete's words, as free text. note?: String, + /// The time the report covers, in seconds. Greater than zero. For a + /// `session_effort` report, it is the time the rating covers. duration_seconds?: f64 = positive(), + /// The record IDs of attachments for this report, such as a photo. attachment_ids?: Vec = record_id_array(), /// The workout this report describes (D238). workout_session_id?: String = record_id(), - /// Injury and illness details (D310). New in 3.0.0. + /// Which side of the body is hurt: left, right, or both. Only on an `injury` + /// report (D310). New in 3.0.0. side?: Side, + /// Whether the problem began suddenly or gradually. Only on an `injury` or + /// `illness` report. New in 3.0.0. onset?: Onset, + /// The day the problem began, a calendar day `YYYY-MM-DD`. Only on an `injury` or + /// `illness` report. New in 3.0.0. onset_date?: String = calendar_date(), + /// Whether the problem is new, ongoing, or resolved. Only on an `injury` or + /// `illness` report. New in 3.0.0. problem_status?: ProblemStatus, + /// How much the problem changed training over the past 7 days. Only on an + /// `injury` or `illness` report. New in 3.0.0. training_impact?: TrainingImpact, + /// The record ID of the first report of the same problem, an athlete report of + /// the same type. Only on an `injury` or `illness` report. New in 3.0.0. first_report_id?: String = record_id(), } refine(refine_athlete_report) @@ -637,39 +993,64 @@ fn refine_athlete_report(value: &Value, issues: &mut Vec) { } model_object! { + /// One nutrient amount in a food or drink, such as its protein. pub struct ReportedNutrient { + /// The nutrient's name. nutrient_name: String, + /// The amount of the nutrient, in `unit`. amount: f64, + /// The unit of `amount`. unit: String, } } model_object! { + /// One food or drink, with any amount and nutrients given for it. pub struct ReportedNutritionItem { + /// The food or drink, in words. food_description: String, + /// How much was eaten or drunk, in `amount_unit`. amount?: f64, + /// The unit of `amount`, such as `ml`. amount_unit?: String, + /// The nutrients in this item. nutrients?: Vec, } } model_object! { + /// What the athlete said they ate or drank, in the athlete's own words. It has no + /// source. A model's reading of it is a separate `nutrition_model_interpretation`. pub struct NutritionEntryData { + /// When the athlete made the entry, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. reported_at: String = utc_timestamp(), + /// The time text given for `reported_at`, and how it was read. input_reported_at: InputTimestampReceipt, + /// How the athlete gave the entry: text, voice, or photo. reported_via: ReportedVia, + /// The athlete's description of what they ate or drank, in their own words. athlete_description: String, + /// The foods and drinks the athlete named, with any amounts they gave. reported_items: Vec, + /// The record IDs of attachments for this entry, such as a photo of the meal. attachment_ids?: Vec = record_id_array(), } } model_object! { + /// A file attached to the record, such as a photo. The file's bytes are kept in a + /// separate file. They are not inside the record. pub struct AttachmentData { + /// The file's original name. file_name: String, + /// The file's media type, such as `image/jpeg`. media_type: String, + /// The file's size, in bytes. Zero or more. byte_count: u64 = nonnegative_int(), + /// The SHA-256 digest of the file's bytes, as 64 lowercase hexadecimal characters. sha256: String = sha256(), + /// A description of the file. description?: String, } } @@ -677,25 +1058,45 @@ model_object! { // ---- Authored records --------------------------------------------------- model_enum! { + /// The kind of test a benchmark is. pub enum BenchmarkType { + /// A named CrossFit workout (a named "workout of the day"), such as Fran or Cindy. + /// Stored as `named_wod`. NamedWod = "named_wod", + /// A running test, such as a 5 km run. + /// Stored as `run`. Run = "run", + /// A HYROX race. + /// Stored as `hyrox`. Hyrox = "hyrox", + /// Stored as `lift`. Lift = "lift", + /// Any other test. + /// Stored as `custom`. Custom = "custom", } } model_enum! { + /// What a benchmark's score measures, and so which field of a score it uses. pub enum ScoreType { + /// The time taken, in `duration_s`. A lower time is better. + /// Stored as `time`. Time = "time", + /// Repetitions, in `reps`. + /// Stored as `reps`. Reps = "reps", + /// The load lifted, in `weight_kg`. + /// Stored as `load`. Load = "load", /// Mean power over `score_duration_s` (D304). New in 3.0.0. + /// Stored as `power`. Power = "power", /// Distance covered in `score_duration_s`. New in 3.0.0. + /// Stored as `distance`. Distance = "distance", /// Energy, such as calories on a machine, in `score_duration_s`. New in 3.0.0. + /// Stored as `energy`. Energy = "energy", } } @@ -713,12 +1114,20 @@ impl ScoreType { } model_object! { + /// A repeatable test, such as Fran or a 5 km run, and how it is scored. pub struct BenchmarkDefinitionData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// A short name for the benchmark, unique in the record, such as `fran`. Lowercase + /// letters, digits, hyphens, and underscores. benchmark_key: String = benchmark_key(), + /// The kind of test. benchmark_type: BenchmarkType, + /// What the score measures, and so which field of a score counts. score_type: ScoreType, + /// What the test is, in words, such as `5 kilometer run for time`. definition: String, + /// Short labels for the test, such as `short` or `endurance`. tags?: Vec = text_array(), /// How long a power, distance, or energy test lasts (D304). score_duration_s?: f64 = positive(), @@ -742,78 +1151,136 @@ fn refine_benchmark_definition(value: &Value, issues: &mut Vec) { } model_object! { + /// A range of scores. A score equal to either end is inside the range. pub struct ScoreRange { + /// The end of the range with the smaller number. low: Score, + /// The end of the range with the larger number. high: Score, } } model_object! { + /// A prediction of the score on one benchmark. pub struct PredictionData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The record ID of the benchmark definition the prediction is for. benchmark_definition_id: String = record_id(), + /// The score the prediction expects. predicted_score: Score, + /// The range the prediction expects the score to fall in. Absent when the + /// prediction gives no range. predicted_range?: ScoreRange, + /// How sure the author is: low, moderate, or high. confidence: Confidence, + /// Why the author expects this score. reasoning: String, } } model_object! { + /// A link from one prediction to the benchmark result it predicted, each at an exact + /// revision. Both must use the same benchmark definition. pub struct PredictionResultLinkData { + /// The prediction, at its exact revision. prediction: EvidenceReference, + /// The benchmark result, at its exact revision. benchmark_result: EvidenceReference, + /// Who made the link. It cannot be a coach. created_by: RecordActor, + /// When the link was made, a UTC instant such as `2026-01-02T03:04:05.678Z`. linked_at: String = utc_timestamp(), + /// The version of the link's content, a whole number from 1. content_version: u64 = positive_int(), + /// Where the link stands, such as `active` or `superseded`. status: AuthoredRecordStatus, } } model_object! { + /// How far a prediction was from the actual result. The software writes it with + /// fixed arithmetic in the benchmark's own score unit. pub struct PredictionGradeData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The prediction-to-result link this grade is for, at its exact revision. prediction_result_link: EvidenceReference, + /// The predicted value minus the actual value, in the benchmark's score unit, + /// rounded to two decimal places. signed_error: f64, + /// The size of the error as a percentage of the actual value, rounded to one + /// decimal place. Zero or more. absolute_error_percentage: f64 = nonnegative(), + /// Whether the actual value fell inside the predicted range, ends included. False + /// when the prediction has no range. result_in_predicted_range: bool, + /// A copy of the predicted score. predicted_score: Score, + /// A copy of the actual result's score. actual_score: Score, } } model_object! { + /// One recorded reason that may explain why a prediction missed. pub struct PredictionErrorCause { + /// The record that supports this cause, at its exact revision. evidence: EvidenceReference, + /// What that record shows and how it relates to the miss. explanation: String, } } model_enum! { + /// Which way the actual result differed from the prediction. pub enum ErrorDirection { + /// The actual result was faster than predicted. + /// Stored as `faster`. Faster = "faster", + /// The actual result was slower than predicted. + /// Stored as `slower`. Slower = "slower", + /// The actual score was higher than predicted. + /// Stored as `higher`. Higher = "higher", + /// The actual score was lower than predicted. + /// Stored as `lower`. Lower = "lower", } } model_enum! { + /// How large a prediction's miss was, by the absolute error percentage. pub enum ErrorSeverity { + /// An error under 5 percent. + /// Stored as `minor`. Minor = "minor", + /// An error from 5 to 15 percent. + /// Stored as `significant`. Significant = "significant", + /// An error over 15 percent. + /// Stored as `severe`. Severe = "severe", } } model_object! { + /// Why a prediction differed from the actual result, based only on recorded evidence. pub struct PredictionErrorAnalysisData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The grade this analysis explains, at its exact revision. prediction_grade: EvidenceReference, + /// Which way the actual result differed from the prediction. error_direction: ErrorDirection, + /// How large the miss was. error_severity: ErrorSeverity, + /// The recorded causes, in order. Empty when nothing in the record explains the miss. causes: Vec, + /// Whether the miss is unexplained. It must be true when `causes` is empty. unexplained: bool, + /// A short lesson for future predictions. lesson?: String, } refine(refine_error_analysis) @@ -828,11 +1295,18 @@ fn refine_error_analysis(value: &Value, issues: &mut Vec) { } model_object! { + /// A training plan: its aim and the days it covers. Its sessions are planned + /// session records that name it. pub struct TrainingPlanData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The plan's title. title: String, + /// What the plan aims to achieve. objective?: String, + /// The first day of the plan, a calendar day `YYYY-MM-DD`. start_date?: String = calendar_date(), + /// The last day of the plan, a calendar day `YYYY-MM-DD`. end_date?: String = calendar_date(), /// The event the plan prepares for (D299). New in 3.0.0. event_id?: String = record_id(), @@ -840,28 +1314,50 @@ model_object! { } model_enum! { + /// Whether a planned session is still planned, was done, or will not happen. pub enum CompletionStatus { + /// Stored as `planned`. Planned = "planned", + /// Stored as `completed`. Completed = "completed", + /// Stored as `skipped`. Skipped = "skipped", + /// Stored as `cancelled`. Cancelled = "cancelled", } } model_object! { + /// One training session planned for a day, with its blocks of work. pub struct PlannedSessionData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The record ID of the training plan this session belongs to. Absent for a + /// session outside any plan. training_plan_id?: String = record_id(), + /// The session's title. title: String, + /// The day the session is planned for, a calendar day `YYYY-MM-DD`. A session + /// needs this or `scheduled_start_at`. scheduled_date?: String = calendar_date(), + /// The planned start, a UTC instant such as `2026-01-02T03:04:05.678Z`. A session + /// needs this or `scheduled_date`. scheduled_start_at?: String = utc_timestamp(), + /// The kind of activity planned, as free text. activity_type?: String, + /// The parts of the session in order, such as a warm-up and the main work. blocks: Vec, + /// Whether the session is still planned, completed, skipped, or cancelled. completion_status: CompletionStatus, + /// The record ID of the workout that completed this session. The workout does not + /// link back. completed_workout_session_id?: String = record_id(), - /// The sport and machine of the whole session (D295). New in 3.0.0. + /// The sport of the whole session (D295). New in 3.0.0. sport?: Sport, + /// The machine of the whole session, such as a rowing machine, or `none` (D295). + /// Required when `sport` is present. New in 3.0.0. machine?: Machine, + /// The machine's manufacturer and model. New in 3.0.0. machine_details?: MachineDetails, } refine(refine_planned_session) @@ -880,32 +1376,52 @@ fn refine_planned_session(value: &Value, issues: &mut Vec) { } model_object! { + /// A note of coaching advice or context for the athlete. pub struct CoachingNoteData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The note's title. title?: String, + /// The note's text. note: String, + /// The first day the note applies to, a calendar day `YYYY-MM-DD`. applies_from?: String = calendar_date(), + /// The last day the note applies to, a calendar day `YYYY-MM-DD`. applies_to?: String = calendar_date(), } } model_object! { + /// A saved review of a period of training, with a summary and recommendations. pub struct SavedTrainingReviewData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The first day of the period reviewed, a calendar day `YYYY-MM-DD`. period_start: String = calendar_date(), + /// The last day of the period reviewed, a calendar day `YYYY-MM-DD`. period_end: String = calendar_date(), + /// What the review found. summary: String, + /// The review's recommendations, one per item. recommendations?: Vec = text_array(), } } model_object! { + /// Something the athlete is working toward, such as a score on a benchmark by a date. pub struct GoalData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The goal's title. title: String, + /// A longer description of the goal. description?: String, + /// The day to reach the goal by, a calendar day `YYYY-MM-DD`. Absent when the goal + /// names an event, because the date then comes from the event. target_date?: String = calendar_date(), + /// The record ID of the benchmark definition the goal is measured on. target_benchmark_definition_id?: String = record_id(), + /// The score the goal aims for on that benchmark. target_score?: Score, /// The event this goal is for (D299). New in 3.0.0. A goal with an /// event takes its date from the event, so it has no target_date. @@ -931,11 +1447,18 @@ fn unit_interval() -> SchemaRef { } model_object! { + /// A model's reading of a nutrition entry, such as the foods and nutrients it + /// estimates. The athlete's own entry stays unchanged in its record. pub struct NutritionModelInterpretationData { + /// Who wrote this record, when, from which records, and its status. authorship: AuthoredRecordMetadata, + /// The record ID of the nutrition entry this reading is about. nutrition_entry_id: String = record_id(), + /// How sure the model is, from 0 to 1. confidence: f64 = unit_interval(), + /// The foods and drinks as the model reads them, with amounts and nutrients. interpreted_items: Vec, + /// How the model reached its reading. explanation?: String, } } diff --git a/core/src/model/grade.rs b/core/src/model/grade.rs index 7e0e652c..4a78a54c 100644 --- a/core/src/model/grade.rs +++ b/core/src/model/grade.rs @@ -19,12 +19,19 @@ pub fn js_round(value: f64) -> f64 { } } +/// The numbers of one prediction grade, in the benchmark's own score unit. #[derive(Debug, Clone, Copy, PartialEq)] pub struct GradeArithmetic { + /// The predicted score value. pub predicted_value: f64, + /// The actual result's score value. pub actual_value: f64, + /// The predicted value minus the actual value, rounded to two decimals. pub signed_error: f64, + /// The size of the error as a percent of the actual value, rounded to one decimal. pub absolute_error_percentage: f64, + /// True when the actual value is inside the predicted range, ends included. False + /// when the prediction has no range. pub result_in_predicted_range: bool, } diff --git a/core/src/model/json_schema.rs b/core/src/model/json_schema.rs index d953992b..d5a81a03 100644 --- a/core/src/model/json_schema.rs +++ b/core/src/model/json_schema.rs @@ -88,6 +88,8 @@ pub struct Components { } impl Components { + /// An empty set of shapes. A reference to a named shape is `prefix` followed by the + /// shape's name. pub fn new(prefix: &str) -> Components { Components { definitions: Definitions { prefix: Some(prefix.to_string()), ..Definitions::default() } } } diff --git a/core/src/model/package.rs b/core/src/model/package.rs index 88978849..853bef6a 100644 --- a/core/src/model/package.rs +++ b/core/src/model/package.rs @@ -27,14 +27,23 @@ pub const ACCEPTED_RECORD_VERSIONS: &[&str] = &["1.0.0", "2.0.0", "2.1.0", "2.1. pub const IMPORTABLE_PACKAGE_VERSIONS: &[&str] = &["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3", "3.0.0", "3.1.0"]; model_enum! { + /// A version of the record format, as written in `athleticstandard_version`. pub enum RecordFormatVersion { + /// Stored as `1.0.0`. V1_0_0 = "1.0.0", + /// Stored as `2.0.0`. V2_0_0 = "2.0.0", + /// Stored as `2.1.0`. V2_1_0 = "2.1.0", + /// Stored as `2.1.1`. V2_1_1 = "2.1.1", + /// Stored as `2.1.2`. V2_1_2 = "2.1.2", + /// Stored as `2.1.3`. V2_1_3 = "2.1.3", + /// Stored as `3.0.0`. V3_0_0 = "3.0.0", + /// Stored as `3.1.0`. V3_1_0 = "3.1.0", } } @@ -47,34 +56,58 @@ impl RecordFormatVersion { } model_object! { + /// The main package document's entry for one generated measurement-series file. A + /// series file holds the samples of one source and quantity. pub struct MeasurementSeriesFileReference { + /// The file's path inside the package, such as + /// `series/--000001.ath-series.json`. file: String = package_relative_path(), + /// The SHA-256 hash of the file, 64 lowercase hexadecimal digits. sha256: String = sha256(), + /// The ID of the source whose samples the file holds. source_id: String = record_id(), + /// The sample quantity the file holds, such as `heart_rate`. quantity: SeriesQuantity, + /// The start of the file's time bounds, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. Every current sample falls inside the bounds. start_at: String = utc_timestamp(), + /// The end of the file's time bounds, a UTC instant. It cannot be before `start_at`. end_at: String = utc_timestamp(), + /// How many current samples the file holds. sample_count: u64 = nonnegative_int(), + /// How many retained revisions of those samples the file holds. revision_count: u64 = nonnegative_int(), + /// How many deletions of those samples the file holds. deletion_count: u64 = nonnegative_int(), + /// How many provider import keys of those samples the file holds. import_key_count: u64 = nonnegative_int(), } } model_object! { + /// One package file the export manifest lists. pub struct ManifestFile { + /// The file's path inside the package. file: String = package_relative_path(), + /// The SHA-256 hash of the file, 64 lowercase hexadecimal digits. sha256: String = sha256(), + /// The file's size in bytes. byte_count: u64 = nonnegative_int(), } } model_object! { + /// How many items of one record type the package holds. pub struct ManifestRecordCount { + /// The record type counted. record_type: RecordType, + /// How many current records of this type, including normally deleted ones. current_record_count: u64 = nonnegative_int(), + /// How many retained revisions of records of this type. revision_count: u64 = nonnegative_int(), + /// How many normal deletions of records of this type. deletion_count: u64 = nonnegative_int(), + /// How many provider import keys of records of this type. import_key_count: u64 = nonnegative_int(), } } @@ -82,12 +115,21 @@ model_object! { model_object! { /// The manifest is written last. It names every package file and its hash. pub struct ExportManifest { + /// The format version the package was written with. athleticstandard_version: RecordFormatVersion, + /// The ID of the database the package was exported from. source_database_id: String = database_id(), + /// The database revision when the package was exported, 0 or more. database_revision: u64 = nonnegative_int(), + /// When the export ran, a UTC instant such as `2026-01-02T03:04:05.678Z`. Absent + /// by default, so two exports of the same database revision are byte-identical. exported_at?: String = utc_timestamp(), + /// Every other file in the package, with its hash and size. The manifest does not + /// list itself. files: Vec, + /// One count entry per record type. record_counts: Vec, + /// How many privacy erasure markers the package holds. erasure_marker_count: u64 = nonnegative_int(), /// True when the package holds only some records of its database, as a /// sync sends them (D313). It merges only into the database it came @@ -168,20 +210,27 @@ fn at(parts: &[&str], index: usize, tail: &[&str]) -> Vec { /// What the history rules read from one current record of a package file. #[derive(Debug, Clone, PartialEq)] pub struct RecordFacts { + /// The record's `record_id`. Empty when missing. pub record_id: String, + /// The record's `record_type` text. Empty when missing. pub record_type: String, + /// The record's `current_revision`. Absent when missing or not a number. pub current_revision: Option, + /// The record's `is_deleted`. False when missing. pub is_deleted: bool, /// The SHA-256 of the data as its record type outputs it. pub data_digest: Option, /// `data.source_id`, `data.quantity`, and `data.recorded_at`, which the /// series rules read. pub data_source_id: String, + /// `data.quantity`. Empty when missing. pub data_quantity: String, + /// `data.recorded_at`. Empty when missing. pub data_recorded_at: String, } impl RecordFacts { + /// The facts of one current record, given as JSON. pub fn of(record: &Value) -> Self { let data = record.get("data").unwrap_or(&Value::Null); RecordFacts { @@ -200,15 +249,21 @@ impl RecordFacts { /// What the history rules read from one retained revision. #[derive(Debug, Clone, PartialEq)] pub struct RevisionFacts { + /// The revision's `record_id`. Empty when missing. pub record_id: String, + /// The revision's `record_type` text. Empty when missing. pub record_type: String, /// The `revision` value as JSON text, which identifies a repeated revision. pub revision_text: String, + /// The `revision` value. Absent when missing or not a number. pub revision: Option, + /// The SHA-256 of the data as its record type outputs it. Absent when the record + /// type is unknown or the data is missing. pub data_digest: Option, } impl RevisionFacts { + /// The facts of one retained revision, given as JSON. pub fn of(revision: &Value) -> Self { RevisionFacts { record_id: text(revision, "record_id").to_string(), @@ -223,15 +278,20 @@ impl RevisionFacts { /// What the history rules read from one deletion record. #[derive(Debug, Clone, PartialEq)] pub struct DeletionFacts { + /// The deleted record's `record_id`. Empty when missing. pub record_id: String, + /// The deletion's `record_revision`. Absent when missing or not a number. pub record_revision: Option, } /// What the history rules read from one provider import key. #[derive(Debug, Clone, PartialEq)] pub struct ImportKeyFacts { + /// The key's `record_id`. Empty when missing. pub record_id: String, + /// The key's `match_key_method`. Empty when missing. pub match_key_method: String, + /// The key's `match_key`. Empty when missing. pub match_key: String, } @@ -240,9 +300,13 @@ pub struct ImportKeyFacts { /// not be held to check it. #[derive(Debug, Clone, Default, PartialEq)] pub struct HistoryFacts { + /// One entry per item of `records`, in file order. pub records: Vec, + /// One entry per item of `record_revisions`, in file order. pub revisions: Vec, + /// One entry per item of `record_deletions`, in file order. pub deletions: Vec, + /// One entry per item of `record_import_keys`, in file order. pub import_keys: Vec, } diff --git a/core/src/model/record.rs b/core/src/model/record.rs index d54a9c00..b069e9bb 100644 --- a/core/src/model/record.rs +++ b/core/src/model/record.rs @@ -15,7 +15,7 @@ use crate::json::{Map, Value}; use crate::model_object; macro_rules! record_types { - ($($variant:ident => $data:ident),* $(,)?) => { + ($($(#[$meta:meta])* $variant:ident => $data:ident),* $(,)?) => { /// The data object of a record, by record type. /// /// A workout is the largest variant. Records are built and read one @@ -25,10 +25,11 @@ macro_rules! record_types { #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))] #[allow(clippy::large_enum_variant)] pub enum RecordData { - $($variant($data)),* + $($(#[$meta])* $variant($data)),* } impl RecordData { + /// The record type this data belongs to. pub fn record_type(&self) -> RecordType { match self { $(RecordData::$variant(_) => RecordType::$variant),* @@ -67,38 +68,68 @@ macro_rules! record_types { } record_types! { + /// The data of an `athlete_profile` record: the athlete's profile. AthleteProfile => AthleteProfileData, + /// The data of a `source` record: who wrote measured data and by which route. Source => SourceData, + /// The data of a `source_device` record: a device behind a source's data. SourceDevice => SourceDeviceData, + /// The data of a `point_measurement` record: one measured value. PointMeasurement => PointMeasurementData, + /// The data of a `measurement_sample` record: one sample in a dense series. MeasurementSample => MeasurementSampleData, + /// The data of a `sleep_session` record: one sleep. SleepSession => SleepSessionData, + /// The data of a `workout_session` record: one workout. WorkoutSession => WorkoutSessionData, + /// The data of a `benchmark_result` record: the score of one benchmark attempt. BenchmarkResult => BenchmarkResultData, + /// The data of a `provider_summary` record: a total or duration a source reported. ProviderSummary => ProviderSummaryData, + /// The data of a `provider_score` record: a composite score from a provider. ProviderScore => ProviderScoreData, + /// The data of an `athlete_report` record: something the athlete said. AthleteReport => AthleteReportData, + /// The data of a `nutrition_entry` record: what the athlete said they ate or drank. NutritionEntry => NutritionEntryData, + /// The data of an `attachment` record: a file the athlete attached. Attachment => AttachmentData, + /// The data of a `benchmark_definition` record: a named test and its scoring. BenchmarkDefinition => BenchmarkDefinitionData, + /// The data of a `prediction` record: a predicted benchmark score. Prediction => PredictionData, + /// The data of a `prediction_result_link` record: a prediction and its result. PredictionResultLink => PredictionResultLinkData, + /// The data of a `prediction_grade` record: a prediction graded against its result. PredictionGrade => PredictionGradeData, + /// The data of a `prediction_error_analysis` record: why a prediction missed. PredictionErrorAnalysis => PredictionErrorAnalysisData, + /// The data of a `training_plan` record. TrainingPlan => TrainingPlanData, + /// The data of a `planned_session` record: one planned training session. PlannedSession => PlannedSessionData, + /// The data of a `coaching_note` record. CoachingNote => CoachingNoteData, + /// The data of a `saved_training_review` record: a review of training over a range of dates. SavedTrainingReview => SavedTrainingReviewData, + /// The data of a `goal` record. Goal => GoalData, + /// The data of a `nutrition_model_interpretation` record: a reading of a nutrition entry. NutritionModelInterpretation => NutritionModelInterpretationData, + /// The data of an `intensity_reference` record, such as a threshold. IntensityReference => IntensityReferenceData, + /// The data of an `event` record: a race or competition. Event => EventData, + /// The data of an `approval` record: the exact record versions approved. Approval => ApprovalData, + /// The data of a `calculation_result` record: one saved calculation result. CalculationResult => CalculationResultData, + /// The data of a `device_recording` record: one device's recording of one quantity. DeviceRecording => DeviceRecordingData, } -/// Which of the three record classes a type belongs to. +/// Which class of record a type belongs to: measured, athlete-reported, authored, or +/// reference. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RecordClass { /// Device or provider data. Requires a source. @@ -112,6 +143,7 @@ pub enum RecordClass { } impl RecordType { + /// The class this record type belongs to. pub fn class(self) -> RecordClass { use RecordType::*; match self { @@ -285,15 +317,24 @@ pub type Extensions = crate::json::JsonObject; #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CurrentRecord { + /// The record's ID, a lowercase UUID version 7. It never changes. pub record_id: String, + /// When the record was created, a UTC instant such as `2026-01-02T03:04:05.678Z`. pub created_at: String, + /// The number of the latest retained revision, from 1 up. pub current_revision: u64, + /// True when a normal deletion hides the record from current views. Its data and + /// history remain. pub is_deleted: bool, + /// Namespaced extension values, with keys such as `org.example/widget`. Absent when + /// the record has none. pub extensions: Option, + /// The record's complete current data. Its variant gives the record type. pub data: RecordData, } impl CurrentRecord { + /// The record's type, read from its data. pub fn record_type(&self) -> RecordType { self.data.record_type() } @@ -345,26 +386,38 @@ impl CurrentRecord { #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct RecordRevision { + /// The ID of the record this revision belongs to. pub record_id: String, + /// This revision's number, from 1 up. pub revision: u64, + /// The revision before this one: absent for revision 1, otherwise `revision - 1`. pub previous_revision: Option, + /// When this state became available to the database, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. It cannot be earlier than the previous revision's. pub became_known_at: String, + /// How this state became known to the database. pub became_known_at_basis: BecameKnownAtBasis, + /// Who made the change. pub changed_by: RecordActor, + /// The complete record data at this revision. pub data: RecordData, + /// The record's extension values at this revision. Absent when it had none. pub extensions: Option, } impl RecordRevision { + /// The record's type, read from the revision's data. pub fn record_type(&self) -> RecordType { self.data.record_type() } + /// Validate and decode a retained revision. pub fn from_value(value: &Value) -> Result { record_revision_schema().validate(value)?; Self::from_checked(value) } + /// Validate and decode a retained revision that must not be a measurement sample. pub fn from_value_non_sample(value: &Value) -> Result { non_sample_revision_schema().validate(value)?; Self::from_checked(value) @@ -387,6 +440,7 @@ impl RecordRevision { }) } + /// The revision as JSON, with fields in published order. pub fn to_value(&self) -> Value { let mut map = Map::new(); map.insert("record_id".into(), Value::String(self.record_id.clone())); @@ -419,9 +473,13 @@ fn record_type_of(value: &Value) -> Result { model_object! { /// A normal deletion. The record and its history stay; the record is hidden. pub struct RecordDeletion { + /// The ID of the deleted record. record_id: String = record_id(), + /// The revision that was current when the record was deleted. record_revision: u64 = revision_number(), + /// When the record was deleted, a UTC instant such as `2026-01-02T03:04:05.678Z`. deleted_at: String = utc_timestamp(), + /// Who deleted the record. A coach cannot delete a record. deleted_by: RecordActor, } refine(refine_deletion_actor) @@ -436,8 +494,11 @@ fn refine_deletion_actor(value: &Value, issues: &mut Vec) { model_object! { /// The value-free trace a privacy erasure leaves behind. pub struct RecordErasureMarker { + /// The ID of the erased record. record_id: String = record_id(), + /// When the record was erased, a UTC instant such as `2026-01-02T03:04:05.678Z`. erased_at: String = utc_timestamp(), + /// Why the record was erased. reason_code: ErasureReasonCode, } } @@ -445,9 +506,14 @@ model_object! { model_object! { /// A provider matching key. It is separate from the stable record ID. pub struct RecordImportKey { + /// The ID of the record this key matches. record_id: String = record_id(), + /// The versioned import recipe that made the key, such as `apple_health/v1`. match_key_method: String, + /// The key the import route builds from the source's data. One key matches one + /// record. match_key: String, + /// When the key was recorded, a UTC instant such as `2026-01-02T03:04:05.678Z`. imported_at: String = utc_timestamp(), } } @@ -585,11 +651,12 @@ pub fn non_sample_revision_schema() -> SchemaRef { &SCHEMA } -/// `MeasurementSampleRecord` and `MeasurementSampleRevision`. +/// `MeasurementSampleRecord`: the current-record shape for a measurement sample. pub fn measurement_sample_record_schema() -> SchemaRef { current_record_variant(RecordType::MeasurementSample) } +/// `MeasurementSampleRevision`: the revision shape for a measurement sample. pub fn measurement_sample_revision_schema() -> SchemaRef { revision_variant(RecordType::MeasurementSample) } diff --git a/core/src/model/recording.rs b/core/src/model/recording.rs index 011cf41f..99b6eaad 100644 --- a/core/src/model/recording.rs +++ b/core/src/model/recording.rs @@ -49,14 +49,30 @@ model_enum! { /// What a recording records. Each has one unit, except cadence, whose /// unit follows the sport (D304). pub enum RecordingQuantity { + /// Heart rate, in beats per minute (`bpm`). + /// Stored as `heart_rate`. HeartRate = "heart_rate", + /// Power, in watts (`W`). + /// Stored as `power`. Power = "power", + /// Cadence, in `rpm` for cycling, `steps/min` for running and walking, and + /// `strokes/min` for rowing, swimming, and cross-country skiing. + /// Stored as `cadence`. Cadence = "cadence", + /// Speed, in metres per second (`m/s`). + /// Stored as `speed`. Speed = "speed", + /// Distance, in metres (`m`). + /// Stored as `distance`. Distance = "distance", + /// Altitude, in metres (`m`). + /// Stored as `altitude`. Altitude = "altitude", + /// Temperature, in degrees Celsius (`°C`). + /// Stored as `temperature`. Temperature = "temperature", /// Latitude and longitude in degrees, kept together. + /// Stored as `position`. Position = "position", } } @@ -80,17 +96,23 @@ model_enum! { /// What one reading means (D305). pub enum ReadingKind { /// The value at one instant. + /// Stored as `instant`. Instant = "instant", /// A total over the reading's interval, such as energy over a minute. + /// Stored as `interval_total`. IntervalTotal = "interval_total", /// One value held over the reading's interval. + /// Stored as `interval_held`. IntervalHeld = "interval_held", /// A running total since the recording began, such as distance. + /// Stored as `counter`. Counter = "counter", } } impl ReadingKind { + /// Whether a reading of this kind covers an interval and so has a duration: + /// true for `interval_total` and `interval_held`. pub fn has_duration(self) -> bool { matches!(self, ReadingKind::IntervalTotal | ReadingKind::IntervalHeld) } @@ -100,7 +122,10 @@ model_object! { /// A timer stop: from `start_offset_ms` the device was paused, until /// `end_offset_ms`. A pause is not a gap and not a zero. pub struct RecordingPause { + /// When the timer stopped, in milliseconds after the recording's `start_at`. start_offset_ms: u64 = nonnegative_int(), + /// When the timer started again, in milliseconds after the recording's + /// `start_at`. Not before `start_offset_ms`. end_offset_ms: u64 = nonnegative_int(), } } @@ -110,13 +135,24 @@ model_object! { /// revision wrote it, how many readings it holds, and the fingerprint of /// its readings. pub struct RecordingBlockRef { + /// Which window the block covers, counted from 0. Window `n` starts + /// `n` times `window_ms` milliseconds after the recording's `start_at`. window_index: u64 = nonnegative_int(), + /// Which part of its window the block is, counted from 0. A window with + /// too many readings is split into parts. part: u64 = nonnegative_int(), /// The revision that wrote this version of the block. version: u64 = positive_int(), + /// The number of readings in the block. More than 0. reading_count: u64 = positive_int(), + /// The offset of the block's first reading, in milliseconds after the + /// recording's `start_at`. first_offset_ms: u64 = nonnegative_int(), + /// The offset of the block's last reading, in milliseconds after the + /// recording's `start_at`. Not before `first_offset_ms`. last_offset_ms: u64 = nonnegative_int(), + /// The SHA-256 of the block's stored readings text, as 64 lowercase + /// hexadecimal characters. sha256: String = sha256(), } } @@ -130,23 +166,42 @@ fn window_ms() -> SchemaRef { model_object! { /// One device's recording of one quantity (D305). pub struct DeviceRecordingData { + /// The record ID of the `source` record this recording came from. source_id: String = record_id(), + /// The source's own ID for this recording. Absent when the source gives none. provider_record_id?: String, + /// The provider's own reporting periods this recording belongs to, such as + /// a WHOOP physiological cycle or an Oura day. provider_reporting_periods?: Vec, + /// When the data was received, a UTC instant such as + /// `2026-01-02T03:04:05.678Z`. `received_at_basis` says which time it is. received_at: String = utc_timestamp(), + /// Which time `received_at` holds, such as a time the provider supplied + /// or the time of the import. received_at_basis: super::common::ReceivedAtBasis, + /// Values the source sent that have no typed field, kept under the names + /// they arrived with. supplied_fields?: super::common::SuppliedFields = super::schema::supplied_fields(), + /// On what basis the software stored some values. The software writes it; + /// the source never sends it. field_basis?: super::common::FieldBasis, + /// What the recording measures, such as power or heart rate. quantity: RecordingQuantity, + /// The unit of every reading. It must fit `quantity`: `bpm`, `W`, `rpm`, + /// `steps/min`, `strokes/min`, `m/s`, `m`, `°C`, or `deg`. unit: String, + /// What each reading means: a value at one instant, a total or a held value + /// over an interval, or a running total since the recording began. reading_kind: ReadingKind, /// The instant offset 0 stands for. start_at: String = utc_timestamp(), /// The last instant a reading covers. end_at: String = utc_timestamp(), + /// The start time as the source wrote it, and how it was read. input_start_timestamp: InputTimestampReceipt, /// The length of every window of this recording, in milliseconds. window_ms: u64 = window_ms(), + /// The number of readings: the sum of the blocks' reading counts. reading_count: u64 = nonnegative_int(), /// The workout this recording belongs to, when one is known. workout_session_id?: String = record_id(), @@ -155,7 +210,11 @@ model_object! { /// The source worked these values out instead of measuring them, such /// as a rowing machine's watts from pace (D323). computed_by_source?: bool, + /// The times the device's timer was stopped. A pause is not a gap and not + /// a zero. pauses?: Vec, + /// The blocks that hold this revision's readings, each once, in window and + /// part order. blocks: Vec, } refine(refine_recording) @@ -221,19 +280,23 @@ fn refine_recording(value: &Value, issues: &mut Vec) { pub struct Reading { /// Milliseconds after the recording's `start_at`. pub offset_ms: u64, + /// The reading's value: a number, or a position for a `position` recording. pub value: ReadingValue, /// For an interval reading: how long the interval lasts. pub duration_ms: Option, } +/// The value of one reading. #[derive(Debug, Clone, Copy, PartialEq)] pub enum ReadingValue { + /// A number in the recording's unit. Number(f64), /// Latitude and longitude in degrees. Position(f64, f64), } impl ReadingValue { + /// The number, or none for a position. pub fn number(self) -> Option { match self { ReadingValue::Number(value) => Some(value), @@ -246,13 +309,20 @@ impl ReadingValue { /// readings, durations, each in reading order. Equal offsets keep their order. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] pub struct BlockReadings { + /// Each reading's offset, in milliseconds after the recording's `start_at`. pub offsets_ms: Vec, + /// Each reading's value: a number, or `[latitude, longitude]` in degrees for a + /// position. pub values: Vec, + /// Each reading's duration, in milliseconds. Absent when no reading in the + /// block has a duration. #[serde(default, skip_serializing_if = "Option::is_none")] pub durations_ms: Option>, } impl BlockReadings { + /// The stored form of `readings`. When any reading has a duration, every + /// reading gets one, and a reading without one gets 0. pub fn from_readings(readings: &[Reading]) -> BlockReadings { let has_durations = readings.iter().any(|reading| reading.duration_ms.is_some()); BlockReadings { @@ -374,7 +444,9 @@ pub fn sha256_hex(text: &str) -> String { /// One block as written: its reference in the record and its stored readings. #[derive(Debug, Clone, PartialEq)] pub struct PlannedBlock { + /// The block's entry in the record's `blocks` list. pub block: RecordingBlockRef, + /// The block's readings as stored. pub readings: BlockReadings, } diff --git a/core/src/model/schema.rs b/core/src/model/schema.rs index a4befda3..7cb22bd8 100644 --- a/core/src/model/schema.rs +++ b/core/src/model/schema.rs @@ -23,7 +23,9 @@ pub const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0; /// One step in the location of an issue. #[derive(Debug, Clone, PartialEq, Eq)] pub enum PathSegment { + /// A field of an object, by name. Key(String), + /// A position in a list, from 0. Index(usize), } @@ -51,18 +53,28 @@ impl From for PathSegment { /// The kind of validation issue. The names match the published issue codes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IssueCode { + /// The value has the wrong JSON type, or is missing (`invalid_type`). InvalidType, + /// The value is not one of the allowed values (`invalid_value`). InvalidValue, + /// The value matches none of the allowed shapes (`invalid_union`). InvalidUnion, + /// A key of a free-form object is not allowed (`invalid_key`). InvalidKey, + /// A string does not have the required format, such as a UTC instant (`invalid_format`). InvalidFormat, + /// A number, string, or list is below its minimum (`too_small`). TooSmall, + /// A number, string, or list is above its maximum (`too_big`). TooBig, + /// An object has fields its shape does not allow (`unrecognized_keys`). UnrecognizedKeys, + /// A rule across fields failed, such as an end before its start (`custom`). Custom, } impl IssueCode { + /// The published issue code, such as `invalid_type`. pub fn as_str(self) -> &'static str { match self { IssueCode::InvalidType => "invalid_type", @@ -89,8 +101,11 @@ impl IssueCode { /// One validation problem with its location. #[derive(Debug, Clone, PartialEq)] pub struct Issue { + /// Where the problem is, from the top of the checked value. pub path: Vec, + /// The kind of problem, as the npm client's validator names it. pub code: IssueCode, + /// The message, as the npm client's validator writes it. pub message: String, } @@ -104,6 +119,7 @@ impl Issue { } } + /// The issue as `{"path": [...], "code": ..., "message": ...}`. pub fn to_json(&self) -> Value { let path: Vec = self .path @@ -120,10 +136,12 @@ impl Issue { /// A value did not match its shape. The first issue is the one shown to a person. #[derive(Debug, Clone, PartialEq)] pub struct ValidationError { + /// Every problem found, in the published order. pub issues: Vec, } impl ValidationError { + /// One `custom` problem at `path`. pub fn single(path: Vec, message: impl Into) -> Self { ValidationError { issues: vec![Issue { path, code: IssueCode::Custom, message: message.into() }] } } @@ -150,6 +168,7 @@ impl std::fmt::Display for ValidationError { impl std::error::Error for ValidationError {} +/// A shape that lives for the whole program. pub type SchemaRef = &'static Schema; /// A string format with a fixed published pattern. @@ -163,57 +182,91 @@ pub enum StringFormat { /// One check on a value that already has the right type. pub enum Check { + /// A string has at least this many characters. MinLength(usize), + /// A string has at most this many characters. MaxLength(usize), + /// A string has this format. Format(StringFormat), /// A regular-expression check. `source` is the published pattern; `test` is /// the equivalent hand-written test. Pattern { + /// The published regular expression. source: &'static str, + /// The test that accepts the same strings. test: fn(&str) -> bool, + /// The message when the test fails. message: &'static str, }, /// A string refinement that does not appear in JSON Schema. StringRefine { + /// The test a valid string passes. test: fn(&str) -> bool, + /// The message when the test fails. message: &'static str, }, + /// A number is at least, or more than, `value`. Minimum { + /// The limit. value: f64, + /// True when the limit itself is allowed. inclusive: bool, }, + /// A number is at most, or less than, `value`. Maximum { + /// The limit. value: f64, + /// True when the limit itself is allowed. inclusive: bool, }, + /// A list has at most this many items. MaxItems(usize), /// A refinement over the whole value. It appends issues with paths /// relative to the value. Refine(fn(&Value, &mut Vec)), } +/// The JSON type a shape accepts. pub enum Kind { + /// A string. String, + /// A number. Number { + /// True when only whole numbers are allowed. integer: bool, }, + /// `true` or `false`. Boolean, + /// `null`. Null, + /// One of these strings. Enum(&'static [&'static str]), + /// Exactly this string. Literal(&'static str), + /// An object with these fields and no others. Object { + /// The fields, in published order. fields: Vec, }, + /// A list whose items have this shape. Array(SchemaRef), + /// An object whose keys and values each have one shape. Record { + /// The shape of every key. key: SchemaRef, + /// The shape of every value. value: SchemaRef, }, + /// A value that matches any one of these shapes. Union(Vec), + /// An object whose shape is chosen by the string in one field. Discriminated { + /// The field that names the shape. key: &'static str, + /// Each allowed name and its shape. options: Vec<(&'static str, SchemaRef)>, }, + /// `null`, or a value with this shape. Nullable(SchemaRef), /// Any JSON value (`z.json()`). Json, @@ -221,15 +274,23 @@ pub enum Kind { ExtensionValue, } +/// One field of an object shape. pub struct Field { + /// The field's JSON name. pub name: &'static str, + /// The field's shape. pub schema: SchemaRef, + /// True when the field may be absent. pub optional: bool, } +/// A published shape: a JSON type, its checks, and an optional description. pub struct Schema { + /// The JSON type. pub kind: Kind, + /// The checks a value of that type must pass, in order. pub checks: Vec, + /// The description the published JSON Schema carries. pub description: Option<&'static str>, /// The published schema lists this description before the type. The /// original wrapped the field after describing it. @@ -237,19 +298,23 @@ pub struct Schema { } impl Schema { + /// A shape of this type with no checks. pub const fn new(kind: Kind) -> Self { Schema { kind, checks: Vec::new(), description: None, description_first: false } } + /// This shape with one more check. pub fn check(mut self, check: Check) -> Self { self.checks.push(check); self } + /// This shape with a rule over the whole value. pub fn refine(self, refine: fn(&Value, &mut Vec)) -> Self { self.check(Check::Refine(refine)) } + /// This shape with a description. pub fn describe(mut self, description: &'static str) -> Self { self.description = Some(description); self @@ -262,6 +327,7 @@ impl Schema { self } + /// An object shape's fields, or none for any other shape. pub fn fields(&self) -> &[Field] { match &self.kind { Kind::Object { fields } => fields, @@ -313,6 +379,7 @@ impl Schema { } } + /// Check a value, and return every issue when it does not match. pub fn validate(&'static self, value: &Value) -> Result<(), ValidationError> { let issues = self.issues(value); if issues.is_empty() { @@ -325,6 +392,7 @@ impl Schema { /// A type with a published shape. pub trait Shape { + /// The type's shape. fn schema() -> SchemaRef; } @@ -756,32 +824,39 @@ pub fn custom(issues: &mut Vec, path: &[&str], message: impl Into // ---- Shape constructors ------------------------------------------------- +/// Any string. pub fn string() -> Schema { Schema::new(Kind::String) } +/// Any number. pub fn number() -> Schema { Schema::new(Kind::Number { integer: false }) } +/// Any whole number. pub fn integer() -> Schema { Schema::new(Kind::Number { integer: true }) } +/// At least `value`. pub fn min(value: f64) -> Check { Check::Minimum { value, inclusive: true } } +/// At most `value`. pub fn max(value: f64) -> Check { Check::Maximum { value, inclusive: true } } +/// More than `value`. pub fn above(value: f64) -> Check { Check::Minimum { value, inclusive: false } } macro_rules! static_schema { ($name:ident, $build:expr) => { + #[doc = concat!("The shared `", stringify!($name), "` shape: `", stringify!($build), "`.")] pub fn $name() -> SchemaRef { static SCHEMA: LazyLock = LazyLock::new(|| $build); &SCHEMA @@ -927,13 +1002,17 @@ macro_rules! model_enum { } impl $name { + /// Every value, in published order. pub const ALL: &'static [$name] = &[$($name::$variant),*]; + /// Every value's stored name, in published order. pub const NAMES: &'static [&'static str] = &[$($text),*]; + /// The value's stored name. pub fn as_str(self) -> &'static str { match self { $($name::$variant => $text),* } } + /// The value with this stored name, or `None`. pub fn parse(text: &str) -> Option { match text { $($text => Some($name::$variant),)* _ => None } } diff --git a/core/src/model/time.rs b/core/src/model/time.rs index e5e4d73e..2e818e1c 100644 --- a/core/src/model/time.rs +++ b/core/src/model/time.rs @@ -18,10 +18,12 @@ fn digits(bytes: &[u8]) -> Option { Some(bytes.iter().fold(0, |total, digit| total * 10 + u32::from(digit - b'0'))) } +/// Whether a year is a leap year under the Gregorian rule. pub fn is_leap_year(year: u32) -> bool { year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) } +/// The number of days in a month of a year, for months 1 to 12. 0 for any other month. pub fn days_in_month(year: u32, month: u32) -> u32 { match month { 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, @@ -47,6 +49,7 @@ pub fn parse_calendar_date(text: &str) -> Option<(u32, u32, u32)> { Some((year, month, day)) } +/// Whether `text` is a valid calendar day, `YYYY-MM-DD`. pub fn is_calendar_date(text: &str) -> bool { parse_calendar_date(text).is_some() } @@ -75,6 +78,7 @@ pub fn parse_utc_timestamp(text: &str) -> Option { Some(((days * 24 + hour as i64) * 60 + minute as i64) * 60_000 + second as i64 * 1000 + millisecond as i64) } +/// Whether `text` is a UTC instant in the stored form, such as `2026-01-02T03:04:05.678Z`. pub fn is_utc_timestamp(text: &str) -> bool { parse_utc_timestamp(text).is_some() } @@ -122,6 +126,7 @@ pub fn now_utc() -> String { format_utc_millis(now_millis()) } +/// The current time in milliseconds since 1970-01-01 UTC. 0 when the clock reads earlier. pub fn now_millis() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) diff --git a/core/src/model/training.rs b/core/src/model/training.rs index 431989f6..1cb09541 100644 --- a/core/src/model/training.rs +++ b/core/src/model/training.rs @@ -16,14 +16,26 @@ use crate::{model_enum, model_object}; model_enum! { /// What the body is doing (D295). pub enum Sport { + /// Stored as `running`. Running = "running", + /// Stored as `walking`. Walking = "walking", + /// Stored as `cycling`. Cycling = "cycling", + /// Stored as `swimming`. Swimming = "swimming", + /// Stored as `rowing`. Rowing = "rowing", + /// Cross-country skiing. A ski erg workout is this sport with `machine: ski_erg`. + /// Stored as `cross_country_skiing`. CrossCountrySkiing = "cross_country_skiing", + /// Stored as `strength`. Strength = "strength", + /// Mixed training such as high-intensity interval training (HIIT) or cross + /// training. + /// Stored as `functional_fitness`. FunctionalFitness = "functional_fitness", + /// Stored as `other`. Other = "other", } } @@ -33,13 +45,26 @@ model_enum! { /// `unknown` means the source did not say; it never matches a threshold /// automatically. pub enum Machine { + /// No machine produced the numbers. + /// Stored as `none`. None = "none", + /// Stored as `treadmill`. Treadmill = "treadmill", + /// A stationary bike, including a smart trainer with the athlete's own bike. + /// Stored as `stationary_bike`. StationaryBike = "stationary_bike", + /// Stored as `air_bike`. AirBike = "air_bike", + /// Stored as `rowing_machine`. RowingMachine = "rowing_machine", + /// A ski erg. Its sport is `cross_country_skiing`. + /// Stored as `ski_erg`. SkiErg = "ski_erg", + /// A machine not in this list. + /// Stored as `other`. Other = "other", + /// The source did not say. It never matches a threshold automatically. + /// Stored as `unknown`. Unknown = "unknown", } } @@ -48,7 +73,10 @@ model_object! { /// Who made a machine and which model it is, as the source or the athlete /// supplied them. pub struct MachineDetails { + /// The company that made the machine. At least one of `manufacturer` and + /// `model` is present. manufacturer?: String, + /// The machine's model name. model?: String, } refine(refine_machine_details) @@ -70,9 +98,14 @@ model_object! { /// it was indoors. It says nothing about the athlete. #[cfg_attr(feature = "uniffi", uniffi(name = "TrainingEnvironment"))] pub struct Environment { + /// The altitude, in metres. altitude_m?: f64, + /// The temperature of the surroundings, in degrees Celsius. temperature_c?: f64, + /// The humidity, in percent, from 0 to 100. humidity_pct?: f64 = percent(), + /// True when the activity was indoors. Set only from an explicit indoor flag, + /// never from the machine. indoor?: bool, } refine(refine_environment) @@ -90,10 +123,18 @@ model_object! { /// (D296). The field that holds it says what it is for: a threshold /// applies after it, a block starts after it, a key effort comes after it. pub struct After { + /// The time already passed since the start, in seconds. Zero or more. time_s?: f64 = nonnegative(), + /// The distance already covered since the start, in metres. Zero or more. distance_m?: f64 = nonnegative(), + /// The work already done since the start, in kilojoules. Zero or more. work_kj?: f64 = nonnegative(), + /// The work already done above the threshold that `threshold_reference` + /// names, in kilojoules. Zero or more. Needs `threshold_reference`. work_above_threshold_kj?: f64 = nonnegative(), + /// The exact version of the threshold that `work_above_threshold_kj` is + /// counted above, as a record ID and revision. Used only with + /// `work_above_threshold_kj`. threshold_reference?: EvidenceReference, } refine(refine_after) @@ -116,8 +157,8 @@ fn refine_after(value: &Value, issues: &mut Vec) { } } -/// Check that `machine` is present wherever `sport` is (D295). `path` is the -/// path of the object that holds them. +/// Check that `machine` is present wherever `sport` or `machine_details` is +/// (D295). `path` is the path of the object that holds them. pub fn sport_needs_machine(value: &Value, path: &[&str], issues: &mut Vec) { if value.get("sport").is_some() && value.get("machine").is_none() { let mut full: Vec<&str> = path.to_vec(); @@ -136,17 +177,50 @@ pub fn sport_needs_machine(value: &Value, path: &[&str], issues: &mut Vec model_enum! { /// What an intensity reference holds. Each quantity has one unit. pub enum IntensityQuantity { + /// The power at the upper of the two thresholds, such as critical power, + /// in watts (`W`). + /// Stored as `threshold_power`. ThresholdPower = "threshold_power", + /// The heart rate at the upper of the two thresholds, in beats per minute + /// (`bpm`). + /// Stored as `threshold_heart_rate`. ThresholdHeartRate = "threshold_heart_rate", + /// The speed at the upper of the two thresholds, such as critical speed, in + /// metres per second (`m/s`). A pace is stored as a speed. + /// Stored as `threshold_speed`. ThresholdSpeed = "threshold_speed", + /// The athlete's maximum heart rate, in beats per minute (`bpm`). + /// Stored as `maximum_heart_rate`. MaximumHeartRate = "maximum_heart_rate", + /// The heaviest load for one full repetition of `movement`, in kilograms + /// (`kg`). + /// Stored as `one_rep_max`. OneRepMax = "one_rep_max", + /// The work the athlete can do above threshold power, in kilojoules (`kJ`). + /// Stored as `work_capacity_above_threshold`. WorkCapacityAboveThreshold = "work_capacity_above_threshold", + /// The highest power over a very short time, such as the best 1-second or + /// 5-second power, in watts (`W`). + /// Stored as `peak_power`. PeakPower = "peak_power", + /// A time to exhaustion, in seconds (`s`). + /// Stored as `time_to_exhaustion`. TimeToExhaustion = "time_to_exhaustion", + /// The heart rate at the aerobic threshold, the lower of the two + /// thresholds, in beats per minute (`bpm`). + /// Stored as `aerobic_threshold_heart_rate`. AerobicThresholdHeartRate = "aerobic_threshold_heart_rate", + /// The power at the aerobic threshold, the lower of the two thresholds, in + /// watts (`W`). + /// Stored as `aerobic_threshold_power`. AerobicThresholdPower = "aerobic_threshold_power", + /// The speed at the aerobic threshold, the lower of the two thresholds, in + /// metres per second (`m/s`). + /// Stored as `aerobic_threshold_speed`. AerobicThresholdSpeed = "aerobic_threshold_speed", + /// The distance the athlete can cover above threshold speed, in metres + /// (`m`). + /// Stored as `distance_capacity_above_threshold`. DistanceCapacityAboveThreshold = "distance_capacity_above_threshold", } } @@ -178,14 +252,19 @@ model_enum! { /// How an intensity reference was found (D294, D318). pub enum IntensityBasis { /// A planned test. Needs evidence. + /// Stored as `test`. Test = "test", /// A formula or a fitted model, named by `method`. + /// Stored as `model`. Model = "model", /// A setting a device holds, such as the threshold a watch uses for zones. + /// Stored as `device`. Device = "device", /// A person set it on purpose. + /// Stored as `set`. Set = "set", /// Taken from the athlete's own ordinary recordings. Needs evidence. + /// Stored as `recorded`. Recorded = "recorded", } } @@ -193,19 +272,40 @@ model_enum! { model_object! { /// One dated value that training intensity is set against (D294). pub struct IntensityReferenceData { + /// Who wrote the value, when, and whether it is in effect. Its evidence + /// lists the tests, workouts, or device values the value came from. authorship: AuthoredRecordMetadata, + /// What the value is, such as threshold power or maximum heart rate. quantity: IntensityQuantity, + /// The value, in `unit`. More than 0. value: f64 = super::schema::positive(), + /// The one unit `quantity` allows: `W`, `bpm`, `m/s`, `kg`, `kJ`, `s`, or `m`. unit: String, + /// The sport the value is for. Required for every quantity except + /// `maximum_heart_rate` and `one_rep_max`. sport?: Sport, + /// The machine the value is for. Required wherever `sport` is present. machine?: Machine, + /// Who made the machine and which model it is. Needs `machine`. machine_details?: MachineDetails, + /// The lift a `one_rep_max` is for, in the same words as strength sets, such + /// as `back squat`. Required for `one_rep_max` and used only with it. movement?: String, + /// The day the value takes effect, a calendar day, `YYYY-MM-DD`. effective_date: String = calendar_date(), + /// How the value was found: a test, a model, a device setting, a person's + /// choice, or the athlete's own recordings. basis: IntensityBasis, + /// The name of the test or model that gave the value, from an open list, + /// such as `highest_heart_rate_held_5_s`. method: String, + /// The surroundings this value is for, such as heat or altitude. A value + /// with `environment` is used only when a plan or an app names it. environment?: Environment, + /// How much was already done when this value applies. A value with `after` + /// is used only when a plan or an app names it. after?: After, + /// Free text about the value. note?: String, } refine(refine_intensity_reference) @@ -247,18 +347,27 @@ model_enum! { /// What happened at an event. Whether the record is in effect is /// `authorship.status`; this says how the event went (D299). pub enum EventCompletionStatus { + /// Stored as `planned`. Planned = "planned", + /// Stored as `completed`. Completed = "completed", + /// Stored as `skipped`. Skipped = "skipped", + /// Stored as `did_not_finish`. DidNotFinish = "did_not_finish", + /// Stored as `cancelled`. Cancelled = "cancelled", } } model_enum! { + /// How important an event is to the athlete: `A`, `B`, or `C`. pub enum EventPriority { + /// Stored as `A`. A = "A", + /// Stored as `B`. B = "B", + /// Stored as `C`. C = "C", } } @@ -266,11 +375,18 @@ model_enum! { model_object! { /// One piece of an event. Its label matches the result's segment label. pub struct EventSegment { + /// The segment's name, such as `run 1`. It is the same as the label of the + /// matching segment in the result. label: String, + /// What the body does in this segment. sport: Sport, + /// The machine used in this segment, or `none`. machine: Machine, + /// Who made the machine and which model it is. machine_details?: MachineDetails, + /// The segment's distance, in metres. More than 0. distance_m?: f64 = super::schema::positive(), + /// How long the segment is expected to take, in seconds. More than 0. expected_duration_s?: f64 = super::schema::positive(), } } @@ -278,8 +394,11 @@ model_object! { model_object! { /// A part of the event that matters, and how far into it it comes. pub struct KeyEffort { + /// What the effort is, in words. description: String, + /// How much of the event is already done when the effort comes. after?: After, + /// How long the effort is expected to last, in seconds. More than 0. expected_duration_s?: f64 = super::schema::positive(), } } @@ -287,18 +406,34 @@ model_object! { model_object! { /// A race or competition (D299). pub struct EventData { + /// Who wrote the event, when, and whether the record is in effect. How the + /// event went is `completion_status`. authorship: AuthoredRecordMetadata, + /// The event's name. title: String, + /// What happened at the event, such as `completed` or `did_not_finish`. completion_status: EventCompletionStatus, + /// The first day of the event, a calendar day, `YYYY-MM-DD`. start_date: String = calendar_date(), + /// The last day of the event, `YYYY-MM-DD`. Not before `start_date`. end_date?: String = calendar_date(), + /// When the event starts, a UTC instant such as `2026-01-02T03:04:05.678Z`. + /// Absent when the start time is not known. start_at?: String = utc_timestamp(), + /// How important the event is: `A`, `B`, or `C`. priority?: EventPriority, + /// The kind of event, as free text, such as `fitness_race`. event_type?: String, + /// The pieces of the event, at least one, each with its sport and machine. segments: Vec, + /// The surroundings expected at the event, such as temperature or altitude. expected_environment?: Environment, + /// The parts of the event that matter, and how far into it each comes. key_efforts?: Vec, + /// Free text about the event. description?: String, + /// The record IDs of the workouts or benchmark results from the event, each + /// listed once. result_record_ids?: Vec = super::common::record_id_array(), } refine(refine_event) @@ -330,8 +465,14 @@ fn refine_event(value: &Value, issues: &mut Vec) { model_object! { /// The exact versions a coach or the athlete approved (D293). pub struct ApprovalData { + /// Who approved, when, and whether the approval is in effect. The author is + /// a coach or the athlete. `status` is `active` or `cancelled`. authorship: AuthoredRecordMetadata, + /// The exact record versions approved, each as a record ID and revision. At + /// least one, each listed once. Each is an authored record other than an + /// approval. subjects: Vec, + /// The approver's comment. note?: String, } refine(refine_approval) @@ -377,7 +518,10 @@ fn refine_approval(value: &Value, issues: &mut Vec) { model_object! { /// One setting a calculation method used. pub struct CalculationParameter { + /// The setting's name, such as `window_days`. Each name appears once in a + /// result. name: String, + /// The value the method used for the setting, as any JSON value. value: crate::json::JsonValue = super::schema::json_value(), } } @@ -385,8 +529,12 @@ model_object! { model_object! { /// One value a calculation produced. pub struct CalculationValue { + /// The value's name, such as `threshold_power`. name: String, + /// The number. A true or false label is saved as 1 or 0. value: f64, + /// The value's unit, such as `W`. A true or false label has the unit + /// `boolean`. unit: String, } } @@ -395,14 +543,28 @@ model_object! { /// One saved calculation result (D308). Its evidence lists every record /// and revision the calculation read. pub struct CalculationResultData { + /// Who saved the result, when, and whether it is in effect. Its evidence + /// lists every record and revision the calculation read, at least one. authorship: AuthoredRecordMetadata, + /// The calculation's name, such as `critical-power`. calculation: String, + /// The operation name of the method that ran, such as + /// `critical_power_hyperbolic`. method: String, + /// The SHA-256 of the calculation file that ran, as 64 lowercase hexadecimal + /// characters. method_file_sha256?: String = super::common::sha256(), + /// Every setting the method used, each name once. May be empty. parameters: Vec, + /// The start of the period the calculation covered, a calendar day, + /// `YYYY-MM-DD`. period_start?: String = calendar_date(), + /// The end of the period the calculation covered, `YYYY-MM-DD`. Not before + /// `period_start`. period_end?: String = calendar_date(), + /// The values the calculation produced, at least one. results: Vec, + /// Free text about the result. note?: String, } refine(refine_calculation_result) @@ -439,12 +601,16 @@ model_enum! { /// of `record_links`, which erasure follows (D107). pub enum RecordLinkRole { /// A version an approval approves (D293). + /// Stored as `approval_subject`. ApprovalSubject = "approval_subject", /// A workout or benchmark result of an event (D299). + /// Stored as `event_result`. EventResult = "event_result", /// The one intensity reference a target is pinned to (D300). + /// Stored as `target_reference`. TargetReference = "target_reference", /// The threshold an `after` value counts work above (D296). + /// Stored as `after_threshold`. AfterThreshold = "after_threshold", } } @@ -452,7 +618,9 @@ model_enum! { /// One reference from inside a record's data. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RecordLink { + /// Why the record names the other record. pub role: RecordLinkRole, + /// The record ID of the record named. pub record_id: String, /// The exact revision, or none when the reference names only the record. pub revision: Option, @@ -471,6 +639,8 @@ fn after_links(after: Option<&After>, links: &mut Vec) { } impl IntensityReferenceData { + /// The records this value names from inside its data: the threshold in + /// `after`, when there is one. pub fn record_links(&self) -> Vec { let mut links = Vec::new(); after_links(self.after.as_ref(), &mut links); @@ -479,6 +649,8 @@ impl IntensityReferenceData { } impl EventData { + /// The records this event names from inside its data: the threshold in each + /// key effort's `after`, and each record in `result_record_ids`. pub fn record_links(&self) -> Vec { let mut links = Vec::new(); for effort in self.key_efforts.iter().flatten() { @@ -492,6 +664,7 @@ impl EventData { } impl ApprovalData { + /// The record versions this approval names: one link for each subject. pub fn record_links(&self) -> Vec { self.subjects.iter().map(|subject| RecordLink::exact(RecordLinkRole::ApprovalSubject, subject)).collect() } @@ -503,22 +676,32 @@ model_enum! { /// How a group of blocks runs. pub enum GroupFormat { /// A set number of rounds. + /// Stored as `rounds`. Rounds = "rounds", /// As many rounds as possible in `time_cap_s`. + /// Stored as `amrap`. Amrap = "amrap", /// A new round starts every `round_interval_s`. + /// Stored as `emom`. Emom = "emom", /// The work done as fast as possible, with an optional `time_cap_s`. + /// Stored as `for_time`. ForTime = "for_time", } } model_enum! { + /// What a planned block is for in its session. pub enum BlockRole { + /// Stored as `warm_up`. WarmUp = "warm_up", + /// Stored as `work`. Work = "work", + /// Stored as `recovery`. Recovery = "recovery", + /// Stored as `rest`. Rest = "rest", + /// Stored as `cool_down`. CoolDown = "cool_down", } } @@ -526,22 +709,46 @@ model_enum! { model_enum! { /// What ends a block. pub enum EndsBy { + /// Stored as `time`. Time = "time", + /// Stored as `distance`. Distance = "distance", + /// Stored as `reps`. Reps = "reps", + /// Stored as `energy`. Energy = "energy", + /// Stored as `open`. Open = "open", } } model_enum! { + /// What a planned target measures. Each has its own unit, and most may also be + /// a percent of an intensity reference. pub enum TargetQuantity { + /// Power, in `W` or as a percent of a power intensity reference. + /// Stored as `power`. Power = "power", + /// Heart rate, in `bpm` or as a percent of a heart rate intensity reference. + /// Stored as `heart_rate`. HeartRate = "heart_rate", + /// Speed, in `m/s` or as a percent of a speed intensity reference. + /// Stored as `speed`. Speed = "speed", + /// Cadence, in `rpm`, `steps/min`, or `strokes/min`. Never a percent. + /// Stored as `cadence`. Cadence = "cadence", + /// A load, always as a percent of `one_rep_max`. A fixed load goes in + /// `planned_weight_kg`. + /// Stored as `load`. Load = "load", + /// An effort rating. Its unit is the name of the rating scale, such as + /// `rpe_1_10`. + /// Stored as `effort`. Effort = "effort", + /// How much of the work capacity above threshold power to use, in `kJ` or as + /// a percent of `work_capacity_above_threshold`. Needs `method`. + /// Stored as `work_capacity_used`. WorkCapacityUsed = "work_capacity_used", } } @@ -586,12 +793,25 @@ model_object! { /// A range a block asks for: fixed, or a percent of an intensity reference /// (D300). One value is written as the same number twice. pub struct PlannedTarget { + /// What the target measures. quantity: TargetQuantity, + /// The low end of the range, in `unit`. Zero or more. low: f64, + /// The high end of the range, in `unit`. Not below `low`. One value is the + /// same number in `low` and `high`. high: f64, + /// The unit of `low` and `high`: the quantity's own unit, or `%` for a + /// percent of an intensity reference. unit: String, + /// For a `%` target: the intensity reference quantity it is a percent of, + /// such as `threshold_power`. Required with `%` and used only with it. relative_to?: IntensityQuantity, + /// For a `%` target: one exact intensity reference version to use, as a + /// record ID and revision. When absent, the target uses the value in effect + /// on the session date, as known when the session started. relative_to_record?: EvidenceReference, + /// The name of the method that works out the target. Required for + /// `work_capacity_used`. method?: String, } refine(refine_target) @@ -653,27 +873,57 @@ macro_rules! planned_block { model_object! { $(#[$meta])* pub struct $name { + /// The kind of block, as free text, such as `warm_up`, `strength`, or + /// `skill`. block_type: String, + /// The block's short name. title: String, + /// What to do in the block, as free text. instructions?: String, + /// The planned length of the block, in seconds. More than 0. planned_duration_s?: f64 = super::schema::positive(), + /// The planned distance, in metres. More than 0. planned_distance_m?: f64 = super::schema::positive(), + /// The planned number of repetitions. More than 0. planned_reps?: u64 = super::schema::positive_int(), + /// The planned fixed load, in kilograms. More than 0. planned_weight_kg?: f64 = super::schema::positive(), $($children)* + /// How the group of child `blocks` runs. Required with `blocks` and + /// used only with them. group_format?: GroupFormat, + /// The number of rounds. Required for `rounds`. Allowed for `emom` and + /// `for_time`. Not allowed for `amrap`. round_count?: u64 = super::schema::positive_int(), + /// The time limit, in seconds. Required for `amrap`. Allowed for + /// `for_time`. More than 0. time_cap_s?: f64 = super::schema::positive(), + /// The time from the start of one round to the start of the next, in + /// seconds. Required for `emom` and used only with it. round_interval_s?: f64 = super::schema::positive(), + /// What the block is for in the session, such as warm-up or work. block_role?: BlockRole, + /// The movement, in the same words as strength sets, such as + /// `back squat`. movement?: String, + /// What the body does in this block. A target relative to a threshold + /// needs a sport here, on a parent block, or on the session. sport?: Sport, + /// The machine used in this block. Required wherever `sport` is present. machine?: Machine, + /// Who made the machine and which model it is. Needs `machine`. machine_details?: MachineDetails, + /// The planned repetitions for each round, each more than 0. With + /// `round_count`, it lists one number for each round. reps_by_round?: Vec = reps_by_round(), + /// The planned energy, in kilocalories, such as a calorie amount on a + /// rowing machine. More than 0. planned_energy_kcal?: f64 = super::schema::positive(), + /// What ends the block: time, distance, reps, energy, or `open`. ends_by?: EndsBy, + /// The ranges the block asks for. At least one when present. targets?: Vec, + /// How much of the session is already done when this block starts. after?: After, } refine($refine) @@ -747,11 +997,16 @@ planned_block!( /// A block inside a group (D300). PlannedChildBlock, refine_block, - [blocks?: Vec,] + [ + /// The child blocks, run as a group as `group_format` says. At least one + /// when present. + blocks?: Vec, + ] ); -/// Every target in a block and its children, with whether a sport and machine -/// apply to it from the block, a parent block, or the session. +/// Add to `links` every record a block and its children name from inside their +/// data: the threshold in each `after`, and the intensity reference each target +/// pins with `relative_to_record`. pub fn block_target_links(block: &Value, links: &mut Vec) { if let Some(after) = block.get("after") { if let Some(reference) = after.get("threshold_reference") { @@ -807,8 +1062,15 @@ pub fn threshold_targets_need_sport(block: &Value, inherited: bool, path: &mut V model_enum! { /// How many follow-up questions to ask (D298). pub enum FollowUpQuestions { + /// Ask every question. + /// Stored as `ask_all`. AskAll = "ask_all", + /// Ask only the questions that change which records are saved. + /// Stored as `ask_required_only`. AskRequiredOnly = "ask_required_only", + /// Ask nothing. An agent may answer a question marked assumable from + /// context, and the value is labelled as assumed. Other fields stay empty. + /// Stored as `ask_none`. AskNone = "ask_none", } } @@ -816,8 +1078,11 @@ model_enum! { model_object! { /// The machine the athlete uses for a sport unless they say otherwise. pub struct MachineDefault { + /// The sport this default is for. sport: Sport, + /// The machine the athlete uses for that sport unless they say otherwise. machine: Machine, + /// Who made the machine and which model it is. machine_details?: MachineDetails, } } @@ -826,9 +1091,14 @@ model_object! { /// The athlete's own statements about how they train and want to be /// asked (D297). An agent saves them only after the athlete confirms. pub struct AthletePreferences { + /// The athlete's main sports, each listed once. main_sports?: Vec, + /// The usual machine for each sport, with each sport listed once. machine_defaults?: Vec, + /// How many follow-up questions to ask. When absent, every question is + /// asked. follow_up_questions?: FollowUpQuestions, + /// How the athlete wants to be spoken to, as free text. communication?: String, } refine(refine_preferences) @@ -858,11 +1128,22 @@ fn refine_preferences(value: &Value, issues: &mut Vec) { // ---- Original file fingerprint (spec section 4.6, D307) ------------------- model_enum! { + /// The format of a workout's original file. pub enum OriginalFileFormat { + /// A FIT activity file (`.fit`). + /// Stored as `fit`. Fit = "fit", + /// A GPX file (`.gpx`). + /// Stored as `gpx`. Gpx = "gpx", + /// A TCX file (`.tcx`). + /// Stored as `tcx`. Tcx = "tcx", + /// An Apple Health export. + /// Stored as `apple_health_export`. AppleHealthExport = "apple_health_export", + /// Any other format. + /// Stored as `other`. Other = "other", } } @@ -870,7 +1151,11 @@ model_enum! { model_enum! { /// Whether the file holds this workout or a whole account export. pub enum OriginalFileScope { + /// A file that holds this workout, such as one FIT file. + /// Stored as `workout`. Workout = "workout", + /// A whole account export that holds this workout among other data. + /// Stored as `account_export`. AccountExport = "account_export", } } @@ -879,11 +1164,18 @@ model_object! { /// The fingerprint of the smallest file that holds the workout. The file /// itself is not kept (D153, D307). pub struct OriginalFile { + /// The SHA-256 of the file's bytes, as 64 lowercase hexadecimal characters. sha256: String = super::common::sha256(), + /// The file's format. format: OriginalFileFormat, + /// The file's size, in bytes. More than 0. byte_count: u64 = super::schema::positive_int(), + /// The file's name. file_name?: String, + /// The file's path inside a zip archive. Absent when the file was not in + /// a zip archive. entry?: String, + /// Whether the file holds this workout or a whole account export. scope: OriginalFileScope, } } @@ -891,24 +1183,38 @@ model_object! { // ---- Injury and illness reports (spec section 4.9, D310) ------------------ model_enum! { + /// Which side of the body an injury is on. Used only on an injury report. pub enum Side { + /// Stored as `left`. Left = "left", + /// Stored as `right`. Right = "right", + /// Stored as `both`. Both = "both", } } model_enum! { + /// How an injury or illness started. pub enum Onset { + /// Stored as `sudden`. Sudden = "sudden", + /// Stored as `gradual`. Gradual = "gradual", } } model_enum! { + /// Whether an injury or illness is new, ongoing, or resolved. pub enum ProblemStatus { + /// The first report of this problem. + /// Stored as `new`. New = "new", + /// A later report of a problem already reported. `first_report_id` names + /// the first report. + /// Stored as `ongoing`. Ongoing = "ongoing", + /// Stored as `resolved`. Resolved = "resolved", } } @@ -916,8 +1222,11 @@ model_enum! { model_enum! { /// How much the problem changed training over the past 7 days. pub enum TrainingImpact { + /// Stored as `full`. Full = "full", + /// Stored as `reduced`. Reduced = "reduced", + /// Stored as `none`. None = "none", } } @@ -979,5 +1288,9 @@ planned_block!( /// A block of a planned session. It may hold a group of child blocks (D300). PlannedSessionBlock, refine_block, - [blocks?: Vec,] + [ + /// The child blocks, run as a group as `group_format` says. At least one + /// when present. + blocks?: Vec, + ] ); diff --git a/core/src/save.rs b/core/src/save.rs index 48a03e23..99fcf4cc 100644 --- a/core/src/save.rs +++ b/core/src/save.rs @@ -18,16 +18,22 @@ pub const SQL_SCHEMA_VERSION: u32 = 9; #[derive(Debug, Clone, PartialEq, serde::Serialize)] #[serde(untagged)] pub enum Sql { + /// SQL `NULL`. Null, + /// A whole number. Integer(i64), + /// A floating-point number. Real(f64), + /// Text. Text(String), } /// One statement and its values, in order. #[derive(Debug, Clone, PartialEq, serde::Serialize)] pub struct Statement { + /// The SQL text, with `?` placeholders for the values. pub sql: String, + /// The values for the placeholders, in order. pub values: Vec, } @@ -377,11 +383,13 @@ pub fn typed_columns(data: &RecordData) -> Vec<(&'static str, Sql)> { /// Rows in one child table that belong to a record. pub struct ChildRows { + /// The child table's name. pub table: &'static str, /// The column that names the owning record. pub owner_column: &'static str, /// Column names after the owner column. pub columns: &'static [&'static str], + /// One list of values per row, in `columns` order, without the owner column. pub rows: Vec>, } @@ -591,14 +599,17 @@ fn attachment_links(data: &RecordData) -> ChildRows { /// Which optional tables and columns exist at a SQL schema step. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Layout { + /// The database's SQL schema step. pub sql_schema_version: u32, } impl Layout { + /// The layout of the SQL schema step this core writes. pub fn current() -> Self { Layout { sql_schema_version: SQL_SCHEMA_VERSION } } + /// Whether a typed table has a column at this step. pub fn has_column(self, table: &str, column: &str) -> bool { let before_step_3 = self.sql_schema_version < 3 && table == "workout_sessions" && STEP_3_WORKOUT_COLUMNS.contains(&column); @@ -607,6 +618,7 @@ impl Layout { !(before_step_3 || before_step_6 || before_step_8) } + /// Whether a table exists at this step. pub fn has_table(self, table: &str) -> bool { let before_step_3 = self.sql_schema_version < 3 && table == "workout_route_points"; let before_step_7 = self.sql_schema_version < 7 diff --git a/core/src/thresholds.rs b/core/src/thresholds.rs index c599fe6b..88bbe823 100644 --- a/core/src/thresholds.rs +++ b/core/src/thresholds.rs @@ -105,7 +105,11 @@ fn serialize_date(date: &NaiveDate, serializer: S) -> Resu /// A refusal: the operation it came from and a plain sentence saying why. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct ThresholdError { + /// The operation that refused, such as `critical_power_hyperbolic`. + /// It is `threshold` when the operation name itself is not known. pub operation: &'static str, + /// A plain sentence that says why, such as "needs a best effort of 720 s or + /// longer". pub message: String, } @@ -300,7 +304,10 @@ pub fn check_sport_machine(operation: &str, sport: &str, machine: &str) -> Resul #[derive(Debug, Clone, Copy, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct BestEffort { + /// The effort's duration in seconds. pub duration_s: f64, + /// The best mean over that duration: power in watts (W) for the power + /// methods, or speed in metres per second (m/s) for the speed methods. pub mean: f64, } @@ -309,9 +316,15 @@ pub struct BestEffort { #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortOrigin { + /// The ID of the workout record the effort came from. pub workout: String, + /// The ID of the source record (the device or app) that wrote the + /// recording the effort came from. pub source: String, + /// Where the effort starts, in milliseconds since 1970-01-01 UTC. pub start_ms: i64, + /// Where the effort ends, in milliseconds since 1970-01-01 UTC. The effort + /// runs up to this instant, not including it. pub end_ms: i64, } @@ -319,8 +332,16 @@ pub struct EffortOrigin { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct EffortLabels { + /// The number of distinct workouts the efforts came from. A value of 1 + /// means every effort came from one workout, which is reliable only for a + /// dedicated test with recovery between the efforts. pub rides_used: u64, + /// The number of effort pairs whose time ranges overlap, such as a + /// best 7 minutes inside the best 12 minutes. Such efforts are not + /// independent; the fit still runs. pub overlapping_efforts: u64, + /// The number of distinct sources (devices or apps) the efforts came from. + /// More than 1 means two power meters or two watches were combined. pub sources_used: u64, } @@ -872,32 +893,48 @@ fn three_parameter( /// The result of a two-parameter critical power fit (main study 5.2, /// supplement 4.1 and 4.2). The nonlinear form adds `iterations`, -/// `sum_of_squares` (s²), and its starting values. +/// `sum_of_squares`, and its starting values. `sum_of_squares` is the final +/// sum of squared errors, in seconds squared; it is not the variance. #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CriticalPowerResult { + /// The operation that made this result: `critical_power_linear_work_time`, + /// `critical_power_linear_inverse_time`, or `critical_power_hyperbolic`. pub operation: String, - /// W. + /// The critical power (`CP`) from the fit, in watts: the highest power that can be held + /// without steadily using up a limited store of work. pub threshold_power: f64, - /// kJ. + /// The work capacity above critical power (`W′`) from the fit, in kilojoules: the limited + /// amount of extra work that can be done above critical power before stopping. pub work_capacity_above_threshold: f64, - /// W. + /// The standard error of `threshold_power`, in watts. pub threshold_power_standard_error: f64, - /// %. + /// The standard error of `threshold_power` as a percentage of it. pub threshold_power_standard_error_pct: f64, - /// kJ. + /// The standard error of `work_capacity_above_threshold`, in kilojoules. pub work_capacity_above_threshold_standard_error: f64, - /// %. + /// The standard error of `work_capacity_above_threshold` as a percentage of it. pub work_capacity_above_threshold_standard_error_pct: f64, + /// True when the standard error of `threshold_power` is at most 5 % of it + /// and the standard error of `work_capacity_above_threshold` is at most + /// 10 % of it. pub fit_acceptable: bool, + /// The iteration at which the nonlinear fit converged, from 1 to 100. + /// Present only for `critical_power_hyperbolic`. #[serde(skip_serializing_if = "Option::is_none")] pub iterations: Option, + /// The final sum of squared errors between the effort durations and the + /// fitted durations, in seconds squared. Present only for + /// `critical_power_hyperbolic`, which fits on time. #[serde(skip_serializing_if = "Option::is_none")] pub sum_of_squares: Option, - /// Starting `CP` in W, unrounded, for a reader to repeat the fit. + /// The starting critical power for the nonlinear fit, in watts, unrounded, + /// so a reader can repeat the fit. Present only for + /// `critical_power_hyperbolic`. #[serde(skip_serializing_if = "Option::is_none")] pub start_threshold: Option, - /// Starting `W′` in J, unrounded. + /// The starting work capacity above critical power for the nonlinear fit, + /// in joules, unrounded. Present only for `critical_power_hyperbolic`. #[serde(skip_serializing_if = "Option::is_none")] pub start_capacity: Option, /// The efforts used, in order of increasing duration. @@ -960,30 +997,54 @@ pub fn critical_power_hyperbolic(efforts: &[BestEffort]) -> Result, } @@ -1028,24 +1089,45 @@ pub fn critical_power_three_parameter( #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CriticalSpeedResult { + /// The operation that made this result: + /// `critical_speed_linear_distance_time`, `critical_speed_linear_inverse_time`, + /// or `critical_speed_hyperbolic`. pub operation: String, - /// m/s. + /// The critical speed (`CS`) from the fit, in m/s. pub threshold_speed: f64, - /// m. + /// The distance that can be covered above critical speed (`D′`), from the fit, in metres. pub distance_above_threshold: f64, + /// The standard error of `threshold_speed`, in m/s. pub threshold_speed_standard_error: f64, + /// The standard error of `threshold_speed` as a percentage of it. pub threshold_speed_standard_error_pct: f64, + /// The standard error of `distance_above_threshold`, in metres. pub distance_above_threshold_standard_error: f64, + /// The standard error of `distance_above_threshold` as a percentage of it. pub distance_above_threshold_standard_error_pct: f64, + /// True when the standard error of `threshold_speed` is at most 5 % of it + /// and the standard error of `distance_above_threshold` is at most 10 % of + /// it. pub fit_acceptable: bool, + /// The iteration at which the nonlinear fit converged, from 1 to 100. + /// Present only for `critical_speed_hyperbolic`. #[serde(skip_serializing_if = "Option::is_none")] pub iterations: Option, + /// The final sum of squared errors between the effort durations and the + /// fitted durations, in seconds squared. Present only for + /// `critical_speed_hyperbolic`, which fits on time. #[serde(skip_serializing_if = "Option::is_none")] pub sum_of_squares: Option, + /// The starting threshold speed for the nonlinear fit, in m/s, + /// unrounded, so a reader can repeat the fit. Present only for + /// `critical_speed_hyperbolic`. #[serde(skip_serializing_if = "Option::is_none")] pub start_threshold: Option, + /// The starting distance above threshold for the nonlinear fit, in + /// metres, unrounded. Present only for `critical_speed_hyperbolic`. #[serde(skip_serializing_if = "Option::is_none")] pub start_capacity: Option, + /// The efforts used, in order of increasing duration. pub efforts: Vec, } @@ -1105,29 +1187,52 @@ pub fn critical_speed_hyperbolic(efforts: &[BestEffort]) -> Result, } @@ -1171,11 +1276,15 @@ pub fn critical_speed_three_parameter( #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct FractionOf20MinuteResult { + /// The operation that made this result: always `fraction_of_best_20_minute_power`. pub operation: String, - /// W. + /// The threshold power, in watts: `fraction` × `best_20_minute_power`. pub threshold_power: f64, - /// W. + /// The best mean power over a fully recorded 1200 seconds (20 minutes) + /// in the window, in watts. pub best_20_minute_power: f64, + /// The fraction of `best_20_minute_power` taken as the threshold, from 0.80 + /// to 1.00. The default is 0.95. pub fraction: f64, } @@ -1183,11 +1292,15 @@ pub struct FractionOf20MinuteResult { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct FractionOf8MinuteResult { + /// The operation that made this result: always `fraction_of_best_8_minute_power`. pub operation: String, - /// W. + /// The threshold power, in watts: `fraction` × `best_8_minute_power`. pub threshold_power: f64, - /// W. + /// The best mean power over a fully recorded 480 seconds (8 minutes) + /// in the window, in watts. pub best_8_minute_power: f64, + /// The fraction of `best_8_minute_power` taken as the threshold, from 0.80 + /// to 1.00. The default is 0.90. pub fraction: f64, } @@ -1342,20 +1455,29 @@ fn check_test_interval(operation: &'static str, interval_ms: i64) -> Result<(), #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThreeMinuteCyclingResult { + /// The operation that made this result: always `three_minute_all_out_cycling_test`. pub operation: String, - /// W. + /// The end-test power, in watts: the mean power over the last 30 s of the 180 s test. + /// It is the test's estimate of critical power. pub threshold_power: f64, - /// kJ. + /// The work above end-test power in the first 150 s, in kilojoules: the work over + /// the first 150 s minus `threshold_power` × 150 s. pub work_capacity_above_threshold: f64, - /// W. + /// The mean power over the first 150 s of the test, in watts. pub mean_power_first_150_s: f64, - /// W. + /// The mean power over the whole 180 s test, in watts. pub mean_power_180_s: f64, - /// Seconds from the start to the first highest reading. + /// Seconds from the test start to the first highest power reading. Over 30 s + /// suggests the athlete did not start all out. pub highest_reading_time_s: f64, - /// W. + /// The mean power over the first 30 s of the test, in watts. pub mean_first_30_s: f64, + /// `mean_first_30_s` divided by `threshold_power`. A value near 1 means + /// the athlete paced the effort, so the test is not valid. pub end_test_ratio: f64, + /// How the bike set resistance during the test: `fixed_resistance`, + /// `constant_cadence`, or `free` (the rider changes gear, or the trainer + /// sets no mode). pub resistance_mode: String, } @@ -1363,18 +1485,26 @@ pub struct ThreeMinuteCyclingResult { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThreeMinuteRowingResult { + /// The operation that made this result: always `three_minute_all_out_rowing_test`. pub operation: String, - /// W. + /// The end-test power, in watts: the mean power over the last 30 s of the 180 s test. + /// It is the test's estimate of critical power. pub threshold_power: f64, - /// kJ. Stays in the calculation result only. + /// The work above end-test power in the first 150 s, in kilojoules. It did not track + /// `W′` in the one study of this test, so it stays in the calculation result and is + /// never saved. pub work_above_end_test_power: f64, - /// W. + /// The mean power over the first 150 s of the test, in watts. pub mean_power_first_150_s: f64, - /// W. + /// The mean power over the whole 180 s test, in watts. pub mean_power_180_s: f64, + /// Seconds from the test start to the first highest power reading. Over 30 s + /// suggests the athlete did not start all out. pub highest_reading_time_s: f64, - /// W. + /// The mean power over the first 30 s of the test, in watts. pub mean_first_30_s: f64, + /// `mean_first_30_s` divided by `threshold_power`. A value near 1 means + /// the athlete paced the effort, so the test is not valid. pub end_test_ratio: f64, } @@ -1468,17 +1598,23 @@ pub fn three_minute_all_out_rowing_test( #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThreeMinuteRunningResult { + /// The operation that made this result: always `three_minute_all_out_running_test`. pub operation: String, - /// m/s. + /// The end-test speed, in m/s: the distance covered in the last 30 s of the + /// 180 s test, divided by 30 s. It is the test's estimate of critical speed. pub threshold_speed: f64, - /// m. + /// The distance covered above end-test speed in the first 150 s, in metres: the + /// distance over the first 150 s minus `threshold_speed` × 150 s. pub distance_above_threshold: f64, - /// m/s. + /// The mean speed over the first 150 s of the test, in m/s. pub mean_speed_first_150_s: f64, - /// Start of the fastest stretch between two distance readings. + /// Seconds from the test start to the start of the fastest stretch between two + /// distance readings. Over 30 s suggests the athlete did not start all out. pub highest_reading_time_s: f64, - /// m/s. + /// The mean speed over the first 30 s of the test, in m/s. pub mean_first_30_s: f64, + /// `mean_first_30_s` divided by `threshold_speed`. A value near 1 means + /// the athlete paced the effort, so the test is not valid. pub end_test_ratio: f64, } @@ -1535,8 +1671,13 @@ pub fn three_minute_all_out_running_test( /// its elapsed time, and its start instant. #[derive(Debug, Clone, Copy, PartialEq, Serialize)] pub struct Swim { + /// The swim's distance in metres. It must be exactly 400 for the 400 m + /// swim and exactly 200 for the 200 m swim. pub distance_m: f64, + /// The swim's elapsed time in seconds. It must be more than 0. pub elapsed_s: f64, + /// When the swim started, in milliseconds since 1970-01-01 UTC. The two + /// swims must start no more than 7 days apart. pub start_ms: i64, } @@ -1544,14 +1685,18 @@ pub struct Swim { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct CriticalSwimSpeedResult { + /// The operation that made this result: always `critical_swim_speed_400_and_200_m`. pub operation: String, - /// m/s. + /// The critical swim speed, in m/s: 200 m divided by the 400 m time minus + /// the 200 m time. pub threshold_speed: f64, - /// m. Stays in the calculation result only. + /// The distance that can be covered above critical swim speed (`D′`), in metres: + /// 400 m minus `threshold_speed` × the 400 m time. It was not reliable in studies, + /// so it stays in the calculation result and is never saved. pub distance_above_threshold: f64, - /// s. + /// The elapsed time of the 400 m swim, in seconds. pub time_400_m: f64, - /// s. + /// The elapsed time of the 200 m swim, in seconds. pub time_200_m: f64, } @@ -1599,16 +1744,21 @@ pub fn critical_swim_speed_400_and_200_m( #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ThirtyMinuteTimeTrialResult { + /// The operation that made this result: always `thirty_minute_running_time_trial`. pub operation: String, - /// m/s. + /// The threshold speed, in m/s: the distance covered in the 30 minutes + /// divided by 1800 s. pub threshold_speed: f64, - /// bpm. + /// The threshold heart rate, in beats per minute: the time-weighted + /// mean heart rate over the whole 30 minutes. pub threshold_heart_rate: f64, - /// m. + /// The distance covered in the 30 minutes, in metres. pub distance_30_min: f64, - /// bpm. + /// The time-weighted mean heart rate over the first 10 minutes, in beats per + /// minute. With `heart_rate_last_20_min`, it shows how far heart rate rose. pub heart_rate_first_10_min: f64, - /// bpm. + /// The time-weighted mean heart rate over the last 20 minutes, in + /// beats per minute. pub heart_rate_last_20_min: f64, } @@ -1655,7 +1805,9 @@ pub fn thirty_minute_running_time_trial( #[serde(into = "(i64, f64)")] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct TimedReading { + /// Milliseconds from the recording's start. pub offset_ms: i64, + /// The reading's value, such as power in watts. pub value: f64, } @@ -1674,7 +1826,12 @@ impl From<(i64, f64)> for TimedReading { /// One power recording in the window: `(offset_ms, watts)` and its interval. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct PowerRecording { + /// The power readings, each as `(offset_ms, watts)`: milliseconds from the + /// recording's start, and the power. pub readings: Vec<(i64, f64)>, + /// The recording interval in milliseconds. Each reading counts until the + /// next reading or for this long, whichever is shorter. A recording with + /// an interval of 0 or less is skipped. pub interval_ms: i64, } @@ -1682,13 +1839,19 @@ pub struct PowerRecording { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct PeakPowerResult { + /// The operation that made this result: `best_1_second_power` or + /// `best_5_second_power`. pub operation: String, - /// W. + /// The highest mean power over 1 second or 5 seconds in the recordings, in + /// watts. pub peak_power: f64, - /// The index of the recording in the input list. + /// The position in the input list of the recording that holds the best + /// effort, counting from 0. pub recording_index: u64, - /// The effort's range `[start_offset_ms, end_offset_ms)`. + /// Where the effort starts, in milliseconds from the recording's start. pub start_offset_ms: i64, + /// Where the effort ends, in milliseconds from the recording's start. + /// The effort runs up to this time, not including it. pub end_offset_ms: i64, /// The readings from 5 s before the effort to 5 s after it. pub readings_around_best: Vec, @@ -1758,9 +1921,16 @@ pub fn best_5_second_power(recordings: &[PowerRecording]) -> Result, + /// The age in years, when it is outside 18 to 80. Absent when the birth + /// year is missing. #[serde(skip_serializing_if = "Option::is_none")] pub age_years: Option, + /// A plain sentence that says why there is no value. pub message: String, } @@ -1817,15 +1995,26 @@ pub fn age_formula_208_minus_0_7_age( /// no step-rate recording. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct HeartRateRecording { + /// The ID of the workout record the readings belong to. pub workout: String, + /// The ID of the record that holds the heart-rate readings: a device + /// recording, or the workout itself when the readings are stored on it. pub recording: String, - /// The workout's start instant; a tie between workouts goes to the latest. + /// When the workout started, in milliseconds since 1970-01-01 UTC. When two + /// workouts hold the same highest value, the one that started later is + /// reported. pub workout_start_ms: i64, /// The workout's start date in the athlete's time zone. #[serde(serialize_with = "serialize_date")] pub workout_date: NaiveDate, + /// The workout's sport, such as `running`. The step-rate check runs only + /// for `running`. pub sport: String, + /// The heart-rate readings, each as `(offset_ms, bpm)`. Readings below 30 + /// or above 250 beats per minute are ignored. pub heart_rate: Vec<(i64, f64)>, + /// The step-rate readings, each as `(offset_ms, steps per minute)`. Empty + /// when the workout has no step-rate recording. pub step_rate: Vec<(i64, f64)>, } @@ -1833,10 +2022,14 @@ pub struct HeartRateRecording { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct HeldHeartRateFound { + /// The ID of the workout the held value came from. pub workout: String, + /// The ID of the record that holds those heart-rate readings: a device + /// recording, or the workout itself when the readings are stored on it. pub recording: String, /// Seconds into the workout at the start of the run. pub time_s: f64, + /// The workout's sport, such as `running`. pub sport: String, } @@ -1844,9 +2037,15 @@ pub struct HeldHeartRateFound { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ExcludedRun { + /// The ID of the workout the run was in. pub workout: String, + /// Seconds into the workout at the start of the run. pub time_s: f64, + /// The run's held value in beats per minute: its lowest reading. pub value_bpm: f64, + /// Why the run was left out: always `matches_step_rate`. Every reading in + /// the run was within 2 of the nearest step-rate reading, so the watch was + /// probably counting steps. pub reason: String, } @@ -1854,18 +2053,36 @@ pub struct ExcludedRun { #[derive(Debug, Clone, PartialEq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct HeldHeartRateResult { + /// The operation that made this result: always `highest_heart_rate_held_5_s`. pub operation: String, + /// The highest heart rate held for 5 seconds, in beats per minute. + /// The true maximum is at least this value. Absent when no value held + /// for 5 seconds was found. pub maximum_heart_rate_bpm: Option, + /// True when `maximum_heart_rate_bpm` is present. A held value is a lower + /// bound, because ordinary sessions rarely reach the true maximum. pub lower_bound: bool, + /// Where the held value was found. Absent when there is no held value. pub found_in: Option, + /// The highest single heart-rate reading in the workouts read, in beats per + /// minute. Readings below 30 or above 250 are ignored. Absent when there + /// were no readings. pub highest_single_reading_bpm: Option, + /// The number of distinct workouts in the window, and of the chosen sport + /// when one was given, whose heart-rate readings were read. pub workouts_read: u64, + /// The number of those workouts with at least one value held for 5 + /// seconds that was not left out for matching the step rate. pub workouts_with_runs: u64, + /// Runs left out because they matched the step rate. pub excluded: Vec, + /// What the estimate lacked: `["held_heart_rate_readings"]` when no value + /// was held for 5 seconds. Empty when a value was found. #[serde(skip_serializing_if = "Vec::is_empty")] pub missing: Vec, - /// The first and last day of the window, `YYYY-MM-DD`. + /// The first day of the window, `YYYY-MM-DD`: 365 days before `period_end`. pub period_start: String, + /// The last day of the window, `YYYY-MM-DD`: the date the estimate is for. pub period_end: String, } diff --git a/mobile/CONTRIBUTING.md b/mobile/CONTRIBUTING.md index da121a46..3d8b2c28 100644 --- a/mobile/CONTRIBUTING.md +++ b/mobile/CONTRIBUTING.md @@ -26,12 +26,13 @@ UniFFI generates Swift and Kotlin from two crates converters, and the extension calls. `mobile/uniffi.toml` names them. A Rust doc comment becomes the Swift or Kotlin documentation that Xcode and Android -Studio show. The phone crate denies missing documentation (`#![deny(missing_docs)]` -in `src/lib.rs`), so every call, and every type, field, and case it defines, has one. -Every call is in this crate. Of the record and result types from the core, about -half have a description, and few of their fields and cases do; SPEC.md describes -the record fields. The generated Swift and Kotlin, the XCFramework, and the native Android -libraries are build output and are not committed +Studio show. Both crates deny missing documentation (`#![deny(missing_docs)]` in +`core/src/lib.rs` and `mobile/src/lib.rs`), so every call, type, field, and case an app +sees has a description. Each value of a list of allowed values also says how it is +stored, such as ``Stored as `import_time`.``; write that line for a new value too. + +The generated Swift and Kotlin, the XCFramework, and the native Android libraries are +build output and are not committed ([D327](../build-history/v3.1.0/decisions.md#d327-phones-open-the-same-sqlite-file-through-the-existing-store)). A phone write builds the npm client's JSON request and runs the same protocol From 93b27bee2aa6c22614be43cac693ec420b3c1136 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 20:57:25 -0600 Subject: [PATCH 26/30] Point the evidence at the rebased commits. The branch was rebased onto two npm lockfile updates on main, which changed every commit ID. The evidence now names the rebased commits and records the checks run after the descriptions commit. Co-Authored-By: Claude Opus 5.5 --- build-history/v3.1.0/appendix/release-evidence.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/build-history/v3.1.0/appendix/release-evidence.md b/build-history/v3.1.0/appendix/release-evidence.md index a662f40e..62b378f8 100644 --- a/build-history/v3.1.0/appendix/release-evidence.md +++ b/build-history/v3.1.0/appendix/release-evidence.md @@ -2,9 +2,10 @@ This is the evidence for the release gates of 3.1.0 ([spec](../spec.md) section 3). It was gathered on 2026-11-30 on an Apple silicon Mac (arm64) with Rust 1.100.0 and Swift -6.4, from commit `797813b` of the build, with synthetic data. No live provider account -was used. An earlier run, from commit `fda0047` before the typed records (D329), gave -the same results for every check it shared with this one. +6.4, from commit `c1cc8e0` of the build, with synthetic data. (The run named the commit +`797813b`; the branch was then rebased onto two npm lockfile updates on `main`.) No live +provider account was used. An earlier run, from commit `c075431` before the typed +records (D329), gave the same results for every check it shared with this one. Each staging run writes `apple-report.json` and `android-report.json` with the hashes, the source commit, the targets, and the tool versions; the release job adds both to the GitHub release. @@ -30,6 +31,13 @@ GitHub release. | Version | Each binding reports 3.1.0, and an outdated 2.1.0 file migrates to SQL step 9 on macOS and on both emulators | | The whole workspace | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass, also without the `cli` feature for the library and the phone crate; `cargo test` (workspace) gives 942 passed, 0 failed, 18 ignored (the 7 terminal tests ran outside the sandbox); npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (3.0.0 gate 5) passes | +After the rebase, commit `76f6e8d` added a description to every record and result +type and made the core deny missing documentation. It changes only comments, so the +emulator runs were not repeated. On it: `cargo test` gives 942 passed, 0 failed, 18 +ignored; the Swift tests on macOS give 38 passed; the Android library, its tests, and +the example app compile; npm gives 105 passed, 1 skipped; the WebAssembly gate passes; +and every one of the 1,742 items in the generated Swift has a description. + ## 2. Found and fixed while gathering this evidence - **A path check on Windows.** A phone storage test expected the backup path to end in From 511e1c374986f552c7603e649e2bd9ccb9c75b5f Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 21:14:41 -0600 Subject: [PATCH 27/30] Update zip to 9.9 for its security fixes. zip 2.6.1 has open security advisories: two critical (a zip whose two copies of an entry's header disagree can bypass checks and overwrite files), two high (unbounded symbolic link targets during extraction), and AES authentication on an early end of file. Every version up to 9.0.4 is affected. The fix needs version 9, which the "2.2" requirement does not allow, so the update changes both manifests. In zip 9 reading an entry's name can fail, so the three places that read a name now pass that failure on. zip 9 also stops reading an entry at its declared size by itself. The import safety test no longer expects the library to read past it, and accepts either refusal: the library's, or the import's own measured reader's. Nothing is written in either case. zip's compression code now uses Rust libraries for bzip2 and xz instead of three C libraries. No other dependency changes. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 338 +++++++++++++---------------------------- Cargo.toml | 2 +- host/Cargo.toml | 2 +- src/import/input.rs | 4 +- src/package/zipped.rs | 2 +- tests/import_safety.rs | 12 +- 6 files changed, 120 insertions(+), 240 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ee6c8db0..461f54e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,13 +10,14 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aes" -version = "0.8.4" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" dependencies = [ - "cfg-if", "cipher", - "cpufeatures 0.2.17", + "cpubits", + "cpufeatures", + "zeroize", ] [[package]] @@ -84,15 +85,6 @@ version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" -[[package]] -name = "arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "askama" version = "0.16.1" @@ -372,15 +364,6 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - [[package]] name = "block-buffer" version = "0.12.1" @@ -397,12 +380,6 @@ version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "bytes" version = "1.12.2" @@ -414,21 +391,11 @@ dependencies = [ [[package]] name = "bzip2" -version = "0.5.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47" +checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" dependencies = [ - "bzip2-sys", -] - -[[package]] -name = "bzip2-sys" -version = "0.1.13+1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14" -dependencies = [ - "cc", - "pkg-config", + "libbz2-rs-sys", ] [[package]] @@ -482,6 +449,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chrono" version = "0.4.45" @@ -519,11 +492,11 @@ dependencies = [ [[package]] name = "cipher" -version = "0.4.4" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "crypto-common 0.1.7", + "crypto-common", "inout", ] @@ -599,9 +572,12 @@ checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "constant_time_eq" -version = "0.3.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] [[package]] name = "core-foundation" @@ -625,15 +601,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - [[package]] name = "cpufeatures" version = "0.3.1" @@ -643,21 +610,6 @@ dependencies = [ "libc", ] -[[package]] -name = "crc" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" -dependencies = [ - "crc-catalog", -] - -[[package]] -name = "crc-catalog" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" - [[package]] name = "crc32fast" version = "1.5.5" @@ -667,12 +619,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - [[package]] name = "crypto-bigint" version = "0.7.11" @@ -690,16 +636,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - [[package]] name = "crypto-common" version = "0.2.2" @@ -738,9 +674,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" dependencies = [ "cfg-if", - "cpufeatures 0.3.1", + "cpufeatures", "curve25519-dalek-derive", - "digest 0.11.3", + "digest", "fiat-crypto", "rustc_version", "subtle", @@ -781,37 +717,15 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "derive_arbitrary" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", - "subtle", -] - [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer 0.12.1", + "block-buffer", "const-oid", - "crypto-common 0.2.2", + "crypto-common", "ctutils", "zeroize", ] @@ -834,7 +748,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" dependencies = [ "der", - "digest 0.11.3", + "digest", "elliptic-curve", "rfc6979", "signature", @@ -879,8 +793,8 @@ checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" dependencies = [ "base16ct", "crypto-bigint", - "crypto-common 0.2.2", - "digest 0.11.3", + "crypto-common", + "digest", "ff", "group", "hybrid-array", @@ -1077,16 +991,6 @@ dependencies = [ "slab", ] -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - [[package]] name = "getrandom" version = "0.2.17" @@ -1098,20 +1002,6 @@ dependencies = [ "wasi", ] -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 5.3.0", - "wasip2", - "wasm-bindgen", -] - [[package]] name = "getrandom" version = "0.4.3" @@ -1119,9 +1009,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", - "r-efi 6.0.0", + "r-efi", "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1195,22 +1087,13 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - [[package]] name = "hmac" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest 0.11.3", + "digest", ] [[package]] @@ -1509,11 +1392,11 @@ dependencies = [ [[package]] name = "inout" -version = "0.1.4" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -1623,7 +1506,7 @@ dependencies = [ "base64 0.23.1", "ed25519-dalek", "getrandom 0.4.3", - "hmac 0.13.0", + "hmac", "js-sys", "p256", "p384", @@ -1637,6 +1520,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "libbz2-rs-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5314d1d545fce0307c770d791adf20d997e0b63b64e1ffeed8a920e290eabe4" + [[package]] name = "libc" version = "0.2.191" @@ -1730,24 +1619,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] -name = "lzma-rs" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e" -dependencies = [ - "byteorder", - "crc", -] - -[[package]] -name = "lzma-sys" -version = "0.1.20" +name = "lzma-rust2" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27" +checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890" dependencies = [ - "cc", - "libc", - "pkg-config", + "sha2", ] [[package]] @@ -1763,7 +1640,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" dependencies = [ "cfg-if", - "digest 0.11.3", + "digest", ] [[package]] @@ -1805,6 +1682,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -1902,12 +1791,12 @@ checksum = "e3c406c9e2aa74554e662d2c2ee11cd3e73756988800be7e6f5eddb16fed4699" [[package]] name = "pbkdf2" -version = "0.12.2" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" dependencies = [ - "digest 0.10.7", - "hmac 0.12.1", + "digest", + "hmac", ] [[package]] @@ -2116,6 +2005,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppmd-rust" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd4acc8d264ea385db64ccfdcdfd5909ee9eda0975666723d59f3bfec80b3611" + [[package]] name = "primefield" version = "0.14.0" @@ -2123,7 +2018,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" dependencies = [ "crypto-bigint", - "crypto-common 0.2.2", + "crypto-common", "ff", "rand_core 0.10.1", "subtle", @@ -2193,12 +2088,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - [[package]] name = "r-efi" version = "6.0.0" @@ -2233,7 +2122,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ "crypto-bigint", - "hmac 0.13.0", + "hmac", ] [[package]] @@ -2258,10 +2147,10 @@ checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699" dependencies = [ "const-oid", "crypto-bigint", - "crypto-common 0.2.2", + "crypto-common", "crypto-primes", - "digest 0.11.3", - "hmac 0.13.0", + "digest", + "hmac", "pkcs1", "pkcs8", "rand_core 0.10.1", @@ -2418,7 +2307,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c091b4ca9c4d51c1a959fa746cc74f5a612a2242070a4ae7b14e22b04c71f8c" dependencies = [ "base64 0.23.1", - "hmac 0.13.0", + "hmac", "instant-xml", "jiff", "md-5", @@ -2607,13 +2496,13 @@ dependencies = [ [[package]] name = "sha1" -version = "0.10.7" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", + "cpufeatures", + "digest", ] [[package]] @@ -2623,8 +2512,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", + "cpufeatures", + "digest", ] [[package]] @@ -2649,7 +2538,7 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" dependencies = [ - "digest 0.11.3", + "digest", "rand_core 0.10.1", ] @@ -2893,6 +2782,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", + "js-sys", "num-conv", "powerfmt", "serde_core", @@ -3086,6 +2976,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.1" @@ -3350,15 +3246,6 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - [[package]] name = "wasm-bindgen" version = "0.2.130" @@ -3589,12 +3476,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - [[package]] name = "wnaf" version = "0.14.1" @@ -3619,15 +3500,6 @@ version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" -[[package]] -name = "xz2" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2" -dependencies = [ - "lzma-sys", -] - [[package]] name = "yoke" version = "0.8.4" @@ -3727,27 +3599,29 @@ dependencies = [ [[package]] name = "zip" -version = "2.6.1" +version = "9.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9" dependencies = [ "aes", - "arbitrary", "bzip2", "constant_time_eq", "crc32fast", - "crossbeam-utils", "deflate64", "flate2", - "getrandom 0.3.4", - "hmac 0.12.1", + "getrandom 0.4.3", + "hmac", "indexmap", - "lzma-rs", + "libc", + "lzma-rust2", "memchr", + "nix", "pbkdf2", + "ppmd-rust", "sha1", "time", - "xz2", + "typed-path", + "windows-sys 0.61.2", "zeroize", "zopfli", "zstd", @@ -3779,27 +3653,27 @@ dependencies = [ [[package]] name = "zstd" -version = "0.13.5" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278" +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.4.1" +version = "8.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819" +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.1.3+zstd.1.5.7" +version = "2.2.0+zstd.1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" dependencies = [ "cc", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index 713558cf..c3eec392 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,7 +45,7 @@ sha2 = "0.11.0" terminal_size = { version = "0.4.4", optional = true } ureq = { version = "2.12", optional = true } uuid = { version = "1.29", features = ["v7"] } -zip = { version = "2.2", optional = true } +zip = { version = "9", optional = true } flate2 = { version = "1.1", optional = true } [[test]] diff --git a/host/Cargo.toml b/host/Cargo.toml index 35712e5e..f1687530 100644 --- a/host/Cargo.toml +++ b/host/Cargo.toml @@ -30,7 +30,7 @@ tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "s ureq = { version = "2.12", features = ["json"] } url = "2.5.9" uuid = { version = "1.29.3", features = ["v4", "v7"] } -zip = "2.2" +zip = "9" [dev-dependencies] jsonwebtoken = { version = "12.0.0", features = ["rust_crypto"] } diff --git a/src/import/input.rs b/src/import/input.rs index f0fc5f99..5701b9f7 100644 --- a/src/import/input.rs +++ b/src/import/input.rs @@ -95,7 +95,7 @@ pub fn open_zip(path: &Path) -> Result { let mut expanded: u64 = 0; for index in 0..archive.len() { let entry = archive.by_index_raw(index).map_err(|error| zip_error(path, error))?; - let name = entry.name().to_string(); + let name = entry.name().map_err(|error| zip_error(path, error))?.to_string(); check_entry_name(&name)?; let mode = (external_attributes(&mut raw, entry.central_header_start())? >> 16) & 0o170000; if mode == 0o120000 { @@ -196,7 +196,7 @@ impl ZipIndex { check_entry_name(&entry.name)?; let mut archive = open_archive(&self.path)?; let file = archive.by_index(entry.index).map_err(|error| zip_error(&self.path, error))?; - if file.name() != entry.name { + if file.name().map_err(|error| zip_error(&self.path, error))? != entry.name.as_str() { return Err(Error::stale(format!("{} changed while it was read", self.path.display()))); } check_entry_size(&entry.name, file.size(), file.compressed_size())?; diff --git a/src/package/zipped.rs b/src/package/zipped.rs index 7a731a0a..53719351 100644 --- a/src/package/zipped.rs +++ b/src/package/zipped.rs @@ -38,7 +38,7 @@ pub fn unpack(bytes: &[u8], folder: &Path) -> Result<(), String> { if entry.is_dir() { continue; } - let name = entry.name().to_string(); + let name = entry.name().map_err(|error| error.to_string())?.to_string(); let relative = Path::new(&name); if relative.components().any(|component| !matches!(component, Component::Normal(_))) { return Err(format!("the zip names a path outside the package: {name}")); diff --git a/tests/import_safety.rs b/tests/import_safety.rs index 1c3dd956..77ab4578 100644 --- a/tests/import_safety.rs +++ b/tests/import_safety.rs @@ -277,8 +277,13 @@ fn zip_declaring(name: &str, data: &[u8], declared: u32) -> Vec { out } -/// The count after "got at least" in the measured reader's refusal. +/// The bytes read before a refusal: the count after "got at least" in the +/// measured reader's refusal, or the declared size when the archive library +/// stopped there first, as zip 9 does. fn counted(error: &str, declared: usize) -> u64 { + if error.ends_with("File is larger than its declared uncompressed size") { + return declared as u64; + } let prefix = format!("too many bytes in the stream. expected {declared}. got at least "); let rest = error.strip_prefix(&prefix).unwrap_or_else(|| panic!("{error}")); rest.parse().unwrap() @@ -301,7 +306,8 @@ fn an_entry_that_expands_past_its_declared_size_is_refused_while_it_is_read() { let path = directory.path().join("whoop.zip"); std::fs::write(&path, zip_declaring(name, &data, text.len() as u32)).unwrap(); - // The archive library alone, which trusts the header, gives every byte. + // The archive library reports the declared size. Since zip 9 it also stops + // reading at that size, but the checks below do not rely on it. let mut archive = zip::ZipArchive::new(std::fs::File::open(&path).unwrap()).unwrap(); let mut entry = archive.by_index(0).unwrap(); assert_eq!(entry.size(), text.len() as u64); @@ -313,7 +319,7 @@ fn an_entry_that_expands_past_its_declared_size_is_refused_while_it_is_read() { } total += count as u64; } - assert_eq!(total, expanded); + assert!(total < expanded, "the library read {total} of {expanded} bytes"); drop(entry); // The checked index accepts the headers. Reading counts the real bytes From 779f2e974fa4fc0547404e06233a22f2d927e547 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 22:07:21 -0600 Subject: [PATCH 28/30] Read a calendar-day bound on a range calculation as the whole day. A calculation that did not group by day, week, or month compared a `--from` or `--to` day with the stored timestamps as text, so `--to 2026-10-31` left out every reading of 31 October and ignored `--timezone`. The 1.0.0 specification says a day bound uses the request's or the saved time zone. Now every range calculation does that, as the grouped ones already did; with no time zone it is refused and asks for one (D335). Exact instants, provider period summaries, and workout drift are unchanged. The 2.1.0 reference test names the two cases this changes. A new test works the rule through by hand, and a shared reader case runs it through the database, the memory snapshot, and the phone bundle. The repair test looked for "999" anywhere in the output, which the new range end contains; it now checks the mean. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- build-history/v3.1.0/decisions.md | 30 +++++++++++ build-history/v3.1.0/spec.md | 5 +- core/src/calculate/range.rs | 38 ++++++++----- tests/calculate_day_bounds.rs | 87 ++++++++++++++++++++++++++++++ tests/calculate_golden.rs | 15 +++++- tests/calculation_support/cases.rs | 32 +++++++++++ tests/cli_executable.rs | 7 ++- 8 files changed, 197 insertions(+), 19 deletions(-) create mode 100644 tests/calculate_day_bounds.rs diff --git a/AGENTS.md b/AGENTS.md index f3274c80..4b1e8a72 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,7 @@ 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: 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, the last released 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/v3.1.0/spec.md`** — version 3.1.0, built and not released, the current version: the library for iPhone and Android apps in `mobile/`, with Swift and Kotlin bindings generated by UniFFI, calculations that read their data through one reader interface, a host client with browser sign-in, and SQL migration step 9, which records the version (D325–D334). `mobile/README.md` is the guide for app developers. +10. **`build-history/v3.1.0/spec.md`** — version 3.1.0, built and not released, the current version: the library for iPhone and Android apps in `mobile/`, with Swift and Kotlin bindings generated by UniFFI, calculations that read their data through one reader interface, a host client with browser sign-in, SQL migration step 9, which records the version, and a range-calculation fix (D325–D335). `mobile/README.md` is the guide for app developers. 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. diff --git a/build-history/v3.1.0/decisions.md b/build-history/v3.1.0/decisions.md index 49ff61c6..c83e46d8 100644 --- a/build-history/v3.1.0/decisions.md +++ b/build-history/v3.1.0/decisions.md @@ -358,3 +358,33 @@ Rejected alternatives: is not built. - Release 3.1.0 without a migration step. Rejected because a new database must reach the program's version, and every earlier version recorded its own. + +## D335. A calendar-day bound on a range calculation covers the whole day + +When `--from` or `--to` of `ath calculate` is a calendar day (`YYYY-MM-DD`), it covers +that whole day in the request's time zone, or else the athlete profile's default time +zone. With neither, the calculation is refused and asks for one. An exact UTC instant +stays as given and needs no time zone. This applies to every range calculation, as it +already did to the ones that group by day, week, or month, or read calendar days +(`coverage`, `correlation`). A provider period summary still compares provider dates, +and a workout drift reads one session. + +The 1.0.0 specification (section 8) already says a date-only bound on `calculate` uses +the explicit or saved time zone before it becomes a time range. The 2.1.0 program, and +every version since, instead compared a day with the stored timestamps as text when +the calculation did not group: `2026-10-31T06:00:00.000Z` sorts after `2026-10-31`, so +`--to 2026-10-31` left out every reading of 31 October. The `summary` skill's own +example, `--from 2026-10-01 --to 2026-10-31 --timezone Europe/London`, lost its last day +and ignored the time zone. + +A request with a day bound and no time zone, which used to give an answer that left +out the last day, is now refused. The two 2.1.0 reference cases this changes are named +in `tests/calculate_golden.rs`, and `tests/calculate_day_bounds.rs` tests the rule. + +Rejected alternatives: + +- Treat a day as a UTC day when no time zone is known. Rejected because every other + calendar day in a calculation uses the athlete's time zone, and a UTC day silently + moves the edges for anyone outside UTC. +- Keep the text comparison and document it. Rejected because it contradicts the 1.0.0 + specification and the `--to` help ("latest day"), and loses data without saying so. diff --git a/build-history/v3.1.0/spec.md b/build-history/v3.1.0/spec.md index f3781039..87b4f02c 100644 --- a/build-history/v3.1.0/spec.md +++ b/build-history/v3.1.0/spec.md @@ -1,6 +1,6 @@ # Athletic Standard 3.1.0 — the library for iPhone and Android apps -Status: **built; not released.** The decisions are D325–D334 in +Status: **built; not released.** The decisions are D325–D335 in [decisions.md](decisions.md). The approved plan is [mobile-library-plan.md](appendix/mobile-library-plan.md). Progress is in [progress.md](progress.md), and the evidence in @@ -33,6 +33,9 @@ In 3.1.0: Swift package is this repository, installed by version. - App guides for Swift and Android, with tested examples that are starting points for an app. +- A calendar-day bound on any range calculation covers the whole day in a time zone + (D335). +- The `zip` library moves from 2.6 to 9.9 for its security fixes. - Version 3.1.0 and migration step 9 (section 2). Not in 3.1.0: diff --git a/core/src/calculate/range.rs b/core/src/calculate/range.rs index e567dd9c..74e26cbc 100644 --- a/core/src/calculate/range.rs +++ b/core/src/calculate/range.rs @@ -22,7 +22,7 @@ use serde::Serialize; use super::definition::shipped_method; use super::reader::{CalculationReader, InputRequest, PeriodRequest, RangeInput as Input}; use super::record::parse_millis; -use crate::calendar::{resolve_calendar_range_with, CalendarRangeRequest}; +use crate::calendar::{looks_like_calendar_date, resolve_calendar_range_with, CalendarRangeRequest}; use crate::error::{Error, Result}; use crate::json::{self, Value}; use crate::model::{point_measurement_unit, series_quantity_unit, EvidenceReference, PointMeasurementType}; @@ -171,15 +171,17 @@ pub struct CalculateOptions { /// The record ID of the workout session to read. Required for `workout-drift`. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub workout_session_id: Option, - /// A calendar day (`YYYY-MM-DD`) or an exact UTC instant. + /// The start of the window: a calendar day (`YYYY-MM-DD`), read from its first + /// moment in the time zone, or an exact UTC instant. Absent means no start. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub from: Option, - /// The end of the window: a calendar day (`YYYY-MM-DD`) or an exact UTC instant. - /// Absent means no end. + /// The end of the window: a calendar day (`YYYY-MM-DD`), read to its last moment in + /// the time zone, or an exact UTC instant. Absent means no end. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub to: Option, /// The IANA time zone name for calendar days, such as `Europe/London`. Absent - /// uses the athlete profile's default time zone. + /// uses the athlete profile's default time zone. A calendar day with neither is + /// refused. #[cfg_attr(feature = "uniffi", uniffi(default = None))] pub time_zone: Option, /// The calendar grouping for `summary` and `baseline`. @@ -211,12 +213,14 @@ impl CalculateOptions { #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] pub struct ReceiptRange { - /// The start of the window read, included: a calendar day (`YYYY-MM-DD`) or a UTC - /// instant. For `workout-drift`, the workout's start. Absent when the window has no start. + /// The start of the window read, included: a UTC instant, or for a provider period + /// summary the day given. For `workout-drift`, the workout's start. Absent when the + /// window has no start. #[serde(skip_serializing_if = "Option::is_none")] pub from: Option, - /// The end of the window read, included: a calendar day (`YYYY-MM-DD`) or a UTC - /// instant. For `workout-drift`, the workout's end. Absent when the window has no end. + /// The end of the window read, included: a UTC instant, or for a provider period + /// summary the day given. For `workout-drift`, the workout's end. Absent when the + /// window has no end. #[serde(skip_serializing_if = "Option::is_none")] pub to: Option, /// The IANA time zone name used for calendar days. Absent when none was used. @@ -594,22 +598,28 @@ pub fn calculate(reader: &R, options: &CalculateOptions) - if operation == Operation::Correlation && options.other_quantity.is_none() { return Err(Error::other("correlation needs --other-quantity").into()); } - let needs_calendar = !period_summary - && operation != Operation::WorkoutDrift + // A provider period summary compares provider dates, and a workout drift reads one + // session, so neither turns a bound into instants. + let instant_range = !period_summary && operation != Operation::WorkoutDrift; + let needs_calendar = instant_range && (options.group != Group::None || operation == Operation::Coverage || operation == Operation::Correlation); - let (from, to, time_zone) = if needs_calendar { + // A calendar-day bound covers that whole day in the request's time zone, else the + // profile's (D335). An exact instant stays as given. + let day_bound = instant_range + && [&options.from, &options.to].into_iter().flatten().any(|bound| looks_like_calendar_date(bound)); + let (from, to, time_zone) = if needs_calendar || day_bound { let range = resolve_calendar_range_with( &CalendarRangeRequest { from: options.from.clone(), to: options.to.clone(), time_zone: options.time_zone.clone(), - raw: false, + raw: !needs_calendar, }, || reader.saved_time_zone(), )?; (range.from, range.to, range.time_zone.or_else(|| options.time_zone.clone())) } else { - // Without calendar days the bounds are compared as given. + // Exact instants are compared as given. (options.from.clone(), options.to.clone(), options.time_zone.clone()) }; let expected_unit = if !period_summary && kind == RecordKind::Measurement { diff --git a/tests/calculate_day_bounds.rs b/tests/calculate_day_bounds.rs new file mode 100644 index 00000000..5e0e02cb --- /dev/null +++ b/tests/calculate_day_bounds.rs @@ -0,0 +1,87 @@ +//! A calendar-day bound on a range calculation without calendar grouping +//! covers that whole day, in the request's time zone or else the profile's +//! (D335). Before 3.1.0 such a bound was compared as text, so readings during +//! the last day were left out. `tests/calculate_readers.rs` runs the same case +//! through both readers. + +mod calculation_support; + +use calculation_support::Lab; +use serde_json::{json, Value}; + +/// Readings around 2 and 3 October, two of them on the edge of a Chicago day. +fn readings(lab: &mut Lab) { + lab.write(&[ + // 1 October 22:00 in Chicago. + json!({ "id": "before", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-02T03:00:00.000Z", "value": 40.0 }), + json!({ "id": "first", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-02T06:00:00.000Z", "value": 50.0 }), + // 3 October 22:00 in Chicago. + json!({ "id": "last", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-04T03:00:00.000Z", "value": 60.0 }), + json!({ "id": "after", "record_type": "point_measurement", "quantity": "hrv_rmssd", "at": "2026-10-04T06:00:00.000Z", "value": 70.0 }), + ]); +} + +fn summary(lab: &mut Lab, extra: Value) -> Value { + let mut request = json!({ "operation": "summary", "quantity": "hrv_rmssd" }); + request.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + lab.calculate(&request) +} + +#[test] +fn the_last_day_is_read_in_the_profile_time_zone() { + let mut lab = Lab::new(); + lab.write_one( + &json!({ "id": "profile", "record_type": "athlete_profile", "default_time_zone": "America/Chicago" }), + ); + readings(&mut lab); + let receipt = summary(&mut lab, json!({ "from": "2026-10-02", "to": "2026-10-03" })); + assert_eq!( + receipt["range"], + json!({ "from": "2026-10-02T05:00:00.000Z", "to": "2026-10-04T04:59:59.999Z", "time_zone": "America/Chicago" }) + ); + // `first` and `last` fall on 2 and 3 October in Chicago. + assert_eq!(receipt["input"]["record_count"], 2, "{receipt}"); + assert_eq!(receipt["result"][0]["mean"], 55.0, "{receipt}"); +} + +#[test] +fn a_given_time_zone_comes_first() { + let mut lab = Lab::new(); + lab.write_one( + &json!({ "id": "profile", "record_type": "athlete_profile", "default_time_zone": "America/Chicago" }), + ); + readings(&mut lab); + let receipt = summary(&mut lab, json!({ "from": "2026-10-02", "to": "2026-10-03", "time_zone": "UTC" })); + assert_eq!( + receipt["range"], + json!({ "from": "2026-10-02T00:00:00.000Z", "to": "2026-10-03T23:59:59.999Z", "time_zone": "UTC" }) + ); + // `before` and `first` fall on 2 October in UTC; `last` is on 4 October. + assert_eq!(receipt["result"][0]["mean"], 45.0, "{receipt}"); +} + +#[test] +fn a_day_bound_without_a_time_zone_is_refused() { + let mut lab = Lab::new(); + readings(&mut lab); + for request in [ + json!({ "operation": "summary", "quantity": "hrv_rmssd", "to": "2026-10-03" }), + json!({ "operation": "trend", "quantity": "hrv_rmssd", "from": "2026-10-02" }), + ] { + let answer = lab.calculate(&request); + assert_eq!( + answer["error"], + "a calendar-day series view needs --timezone or a default timezone in the athlete profile", + "{request}" + ); + } +} + +#[test] +fn exact_instants_need_no_time_zone_and_stay_as_given() { + let mut lab = Lab::new(); + readings(&mut lab); + let receipt = summary(&mut lab, json!({ "from": "2026-10-02T06:00:00.000Z", "to": "2026-10-04T03:00:00.000Z" })); + assert_eq!(receipt["range"], json!({ "from": "2026-10-02T06:00:00.000Z", "to": "2026-10-04T03:00:00.000Z" })); + assert_eq!(receipt["result"][0]["mean"], 55.0, "{receipt}"); +} diff --git a/tests/calculate_golden.rs b/tests/calculate_golden.rs index 92371506..d4a13581 100644 --- a/tests/calculate_golden.rs +++ b/tests/calculate_golden.rs @@ -146,9 +146,22 @@ fn range(store: &mut Store, call: &str, input: &Value, _: &Path) -> (Value, Comp (output, Compare::Exact) } +/// Cases whose 2.1.0 output a later decision changed, with the reason. +/// `tests/calculate_day_bounds.rs` tests their new behavior. +const CHANGED_SINCE_2_1_0: &[(&str, &str)] = &[ + ("summary with raw text bounds", "D335: a calendar-day bound covers the whole day in a time zone"), + ("trend needs two inputs", "D335: a calendar-day bound with no time zone is refused"), +]; + #[test] fn range_calculations_match_the_reference() { - Scenario::open("calculate/range.json").check(range); + let mut scenario = Scenario::open("calculate/range.json"); + for (name, _) in CHANGED_SINCE_2_1_0 { + let before = scenario.cases.len(); + scenario.cases.retain(|case| case["name"].as_str() != Some(*name)); + assert_eq!(scenario.cases.len() + 1, before, "the reference has no case named {name}"); + } + scenario.check(range); } /// The 2.1.1 calculation files, kept so the recorded 2.1.0 results can be diff --git a/tests/calculation_support/cases.rs b/tests/calculation_support/cases.rs index ff9af7c6..0c754648 100644 --- a/tests/calculation_support/cases.rs +++ b/tests/calculation_support/cases.rs @@ -38,9 +38,41 @@ pub fn all() -> Vec { workouts(), one_record_lookups(), receipt_cap(), + day_bounds(), ] } +/// A calendar-day bound on a calculation without calendar grouping covers that +/// whole day, in the request's time zone or else the profile's (D335). Exact +/// instants stay as given. +fn day_bounds() -> Case { + let summary = |extra: Value| { + let mut request = json!({ "operation": "summary", "quantity": "hrv_rmssd" }); + request.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + calculate(request) + }; + Case { + name: "calendar-day bounds", + records: vec![ + json!({ "id": "profile", "record_type": "athlete_profile", "default_time_zone": "America/Chicago" }), + // 1 October 22:00 in Chicago. + point("before", "hrv_rmssd", "2026-10-02T03:00:00.000Z", 40.0), + point("first", "hrv_rmssd", "2026-10-02T06:00:00.000Z", 50.0), + // 3 October 22:00 in Chicago. + point("last", "hrv_rmssd", "2026-10-04T03:00:00.000Z", 60.0), + point("after", "hrv_rmssd", "2026-10-04T06:00:00.000Z", 70.0), + ], + requests: vec![ + summary(json!({ "from": "2026-10-02", "to": "2026-10-03" })), + summary(json!({ "from": "2026-10-02", "to": "2026-10-03", "time_zone": "UTC" })), + summary(json!({ "to": "2026-10-03" })), + summary(json!({ "from": "2026-10-02T06:00:00.000Z", "to": "2026-10-04T03:00:00.000Z" })), + calculate(json!({ "operation": "baseline", "quantity": "hrv_rmssd", "from": "2026-10-02" })), + calculate(json!({ "operation": "trend", "quantity": "hrv_rmssd", "to": "2026-10-03" })), + ], + } +} + /// Equal times, deleted records, a deleted source, a manual source, and a /// corrected record. fn ties_deletions_and_sources() -> Case { diff --git a/tests/cli_executable.rs b/tests/cli_executable.rs index f9402b7f..eee1a4ed 100644 --- a/tests/cli_executable.rs +++ b/tests/cli_executable.rs @@ -324,7 +324,10 @@ fn a_repair_from_revisions_restores_the_values_a_calculation_reads() { assert_eq!(output.status, 0, "{output:?}"); output.stdout }; - assert!(baseline(folder.path()).contains("999"), "the damaged typed column is what the calculation reads"); + assert!( + baseline(folder.path()).contains("\"mean\": 999"), + "the damaged typed column is what the calculation reads" + ); assert_eq!(ath(folder.path(), &["check"], b"").status, 1, "check reports the damaged column"); let temporary = private_folder(); @@ -334,7 +337,7 @@ fn a_repair_from_revisions_restores_the_values_a_calculation_reads() { let checked = ath(folder.path(), &["check"], b""); assert_eq!(checked.status, 0, "{checked:?}"); let after = baseline(folder.path()); - assert!(!after.contains("999") && after.contains("64"), "{after}"); + assert!(!after.contains("\"mean\": 999") && after.contains("\"mean\": 64"), "{after}"); } #[test] From dee6e1164b58992e515d72ba4c7356e834844a41 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 22:07:21 -0600 Subject: [PATCH 29/30] Name all six coach record types and all six score types. SPEC.md said in three places that a coach writes only coaching notes, training plans, and planned sessions. Since 3.0.0 a coach also writes intensity references, events, and approvals, as SPEC.md section 6 and the code already say. The tool skill's grading reference and the CrossFit skill's records reference listed three score types. `power`, `distance`, and `energy` were added in 3.0.0, with `power_w`, `distance_m`, and `energy_kcal`. Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 18 ++++++++++-------- skills/athletic-standard/references/grading.md | 4 +++- skills/crossfit/references/records.md | 7 ++++--- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/SPEC.md b/SPEC.md index bb70dd80..e95e04a7 100644 --- a/SPEC.md +++ b/SPEC.md @@ -204,9 +204,10 @@ event time inside `data`. The coach actor is new in 2.1.3. `coach` is a nonempty name. `coach_id` is a lowercase UUID in the 8-4-4-4-12 form, assigned by the host that accepted the change. The name and ID record who wrote the change. They grant no access. A coach may change -only `coaching_note`, `training_plan`, and `planned_session` records. A coach cannot -change a measured record, an athlete report, or any other record type, and cannot -delete a record. +only `coaching_note`, `training_plan`, `planned_session`, `intensity_reference`, +`event`, and `approval` records; the last three are new in 3.0.0 (section 6). A coach +cannot change a measured record, an athlete report, or any other record type, and +cannot delete a record. ### 4.4 Normal deletion @@ -278,9 +279,9 @@ A tool author requires `author_type: "tool"`, `tool`, `tool_version`, and `calculation_version`. A coach author has the same fields as the coach actor (section 4.3): `author_type: -"coach"`, `coach`, and `coach_id`. Only `coaching_note`, `training_plan`, and -`planned_session` records may have a coach author. A `prediction_result_link` cannot -name a coach as `created_by`. +"coach"`, `coach`, and `coach_id`. Only `coaching_note`, `training_plan`, +`planned_session`, `intensity_reference`, `event`, and `approval` records may have a +coach author. A `prediction_result_link` cannot name a coach as `created_by`. ### 5.2 Input timestamp receipts @@ -1430,8 +1431,9 @@ Authored records are a third class. They name an author and exact evidence. They not measurements and are not athlete reports. A coach writes authored advice, like an agent. A coach can author or change only -coaching notes, training plans, and planned sessions, so a coach is never the author -or actor of a measured record or an athlete report. +coaching notes, training plans, planned sessions, intensity references, events, and +approvals, so a coach is never the author or actor of a measured record or an athlete +report. Calculations remain separate by quantity and source unless the operation explicitly compares sources. Device baselines exclude `manual` sources. RMSSD and SDNN never diff --git a/skills/athletic-standard/references/grading.md b/skills/athletic-standard/references/grading.md index a441be83..dd481534 100644 --- a/skills/athletic-standard/references/grading.md +++ b/skills/athletic-standard/references/grading.md @@ -63,7 +63,9 @@ prediction or result. ## Arithmetic -The benchmark definition selects `duration_s`, `reps`, or `weight_kg`. +The benchmark definition's `score_type` selects the score value: `time` reads +`duration_s`, `reps` reads `reps`, `load` reads `weight_kg`, `power` reads `power_w`, +`distance` reads `distance_m`, and `energy` reads `energy_kcal`. ```text signed_error = predicted value - actual value diff --git a/skills/crossfit/references/records.md b/skills/crossfit/references/records.md index e21782ed..58650907 100644 --- a/skills/crossfit/references/records.md +++ b/skills/crossfit/references/records.md @@ -96,12 +96,13 @@ need, raise `authorship.content_version` by one, update `authored_at`, and updat ## Goals and a custom benchmark A goal that is a benchmark names the definition and the target score. A score is -`{ "duration_s": ... }`, `{ "reps": ... }`, or `{ "weight_kg": ... }`. +`{ "duration_s": ... }`, `{ "reps": ... }`, `{ "weight_kg": ... }`, `{ "power_w": ... }`, +`{ "distance_m": ... }`, or `{ "energy_kcal": ... }`. For a test that `ath init` does not seed, create a `benchmark_definition` first. `benchmark_key` is lowercase letters, digits, `-`, and `_`. `benchmark_type` is -`named_wod`, `run`, `hyrox`, `lift`, or `custom`. `score_type` is `time`, `reps`, or -`load`. +`named_wod`, `run`, `hyrox`, `lift`, or `custom`. `score_type` is `time`, `reps`, +`load`, `power`, `distance`, or `energy`. ```json ath-record-example [ From c638b40bb144ac6eb03cfaf4d1074b6e96229e6b Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 30 Nov 2026 22:15:21 -0600 Subject: [PATCH 30/30] Record the fixes made before review, and gather the evidence again. Progress gains step 11: the zip security update, calendar-day range bounds (D335), the coach record types in SPEC.md, and the score types in two skill references. The evidence is gathered again from commit dee6e11: 946 Rust tests, the Swift package installed by version (33 tests in each of two runs, with byte-identical zips), the Android library installed by coordinate in the example app (37 tests on each emulator, debug and shrunk release), and the round trip on every platform. Co-Authored-By: Claude Opus 5.5 --- .../v3.1.0/appendix/release-evidence.md | 32 +++++++++---------- build-history/v3.1.0/progress.md | 22 +++++++++++++ 2 files changed, 38 insertions(+), 16 deletions(-) diff --git a/build-history/v3.1.0/appendix/release-evidence.md b/build-history/v3.1.0/appendix/release-evidence.md index 62b378f8..ba08babf 100644 --- a/build-history/v3.1.0/appendix/release-evidence.md +++ b/build-history/v3.1.0/appendix/release-evidence.md @@ -2,10 +2,10 @@ This is the evidence for the release gates of 3.1.0 ([spec](../spec.md) section 3). It was gathered on 2026-11-30 on an Apple silicon Mac (arm64) with Rust 1.100.0 and Swift -6.4, from commit `c1cc8e0` of the build, with synthetic data. (The run named the commit -`797813b`; the branch was then rebased onto two npm lockfile updates on `main`.) No live -provider account was used. An earlier run, from commit `c075431` before the typed -records (D329), gave the same results for every check it shared with this one. +6.4, from commit `dee6e11` of the build, with synthetic data. No live provider account +was used. Earlier runs, from commit `c075431` before the typed records (D329) and from +`c1cc8e0` before the `zip` update and D335, gave the same results for every check they +shared with this one. Each staging run writes `apple-report.json` and `android-report.json` with the hashes, the source commit, the targets, and the tool versions; the release job adds both to the GitHub release. @@ -16,27 +16,22 @@ GitHub release. |---|---| | Model vectors through each binding | 7,399 cases: 7,285 run, 114 skipped for the four documented reasons, 0 failed | | Coaching record examples | 20 blocks, 53 shape checks, 0 failed | -| Calculations through the database | 49 cases, 113 requests, 0 differences from the desktop | -| Calculations through the memory snapshot | 99 requests match the desktop; 14 that read device recordings or intensity references get the documented refusal (D326) | -| Both calculation readers on the desktop | 42 worked examples and 71 case requests: 30 and 69 match, 12 and 2 get the documented refusal; the 100,000-input limit holds on both | +| Calculations through the database | 50 cases, 119 requests, 0 differences from the desktop | +| Calculations through the memory snapshot | 105 requests match the desktop; 14 that read device recordings or intensity references get the documented refusal (D326) | +| Both calculation readers on the desktop | 42 worked examples and 77 case requests: 30 and 75 match, 12 and 2 get the documented refusal; the 100,000-input limit holds on both | | Swift package installed by version from a tagged clone of this repository with the release commit staged, on macOS | 33 tests passed: 28 package tests and 5 host tests | | Swift package from the repository root, on macOS | 38 tests passed: 28 package tests, 5 host tests, and 5 example tests | | Android library installed by coordinate in the example app, API 36 (4 KB pages) and API 37.1 (16 KB pages) emulators | 37 tests passed on each, in a debug build and in a shrunk release build: the library's 32 and the example's 5 | -| Android library from source, the same two emulators | 32 tests passed on each | | Guides | 37 code samples in the Swift and Android guides match the example apps' marked regions; every region is shown | | 16 KB alignment of every native library in the shrunk release APK | 4 of 4 libraries aligned (both ABIs of the library and of JNA) | | Desktop round trip | Passed on macOS and on both emulators: the desktop `ath` created the file, the phone library corrected a reading, and the desktop `ath` found the edit at revision 2, revision 1 kept, and a passing `ath check` | -| XCFramework zip | Two staging runs gave the same bytes for `AthleticStandardFFI-3.1.0.xcframework.zip` (SHA-256 `4309b67e…912f`) | +| XCFramework zip | Two staging runs gave the same bytes for `AthleticStandardFFI-3.1.0.xcframework.zip` (SHA-256 `d7af955c…e868`) | | Swift package release commit | Differs from the root `Package.swift` only in the binary target line, and adds the two generated Swift files; the test package resolved version 3.1.0 to it | | Version | Each binding reports 3.1.0, and an outdated 2.1.0 file migrates to SQL step 9 on macOS and on both emulators | -| The whole workspace | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass, also without the `cli` feature for the library and the phone crate; `cargo test` (workspace) gives 942 passed, 0 failed, 18 ignored (the 7 terminal tests ran outside the sandbox); npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (3.0.0 gate 5) passes | +| The whole workspace | `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings` pass, also without the `cli` feature for the library and the phone crate; `cargo test` (workspace) gives 946 passed, 0 failed, 18 ignored (the 7 terminal tests ran outside the sandbox); npm gives 105 passed, 1 skipped (a Windows-only test); the WebAssembly gate (3.0.0 gate 5) passes | -After the rebase, commit `76f6e8d` added a description to every record and result -type and made the core deny missing documentation. It changes only comments, so the -emulator runs were not repeated. On it: `cargo test` gives 942 passed, 0 failed, 18 -ignored; the Swift tests on macOS give 38 passed; the Android library, its tests, and -the example app compile; npm gives 105 passed, 1 skipped; the WebAssembly gate passes; -and every one of the 1,742 items in the generated Swift has a description. +Every one of the 1,742 items in the generated Swift has a description. The core and the +phone crate deny missing documentation, so the build checks this. ## 2. Found and fixed while gathering this evidence @@ -48,6 +43,11 @@ and every one of the 1,742 items in the generated Swift has a description. one device could end the other's session between its sign-in and its refresh. The provider now forgets only the tokens of the person the test signed in as. +- **Found while preparing the review** (progress step 11): `zip` 2.6.1 had open + security advisories and is now 9.9.0; a calendar-day bound on a range calculation + without grouping left out its last day (D335); SPEC.md listed three of the six record + types a coach may write; two skill references listed three of the six score types. + ## 3. Not verified - The iPhone simulator. Xcode's license was not accepted on the build machine, so diff --git a/build-history/v3.1.0/progress.md b/build-history/v3.1.0/progress.md index 7a87a629..3bd82530 100644 --- a/build-history/v3.1.0/progress.md +++ b/build-history/v3.1.0/progress.md @@ -15,6 +15,7 @@ Status: **built; not released.** The plan is [spec.md](spec.md). Evidence: | 8 | Records and calculation answers as generated Swift and Kotlin types (D329) | Mac and two Android emulators pass; iPhone simulator not run | | 9 | The Swift package served from this repository (D332) | staged and installed by version from a tagged clone; the release workflows not run | | 10 | App guides, starting-point examples, and the contributor page | the guide check passes; both examples' tests pass on a Mac and on two Android emulators | +| 11 | Fixes found while preparing the review: `zip` security update, calendar-day range bounds (D335), coach record types in SPEC.md, score types in two skills | done | The phone work was built on 3.0.0 as build steps 12 to 17, and moved here when 3.0.0 was released without it (D334). @@ -204,3 +205,24 @@ was released without it (D334). value of a list of allowed values also says how it is stored. - `mobile/CONTRIBUTING.md` holds the build, test, and release notes. The main README has a "Build an app" section. + +## Step 11: fixes found while preparing the review + +- `zip` 2.6.1 had open security advisories (two critical, two high, one medium). It is + now 9.9.0. In zip 9 reading an entry's name can fail, and the library stops reading + an entry at its declared size by itself; the import safety test accepts either + refusal. The `rustls`, `rustls-webpki`, and `libsql-sqlite3-parser` advisories come + only through `libsql` 0.10.0 in `ath-host`, the newest release, so they wait for it. +- A calendar-day `--from` or `--to` on a range calculation now covers the whole day in + the request's or the profile's time zone (D335). Before, a calculation that did not + group compared the day as text and left out the last day. +- SPEC.md said in three places that a coach writes only coaching notes, plans, and + planned sessions. Since 3.0.0 a coach also writes intensity references, events, and + approvals, as SPEC.md section 6 and the code say. +- The tool skill's grading reference and the CrossFit skill's records reference listed + three score types. There are six: `power`, `distance`, and `energy` were added in + 3.0.0. +- Not changed: the `training_impact` question ("did it change your training: full, + reduced, or none?") can be read two ways. Its values are described only by their + stored names until its meaning is decided. +