From 5496fe6f450e2c2a527ecfcdf3f07a8c6e10df9b Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 23 Nov 2026 16:57:48 -0600 Subject: [PATCH 01/26] Plan version 2.1.3: an optional host for sharing a record. Record the 2.1.3 plan, decisions D254-D267, the hosted-storage study, and the local hosting experiments. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 +- build-history/README.md | 1 + .../v2.1.3/appendix/hosted-storage-options.md | 331 +++++++++++++++ .../v2.1.3/appendix/hosting-experiments.md | 143 +++++++ build-history/v2.1.3/decisions.md | 372 ++++++++++++++++ build-history/v2.1.3/progress.md | 20 + build-history/v2.1.3/spec.md | 400 ++++++++++++++++++ 7 files changed, 1273 insertions(+), 5 deletions(-) create mode 100644 build-history/v2.1.3/appendix/hosted-storage-options.md create mode 100644 build-history/v2.1.3/appendix/hosting-experiments.md create mode 100644 build-history/v2.1.3/decisions.md create mode 100644 build-history/v2.1.3/progress.md create mode 100644 build-history/v2.1.3/spec.md diff --git a/AGENTS.md b/AGENTS.md index 92e42fab..a2afd330 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,11 +21,12 @@ 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, the current version: 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/*/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. -9. **`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. -10. **`build-history/*/progress.md`** — what's done and what's next. -11. **`docs/connections.md`** — per-provider data research (what WHOOP/Oura/Garmin/Apple Health each provide via which path). -12. **`SPEC.md`** — the public field-level format reference. The normative model for version 2.1.2 is the Rust model in `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), 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, planned and not built: an optional host program (`ath-host`) for sharing a record, human coach authorship, SQL migration step 7, and a storage interface with a native SQLite backend and a libSQL remote backend. Its `appendix/` holds the hosted-storage study and the hosting experiments. +9. **`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. +10. **`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. +11. **`build-history/*/progress.md`** — what's done and what's next. +12. **`docs/connections.md`** — per-provider data research (what WHOOP/Oura/Garmin/Apple Health each provide via which path). +13. **`SPEC.md`** — the public field-level format reference. The normative model for version 2.1.2 is the Rust model in `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), 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 f464aa79..522ca053 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -40,6 +40,7 @@ build-history/ | [v2.1.0](v2.1.0/spec.md) | Released. This is the installed software until 2.1.1 is released. | | [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) | Planned: an optional host for sharing a record, coach authorship, and a storage interface with native and libSQL backends. See its [decisions](v2.1.3/decisions.md), [progress](v2.1.3/progress.md), and [storage study](v2.1.3/appendix/hosted-storage-options.md). | ## Drafts that were not approved diff --git a/build-history/v2.1.3/appendix/hosted-storage-options.md b/build-history/v2.1.3/appendix/hosted-storage-options.md new file mode 100644 index 00000000..76075bdc --- /dev/null +++ b/build-history/v2.1.3/appendix/hosted-storage-options.md @@ -0,0 +1,331 @@ +# Where a hosted record can live: options and how to choose + +This study supports D256–D259, D264 and D265. It compares the ways to store athlete +records on a server that many athletes share. It also compares the places the host +program can run. Facts were checked on 2026-11-23 against each vendor's own +documentation. Services change often. Check the current documentation before you +rely on a limit. + +The study does not recommend a vendor. It explains what version 2.1.3 builds and +why, and it gives the questions a developer or operator should answer before +choosing. + +## 1. What the record needs from storage + +These requirements come from the record format and the existing library. They are +the same for every operator. + +| # | Requirement | Why | +|---|---|---| +| R1 | Runs the existing SQL schema and record rules unchanged: STRICT tables, triggers, deferred foreign keys, revision chains, erasure. | The library is the only place record rules live (D210). A second implementation of those rules would drift. | +| R2 | Keeps one database per athlete, for any number of athletes. | A database is the unit of isolation, export, restore, and moving (D256). | +| R3 | Restores one athlete to an earlier moment without changing anyone else. | A shared restore would roll back other athletes or bring back revoked access. | +| R4 | Keeps the complete portable package possible. | The athlete must be able to leave with everything (D82). | +| R5 | Can be reached by a Rust program running on an ordinary server. | The host calls the Rust library for every record operation (D257). | +| R6 | Lets an operator lock each athlete's database with its own key, where wanted. | It limits what a copied disk or backup reveals. | +| R7 | Can be run without any vendor. | Anyone can run their own host. | +| R8 | Is mature enough to hold a health record. | Losing or corrupting a record cannot be undone. | + +Two further facts shape the choice: + +- **Every SQL statement over a network is a round trip.** A local SQLite call takes + microseconds. A call to a database in the same region takes milliseconds. The + library's writes run many statements. Large imports must be sent in batches. +- **The library speaks to SQLite through one crate, rusqlite, in 31 files.** Any + remote option needs a second backend behind the storage interface (D257). The + record rules stay in one place either way. + +## 2. Summary + +"Yes" means documented by the vendor or shown by a test in this study. "No" means +documented as unavailable. "Not stated" means the documentation does not say. + +| Option | R1 SQL rules | R2 many databases | R3 restore one | R5 Rust from any server | R6 own keys | R7 self-run | R8 maturity | +|---|---|---|---|---|---|---|---| +| Native SQLite directory | Yes | Yes, limited by disk | With Litestream | Yes (in process) | Not in 2.1.3 | Yes | SQLite | +| Turso Cloud, libSQL engine | Expected; to qualify (D258) | Yes, no database limit except on the no-cost plan | Yes, 1–90 days by plan | Yes, `libsql` crate | Yes, on its two highest plans | No | Years in production | +| Turso Cloud, Turso engine | To qualify | Yes | Yes | Yes, `turso_serverless` crate | Yes | No | "Early preview" on the cloud | +| Self-run libSQL server (`sqld`) | Expected | Yes, as namespaces | With its S3 backup | Yes, `libsql` crate | Not checked | Yes | Last release 2025-02-14 | +| Bunny Database | Expected (libSQL) | 50 databases of 1 GB in preview | Not documented | Yes, `libsql` crate | Not stated | No | Public preview | +| Cloudflare Durable Objects (SQLite) | Partly: no `BEGIN` or `SAVEPOINT` in `sql.exec` | Yes, unlimited objects, 10 GB each | Yes, 30 days | No: code must run in a Worker | No | No | Generally available | +| Cloudflare D1 | Partly: transactions only through `batch()` | Up to 1,000,000, 10 GB each | Yes, 30 days | Only by a rate-limited HTTP API | No | No | Generally available | +| SQLite Cloud | Expected | Not stated | Yes, 24 hours by default | No Rust SDK | Not stated | No | Not stated | +| Turso Sync on a file written by rusqlite | No: writes not seen | — | — | — | — | — | Failed in test | +| rqlite, dqlite | No | No | — | — | — | Yes | Active | +| Postgres services (Supabase, Neon, Prisma Postgres, Nile) | No: second SQL model | Varies | Varies | Yes | Mostly no | Partly | Mature | +| Device sync engines (PowerSync, ElectricSQL) | Not a store | — | — | — | — | — | — | + +## 3. The options in detail + +### 3.1 Native SQLite files in a directory + +Each athlete gets a private directory with `athlete.ath.sqlite` and its +`attachments/` folder. The host opens the file in process with the same library the +CLI uses. + +- **Fits R1, R4, R5, R7 and R8 without new code.** It is the reference + implementation. Every existing test already covers it. +- **One writer per disk.** SQLite allows one writer per file, and only one host + process may own a directory. More host machines need a routing table that says + which machine serves which athlete. Moving an athlete follows the move protocol + (D267). +- **Disk size limits the number of athletes per machine.** For example, a Railway + volume holds up to 1 TB without contacting Railway, and a service can have only + one volume ([Railway volumes](https://docs.railway.com/volumes/reference)). +- **Backups need a separate tool.** Litestream copies each change in a directory of + SQLite databases to S3-compatible storage within about a second. It restores one + database at a time to a chosen moment ([directory replication](https://litestream.io/guides/directory/)). + Version 0.5.18 was released on 2026-11-03. + - Litestream needs WAL mode and wants to control checkpoints + ([tips and caveats](https://litestream.io/tips/)). The library uses WAL for + writes. Its `close()` runs a truncating checkpoint, and a fresh restore briefly + switches the journal mode. The host must keep connections open and must be + tested with Litestream before the recipe is published. + - Litestream does not copy attachments. The host copies each attachment when it is + uploaded. + - Litestream 0.5.x has no client-side encryption. Only bucket-level encryption is + available ([configuration](https://litestream.io/reference/config/)). +- **Per-athlete keys are possible but not in 2.1.3.** rusqlite can be built with + SQLCipher (`bundled-sqlcipher`). No source confirms that Litestream can replicate + an encrypted file. Version 2.1.3 does not offer this (D264). + +### 3.2 Turso Cloud + +Turso Cloud hosts SQLite-compatible databases reached over the network. It offers +two engines ([Turso Cloud](https://docs.turso.tech/turso-cloud)): + +- **libSQL**, a fork of SQLite that Turso describes as "battle-tested in production + on Turso Cloud for years". Rust programs reach it with the `libsql` crate + (0.10.0, October 2026) with the `remote` feature + ([Rust reference](https://docs.turso.tech/sdk/rust/reference)). +- **Turso**, a rewrite of SQLite in Rust. On Turso Cloud these databases are in + "early preview". Rust programs reach them with `turso_serverless`. The engine + dropped its beta warning in July 2026 and has not reached 1.0. Its maintainers + advise keeping independent backups ([repository](https://github.com/tursodatabase/turso)). + +Facts that matter here: + +- **Database count.** Turso's no-cost plan allows 100 databases. Its other plans + have no database limit. An idle database costs only its storage. +- **Restore.** Each database can be restored to an earlier moment. The window is + 1 to 90 days depending on plan. +- **Own keys.** A database can be encrypted with a key the operator supplies. The + key is passed on each connection and Turso does not store it. It is available on + Turso's two highest plans. A key cannot be changed in place yet + ([encryption](https://docs.turso.tech/cloud/encryption)). +- **Differences from local SQLite** ([limitations](https://docs.turso.tech/cloud/limitations)): + `application_id` and `user_version` are read-only. `journal_mode` and + `busy_timeout` are not supported. The library already treats its metadata table + as authoritative (D93), so the remote backend reads the header values and does + not write them. +- **Not stated in the documentation:** whether `PRAGMA foreign_keys` holds for every + statement on a remote connection, and whether the SQLite online backup API is + available. The JavaScript libSQL client used by 2.1.0 lost the setting between + statements ([remote targets](../../../packages/npm/REMOTE-TARGETS.md)). The + qualification suite tests both (D258). +- **Regions.** The pages read do not list Turso's regions. Place the host and the + databases in the same region and measure the round trip. +- **Ownership.** Supabase announced on 2026-10-02 that it is acquiring Turso. It + says Turso keeps operating its platform and that nothing changes for existing + users ([announcement](https://supabase.com/blog/supabase-is-acquiring-turso)). + +### 3.3 A self-run libSQL server + +The libSQL server (`sqld`) serves many databases ("namespaces") and can back them up +to S3 ([libSQL](https://github.com/tursodatabase/libsql)). It speaks the same +protocol as Turso Cloud's libSQL databases, so the same backend reaches it. Its last +release was v0.24.32 on 2025-02-14, and its maintainers point new projects to the +Turso engine. It is useful for tests and for operators who want the remote mode +without a vendor. It is a weak choice for new production use because it is no longer +actively released. + +### 3.4 Bunny Database + +Bunny Database is built on libSQL and is reached with the same `libsql` crate +([Rust](https://bunny.net/docs/database/connect/rust)). It has been in public preview +since 2026-02-03. Preview accounts are limited to 50 databases of 1 GB each, raised +on request ([limits](https://docs.bunny.net/database/limits)). It documents no +per-database restore, and up to 10 seconds of writes can be lost when its main server +fails ([durability](https://bunny.net/docs/database/durability-and-consistency)). +It is worth testing again when it leaves preview. + +### 3.5 Cloudflare Durable Objects with SQLite storage + +Each Durable Object has its own SQLite database. Objects are unlimited, each holds up +to 10 GB, and each can be restored to any moment in the last 30 days +([limits](https://developers.cloudflare.com/durable-objects/platform/limits/), +[SQLite storage](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/)). +It became generally available on 2025-04-07. + +It does not fit this library as built: + +- Code that uses the database must run inside a Cloudflare Worker. Rust runs there + only as WebAssembly through the `worker` crate, without rusqlite. +- `sql.exec` cannot run `BEGIN` or `SAVEPOINT`. Transactions use the storage API's + own functions, so the store's transaction code would change. +- Keys are managed by Cloudflare + ([data security](https://developers.cloudflare.com/durable-objects/reference/data-security/)). + +Using it means moving the host into Cloudflare, not pointing an existing host at a +database. It is the closest match after Turso for operators who already run on +Cloudflare. + +### 3.6 Cloudflare D1 + +D1 offers up to 1,000,000 databases per account, 10 GB each, and a 30-day restore +([limits](https://developers.cloudflare.com/d1/platform/limits/)). Outside a Worker it +is reached through Cloudflare's HTTP API, which Cloudflare limits to 1,200 requests +every 5 minutes per user ([API limits](https://developers.cloudflare.com/fundamentals/api/reference/limits/)). +A Worker can bind about 5,000 databases. D1 also charges for each database above an +included 100,000. Multi-statement transactions are only available through +`batch()`. These limits rule it out for a host that serves many athletes from +outside Cloudflare. + +### 3.7 SQLite Cloud + +SQLite Cloud (now at sqlite.ai) hosts SQLite databases. Its documentation recommends a +separate database for each tenant ([overview](https://docs.sqlitecloud.io/docs/overview)). +It restores one database to the second, with 24 hours of history by default +([backups](https://docs.sqlitecloud.io/docs/backups)). It has an extension for syncing +copies to devices. It has SDKs for C, Go, JavaScript, PHP, Python and Swift, and none +for Rust. Its documentation does not state a database count limit, a size limit, or +support for keys supplied by the operator. Those questions need an answer from the +vendor before it can be considered. + +### 3.8 Turso Sync on a file written by rusqlite + +Turso Sync keeps a local file and pushes and pulls logical changes. Its conflict rule +is "last push wins", and it only sees changes made through its own connection +([Sync usage](https://docs.turso.tech/sync/usage)). In this study's test, stock `ath` +saved a record into a Sync-created file and Sync reported zero changes to push +([experiments](hosting-experiments.md), test 2). It cannot carry writes made by the +library as built, and last-push-wins conflicts with revision checks (D261). + +### 3.9 rqlite, dqlite and LiteFS + +- **rqlite** serves one database per cluster and does not support explicit + `BEGIN`/`COMMIT` ([FAQ](https://rqlite.io/docs/faq/)). +- **dqlite** is a C library with Go bindings and its own network protocol + ([dqlite](https://github.com/canonical/dqlite)). +- **LiteFS Cloud** shut down on 2024-10-15. Fly.io says it cannot support LiteFS + itself, which is still before 1.0 ([notice](https://community.fly.io/t/sunsetting-litefs-cloud/20829), + [LiteFS](https://docs.fly.io/litefs)). + +None fits a database per athlete with the library's transactions. + +### 3.10 Postgres services + +Supabase, Neon, Prisma Postgres and Nile host Postgres. They are mature, but Postgres +is not SQLite. In this study's test, Postgres rejected the first migration because of +`STRICT` ([experiments](hosting-experiments.md), test 3). A translated schema worked, +but it would be a second SQL model to maintain beside the library (D210, D257). +Their database-per-tenant support also varies: Neon limits projects unless an +account is approved for more, Prisma Postgres allows 1,000 databases, and Nile keeps +tenants as rows in shared tables. + +### 3.11 Device sync engines + +PowerSync keeps SQLite on the device and syncs it with Postgres, MongoDB, MySQL or +SQL Server on the server. Its Rust SDK is in beta. ElectricSQL sends data from +Postgres to devices and leaves writes to your own API. Neither hosts a database per +athlete. Either could sit beside a host later. Neither replaces one. + +## 4. Where the host program runs + +The host is one executable, usually shipped as a container (D265). What it needs +depends on the storage backend. + +| Backend | The host needs | Number of copies | +|---|---|---| +| Native directory | A persistent disk and a long-running process. | One per disk. More machines need routing. | +| libSQL remote | A long-running process with network access. No disk. | As many as needed. | + +Places researched: + +- **A container host with disks, such as Railway.** A service can have one volume. + A service with a volume cannot run replicas, and a redeploy causes a short outage. + Without a volume, a service can run many replicas, up to 42 depending on plan. + Railway encrypts volumes, backups and buckets at rest. Volume backups restore the + whole volume, and wiping a volume deletes its backups + ([volumes](https://docs.railway.com/volumes/reference), + [backups](https://docs.railway.com/volumes/backups), + [security](https://docs.railway.com/enterprise/security)). +- **Supabase Edge Functions.** They run TypeScript, or Rust compiled to + WebAssembly. Each request gets 2 seconds of CPU time, 256 MB of memory and at most + 400 seconds. There is no persistent disk + ([limits](https://supabase.com/docs/guides/functions/limits)). The host cannot run + there as built, and large imports would not fit. Supabase Compute, announced in + October 2026, runs any container. It is a private alpha in one region with no + persistent disk, "for evaluation, not production" + ([alpha](https://supabase.com/blog/supabase-compute-private-alpha)). +- **Cloudflare Workers.** Rust runs only as WebAssembly. See section 3.5. +- **Any machine with Docker.** A rented server or a computer at home works for + either backend. The operator owns updates, disks and network access. + +Attachments need an S3-compatible bucket in remote mode. Railway buckets, Supabase +Storage, Amazon S3 and Cloudflare R2 all speak the S3 protocol. Railway buckets and +Supabase Storage do not keep earlier versions of an object, so a deleted file is gone +unless it was copied elsewhere ([Railway buckets](https://docs.railway.com/storage-buckets), +[Supabase S3](https://supabase.com/docs/guides/storage/s3/compatibility)). + +## 5. What 2.1.3 builds, and why + +Version 2.1.3 builds two database backends (D257): + +1. **Native SQLite directory.** It needs no new dependency, it is what every + existing test covers, and anyone can run it on one machine. It is the reference + that every other backend is compared with. +2. **libSQL remote.** It is the only remote family that meets R1 to R6 together. One + crate reaches three services (Turso Cloud, a self-run libSQL server, Bunny + Database), so the backend is not tied to one vendor's API. Host copies hold no + record data, so an operator can add copies without moving athletes. + +Version 2.1.3 does not build the others: + +- Durable Objects and D1 would need the host to run inside Cloudflare, or would hit + API limits from outside. A Workers-based host is a separate project. +- SQLite Cloud has no Rust client and no stated limits. +- Postgres services need a second SQL model. +- Turso Sync cannot see rusqlite writes and uses last-push-wins. +- rqlite, dqlite and LiteFS do not fit a database per athlete. + +## 6. How to choose for your own host + +Answer these questions in order. + +1. **Do you need anyone but the athlete to reach the record?** If not, use `ath` with + a local file. You need no host. +2. **Will one machine hold every record you expect?** Estimate each record's size + from your own data: `ath stats` reports it. If one disk holds them all, the native + directory backend is the simplest choice. Add Litestream and a scheduled package + export. +3. **Do you need more than one copy of the host running at once, or no disks to + manage?** Use the libSQL remote backend. Choose a provider that has passed the + qualification suite (D258), and put it in the same region as the host. +4. **Must every part run on machines you control?** Use the native directory backend, + or a self-run libSQL server if you accept its release status. Several native hosts + need a routing table and the move protocol. +5. **Do you need each athlete locked with a separate key?** Use the libSQL remote + backend with a provider that accepts keys you supply, and keep the keys in a key + service outside the host. The native backend does not offer this in 2.1.3. +6. **Who can read the records?** Whoever runs the host and its storage can read them. + Per-athlete keys limit what a stolen disk or backup reveals. They do not stop + someone who controls the running host. Tell athletes who runs the host and the + storage when they connect. + +Measure before you commit. Run the qualification suite against your account and +region. Time a workout save and a large import. + +## 7. What would change this decision + +- A provider that passes the qualification suite with a different protocol. It gets + a backend behind the same interface. +- Turso-engine databases leaving early preview on Turso Cloud. They would then be + qualified with `turso_serverless`. +- Bunny Database leaving preview with documented per-database restore. +- Litestream confirming support for encrypted SQLite files. The native backend could + then offer per-athlete keys. +- Supabase Compute becoming generally available with a persistent disk. It would + become another place the host can run. +- A change in Turso's terms or operation after the acquisition. The libSQL backend + also reaches other servers, and every athlete can be exported and moved. diff --git a/build-history/v2.1.3/appendix/hosting-experiments.md b/build-history/v2.1.3/appendix/hosting-experiments.md new file mode 100644 index 00000000..01f18b4d --- /dev/null +++ b/build-history/v2.1.3/appendix/hosting-experiments.md @@ -0,0 +1,143 @@ +# Hosting experiments on version 2.1.2 + +These local experiments informed D256, D257, D259, D261 and D263. They ran on +2026-11-22 and 2026-11-23 against commit 073f9bc on macOS arm64. All athlete data was +synthetic. No live cloud account was used. Database, HTTP and object-storage servers +ran on the same machine. The comparison of services is in +[hosted-storage-options.md](hosted-storage-options.md). + +## Fixture + +The checked-in demo database: 491,520 bytes, 25 current records, 26 revisions, one +attachment, and one heart-rate series. SQLite listed 43 tables, 60 indexes, 16 +triggers and 5 views. Its package was four files totalling 61,028 bytes. + +The demo attachment is 68 bytes, which says little about media transfer. The tests +also used an invented 1024 × 683 PNG of 2,099,567 bytes, and a valid PNG padded to +the 26,214,400-byte attachment limit. + +## 1. A Rust host over the library, one directory per athlete + +A 33-line test server called the library unchanged. Each athlete had a private +directory. The server resolved the directory from the signed-in athlete, never from +the request. + +- Two athletes had records with identical IDs. Each athlete's credentials could read + and change only their own record. +- A Swift client on macOS and a separate agent request corrected the same workout + from the same revision. One succeeded. The other received a conflict. Exactly one + revision was added. +- A write lock held on one athlete did not delay a write for another athlete. +- A test coach credential could read selected workout fields. It could not correct a + record, read the profile, or reach the other athlete. +- An official MCP SDK client called a tool through the same server, and the same + athlete check applied. +- A device copy edited offline replayed a stale correction on reconnect. The host + refused it, and both values stayed readable. An unrelated offline edit applied. + +**What it shows:** the library's revision checks already give safe shared writes +when every write goes through one host. Separation between athletes depended on the +server's own checks. + +## 2. Turso Sync around a file written by rusqlite + +The Turso 0.8.4 local sync server and Sync client were seeded with the demo. Stock +`ath` then added one athlete report to the synced file. `ath` saved it and could read +it. On reopening, the Sync client found 26 local records and zero pending changes. A +fresh client pulled 25 records. + +A separate two-client test of conflicting edits kept the last push. No stale-revision +response was produced. + +**What it shows:** Sync cannot carry writes made by the library as built. Its +conflict rule replaces the library's revision check (D261). + +## 3. The same edit written through Turso's own client + +In a fresh copy, the same report was written through Turso's client: the record, +its revision, its typed row and the database revision. Sync saw four pending +changes, and the second client received the report. After the attachment and the +two file header values were supplied, stock `ath` exported the receiving copy. All +four package files matched a stock export byte for byte. + +**What it shows:** a SQLite-compatible engine can hold the record exactly. Writes +must go through that engine's own connection. That is what the libSQL backend does +(D257). The libSQL remote protocol itself was not tested here. The qualification +suite does that (D258). + +## 4. Postgres + +Postgres rejected the first migration at `STRICT`. A small translated model loaded +the fixture rows. Row-level security with separate login roles hid other athletes' +rows. A translated workout correction kept its history, and stock `ath` restored the +exported result. + +**What it shows:** Postgres can enforce the rules only through a second SQL model +maintained beside the library (D257). + +## 5. A report with a photo, a retry, and a refresh + +The test made a report with the 2,099,567-byte photo. The photo went to an +S3-compatible test server. The rows went into a database through Turso's client, with +a receipt in the same transaction. + +- A truncated upload left the database at revision 3, with no report and no + attachment. +- A complete upload whose reply was then discarded, followed by a retry, left one + report, one attachment and one receipt at revision 4. +- A reader fetched the changed rows and the photo. It detected a partial download and + accepted the intact retry. +- The updated copy passed `ath check`. Its five-file export matched the reference + export byte for byte. A clean import restored the photo intact. + +**What it shows:** upload, verify, then commit with a receipt gives a safe retry +(D259, D261). + +## 6. Export, restore, and files beside the record + +After edits and the 2 MB attachment, the record was exported, restored into a new +workspace, checked and exported again. Every package file matched byte for byte. + +A separate test stopped a workspace and recovered the whole folder. It brought back an +extra report written beside the database, which the standard package does not +include. + +**What it shows:** the package carries the record exactly. A host backup must also +list any supported extra files separately. + +## 7. Two copies with the same revision and different contents + +Two copies were restored from the same package. Each received a different note +through stock `ath`. Both then reported the same database ID and the same database +revision. Their package manifests differed. + +**What it shows:** a refresh that compares only the database ID and revision can +silently overwrite local work. A refresh must compare content (D263). + +## 8. Attachments stored inside the database + +Two attachments stored as BLOBs through Sync kept their bytes. The file sizes and the +byte counts the Sync SDK reported were: + +| File | Sent by the uploading client | Received by a new client | +|---:|---:|---:| +| 2,099,567 | 2,801,287 | 2,121,664 | +| 26,214,400 | 34,954,398 | 26,306,540 | + +The S3 test client moved the same 2,099,567-byte payload unchanged. + +**What it shows:** BLOBs work but add transfer, enlarge every database copy, and +still need ordinary files for export and erasure (D259). + +## Limits of this evidence + +- Everything ran on one machine with synthetic data. +- No live provider account, region or network latency was measured. +- The libSQL remote protocol, provider tokens, per-database keys and provider + restores were not tested. +- The test server implemented one coach read grant and returned one conflict code for + every write error. +- Live sign-in, an iOS device and a remote MCP authorization flow were not tested. + +The qualification suite (D258) and the build steps in the [spec](../spec.md) cover +these. diff --git a/build-history/v2.1.3/decisions.md b/build-history/v2.1.3/decisions.md new file mode 100644 index 00000000..417f08ec --- /dev/null +++ b/build-history/v2.1.3/decisions.md @@ -0,0 +1,372 @@ +# v2.1.3 decisions + +Decisions continue after D253. Earlier decisions stay as they are. The plan is +[spec.md](spec.md). The storage research is in +[hosted-storage-options.md](appendix/hosted-storage-options.md), and the local +experiments are in [hosting-experiments.md](appendix/hosting-experiments.md). + +## D254. Sharing a record ships as 2.1.3, through an optional host program + +The program, npm package, record package, and database metadata use 2.1.3. D152's +single version rule stays. The SQL migration step becomes 7. The maintainer chose +2.1.3 for this work on 2026-11-22. + +Sharing is a separate executable, `ath-host`. It calls the library for every record +operation. The `ath` CLI is built without it and works as before: one local file, no +account, no network (D75). Running a host is a choice an operator makes. + +Version 2.1.3 adds one author variant (D255) and three internal tables. The published +version rule says a patch adds no fields (D96; SPEC.md section 13). As with D227, +this is an exception made by the maintainer's choice. SPEC.md section 13 records it. +Every 2.1.2 record and package stays valid 2.1.3 data. A 2.1.2 program refuses a +2.1.3 database by its SQL step. + +This ends the deferral of sharing in D96. `ath share` stays a placeholder. Sharing +happens through a host, not through a command that sends files. + +Rejected alternatives: + +- Put the host inside `ath`. Rejected because the CLI would gain network code, + sign-in, and dependencies that local users never need. +- Use 2.2.0, which the version rule suggests. Not chosen: the maintainer chose 2.1.3. + The change is mechanical if it is made later. +- Share by sending files between devices. Rejected because a coach must be able to + read and add while the athlete's device is off. + +## D255. A coach is a record author + +`RecordActor` and `AuthoredRecordAuthor` gain a `coach` variant with two fields: +`coach`, the display name when the record was written, and `coach_id`, an opaque +UUID assigned by the host that accepted the write. + +A coach may author `coaching_note`, `training_plan`, and `planned_session` records +and their revisions. A coach cannot author a measured record or an athlete report. +The two-tier wall holds: coach work is authored advice, like agent advice (D228). + +The name and ID are history, not credentials. A host grants rights only from its own +sign-in. A matching name or ID at a new host gives no access. + +Notes and plans must keep their author after the athlete changes coach or host. +Today a coach's note can only be labelled as written by the athlete, an agent, or a +tool. All three are wrong. + +The SQL `author_type` columns have no CHECK constraint, so no table is rebuilt. + +Rejected alternatives: + +- Store coach identity only on the host. Rejected because the author would be lost + when the record leaves the host. +- Record the coach as an agent. Rejected because it misstates who wrote the advice. +- Use the coach's email address as the ID. Rejected because email addresses change + and identify a person outside the record. + +## D256. One database per athlete in every hosted mode + +Every storage backend keeps each athlete's record in its own database. The host's +directory of accounts, grants, clients, and record locations is a separate database. +A request names a host-assigned resource ID. The host resolves it to a database only +after the access check. A record's database ID is not proof of ownership. + +A database is already the unit the library validates, migrates, exports, restores, +and erases. Keeping it as the unit of hosting means one athlete can be restored, +moved, or deleted without touching another. A fault in one athlete's database cannot +change another's rows. It also matches how the services in the study scale: by number +of databases, not size of one database. + +Rejected alternatives: + +- One shared database with an athlete column on every row. Rejected because every + query would need a filter that the schema does not have, a restore would roll back + every athlete, and the package format is per athlete. +- Several athletes in one directory. Rejected because the library places attachments + in a folder beside the database, so athletes would share it (experiment 1). + +## D257. The library gets a storage interface with two database backends + +The store's SQL calls go through one internal interface in `src/store/`. Two backends +implement it in 2.1.3: + +- **Native**: a local SQLite file through bundled rusqlite. Every build has it. +- **libSQL remote**: a database on a server that speaks the libSQL protocol, through + the `libsql` crate. Only `ath-host` has it, behind the `libsql-remote` Cargo + feature. + +The library stays synchronous. The host runs storage work on blocking worker threads. +The record rules stay in one place: the encoder, the revision checks, and the +migrations are the same code on both backends. + +Native is the reference. It needs no new dependency, every existing test covers it, +and anyone can run it on one machine. + +libSQL remote is the second backend because it is the only remote family that meets +the study's requirements R1–R6 together: SQLite rules, unlimited databases per +account, restore of one database, a Rust client from any server, and keys supplied +by the operator. One crate reaches three services (Turso Cloud, a self-run libSQL +server, and Bunny Database), so the backend is not tied to one vendor's API. Host +copies hold no record data, so an operator can add copies without moving athletes. +D93 already planned a hosted libSQL adapter on the same domain operations. D210 +removed libSQL only from local use, and local use keeps rusqlite. + +Rejected alternatives (details in the study): + +- Postgres services (Supabase, Neon, Prisma Postgres, Nile). Rejected because + Postgres rejects the schema and needs a second SQL model (experiment 4). +- Cloudflare Durable Objects. Not built in 2.1.3 because the host would have to run + inside a Worker as WebAssembly, without rusqlite and without `BEGIN`. +- Cloudflare D1. Rejected because, from outside Cloudflare, it is reached only + through an HTTP API limited to 1,200 requests every 5 minutes. +- SQLite Cloud. Not built because it has no Rust client and states no database count + or size limits. +- Turso Sync of a file written by rusqlite. Rejected because Sync did not see the + write (experiment 2), and its conflict rule is last push wins. +- rqlite, dqlite, LiteFS. Rejected because they do not fit one database per athlete + with the library's transactions, and LiteFS Cloud has shut down. +- Make the library asynchronous. Rejected because the CLI and every existing caller + would change for a need only the host has. +- Let the host write rows with its own SQL. Rejected because it would be a second + copy of the record rules (D210). + +## D258. A storage provider is supported only after the qualification suite + +A backend or provider is listed as supported only after a named, reproducible run of +the qualification suite in spec section 8 passes. The report names the provider, +engine, region, crate versions, and date. + +The first runs are a local libSQL server in continuous integration and Turso Cloud +libSQL-engine databases in a manual run. Turso-engine databases on Turso Cloud stay +unlisted while Turso calls them early preview. Bunny Database stays unlisted while it +is in preview. + +On a libSQL server, the remote backend: + +- reads `application_id` and `user_version` but never writes them. Turso Cloud makes + them read-only, and the metadata table is authoritative (D93); +- skips `journal_mode` and `busy_timeout`, which Turso Cloud does not support; +- runs each write as one interactive transaction on one connection, and refuses to + open a database where a dangling reference is not rejected; +- replaces the verified local backup before a migration with a provider restore point + plus a complete package export, and refuses to migrate if either fails (D124); +- sends large imports in batches inside one transaction. + +Turso's documentation does not say whether foreign keys hold on every remote +statement. The JavaScript client in 2.1.0 lost that setting between statements +([remote targets](../../packages/npm/REMOTE-TARGETS.md)). The suite tests it rather +than assuming it. + +Rejected alternatives: + +- List providers from their documentation. Rejected because the documentation leaves + the foreign-key and backup questions open. +- Qualify Turso-engine databases first. Not chosen because they are in early preview + on Turso Cloud, while libSQL has years in production there. + +## D259. Attachments live in a directory or an S3-compatible bucket + +The native backend keeps attachments in the folder beside the database, as today. The +remote mode keeps them in any S3-compatible bucket under `/attachments/`. + +An upload goes to a staging key first. The host checks length, media type, and +SHA-256, then commits the record that names the file, then moves the file to its final +key. Downloads use short-lived signed links issued after the permission check. A +cleanup job removes staged files that no committed record names. + +The S3 protocol is the common interface of every bucket service the study found, so +operators can choose any of them. Upload, verify, then commit gives a safe retry +(experiment 5). + +Rejected alternatives: + +- Store attachments as database BLOBs. Rejected because they add transfer, enlarge + every copy and backup of the database, and still need ordinary files for export and + erasure (experiment 8). +- A vendor's own file API. Rejected because it ties the host to one vendor. + +## D260. Sign-in is provider-neutral OpenID Connect + +The host accepts OAuth access tokens from one configured OpenID Connect provider. It +checks issuer, signature, expiry, intended API, and client. It maps the issuer and +subject to a host principal. Email is never the identity. + +Native apps sign in through the system browser with the authorization code flow and +PKCE (RFC 8252). The host publishes protected-resource metadata (RFC 9728) so CLI, +mobile, and MCP clients can find the provider. + +Two recipes are tested with the same API tests: a hosted provider (WorkOS AuthKit) +and a self-run provider (Keycloak). Other providers that meet the same checks work +without code changes. + +The operator claims the first owner with a one-time local setup command. An athlete +accepts their own invitation. An invitation from a coach cannot make anyone an owner. + +Rejected alternatives: + +- Build accounts and passwords into the host. Rejected because account recovery and + multi-factor sign-in are hard to do safely, and providers already do them. +- Support one provider only. Rejected because an operator must be able to run every + part without a vendor. +- Let the sign-in provider decide record access. Rejected because only the athlete's + grant can give access (D262). + +## D261. Shared edits go through the host + +While a record is connected to a host, edits that others should see are sent to the +host. The host checks the grant, the expected revision, and the request ID, and +commits through the library. Devices refresh from accepted changes (D263). Shared +edits need a connection. + +Every accepted request writes a receipt in the same transaction as the change. A +repeated request with the same ID and body returns the original result. The same ID +with a different body is a conflict. A stale correction is refused, and the client +keeps the person's version for review. + +The library's revision checks already make shared writes safe when one place accepts +them (experiment 1). Coaches only add notes and programming, so concurrent offline +editing by several people is not needed. + +Rejected alternatives: + +- Sync database files between devices and the host. Rejected because the tested sync + did not see library writes, and last-push-wins discards a stale edit instead of + keeping it for review (experiment 2). +- Merge offline edits automatically. Rejected as unnecessary for append-only coach + work, and unsafe for corrections to measured data. + +## D262. Grants are checked on every request; revocation raises an access epoch + +The athlete grants a named coach, through a named app, any of three permissions: read +workout summaries, add coach notes, add programming. Nothing is selected until the +athlete approves. The host checks the current grant on every request, including +lists, counts, searches, attachments, and queued work. + +Revoking a grant raises an access epoch stored in the athlete's database. A coach +write commits only if the epoch it checked is still current, in the same transaction. +A write ordered after the revocation fails. + +The grant directory and the athlete's database are separate databases, so one +transaction cannot cover both. The epoch puts the deciding value inside the athlete's +database. This works the same when several host copies serve one athlete. + +Rejected alternatives: + +- Check the grant only when the request starts. Rejected because a write could commit + after the athlete revoked access. +- Route every grant change and write for an athlete through one process. Rejected as + the only mechanism because the remote mode allows many host copies. +- Let a "read training" grant return full workout JSON. Rejected because workouts hold + routes and heart-rate data that the summary grant does not cover. + +## D263. A device refresh compares content, not only the database revision + +A device keeps an ordinary SQLite copy. It remembers the database revision and the +deterministic package manifest digest of the last copy it verified. Before applying +host changes, it checks that the local file still matches that digest. If it does not, +the device keeps the local file, downloads the hosted copy beside it, and asks the +owner. It never chooses a winner by itself. + +Changes come from `internal_change_log` and are applied through the library with their +revisions unchanged. If a change is missing or cannot be applied, the device falls +back to a verified full package. + +Two copies with different notes reported the same database ID and revision +(experiment 7). Comparing only those numbers would overwrite the athlete's work. + +Rejected alternatives: + +- Replace the device copy with the hosted copy on every refresh. Rejected because it + discards offline local work. +- Copy raw rows into the device database. Rejected because it bypasses the library's + checks. + +## D264. Backups, restores, and keys depend on the backend + +Native backend: Litestream copies each athlete database to S3-compatible storage. The +host copies each attachment when it is uploaded. A scheduled job exports each +athlete's complete package to storage with separate credentials. The Litestream recipe +is published only after it is tested with the library's checkpoints and restores. + +libSQL remote backend: the provider's per-database restore, plus the same scheduled +package export, plus a copy of the attachment bucket. + +Every restore is one athlete. It starts isolated, invalidates sessions, and replays +later erasures and revocations before it serves requests. + +Per-athlete keys: the libSQL backend passes a per-database key when the provider +supports it. The host reads keys from a key service the operator configures, never +from its own directory database. The native backend has no per-athlete encryption in +2.1.3. SQLCipher is a rusqlite build option, but no source confirms that Litestream +can replicate an encrypted file. + +Whoever runs the host and its storage can read records. Keys limit what a copied disk +or backup reveals. The host tells the athlete who runs the host and the storage when +they connect. + +Rejected alternatives: + +- Rely only on a provider's volume snapshots. Rejected because they restore every + athlete at once, and on some hosts wiping the volume deletes them. +- Rely only on a provider's database restore. Rejected because the Turso engine's + maintainers advise independent backups, and the package is the format an athlete + can open anywhere. +- Offer native encryption in 2.1.3. Deferred until backups of encrypted files are + tested. + +## D265. The host is one long-running program + +`ath-host` is one executable, shipped with a container definition. It needs a +long-running process. The native backend also needs a persistent disk, and only one +copy may own that disk. The remote backend needs no disk, and any number of copies +may run. + +Large provider imports take minutes and hundreds of megabytes. A program that runs +per request with seconds of CPU time cannot do them. + +Rejected alternatives: + +- Supabase Edge Functions. Rejected because each request gets 2 seconds of CPU time, + 256 MB of memory, and no persistent disk. +- Cloudflare Workers. Rejected for 2.1.3 because Rust runs there only as WebAssembly, + without rusqlite. +- Supabase Compute. Not a target while it is a private alpha "for evaluation, not + production" with no persistent disk. + +## D266. Clients reach records only through the host API + +Apps, the npm client, Swift code, and MCP tools talk to the host's versioned HTTPS +API. They never receive database credentials. The npm client gains an explicit host +connection. Its handling of `libsql:` and other database URLs stays as +[REMOTE-TARGETS.md](../../packages/npm/REMOTE-TARGETS.md) describes. + +The API description is generated from the Rust definitions, like the npm protocol +declarations, and `cargo test --test generated` checks it. Version 1 contains only operations whose permission and output +were reviewed. A local command becomes remote only after that review. + +A database credential would let a client bypass grants, receipts, and the access +epoch. + +Rejected alternatives: + +- Give each app a database token limited to one athlete. Rejected because the token + would expose the whole database, beyond any grant. +- Expose the local worker protocol over the network. Rejected because some of its + operations take local file paths. + +## D267. A move between hosts has one writer at every step + +Moving a record to another host follows five steps: connect an empty destination, +freeze the source, verify and restore privately at the destination, retire the source +writer with a single-use activation bound to this transfer, then activate the +destination. At most one host accepts writes at any moment. A lost reply is retried +with the same transfer ID. + +If the source cannot be reached, the owner can restore from a device copy or backup. +That copy is labelled a recovered fork, because software cannot prove an unreachable +host stopped writing. + +Changing coach never moves a record. It changes grants only. + +Rejected alternatives: + +- Copy the database and switch clients at once. Rejected because writes made during + the copy would be lost or duplicated. +- Let the destination activate after a timeout. Rejected because a timer cannot prove + the source stopped. diff --git a/build-history/v2.1.3/progress.md b/build-history/v2.1.3/progress.md new file mode 100644 index 00000000..c5d1f7c9 --- /dev/null +++ b/build-history/v2.1.3/progress.md @@ -0,0 +1,20 @@ +# v2.1.3 progress + +Status: **planned; not built**. The plan is [spec.md](spec.md). + +| Step | What | Status | +|---|---|---| +| 1 | Plan, decisions D254–D267, storage study, hosting experiments | done | +| 2 | Version 2.1.3, migration 007, coach authorship | not started | +| 3 | Storage interface with the native backend behind it | not started | +| 4 | libSQL remote backend and the qualification suite | not started | +| 5 | `ath-host` native directory mode: connect, read, write, attachments, refresh, restore | not started | +| 6 | Sign-in and grants | not started | +| 7 | Remote mode with object storage and several host copies | not started | +| 8 | Moves and backups | not started | +| 9 | Clients, starter, `docs/hosting.md`, container and setup guide | not started | +| 10 | Scale and fault runs, release evidence | not started | + +The experiments in step 1 ran on 2.1.2 with synthetic data on one machine +([hosting-experiments.md](appendix/hosting-experiments.md)). No live provider, region, +or network latency has been measured yet. Steps 4 and 7 do that. diff --git a/build-history/v2.1.3/spec.md b/build-history/v2.1.3/spec.md new file mode 100644 index 00000000..58171dbe --- /dev/null +++ b/build-history/v2.1.3/spec.md @@ -0,0 +1,400 @@ +# Athletic Standard 2.1.3 — an optional host for sharing a record + +Status: **approved direction; not built; not released**. Nothing in this plan runs a +hosted service, publishes a package, or lists a skill. + +Today a record lives in one file on one machine. An athlete who works with a coach has +no supported way to let the coach read selected training, or add a note, while the +athlete's device is off. Version 2.1.3 adds an optional host program, `ath-host`. It +serves many athletes' records through a documented HTTPS API. Each athlete keeps a +complete copy that opens offline in ordinary `ath`. Local use does not change and needs +no account (D75, D254). + +The program, the npm package, the record package, and the database metadata use 2.1.3 +(D254). The SQL migration step becomes 7. + +The research behind the storage choices is in +[hosted-storage-options.md](appendix/hosted-storage-options.md). The local experiments +are in [hosting-experiments.md](appendix/hosting-experiments.md). + +## 1. The result + +| Person | What they can do | What success looks like | +|---|---|---| +| Athlete using `ath` alone | Nothing changes. | It works offline with no account. | +| Athlete who connects a host | Upload an existing record, keep a device copy, and refresh it. | Records, history, series, and attachments arrive. The device shows when it last refreshed. A refresh never overwrites local work silently. | +| Athlete working with a coach | Grant a named coach, through a named app, any of three permissions. Revoke them. | The coach sees only what was granted. The next request after a revocation fails. Past coach notes keep their author. | +| Coach | See a roster of the athletes who granted access. Read workout summaries. Add notes and programming. | The coach cannot correct, delete, or export the athlete's history. | +| Host operator | Run the host on one machine or on several, with either storage backend. | Setup, backup, and restore work from the written guide on a clean machine. | +| App developer | Sign a person in, connect to their host, and read and write within grants. | Two independently registered apps use the same record. The athlete can disconnect either one. | +| Athlete leaving a host | Export the complete record, or move it to another host. | The copy opens in stock 2.1.3. Old credentials give no access at the new host. | + +## 2. Scope + +In 2.1.3: + +- Human coach authorship in the record (D255). +- A storage interface in the library, with a native SQLite backend and a libSQL remote + backend (D257, D258). +- Attachments in a local directory or an S3-compatible bucket (D259). +- `ath-host`: sign-in, grants, the versioned API, write receipts, device refresh, moves + between hosts, backups, and limits (D256, D260–D265, D267). +- Clients: a host connection in the npm package, a Swift example, and a small MCP server + (D266). +- `docs/hosting.md`, a guide for operators and developers written from the storage + study. +- A container definition and a setup guide for one machine. + +Not in 2.1.3: + +- A running hosted service. The build ships software and guides. +- Automatic merging of offline edits made by several people (D261). +- Direct database sync between a device and a host database (D261). +- Postgres or any other non-SQLite backend (D257). +- Per-athlete encryption keys on the native backend (D264). +- Changes to calculation methods, skills, or the model gateway key. + +## 3. Who owns what + +| Part | Owns | Does not own | +|---|---|---| +| Library (`src/`) | The record model, validation, revisions, the single encoder, migrations, export and restore, the storage interface and both backends. | Accounts, grants, network requests. | +| `ath` CLI | Local commands, unchanged. Built without the remote backend. | Hosting. | +| `ath-host` | Token checks, grants, the API, receipts, refresh, moves, backups, and limits. It calls the library for every record operation. | Record rules. It never writes record tables with its own SQL. | +| Clients | The sign-in flow, the user interface, and API calls. | Permission decisions. The host makes them. | + +There is one set of record rules (D210). The host and every backend use it. + +## 4. The record in 2.1.3 + +### 4.1 Coach authorship (D255) + +`RecordActor` and `AuthoredRecordAuthor` gain: + +```json +{ "author_type": "coach", "coach": "Display name when written", "coach_id": "6f1c…" } +``` + +The host that accepted the write assigns `coach_id`, an opaque UUID. A coach may author +`coaching_note`, `training_plan`, and `planned_session` records and their revisions. A +coach cannot author a measured record or an athlete report. The two-tier wall holds. + +The Rust model, semantic checks, JSON Schema, npm protocol declarations, and Zod +compatibility schemas gain the variant. The SQL `author_type` columns have no CHECK +constraint, so no table is rebuilt. + +### 4.2 Migration 007 + +`007-version-2-1-3.sql` sets the metadata to 2.1.3 and SQL schema 7. It adds three +internal tables and changes no athlete-owned row (D211): + +- `internal_change_log`: one row for each record revision, deletion, and erasure, with + the database revision that committed it. Triggers fill it in the same transaction, so + direct SQL writers are included. The host reads it to answer "what changed since + revision N" (D263). +- `internal_write_receipts`: one row for each accepted host request: actor, app, + operation, request ID, a keyed digest of the request, and the resulting IDs and + revisions. It holds no request body and no health values (D261). +- `internal_access_state`: one row holding the access epoch (D262). Revoking a grant + raises it. + +None of the three is exported in a package. All are listed in `spec/sql/contract.json` +as internal, like `internal_pending_file_operations`. A local database that never +connects to a host uses only the change log. + +On the native backend, the migration keeps the preview, verified backup, confirmation, +and rollback rules (D124, D211). On the libSQL backend, a provider restore point and a +complete package export replace the verified backup (D258). + +### 4.3 Versions + +- Records and packages written as 1.0.0 through 2.1.2 stay valid. Packages from 2.0.0 + onward still import. +- A package that contains a coach author declares 2.1.3. A 2.1.2 program refuses it + with its existing message. +- A 2.1.2 program refuses a 2.1.3 database by its SQL step. +- `schema/2.1.3/` is generated. `schema/2.1.2/` is not rewritten. +- SPEC.md section 13 records the version-rule exception (D254). + +## 5. Storage + +### 5.1 The storage interface (D257) + +The store's SQL calls go through one internal interface in `src/store/`. It covers what +the store uses today: execute, query, prepared statements, immediate write transactions, +and batches. About 340 call sites in 31 files move behind it. + +| Backend | Opens | Used by | Built into | +|---|---|---|---| +| Native | A local SQLite file through bundled rusqlite. | The CLI, the npm executable, and the host's directory mode. | Every build. | +| libSQL remote | A database on a server that speaks the libSQL protocol, through the `libsql` crate. | The host only. | `ath-host` only, behind the `libsql-remote` Cargo feature. | + +The library stays synchronous. The host runs storage work on blocking worker threads +and drives the libSQL client there. The CLI gains no network code and no dependency. + +### 5.2 Differences on a libSQL server (D258) + +- `application_id` and `user_version` are read but never written. The metadata table is + authoritative (D93). +- `journal_mode` and `busy_timeout` are skipped. The server manages both. +- Each write is one interactive transaction on one connection. The backend refuses to + open a database where a dangling reference is not rejected. +- The SQLite online backup API is not used. Section 4.2 says what replaces it. +- Large imports send rows in batches inside one transaction. Every statement is a + network round trip. + +### 5.3 Attachments (D259) + +- **Directory store:** the folder beside the database, as today. +- **Object store:** any S3-compatible bucket, under `/attachments/`. + An upload goes to a staging key. The host checks length, media type, and SHA-256, + commits the record that names the file, then moves the file to its final key. + Downloads use short-lived signed links issued after the permission check. A cleanup + job removes staged files that no committed record names. + +Attachments are never database BLOBs. + +### 5.4 One database per athlete (D256) + +Each athlete has one database in every backend. The host directory (principals, grants, +registered clients, record locations, routing) is a separate database on the same +backend. A request names a host-assigned resource ID. The host resolves it after the +access check. + +### 5.5 Choosing a backend + +| | Native directory | libSQL remote | +|---|---|---| +| Runs on | One machine with a persistent disk. | Any machine with network access, plus a libSQL server or service. | +| Copies of the host | One per disk. More machines need routing (section 6.1). | Any number. | +| Athletes per host | Limited by disk size. | Limited by the provider. | +| Backups | Litestream, attachment copies, scheduled package export. | Provider restore, attachment bucket copy, scheduled package export. | +| Per-athlete keys | Not in 2.1.3. | Where the provider supports them. | +| Each operation | In process. | Network round trips. | +| Vendor needed | No. | No, if you run a libSQL server yourself. | + +The [study](appendix/hosted-storage-options.md) section 6 gives the questions to ask. + +## 6. The host + +### 6.1 Modes + +**Native directory mode.** One host process owns a data directory: + +``` +/host.sqlite directory: principals, grants, clients, locations +/athletes//athlete.ath.sqlite +/athletes//attachments/ +/staging/ uploads and imports before validation +``` + +A process lock on each athlete directory allows one writer. Several machines can each +own a set of athletes. The directory names the machine that serves each athlete, and a +request for another machine's athlete is forwarded or redirected. Only one machine +accepts writes for an athlete at a time (D267). + +**Remote mode.** Host copies hold no record data. Any copy can serve any athlete. The +libSQL server orders writes to each database. Revision checks, receipts, and the access +epoch handle races between copies (D261, D262). + +### 6.2 Sign-in (D260) + +- One configured OpenID Connect provider. The host checks issuer, signature, expiry, + audience, and client, and maps issuer and subject to a principal. +- Native apps use the system browser with authorization code and PKCE (RFC 8252). +- The host publishes protected-resource metadata (RFC 9728) for CLI, mobile, and MCP + clients. MCP clients follow the MCP authorization specification. +- Tested recipes: WorkOS AuthKit and Keycloak, with the same API tests. +- `ath-host setup` claims the first owner once, on the machine. Athletes accept their + own invitations. A coach's invitation cannot make anyone an owner. +- Recovery uses the provider plus an owner recovery procedure the operator documents. + Recovery rotates sessions. + +### 6.3 Grants (D262) + +| Grant | Allowed | Excluded | +|---|---|---| +| Read workout summaries | List current workouts: record ID, revision, start and end, activity type. | Routes, descriptions, raw samples, source IDs, reports, attachments, extensions, full record JSON. | +| Add coach notes | Append a note with optional title. Evidence links only to revisions visible under the read grant. | Reading other notes, correction, deletion. | +| Add programming | Create plans and planned sessions with schedule and blocks. Link sessions only to plans this coach and app created for this athlete. | Personal records, completion flags, completed workout links, deletion, editing existing plans. | + +- Nothing is selected until the athlete approves. +- The owner keeps full reads, exports, corrections, imports, deletion, and erasure. +- Lists are filtered by grant before counting, sorting, and paging. Attachments, links, + evidence, and derived values follow the same rule. +- Errors, IDs, counts, and timing do not reveal another athlete's records. +- Caches are keyed to the grant version or not shared. +- Revocation raises the access epoch. A write ordered after it fails. Data already + delivered cannot be recalled. + +### 6.4 Writes and retries (D261) + +Example: a coach adds a note. + +1. The app sends `POST /v1/athletes/{id}/notes` with an `Idempotency-Key` header. +2. The host checks the token and the grant, and reads the access epoch. +3. The library commits the note, its first revision, the change-log row, and the receipt + in one transaction. The commit fails if the epoch changed. +4. The response has the record ID and revision. Repeating the request returns the same + result. The same key with a different body is a conflict. + +Corrections name the expected revision. A stale correction is refused, and the client +keeps the person's version for review. Imports keep the whole-database revision check +and an owner-only preview bound to the file digest and database revision. + +### 6.5 API version 1 + +Operations: host capabilities; owner connect, export, refresh, log, correct, import +preview and apply, delete, erase; grant list, create, and revoke; coach roster, workout +summaries, note, and programming; attachment upload and download link; move steps +(D267). + +Stable error codes: expired sign-in, missing permission, unknown resource, stale +revision, request-ID conflict, host moving, limit reached. + +The description is generated from the Rust definitions into `schema/host-api/1/`, and +`cargo test --test generated` checks it (D266). + +### 6.6 Device refresh (D263) + +1. The first connection downloads a verified full package. +2. Later refreshes ask for changes since the device's database revision. The host reads + `internal_change_log` and returns record revisions, deletions, and erasures in + order, with any new attachments. +3. Before applying, the device checks that its file still matches the manifest digest it + last verified. If not, it keeps the local file, downloads the hosted copy beside it, + and asks the owner. +4. The library applies the changes with revisions unchanged. Attachments are checked by + SHA-256. +5. The device computes the new manifest digest and compares it with the host's. +6. A gap or failure falls back to a full package. + +A managed app directory switches complete copies atomically. A file other programs may +open gets a verified sibling copy and a coordinated handoff. + +### 6.7 Moving between hosts (D267) + +| Step | Who accepts writes | On failure | +|---|---|---| +| Owner connects an empty destination. The source may pre-copy files. | Source | The destination cannot show the staged record. | +| Owner freezes the source. It finishes accepted work and signs its final manifest digest and transfer ID. | Neither | Before release, the owner can abort and reopen the source. | +| The destination verifies every file, restores privately, runs `ath check`, and reports ready. | Neither | Resume from the last verified step. Show which host is waiting. | +| The source retires its writer and records a single-use activation for this transfer, destination, and digest. The destination activates once. | Destination | A lost reply is retried with the same transfer ID. The source cannot reopen by itself. | +| The device reconnects and the owner reviews grants. | Destination | Keep an owner recovery copy until cleanup is confirmed. | + +A restore from a device copy when the source cannot be reached is a separate action. It +is labelled a recovered fork. + +### 6.8 Backups and restore (D264) + +- **Native:** Litestream for each athlete database. Attachment copies on upload. A + scheduled package export of each athlete to storage with separate credentials. The + host keeps connections open and avoids truncating checkpoints while Litestream runs. + The recipe is published after the test in step 8 passes. +- **Remote:** the provider's per-database restore, a copy of the attachment bucket, and + the same scheduled package export. +- **Every restore:** one athlete, isolated first, sessions invalidated, later erasures + and revocations replayed from ordered recovery records before serving. If those + records are missing, the restore waits for the owner. +- **Erasure:** the host records an erase intent before applying it, replays unfinished + intents after a failure, and applies erasure to staged copies. + +### 6.9 Security and trust (D264) + +- Whoever runs the host and its storage can read records. The connect screen names who + runs the host and the storage. +- TLS on every connection. Storage encryption at rest is the provider's or the + operator's. +- Per-athlete keys on the libSQL backend where the provider supports them. Keys come + from a key service the operator configures. They are never stored in the directory + database. +- Backup credentials are separate from the host's credentials. +- Logs hold no credentials, request bodies, or health values. + +### 6.10 Limits + +For each athlete: total and expanded upload bytes, page size, job duration, concurrent +jobs, and temporary disk. Uploads expire and can be cancelled. Jobs have opaque IDs, and +only the requester can read their results. A large job for one athlete must not delay a +small write for another. + +## 7. Clients (D266) + +- **npm:** a host client with an explicit host URL and token. Local behavior and + [REMOTE-TARGETS.md](../../packages/npm/REMOTE-TARGETS.md) do not change. +- **Swift:** an example client for macOS and the iOS simulator: sign-in, roster, read a + workout summary, add a note. +- **MCP:** a small server with `list_workout_summaries` and `add_coaching_note`. It acts + with the signed-in person's grants and uses MCP authorization. +- **Starter:** a JavaScript example app that does the same flow. + +## 8. Qualification suite (D258) + +A backend or provider is listed as supported after a named run of this suite passes: + +1. Migrations 001–007 run. STRICT tables, triggers, and foreign keys are enforced. A + dangling reference is refused on the remote connection. +2. The library's write tests pass on the backend: create, correction with stale + detection, deletion, erasure, import preview and apply, receipts. +3. Two writers correct the same record from the same revision. One conflicts. +4. With identical record IDs in two athletes' databases, neither athlete's request + reaches the other. Where the provider has database-scoped credentials, one athlete's + credential cannot open another's database. +5. An export from the backend equals a native export of the same content, byte for byte. +6. Restoring one database to an earlier moment leaves every other database unchanged. A + package restore onto a clean machine passes `ath check`. +7. A network drop during a transaction leaves no partial write. A retry with the same + request ID returns the original result. +8. Timings for a workout save, a 28-day evidence read, and an import of the + 100,000-record workload, with region, hardware, and crate versions. + +First runs: a local libSQL server in continuous integration, and Turso Cloud +libSQL-engine databases in a manual run. + +## 9. Verification + +Before any commit, the four checks in [AGENTS.md](../../AGENTS.md) pass. The build adds: + +- Host tests with two athletes, two coaches, two apps, revocation during a queued write, + and guessed IDs. +- The qualification suite against a local libSQL server. +- Fault tests: stop the process around a note commit, an attachment publication, an + import, each move step, and a restore. Disk full. Staging cleanup after restart. +- Scale runs with the 100,000- and 3-million-record workloads: peak memory, disk + high-water mark, first transfer, unchanged refresh, one-note refresh, and one-athlete + restore time. A small write for a second athlete completes during a large job. +- Regenerated files: `schema/2.1.3/`, `schema/athleticstandard.schema.json`, + `schema/host-api/1/`, `packages/npm/src/generated/protocol.ts`, + `skills/athletic-standard/references/cli.md`, and the demo database. + +## 10. Build order + +Each step ends in something a person can do. A screenshot, a mocked provider, or a +successful sign-in alone does not finish a step. + +| Step | Work | Done when | +|---|---|---| +| 1 | This plan, D254–D267, and the storage study. | Approved. | +| 2 | Version 2.1.3, migration 007, coach authorship. | A coach-authored note survives export and restore. A 2.1.2 program refuses the database. All existing tests pass. | +| 3 | The storage interface, with the native backend behind it. | Every existing test passes with no change in CLI behavior. | +| 4 | The libSQL remote backend and the qualification suite. | The suite passes against a local libSQL server in continuous integration. | +| 5 | `ath-host` in native directory mode: owner connect, read, write with receipts, attachments, device refresh, restore. | An owner saves a report with a photo on one device and opens both on another. | +| 6 | Sign-in and grants: both recipes, three grants, access epoch, roster. | Two coaches, two apps, two athletes. A revocation during a queued write blocks it. | +| 7 | Remote mode with the object store, and several host copies. | Steps 5 and 6 pass in remote mode. A named run of the suite passes against one provider. | +| 8 | Moves and backups: the move protocol, the Litestream recipe, scheduled exports, restore drills. | A record moves native to remote and back. One athlete is restored without changing another. | +| 9 | Clients and guides: npm host client, Swift example, MCP server, starter, `docs/hosting.md`, container and setup guide. | A developer follows the guide from a clean checkout and completes the flow. | +| 10 | Scale and fault runs, release evidence. | The report lists which backends and providers passed and which clients ran. | + +## 11. References + +- [Storage options and how to choose](appendix/hosted-storage-options.md) +- [Hosting experiments](appendix/hosting-experiments.md) +- [Architecture](../../docs/architecture.md) · [Store](../../src/store/mod.rs) · + [Attachments](../../src/files/attachments.rs) · [Export](../../src/package/export.rs) · + [Restore](../../src/package/restore.rs) · [Erasure](../../src/package/erase.rs) +- [OAuth 2.0 for native apps (RFC 8252)](https://www.rfc-editor.org/rfc/rfc8252) · + [Protected resource metadata (RFC 9728)](https://www.rfc-editor.org/rfc/rfc9728) · + [MCP authorization](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) +- [Turso Rust reference](https://docs.turso.tech/sdk/rust/reference) · + [Turso Cloud limitations](https://docs.turso.tech/cloud/limitations) · + [Litestream](https://litestream.io/guides/directory/) From 0068552ffbf369552803197c2cd8ffb5c4c0858a Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 23 Nov 2026 17:31:30 -0600 Subject: [PATCH 02/26] Move to version 2.1.3 with migration step 7 and coach authorship. A record's author, or a revision's actor, can now be a human coach, with the name shown when they wrote it and an ID a host assigned (D255). A coach may write only coaching notes, training plans, and planned sessions, and cannot delete a record, so the two-tier wall holds. A package with a coach author must declare 2.1.3 or later. Migration step 7 adds three internal tables and changes no athlete row (D261 to D263): a change log, which triggers fill with the database revision each write commits; write receipts; and the access epoch. None is exported. An erasure leaves one value-free change-log row for the record, and a restore into an empty database starts a new log. The SQL contract lists the change-log triggers apart from the enforcement triggers. The JSON Schema, the Zod compatibility schemas, SPEC.md, the skills, and the demo database follow, and every skill names 2.1.3. Version 2.1.3 departs from the rule that a patch version adds no field; D254 and SPEC.md section 13 record the exception. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 8 +- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 9 +- SPEC.md | 106 +- examples/demo-athlete/athlete.ath.sqlite | Bin 491520 -> 512000 bytes packages/npm/package-lock.json | 4 +- packages/npm/package.json | 8 +- packages/npm/src/generated/protocol.ts | 4 +- packages/npm/src/schema.ts | 102 +- packages/npm/src/version.ts | 2 +- packages/npm/test/database.test.ts | 20 +- packages/npm/test/examples.test.ts | 2 +- packages/npm/test/public-api.test.ts | 18 +- packages/npm/test/zod-native-vectors.test.ts | 92 + schema/2.1.3/athleticstandard.schema.json | 16018 ++++++++++++++++ schema/2.1.3/export-manifest.schema.json | 142 + schema/2.1.3/measurement-series.schema.json | 1308 ++ schema/athleticstandard.schema.json | 1065 +- skills/athletic-standard/SKILL.md | 22 +- skills/athletic-standard/references/format.md | 13 +- skills/baseline/SKILL.md | 10 +- skills/compare-sources/SKILL.md | 10 +- skills/correlation/SKILL.md | 10 +- skills/coverage/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/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/workout-drift/SKILL.md | 10 +- spec/sql/README.md | 33 +- spec/sql/contract.json | 24 +- spec/sql/migrations/007-version-2-1-3.sql | 103 + src/model/common.rs | 71 +- src/model/package.rs | 26 +- src/model/record.rs | 68 +- src/package/restore.rs | 6 + src/store/contract.rs | 23 +- src/store/encode.rs | 5 +- src/store/migrate.rs | 8 +- src/store/mod.rs | 2 +- src/store/write.rs | 19 + tests/cli_golden.rs | 16 +- tests/migration.rs | 33 +- tests/model_vectors.rs | 20 +- tests/published_files.rs | 4 + tests/published_schema.rs | 68 +- tests/record_2_1_3.rs | 597 + tests/record_lifecycle.rs | 13 +- tests/skill_install.rs | 5 +- tools/public-data-allowlist.json | 2 +- 68 files changed, 20076 insertions(+), 277 deletions(-) create mode 100644 schema/2.1.3/athleticstandard.schema.json create mode 100644 schema/2.1.3/export-manifest.schema.json create mode 100644 schema/2.1.3/measurement-series.schema.json create mode 100644 spec/sql/migrations/007-version-2-1-3.sql create mode 100644 tests/record_2_1_3.rs diff --git a/AGENTS.md b/AGENTS.md index a2afd330..f5645b8e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,13 +20,13 @@ Read these before making decisions — they are the project's memory and outrank 4. **`build-history/v2.0.0/spec.md`** — version 2.0.0. The program, the record, and the database share that version. Garmin and Strava imports and calculation skill files are described there. 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, the current version: 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, planned and not built: an optional host program (`ath-host`) for sharing a record, human coach authorship, SQL migration step 7, and a storage interface with a native SQLite backend and a libSQL remote backend. Its `appendix/` holds the hosted-storage study and the hosting experiments. +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 current version, being built in steps: an optional host program (`ath-host`) for sharing a record, human coach authorship, SQL migration step 7, and a storage interface with a native SQLite backend and a libSQL remote backend. Its `appendix/` holds the hosted-storage study and the hosting experiments. 9. **`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. 10. **`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. 11. **`build-history/*/progress.md`** — what's done and what's next. 12. **`docs/connections.md`** — per-provider data research (what WHOOP/Oura/Garmin/Apple Health each provide via which path). -13. **`SPEC.md`** — the public field-level format reference. The normative model for version 2.1.2 is the Rust model in `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), are tested against the Rust validator, and are not where records are designed. +13. **`SPEC.md`** — the public field-level format reference. The normative model for version 2.1.3 is the Rust model in `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 @@ -37,7 +37,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 (`src/model/`), a command or its help (`src/cli/`), or a protocol operation (`src/protocol/`), run `ATH_WRITE_GENERATED=1 cargo test --test generated` and commit the regenerated files: JSON Schema in `schema/2.1.2/` and `schema/athleticstandard.schema.json`, `packages/npm/src/generated/protocol.ts`, `skills/athletic-standard/references/cli.md` (D80), 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 (`src/model/`), a command or its help (`src/cli/`), or a protocol operation (`src/protocol/`), run `ATH_WRITE_GENERATED=1 cargo test --test generated` and commit the regenerated files: JSON Schema in `schema/2.1.3/` and `schema/athleticstandard.schema.json`, `packages/npm/src/generated/protocol.ts`, `skills/athletic-standard/references/cli.md` (D80), 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 1169f51d..dd0ff54b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -89,7 +89,7 @@ dependencies = [ [[package]] name = "athleticstandard" -version = "2.1.2" +version = "2.1.3" dependencies = [ "chrono", "chrono-tz", diff --git a/Cargo.toml b/Cargo.toml index f2cad53d..5ebc3e2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "athleticstandard" -version = "2.1.2" +version = "2.1.3" 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 def3a64f..b474f2c3 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ package API. ## Upgrade a database -A database from version 1.0.0, 2.0.0, 2.1.0, or 2.1.1 upgrades with `ath migrate`. The +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 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 @@ -418,9 +418,10 @@ keeps the ID. Evidence names both the record ID and revision. The format defines 24 record types for profile data, sources, measurements, sessions, athlete reports, nutrition, attachments, benchmarks, predictions, plans, goals, and saved authored work. [`SPEC.md`](SPEC.md) is the public field reference. -The generated JSON Schemas are in [`schema/2.1.2/`](schema/2.1.2/). The published -2.0.0, 2.1.0, and 2.1.1 schemas stay in [`schema/2.0.0/`](schema/2.0.0/), -[`schema/2.1.0/`](schema/2.1.0/), and [`schema/2.1.1/`](schema/2.1.1/). +The generated JSON Schemas are in [`schema/2.1.3/`](schema/2.1.3/). The published +2.0.0, 2.1.0, 2.1.1, and 2.1.2 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/), and +[`schema/2.1.2/`](schema/2.1.2/). 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 89b1f2db..5281e57e 100644 --- a/SPEC.md +++ b/SPEC.md @@ -1,14 +1,14 @@ -# Athletic Standard Format Specification v2.1.2 +# Athletic Standard Format Specification v2.1.3 **Status:** current format **Live local file:** `athlete.ath.sqlite` **Portable package:** `athlete.ath.json` plus generated files **Normative model:** the Rust record model in [`src/model/`](src/model/) and its semantic checks -**Generated JSON Schemas:** [`schema/2.1.2/`](schema/2.1.2/), generated from that -model. The published 2.0.0, 2.1.0, and 2.1.1 schemas stay in -[`schema/2.0.0/`](schema/2.0.0/), [`schema/2.1.0/`](schema/2.1.0/), and -[`schema/2.1.1/`](schema/2.1.1/). +**Generated JSON Schemas:** [`schema/2.1.3/`](schema/2.1.3/), generated from that +model. The published 2.0.0, 2.1.0, 2.1.1, and 2.1.2 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/), and [`schema/2.1.2/`](schema/2.1.2/). Version 2.0.0 adds workout names, descriptions, text results, heart-rate samples, strength sets, route points, and `supplied_fields` for names the @@ -32,6 +32,12 @@ A version 2.1.1 database upgrades with `ath migrate` to SQL schema step 6, which adds one nullable column. The calculation methods that changed, and the coaching skills, are in [`build-history/v2.1.2/spec.md`](build-history/v2.1.2/spec.md). +Version 2.1.3 adds one author variant: a human coach can author and change coaching +notes, training plans, and planned sessions (sections 4.3 and 5.1). A version 2.1.2 +database upgrades with `ath migrate` to SQL schema step 7, which adds three internal +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). + 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 package for export, import, inspection, and backup. @@ -172,8 +178,23 @@ event time inside `data`. } ``` +```json +{ + "author_type": "coach", + "coach": "Coach name when written", + "coach_id": "6f1c2e4a-3b5d-4c7e-9f80-1a2b3c4d5e6f" +} +``` + `agent_version` is optional. Tool versions are semantic versions. +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. + ### 4.4 Normal deletion A deletion has: @@ -243,6 +264,11 @@ have `agent_version` and `model_version`. 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`. + ### 5.2 Input timestamp receipts Source and report times preserve source text in an input receipt: @@ -805,7 +831,7 @@ The athlete's original nutrition claim remains in the linked source-free |---|---| | `application_marker` | `ATH1` | | `sql_schema_version` | Positive SQL migration version | -| `athleticstandard_version` | `2.1.2` | +| `athleticstandard_version` | `2.1.3` | | `database_id` | Stable UUIDv7 database ID | | `created_at` | Database creation timestamp | @@ -889,6 +915,28 @@ prediction-result links, grades, attachments, plans, nutrition interpretations, and workout completion links. Measured rows require a source foreign key. Athlete-report and nutrition tables have no source column. +### 7.3 Internal tables + +Internal tables hold program state, not athlete records. A JSON package never +includes them, and direct SQL writers must not write them. `spec/sql/contract.json` +lists them under `internal_tables`, with a note for each. + +| Table | Since | Holds | +|---|---|---| +| `internal_pending_file_operations` | step 5 | Attachment file work that a SQL transaction cannot include | +| `internal_change_log` | step 7 | One row for each record revision, deletion, and erasure, with the database revision that committed it | +| `internal_write_receipts` | step 7 | One row for each write request a host accepted, with a keyed digest of the request and its result | +| `internal_access_state` | step 7 | One row with the access epoch, which revoking a host grant raises | + +Triggers fill `internal_change_log` in the same transaction as the change, so a +direct SQL writer that follows the published recipes is included. A row names the +record ID, the record revision (0 for an erasure), and the kind of change. It holds +no health value and has no foreign key. An erasure removes the record's earlier rows +and leaves one erasure row, so the log keeps no more about an erased record than its +marker does (section 4.5). A restore into an empty database starts a new log. `internal_write_receipts` holds no request body. +A database that never connects to a host keeps an empty receipt table and an access +epoch of 0. + ## 8. Portable JSON package An export directory may contain: @@ -1004,16 +1052,19 @@ Validation refuses: - an import key without its current record; - one import key resolving to two records; - an erasure marker whose record still exists; -- duplicate or unsafe package paths. +- duplicate or unsafe package paths; +- a coach author or actor on a record type a coach cannot write, or as `deleted_by`; +- a coach author or actor in a package that declares a version before 2.1.3. The generated JSON Schemas give exhaustive object validation: -- [`schema/2.1.2/athleticstandard.schema.json`](schema/2.1.2/athleticstandard.schema.json) -- [`schema/2.1.2/measurement-series.schema.json`](schema/2.1.2/measurement-series.schema.json) -- [`schema/2.1.2/export-manifest.schema.json`](schema/2.1.2/export-manifest.schema.json) +- [`schema/2.1.3/athleticstandard.schema.json`](schema/2.1.3/athleticstandard.schema.json) +- [`schema/2.1.3/measurement-series.schema.json`](schema/2.1.3/measurement-series.schema.json) +- [`schema/2.1.3/export-manifest.schema.json`](schema/2.1.3/export-manifest.schema.json) -The published 2.0.0, 2.1.0, and 2.1.1 schemas stay in [`schema/2.0.0/`](schema/2.0.0/), -[`schema/2.1.0/`](schema/2.1.0/), and [`schema/2.1.1/`](schema/2.1.1/). A schema checks +The published 2.0.0, 2.1.0, 2.1.1, and 2.1.2 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/), and [`schema/2.1.2/`](schema/2.1.2/). A schema checks structure only. It cannot show that a package's history or relationships are valid; the import checks those. @@ -1025,6 +1076,10 @@ The two-tier wall is structural. Measured records require `source_id`. Authored records are a third class. They name an author and exact evidence. They are 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. + Calculations remain separate by quantity and source unless the operation explicitly compares sources. Device baselines exclude `manual` sources. RMSSD and SDNN never share a calculation. Temperature quantities and activity-specific distances also @@ -1045,7 +1100,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`, or `2.1.2` package; +- accepts a `2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, or `2.1.3` package; - refuses prerelease Athletic Standard versions below `1.0.0`. An empty destination at database revision zero adopts the package database ID and @@ -1112,17 +1167,20 @@ backup operation. A closed, checkpointed database may be copied. ## 13. Version behavior -The program, the record, and the database use one version, `2.1.2` (D152, D184, -D208, D227). The portable document, generated series files, export manifest, and -live database metadata all carry that version. - -A minor version only adds optional fields. A patch version adds no field. Version -2.1.2 is a recorded exception (D227): it adds optional fields and the -`session_effort` report type, and removes or changes nothing. A `2.0.0` record has -no `field_basis` and stays valid, and every 2.1.1 record is valid 2.1.2 data. -`ath migrate` moves a `2.0.0`, `2.1.0`, or `2.1.1` database to `2.1.2` without -changing its records. Software before 2.1.1 refuses a database at SQL schema step 5, -and software before 2.1.2 refuses one at step 6. +The program, the record, and the database use one version, `2.1.3` (D152, D184, +D208, D227, D254). The portable document, generated series files, export manifest, +and live database metadata all carry that version. + +A minor version only adds optional fields. A patch version adds no field. Versions +2.1.2 and 2.1.3 are recorded exceptions. Version 2.1.2 (D227) adds optional fields +and the `session_effort` report type, and removes or changes nothing. Version 2.1.3 +(D254) adds one author variant and three internal tables, and removes or changes +nothing. A `2.0.0` record has no `field_basis` and stays valid, and every 2.1.1 and +2.1.2 record is valid 2.1.3 data. A package with a coach author declares 2.1.3 or +later. `ath migrate` moves a `2.0.0`, `2.1.0`, `2.1.1`, or `2.1.2` database to +`2.1.3` 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, and software before 2.1.3 +refuses one at step 7. 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/examples/demo-athlete/athlete.ath.sqlite b/examples/demo-athlete/athlete.ath.sqlite index ec4307c148f7276e054a7a39525c3ef39f1e8300..350d88d864a0998d8d1f942ce51de07edc0b876f 100644 GIT binary patch delta 3563 zcmcJRZ)_7~9LIaT>)m>7@5Ucj=GgY2!>u^Rx~c=`fXa@o0xfo}GYB@NJ;q_vmb-3% zf~73L3*P{hTw;j)d0~t%%wQxX@r6TQ_>M?I1k@Of1`|S5;yZXTpFX|6+cDIHCf7Xo z>F>GU^L&5b=XX7PxaIJ<))TGE4%zh2HaH~oTN?())W!9uSaKYWGMTAc>>ZY*db<2w zf$}e#o}K!=wQVbQXv&@cm90PMg)#3fgkSHv;n#tQnd0%8A_gxzyl{9C@N!gUiln0( zciM6lYLa}wHp5uj#@Xs5Y8UAyzQHeHNoIxXH|IwX_Mbf2TIruAcQ`BgAIK9#WyLk} zCMLisjBOR>{FwUM8Fzd|?IdRKKKo}F!)$ja=pAm>whD%*pVC_;g7WtEVn^bINM7SygTtsMpweSI_+9w;&I zQ{GSjE3Jg9*qSdcs8=_n=Ruyf4d(%oa!*rN65>{ivnS@?R(4i&qO#}~7 z-ar65<}({kkG5E30hw)y9)o1o6f92?%bfb%b)r$e;=&f6a!~TUpUArM6{6`Gv`JN= znj5RK8H!l`7HbF^?%}4DYU;`=N~d{PBeciIpWg@rtX+DPp?rb zs5FxDUT6iy`mkRO4sub|*hXI`%(H6kN9#CY*?*DruAtRUGyppSJWA;BYm3z_O#}Jd zWfBxYFg#$iC3s~mXjcu^2OaigJ6aJoU+b3kq&r$SI!r_QX5n6IU2FoBY_-?Lrg=)J z9!jN#^3~gV$*W=)t~KDGI)VUkwKe_w&(V>*G-7uCM>n3u|bufVqd^HMRj%Gn)H zE6Rn*^%th=PfZgqH_;UvdxqV^u4YN*26KVQGiw>Q=X=k%XMnxtS?K=R{ki*~`!)9x z*B#eo*AdrNSBvLU`Yv6WS^y5vRF4CTH#_m_zoz=Ms&=3XF?;#y2W^ZhkKONZ#+&8y zXUH~YjS3BHwFT>)!greL4;Qo6dF=eb?wI zy7FjOAxAlS9C56h8AX)4IzV} y)QM)*P?T9Tgv^>DWR?t~<#lS2FHI7F#Mp;6_Tkim=|5S@X2UVuR`*Fawe=r<2axap delta 275 zcmZozAm7j+H$h&pf&l@7flL+zmw^$;X4~j6iJz?)$jZsue1rcPKO38oo}r%6rG_|JSpz8Zfgn zt8ZuD!1jw@mU9*ZCu1T5&pGZQj$-ySHXfGa%$pb!`Lq~Z8Ehv`l;3W9fGw62=q$z? z+vlBRyTZ6Ve*@c2rtRA2*sd{3a`rNCvbqhoKmUo*46|S&s w|9^#TJ_`rXIUvk1ecnyB{o7p+u*ouRpM8?8pJmYohfN1q1h%s@u>bJ~07>>w>i_@% diff --git a/packages/npm/package-lock.json b/packages/npm/package-lock.json index c1cad83e..6477e2ed 100644 --- a/packages/npm/package-lock.json +++ b/packages/npm/package-lock.json @@ -1,12 +1,12 @@ { "name": "athleticstandard", - "version": "2.1.2", + "version": "2.1.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "athleticstandard", - "version": "2.1.2", + "version": "2.1.3", "license": "MIT", "os": [ "linux", diff --git a/packages/npm/package.json b/packages/npm/package.json index 6a3b95df..0d97e941 100644 --- a/packages/npm/package.json +++ b/packages/npm/package.json @@ -1,6 +1,6 @@ { "name": "athleticstandard", - "version": "2.1.2", + "version": "2.1.3", "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", @@ -53,9 +53,9 @@ "types": "./dist/schema.d.ts", "import": "./dist/schema.js" }, - "./json-schema": "./schema/2.1.2/athleticstandard.schema.json", - "./json-schema/export-manifest": "./schema/2.1.2/export-manifest.schema.json", - "./json-schema/measurement-series": "./schema/2.1.2/measurement-series.schema.json", + "./json-schema": "./schema/2.1.3/athleticstandard.schema.json", + "./json-schema/export-manifest": "./schema/2.1.3/export-manifest.schema.json", + "./json-schema/measurement-series": "./schema/2.1.3/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 76ec70cd..cd94beca 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: "2.1.2", - SQL_SCHEMA_VERSION: 6, + ATHLETIC_STANDARD_VERSION: "2.1.3", + SQL_SCHEMA_VERSION: 7, 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 90e76bf0..71c03ca2 100644 --- a/packages/npm/src/schema.ts +++ b/packages/npm/src/schema.ts @@ -3,10 +3,10 @@ * * This file is src/v1/schema.ts from 2.1.0 with the version declarations * changed (ATHLETIC_STANDARD_VERSION, ACCEPTED_RECORD_VERSIONS, and - * IMPORTABLE_PACKAGE_VERSIONS) and the 2.1.2 optional fields copied from the + * IMPORTABLE_PACKAGE_VERSIONS), the 2.1.2 optional fields copied from the * Rust model: session_effort, athlete_report.workout_session_id, and the - * strength-set movement and load basis (D238, D239). Do not design record - * changes here. The native + * strength-set movement and load basis (D238, D239), and the 2.1.3 coach + * author with its rules (D255). Do not design record changes here. The native * Rust model is the source of truth, and test/zod-native-vectors.test.ts * requires the same verdicts from both. Native writes never call this file. * @@ -19,16 +19,16 @@ import { z } from "zod"; import { RecordExtensions, validateExtensionsForRecordType } from "./extensions.js"; -export const ATHLETIC_STANDARD_VERSION = "2.1.2"; +export const ATHLETIC_STANDARD_VERSION = "2.1.3"; /** 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"] 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"] 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", ATHLETIC_STANDARD_VERSION] as const; +export const IMPORTABLE_PACKAGE_VERSIONS = ["2.0.0", "2.1.0", "2.1.1", "2.1.2", ATHLETIC_STANDARD_VERSION] as const; export const RecordFormatVersion = z.enum(ACCEPTED_RECORD_VERSIONS); @@ -108,10 +108,23 @@ export const ToolActor = z.strictObject({ tool_version: Semver, }); +/** The opaque ID a host assigned to a coach (D255): a lowercase UUID. */ +const CoachId = z + .string() + .regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, "lowercase UUID"); + +/** A human coach (D255), as an actor and as an author. New in 2.1.3. */ +const CoachActor = z.strictObject({ + author_type: z.literal("coach"), + coach: z.string().min(1), + coach_id: CoachId, +}); + export const RecordActor = z.discriminatedUnion("author_type", [ AthleteActor, AgentActor, ToolActor, + CoachActor, ]); export const AgentAuthor = AgentActor.extend({ @@ -127,8 +140,52 @@ export const AuthoredRecordAuthor = z.discriminatedUnion("author_type", [ AthleteActor, AgentAuthor, ToolAuthor, + CoachActor, ]); +/** The record types a coach may author and change (D255). */ +const COACH_RECORD_TYPES: readonly string[] = ["coaching_note", "training_plan", "planned_session"]; + +/** Where a record, revision, or deletion names an actor or author. */ +const ACTOR_PATHS: ReadonlyArray = [ + ["changed_by"], + ["deleted_by"], + ["data", "authorship", "author"], + ["data", "created_by"], +]; + +/** The actor paths of `value` that name a coach. */ +function coachPaths(value: unknown): Array { + return ACTOR_PATHS.filter((path) => { + let current: unknown = value; + for (const key of path) { + if (typeof current !== "object" || current === null) { + return false; + } + current = (current as Record)[key]; + } + return ( + typeof current === "object" && + current !== null && + (current as { author_type?: unknown }).author_type === "coach" + ); + }); +} + +/** A coach may write only coaching notes, training plans, and planned sessions. */ +function addCoachRecordTypeIssues(recordType: string, value: unknown, context: z.RefinementCtx): void { + if (COACH_RECORD_TYPES.includes(recordType)) { + return; + } + for (const path of coachPaths(value)) { + context.addIssue({ + code: "custom", + path: [...path], + message: `A coach may write only coaching_note, training_plan, and planned_session records, not ${recordType}`, + }); + } +} + export const AuthoredRecordStatus = z.enum([ "draft", "active", @@ -972,6 +1029,7 @@ function currentRecordVariant( message: (error as Error).message, }); } + addCoachRecordTypeIssues(recordType, value, context); }); } @@ -1110,6 +1168,7 @@ function recordRevisionVariant message: (error as Error).message, }); } + addCoachRecordTypeIssues(recordType, value, context); }); } @@ -1213,12 +1272,18 @@ export const RecordRevision = z.union([ MeasurementSampleRevision, ]); -export const RecordDeletion = z.strictObject({ - record_id: RecordId, - record_revision: RecordRevisionNumber, - deleted_at: UtcTimestamp, - deleted_by: RecordActor, -}); +export const RecordDeletion = z + .strictObject({ + record_id: RecordId, + record_revision: RecordRevisionNumber, + deleted_at: UtcTimestamp, + deleted_by: RecordActor, + }) + .superRefine((value, context) => { + if (value.deleted_by.author_type === "coach") { + context.addIssue({ code: "custom", path: ["deleted_by"], message: "A coach cannot delete a record" }); + } + }); export const ErasureReasonCode = z.enum([ "athlete_request", @@ -1528,6 +1593,19 @@ export const AthleticStandardPackage = z }); } }); + + // A coach author first appears in 2.1.3 (D255). + const declared = value.athleticstandard_version; + if (ACCEPTED_RECORD_VERSIONS.indexOf(declared) < ACCEPTED_RECORD_VERSIONS.indexOf("2.1.3")) { + const message = `A coach author needs Athletic Standard 2.1.3 or later; this package declares ${declared}`; + for (const list of ["records", "record_revisions", "record_deletions"] as const) { + (value[list] as readonly unknown[]).forEach((item, index) => { + for (const path of coachPaths(item)) { + context.addIssue({ code: "custom", path: [list, index, ...path], message }); + } + }); + } + } }); export const ManifestFile = z.strictObject({ diff --git a/packages/npm/src/version.ts b/packages/npm/src/version.ts index d3279828..95a039c4 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 = "2.1.2"; +export const ATH_PACKAGE_VERSION = "2.1.3"; diff --git a/packages/npm/test/database.test.ts b/packages/npm/test/database.test.ts index dd076f57..8457e66e 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: 6, - athleticstandard_version: "2.1.2", + sql_schema_version: 7, + athleticstandard_version: "2.1.3", 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(6); + expect((await database.readDatabaseMetadata(inspected)).sql_schema_version).toBe(7); 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("2.1.2"); + expect(check.metadata?.athleticstandard_version).toBe("2.1.3"); 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 2.1.2"); + expect(text).toContain("unnamed athlete · Athletic Standard 2.1.3"); 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(6); + expect(required.preview.target_sql_schema_version).toBe(7); expect(required.message).toBe( - "Database SQL schema 1 must be upgraded to 6 before other commands can run. Run ath migrate.", + "Database SQL schema 1 must be upgraded to 7 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]); + expect(preview.planned_steps.map((step) => step.target_sql_schema_version)).toEqual([2, 3, 4, 5, 6, 7]); 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(6); + expect((await database.readDatabaseMetadata(other)).sql_schema_version).toBe(7); 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("2.1.2"); + expect(report.athleticstandard_version).toBe("2.1.3"); 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 1b7ce4d1..4d36cdf9 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: "2.1.2", + package_version: "2.1.3", package_records: 2, }); }); diff --git a/packages/npm/test/public-api.test.ts b/packages/npm/test/public-api.test.ts index c4b87ab7..965e85ef 100644 --- a/packages/npm/test/public-api.test.ts +++ b/packages/npm/test/public-api.test.ts @@ -66,10 +66,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("2.1.2"); - expect(root.ATHLETIC_STANDARD_VERSION).toBe("2.1.2"); - expect(schema.ACCEPTED_RECORD_VERSIONS).toEqual(["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2"]); - expect(schema.IMPORTABLE_PACKAGE_VERSIONS).toEqual(["2.0.0", "2.1.0", "2.1.1", "2.1.2"]); + expect(root.ATH_PACKAGE_VERSION).toBe("2.1.3"); + expect(root.ATHLETIC_STANDARD_VERSION).toBe("2.1.3"); + expect(schema.ACCEPTED_RECORD_VERSIONS).toEqual(["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3"]); + expect(schema.IMPORTABLE_PACKAGE_VERSIONS).toEqual(["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3"]); }); it("keeps the generated compile-time check current", () => { @@ -78,7 +78,7 @@ describe("public exports", () => { }); it("repeats the native constants", () => { - expect(database.SQL_SCHEMA_VERSION).toBe(6); + expect(database.SQL_SCHEMA_VERSION).toBe(7); expect(database.SQLITE_APPLICATION_ID).toBe(0x41544831); expect(database.SQLITE_APPLICATION_MARKER).toBe("ATH1"); expect(database.MAX_ATTACHMENT_BYTES).toBe(25 * 1024 * 1024); @@ -104,21 +104,21 @@ 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("2.1.2"); + expect(packageJson.version).toBe("2.1.3"); expect(Object.keys(packageJson.bin)).toEqual(["ath"]); expect(Object.keys(packageJson.exports).sort()).toEqual( [".", "./database", "./schema", ...inventory.json_only_subpaths.map((entry) => entry.subpath)].sort(), ); }); - it("generates the JSON Schema files for 2.1.2", () => { + it("generates the JSON Schema files for 2.1.3", () => { 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\/2\.1\.2\//); + expect(target).toMatch(/^\.\/schema\/2\.1\.3\//); // 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("/2.1.2/"); + expect(document.$id).toContain("/2.1.3/"); } }); diff --git a/packages/npm/test/zod-native-vectors.test.ts b/packages/npm/test/zod-native-vectors.test.ts index d52dc2ed..c3b94de4 100644 --- a/packages/npm/test/zod-native-vectors.test.ts +++ b/packages/npm/test/zod-native-vectors.test.ts @@ -116,3 +116,95 @@ describe("Zod facade and native validator", () => { ]); }); }); + +/** + * The 2.1.3 coach author (D255) has no recorded vector, because 2.1.0 did not + * have it. These cases hold the facade and the native validator to the same + * verdict on its shape, its record types, deletion, and the package version. + */ +describe("the 2.1.3 coach author", () => { + const coach = { author_type: "coach", coach: "Example Coach", coach_id: "6f1c2e4a-3b5d-4c7e-9f80-1a2b3c4d5e6f" }; + const at = "2026-11-20T12:00:00.000Z"; + const noteId = "01890f3e-e7d3-7cc0-88c8-0000000000c1"; + const authorship = { author: coach, authored_at: at, evidence: [], content_version: 1, status: "active" }; + const note = { authorship, note: "Keep every session easy this week." }; + const noteRecord = { + record_id: noteId, + created_at: at, + current_revision: 1, + is_deleted: false, + record_type: "coaching_note", + data: note, + }; + const noteRevision = { + record_id: noteId, + revision: 1, + previous_revision: null, + became_known_at: at, + became_known_at_basis: "local_write", + changed_by: coach, + record_type: "coaching_note", + data: note, + }; + const report = { + report_type: "note", + reported_at: at, + input_reported_at: { timestamp_missing_reason: "not_applicable", utc_offset_missing_reason: "not_applicable" }, + reported_via: "text", + note: "Legs felt heavy.", + }; + const packageAt = (version: string) => ({ + athleticstandard_version: version, + database_id: "01890f3e-e7d3-7cc0-88c8-000000000001", + database_revision: 1, + records: [noteRecord], + record_revisions: [noteRevision], + record_deletions: [], + record_erasure_markers: [], + record_import_keys: [], + measurement_series_files: [], + }); + const cases: Array<{ schema: string; input: unknown; valid: boolean }> = [ + { schema: "RecordActor", input: coach, valid: true }, + { schema: "AuthoredRecordAuthor", input: coach, valid: true }, + { schema: "RecordActor", input: { ...coach, coach_id: coach.coach_id.toUpperCase() }, valid: false }, + { schema: "RecordActor", input: { ...coach, coach_id: "coach@example.com" }, valid: false }, + { schema: "RecordActor", input: { ...coach, coach: "" }, valid: false }, + { schema: "CoachingNoteRecord", input: noteRecord, valid: true }, + { schema: "CoachingNoteRevision", input: noteRevision, valid: true }, + { + schema: "GoalRecord", + input: { ...noteRecord, record_type: "goal", data: { authorship, title: "Row 2000 m under eight minutes" } }, + valid: false, + }, + { + schema: "AthleteReportRevision", + input: { ...noteRevision, record_type: "athlete_report", data: report }, + valid: false, + }, + { + schema: "AthleteReportRevision", + input: { ...noteRevision, record_type: "athlete_report", data: report, changed_by: { author_type: "athlete" } }, + valid: true, + }, + { + schema: "RecordDeletion", + input: { record_id: noteId, record_revision: 1, deleted_at: at, deleted_by: coach }, + valid: false, + }, + { schema: "AthleticStandardPackage", input: packageAt("2.1.3"), valid: true }, + { schema: "AthleticStandardPackage", input: packageAt("2.1.2"), valid: false }, + ]; + + it("gets the same verdict from the facade and the native validator", async () => { + const facade = schemas as unknown as Record; + const native = await callAsync("model.validate_many", { + cases: cases.map((entry) => ({ schema: entry.schema, json_text: JSON.stringify(entry.input) })), + }); + cases.forEach((entry, index) => { + const label = `${entry.schema} ${JSON.stringify(entry.input).slice(0, 80)}`; + expect(facade[entry.schema]!.safeParse(entry.input).success, `facade: ${label}`).toBe(entry.valid); + expect(native.items[index]!.valid, `native: ${label}`).toBe(entry.valid); + }); + }); +}); diff --git a/schema/2.1.3/athleticstandard.schema.json b/schema/2.1.3/athleticstandard.schema.json new file mode 100644 index 00000000..57f4d85b --- /dev/null +++ b/schema/2.1.3/athleticstandard.schema.json @@ -0,0 +1,16018 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://athleticstandard.ai/schema/2.1.3/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" + ] + }, + "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 + } + }, + "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" + } + }, + "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" + } + }, + "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" + } + }, + "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 + } + } + }, + "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" + } + }, + "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 + } + }, + "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 + } + }, + "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" + } + }, + "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" + } + }, + "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" + ] + }, + "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" + } + }, + "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" + ] + }, + "definition": { + "type": "string", + "minLength": 1 + }, + "tags": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "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 + } + }, + "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 + } + }, + "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 + } + }, + "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 + } + }, + "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 + } + }, + "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" + } + }, + "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 + } + }, + "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" + } + }, + "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 + } + }, + "additionalProperties": false + } + }, + "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 + } + ] + } + }, + "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 + } + }, + "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" + } + }, + "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" + } + }, + "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" + } + }, + "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 + } + } + }, + "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" + } + }, + "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 + } + }, + "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 + } + }, + "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" + } + }, + "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" + } + }, + "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" + ] + }, + "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" + } + }, + "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" + ] + }, + "definition": { + "type": "string", + "minLength": 1 + }, + "tags": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "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 + } + }, + "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 + } + }, + "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 + } + }, + "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 + } + }, + "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 + } + }, + "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" + } + }, + "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 + } + }, + "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" + } + }, + "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 + } + }, + "additionalProperties": false + } + }, + "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 + } + ] + } + }, + "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/2.1.3/export-manifest.schema.json b/schema/2.1.3/export-manifest.schema.json new file mode 100644 index 00000000..a4cd8e36 --- /dev/null +++ b/schema/2.1.3/export-manifest.schema.json @@ -0,0 +1,142 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://athleticstandard.ai/schema/2.1.3/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" + ] + }, + "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" + ] + }, + "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 + } + }, + "required": [ + "athleticstandard_version", + "source_database_id", + "database_revision", + "files", + "record_counts", + "erasure_marker_count" + ], + "additionalProperties": false +} diff --git a/schema/2.1.3/measurement-series.schema.json b/schema/2.1.3/measurement-series.schema.json new file mode 100644 index 00000000..4b7c0f74 --- /dev/null +++ b/schema/2.1.3/measurement-series.schema.json @@ -0,0 +1,1308 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://athleticstandard.ai/schema/2.1.3/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" + ] + }, + "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" + } + }, + "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" + } + }, + "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 4f1c0870..57f4d85b 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/2.1.2/athleticstandard.schema.json", + "$id": "https://athleticstandard.ai/schema/2.1.3/athleticstandard.schema.json", "title": "Athletic Standard portable package document", "type": "object", "properties": { @@ -11,7 +11,8 @@ "2.0.0", "2.1.0", "2.1.1", - "2.1.2" + "2.1.2", + "2.1.3" ] }, "database_id": { @@ -3886,6 +3887,29 @@ "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 } ] }, @@ -4111,6 +4135,29 @@ "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 } ] }, @@ -4410,6 +4457,29 @@ "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 } ] }, @@ -4570,6 +4640,29 @@ "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 } ] }, @@ -4832,6 +4925,29 @@ "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 } ] }, @@ -5106,6 +5222,29 @@ "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 } ] }, @@ -5315,6 +5454,29 @@ "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 } ] }, @@ -5587,6 +5749,29 @@ "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 } ] }, @@ -5796,6 +5981,29 @@ "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 } ] }, @@ -6010,6 +6218,29 @@ "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 } ] }, @@ -6237,6 +6468,29 @@ "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 } ] }, @@ -6482,6 +6736,29 @@ "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 } ] }, @@ -6644,6 +6921,29 @@ "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 } ] }, @@ -6822,6 +7122,29 @@ "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 } ] }, @@ -7001,6 +7324,29 @@ "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 } ] }, @@ -7583,7 +7929,30 @@ "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": { @@ -8172,6 +8541,29 @@ "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 } ] }, @@ -8998,6 +9390,29 @@ "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 } ] }, @@ -9525,6 +9940,29 @@ "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 } ] }, @@ -10020,6 +10458,29 @@ "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 } ] }, @@ -10520,6 +10981,29 @@ "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 } ] }, @@ -10776,6 +11260,29 @@ "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 } ] }, @@ -11049,6 +11556,29 @@ "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 } ] }, @@ -11210,6 +11740,29 @@ "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 } ] }, @@ -11296,6 +11849,29 @@ "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 } ] }, @@ -11517,6 +12093,29 @@ "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 } ] }, @@ -11603,6 +12202,29 @@ "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 } ] }, @@ -11875,6 +12497,29 @@ "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 } ] }, @@ -11984,6 +12629,29 @@ "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 } ] }, @@ -12140,6 +12808,29 @@ "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 } ] }, @@ -12226,6 +12917,29 @@ "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 } ] }, @@ -12484,6 +13198,29 @@ "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 } ] }, @@ -12570,6 +13307,29 @@ "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 } ] }, @@ -12840,6 +13600,29 @@ "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 } ] }, @@ -12926,6 +13709,29 @@ "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 } ] }, @@ -13131,6 +13937,29 @@ "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 } ] }, @@ -13217,6 +14046,29 @@ "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 } ] }, @@ -13485,6 +14337,29 @@ "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 } ] }, @@ -13571,6 +14446,29 @@ "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 } ] }, @@ -13776,6 +14674,29 @@ "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 } ] }, @@ -13862,6 +14783,29 @@ "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 } ] }, @@ -14072,6 +15016,29 @@ "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 } ] }, @@ -14158,6 +15125,29 @@ "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 } ] }, @@ -14381,6 +15371,29 @@ "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 } ] }, @@ -14467,6 +15480,29 @@ "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 } ] }, @@ -14700,6 +15736,29 @@ "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 } ] } diff --git a/skills/athletic-standard/SKILL.md b/skills/athletic-standard/SKILL.md index bfec10b4..6e6f9423 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, or 2.1.2 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, or 2.1.3 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 2.1.2 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 2.1.3 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: "2.1.2" + version: "2.1.3" kind: tool --- @@ -14,8 +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 **2.1.2**. A version 1.0.0, 2.0.0, 2.1.0, or 2.1.1 -database upgrades with `ath migrate`. A 2.0.0, 2.1.0, or 2.1.1 package still imports. +This skill expects Athletic Standard **2.1.3**. A version 1.0.0, 2.0.0, 2.1.0, 2.1.1, or +2.1.2 database upgrades with `ath migrate`. A 2.0.0, 2.1.0, 2.1.1, or 2.1.2 package still +imports. Prerelease `0.x` JSON documents are not imported. Local use needs no account, network connection, subscription, or hosted service. @@ -32,16 +33,16 @@ authored record. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 @@ -108,6 +109,11 @@ model interpretations name their author and exact evidence record revisions. Coa advice is always an authored record: never write it as a measurement or as an athlete report. +Since 2.1.3 an author can also be a human coach, with `author_type: "coach"`, the +coach's name, and a `coach_id` that a host assigned. A coach can write only coaching +notes, training plans, and planned sessions. Keep a coach's name and ID as they are. +Never write a coach author yourself: you are an agent. + A link from an athlete report to a workout (`workout_session_id`) is allowed. It says which session the report describes. The report still has no source. diff --git a/skills/athletic-standard/references/format.md b/skills/athletic-standard/references/format.md index db3e3a1b..d0f460a3 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/2.1.2/`. +`schema/2.1.3/`. ## Common record fields @@ -75,6 +75,17 @@ Authored records carry `authorship`, with author, time, ordered evidence, `prediction_result_link` carries its own creator, exact prediction and result revisions, link time, content version, and status. +An author or a revision's `changed_by` is the athlete, an agent, a tool, or, since +2.1.3, a coach: + +```json +{ "author_type": "coach", "coach": "", "coach_id": "" } +``` + +A host assigns `coach_id`. A coach can author and change only `coaching_note`, +`training_plan`, and `planned_session` records, and cannot delete a record. A package +with a coach author declares 2.1.3 or later. + The remaining records are `athlete_profile`, `source`, `source_device`, and `attachment`. diff --git a/skills/baseline/SKILL.md b/skills/baseline/SKILL.md index a4fd8e27..85afea5a 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate baseline . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate baseline . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 4f51e138..386c9ece 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate compare-sources --source --compare-source . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate compare-sources --source --compare-source . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 3faabbf0..b98e0ba2 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate correlation --other-quantity --timezone . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate correlation --other-quantity --timezone . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -15,16 +15,16 @@ both have a reading. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 610bd3e2..5ae69950 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate coverage . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate coverage . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -15,16 +15,16 @@ for each source. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 85cdc8f2..789285b7 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install crossfit. +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install crossfit. metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 999721a2..e2cb3638 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-recovery --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-recovery --record . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -16,16 +16,16 @@ recovery. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 b70af708..561f0f42 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 samples into five zones by percentage of the athlete's known maximum heart rate, crediting only time the samples 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 maximum_heart_rate_bpm on the workout; never estimates it from age. Not for training load (use training-load-heart-rate). license: MIT -compatibility: Requires the ath CLI 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-zones --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply heart-rate-zones --record . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -15,16 +15,16 @@ heart rate. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 6aa5eb49..fca16d95 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hrv-change --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hrv-change --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 dbc642c8..8219a0c6 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hyrox-race-splits --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply hyrox-race-splits --record . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -16,16 +16,16 @@ finish time. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 402c8806..6c2f18cd 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install hyrox. +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Install with ath skill install hyrox. metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 e429c3f2..e5e88245 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate provider-period-summary --period-type . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate provider-period-summary --period-type . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 8bde572d..6a7073bb 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate-change --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate-change --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 293bb94c..750b1c3f 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply resting-heart-rate --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 baa59c78..bc85379d 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-change --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-change --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 a60210b8..482a76e6 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-duration --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-duration --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 a70f1bfe..e267e879 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-efficiency --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-efficiency --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 075bc0c0..2d0739d9 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-interruptions --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-interruptions --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 ea224ffb..bbef8c08 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-regularity --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-regularity --record . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -17,16 +17,16 @@ opposite pattern. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 2d29677f..bae91fd6 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-stages --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-stages --record . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -15,16 +15,16 @@ time counted apart. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 495b7667..7e202384 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-timing --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply sleep-timing --record . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -15,16 +15,16 @@ local clock. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 627362bb..a8982bb4 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply strength-volume --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply strength-volume --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 746fc36d..88d91103 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate summary . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate summary . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 3c92d5d7..44b8d8d4 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-effort --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-effort --record . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 06cc8490..a564fab6 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 samples, the athlete's resting and maximum heart rate, and their 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-heart-rate --record . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath apply training-load-heart-rate --record . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -15,16 +15,16 @@ heart rate sat between resting and maximum. Harder minutes count more. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 f7764a4d..a6fc292d 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate trend . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate trend . metadata: - version: "2.1.2" + version: "2.1.3" kind: calculation --- @@ -15,16 +15,16 @@ source. ## Before the first ath command -This skill runs `ath`, the Athletic Standard program, version 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 ab83a50c..e2c8badc 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 2.1.2 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate workout-drift --session . +compatibility: Requires the ath CLI 2.1.3 or later (npm package athleticstandard) and an Athletic Standard database. Runs with ath calculate workout-drift --session . metadata: - version: "2.1.2" + version: "2.1.3" 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 2.1.2 or later. +This skill runs `ath`, the Athletic Standard program, version 2.1.3 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 2.1.2, update it with `ath --update`. +- If the version is older than 2.1.3, update it with `ath --update`. - Install or update only after the person agrees. Then run `ath --version` again. If - it is still older than 2.1.2, say so and stop. + it is still older than 2.1.3, 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 187e0577..05bc5814 100644 --- a/spec/sql/README.md +++ b/spec/sql/README.md @@ -76,6 +76,8 @@ Then run the record steps below and `COMMIT`. On failure, `ROLLBACK`. | 3 | `migrations/003-version-2.sql` | 3 | | 4 | `migrations/004-version-2-1.sql` | 4 | | 5 | `migrations/005-version-2-1-1.sql` | 5 | +| 6 | `migrations/006-version-2-1-2.sql` | 6 | +| 7 | `migrations/007-version-2-1-3.sql` | 7 | Rules: @@ -92,12 +94,20 @@ Rules: - Migration `005-version-2-1-1.sql` records software version 2.1.1 and creates the internal table `internal_pending_file_operations`. It changes no athlete-owned table or column. Records written before this step stay as they are. +- Migration `006-version-2-1-2.sql` records software version 2.1.2 and adds the + nullable column `athlete_reports.workout_session_id`. It changes no existing row. +- Migration `007-version-2-1-3.sql` records software version 2.1.3 and creates the + internal tables `internal_change_log`, `internal_write_receipts`, and + `internal_access_state`, and the triggers that fill the change log. It changes no + athlete-owned table, column, or row. - 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. To go back, restore the +- Software before 2.1.1 refuses a database at SQL schema 5, software before 2.1.2 + refuses one at schema 6, and software before 2.1.3 refuses one at schema 7. 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. @@ -186,12 +196,29 @@ health values. The table is not athlete-owned history, so a JSON package never includes it. `ath check` reports pending rows as warnings. `contract.json` describes each internal table under `internal_table_notes`. +`internal_change_log` (SQL schema 7) records one row for each record revision, +deletion, and erasure, with the database revision that committed it. The triggers +listed under `internal_triggers` in `contract.json` fill it in the same transaction, +so a direct writer that follows the recipes above is included: a trigger records +`database_state.current_revision + 1`, which is the revision the final `UPDATE` of +the transaction sets. Direct writers must not write the table themselves. Rows hold +record IDs and numbers, no health values, and no foreign keys. An erasure removes the +record's earlier rows and leaves one erasure row. A restore into an empty database +starts a new log. + +`internal_write_receipts` and `internal_access_state` (SQL schema 7) belong to a host +program that shares a record. A receipt holds a keyed digest of an accepted request +and its result, never the request body. The access state holds one access epoch. A +database that never connects to a host keeps no receipts and an epoch of 0. Direct +writers must not write either table. None of the three is part of a JSON package. + ## Enforcement Constraints, foreign keys, and triggers in the migration enforce the two-tier wall, revision order, deletion state, and protected links (D116). Trigger names are listed -in `contract.json`. Invalid direct writes must fail in SQLite even when the Node -library is not used. +in `contract.json` under `enforcement_triggers`. Invalid direct writes must fail in +SQLite even when the Node library is not used. The change-log triggers are listed +separately under `internal_triggers`; they enforce nothing. ## Drift check diff --git a/spec/sql/contract.json b/spec/sql/contract.json index 64179cf0..1d86465a 100644 --- a/spec/sql/contract.json +++ b/spec/sql/contract.json @@ -1,6 +1,6 @@ { "contract": "athleticstandard-sql", - "sql_schema_version": 6, + "sql_schema_version": 7, "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.", @@ -46,6 +46,11 @@ "version": 6, "file": "migrations/006-version-2-1-2.sql", "description": "Upgrade the database to software version 2.1.2. Adds the nullable athlete_reports.workout_session_id link to a workout session. No existing row changes." + }, + { + "version": 7, + "file": "migrations/007-version-2-1-3.sql", + "description": "Upgrade the database to software version 2.1.3. No athlete-owned table or column changes. Adds internal tables for the change log, host write receipts, and the access epoch." } ], "metadata_insert": { @@ -56,7 +61,7 @@ ], "header_pragmas": [ "PRAGMA application_id = 1096042545;", - "PRAGMA user_version = 6;" + "PRAGMA user_version = 7;" ] }, "file_header_pragmas": { @@ -192,13 +197,19 @@ "database_metadata", "record_erasure_markers", "record_import_keys", - "internal_pending_file_operations" + "internal_pending_file_operations", + "internal_change_log", + "internal_write_receipts", + "internal_access_state" ], "internal_table_notes": { "database_metadata": "Written once at creation and by each migration step. Holds the application marker, versions, database ID, and creation time.", "record_erasure_markers": "Written only by privacy erasure. Holds the value-free markers an erasure leaves.", "record_import_keys": "Written only by provider import. Holds provider matching keys, which are separate from record IDs.", - "internal_pending_file_operations": "Written only by the ath program, from SQL schema 5. Holds recovery state for attachment files that a SQL transaction cannot include: operation IDs, kinds, relative paths, and times. It holds no health values. It is not athlete-owned history and is never exported in a JSON package. Direct writers must not write it." + "internal_pending_file_operations": "Written only by the ath program, from SQL schema 5. Holds recovery state for attachment files that a SQL transaction cannot include: operation IDs, kinds, relative paths, and times. It holds no health values. It is not athlete-owned history and is never exported in a JSON package. Direct writers must not write it.", + "internal_change_log": "Maintained only by the triggers listed in internal_triggers, from SQL schema 7. Holds one row for each record revision, deletion, and erasure: the database revision that committed it, the record ID, the record revision (0 for an erasure), and the kind of change. It holds no health values and has no foreign keys. An erasure removes the record's earlier rows and leaves one erasure row, which names no revision. A restore into an empty database starts a new log. It is not athlete-owned history and is never exported in a JSON package. Direct writers must not write it; the triggers record their changes.", + "internal_write_receipts": "Written only by a host through the Athletic Standard library, from SQL schema 7. Holds one row for each accepted host write request: the signed-in person, the app, the request ID, the operation, a keyed digest of the request, the resulting IDs and revisions, the database revision, and the time. It holds no request body and no health values. It is never exported in a JSON package. Direct writers must not write it.", + "internal_access_state": "Written by migration step 7 and by a host through the Athletic Standard library. Holds one row with the access epoch, which revoking a grant raises. It is 0 in a database that never connected to a host. It is never exported in a JSON package. Direct writers must not write it." }, "collection_replacement": { "description": "On every create or correction, ordered child collections and link tables are replaced from the full payload. Delete existing child rows for the parent record_id, then insert the payload order. Omitted children are removed. An empty collection deletes all prior child rows.", @@ -314,5 +325,10 @@ "typed_row_record_type_matches_athlete_reports_insert", "point_measurements_require_source_insert", "prediction_result_links_revision_exists_insert" + ], + "internal_triggers": [ + "internal_change_log_revision_insert", + "internal_change_log_deletion_insert", + "internal_change_log_erasure_insert" ] } diff --git a/spec/sql/migrations/007-version-2-1-3.sql b/spec/sql/migrations/007-version-2-1-3.sql new file mode 100644 index 00000000..63070d52 --- /dev/null +++ b/spec/sql/migrations/007-version-2-1-3.sql @@ -0,0 +1,103 @@ +-- Athletic Standard upgrade to software version 2.1.3 (migration step 7). +-- This file is the executable migration. The ath program embeds it unchanged. +-- +-- See build-history/v2.1.3/spec.md section 4.2 and decisions D254 and D261 +-- to D263. Three internal tables are added. No athlete-owned table, column, +-- or row changes. Records written before this step stay as they are. None of +-- the three tables is part of an exported package, and none holds a health +-- value. +-- +-- internal_change_log has one row for each record revision, deletion, and +-- erasure, with the database revision that committed it (D263). Triggers +-- fill it in the same transaction as the change, so direct SQL writers that +-- follow the published recipes are included. A write raises +-- database_state.current_revision once, at the end of its transaction, so a +-- trigger records the current value plus one. The rows hold only record IDs +-- and numbers, and no foreign keys. An erasure removes the record's earlier +-- rows and leaves one erasure row, which names no revision +-- (record_revision 0), so the log keeps no more than the erasure marker +-- does. A restore into an empty database starts a new log. +-- +-- internal_write_receipts has one row for each write request a host accepted +-- (D261): who sent it, through which app, the request ID, a keyed digest of +-- the request, and the resulting IDs and revisions. It holds no request body. +-- +-- internal_access_state holds the access epoch (D262). Revoking a grant +-- raises it. A local database that never connects to a host keeps it at 0. + +CREATE TABLE internal_change_log ( + database_revision INTEGER NOT NULL CHECK (database_revision >= 1), + record_id TEXT NOT NULL, + record_revision INTEGER NOT NULL CHECK (record_revision >= 0), + change_kind TEXT NOT NULL CHECK (change_kind IN ( + 'revision', + 'deletion', + 'erasure' + )), + PRIMARY KEY (database_revision, record_id, change_kind, record_revision) +) STRICT, WITHOUT ROWID; + +CREATE INDEX internal_change_log_record_idx + ON internal_change_log (record_id); + +CREATE TRIGGER internal_change_log_revision_insert +AFTER INSERT ON record_revisions +BEGIN + INSERT OR IGNORE INTO internal_change_log (database_revision, record_id, record_revision, change_kind) + VALUES ( + (SELECT current_revision + 1 FROM database_state WHERE singleton_id = 1), + NEW.record_id, + NEW.revision, + 'revision' + ); +END; + +CREATE TRIGGER internal_change_log_deletion_insert +AFTER INSERT ON record_deletions +BEGIN + INSERT OR IGNORE INTO internal_change_log (database_revision, record_id, record_revision, change_kind) + VALUES ( + (SELECT current_revision + 1 FROM database_state WHERE singleton_id = 1), + NEW.record_id, + NEW.record_revision, + 'deletion' + ); +END; + +CREATE TRIGGER internal_change_log_erasure_insert +AFTER INSERT ON record_erasure_markers +BEGIN + DELETE FROM internal_change_log + WHERE record_id = NEW.record_id AND change_kind <> 'erasure'; + INSERT OR IGNORE INTO internal_change_log (database_revision, record_id, record_revision, change_kind) + VALUES ( + (SELECT current_revision + 1 FROM database_state WHERE singleton_id = 1), + NEW.record_id, + 0, + 'erasure' + ); +END; + +CREATE TABLE internal_write_receipts ( + principal_id TEXT NOT NULL, + client_id TEXT NOT NULL, + request_id TEXT NOT NULL, + operation TEXT NOT NULL, + request_digest TEXT NOT NULL, + result_json TEXT NOT NULL CHECK (json_valid(result_json)), + database_revision INTEGER NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (principal_id, client_id, request_id) +) STRICT; + +CREATE TABLE internal_access_state ( + singleton_id INTEGER PRIMARY KEY CHECK (singleton_id = 1), + access_epoch INTEGER NOT NULL CHECK (access_epoch >= 0) +) STRICT; + +INSERT INTO internal_access_state (singleton_id, access_epoch) VALUES (1, 0); + +UPDATE database_metadata +SET sql_schema_version = 7, + athleticstandard_version = '2.1.3' +WHERE singleton_id = 1; diff --git a/src/model/common.rs b/src/model/common.rs index 09afd406..44f17416 100644 --- a/src/model/common.rs +++ b/src/model/common.rs @@ -13,6 +13,7 @@ use crate::{model_enum, model_object}; // ---- Checked strings ---------------------------------------------------- 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}$"; +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}$"; pub const SEMVER_PATTERN: &str = r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$"; pub const SHA256_PATTERN: &str = "^[a-f0-9]{64}$"; pub const BENCHMARK_KEY_PATTERN: &str = "^[a-z0-9][a-z0-9_-]*$"; @@ -38,6 +39,16 @@ pub fn is_record_id(text: &str) -> bool { true } +/// A lowercase hyphenated UUID of any version: 8-4-4-4-12 hexadecimal digits. +pub fn is_lowercase_uuid(text: &str) -> bool { + let bytes = text.as_bytes(); + bytes.len() == 36 + && bytes.iter().enumerate().all(|(index, byte)| match index { + 8 | 13 | 18 | 23 => *byte == b'-', + _ => byte.is_ascii_digit() || (b'a'..=b'f').contains(byte), + }) +} + pub fn is_semver(text: &str) -> bool { let (core, rest) = match text.find(['-', '+']) { Some(index) => (&text[..index], &text[index..]), @@ -162,6 +173,15 @@ schema_fn!( }) .check(Check::MaxLength(200)) ); +schema_fn!( + /// The opaque ID a host assigned to a coach (D255). + coach_id, + string().check(Check::Pattern { + source: LOWERCASE_UUID_PATTERN, + test: is_lowercase_uuid, + message: "lowercase UUID" + }) +); schema_fn!( semver, string().check(Check::Pattern { source: SEMVER_PATTERN, test: is_semver, message: "semantic version" }) @@ -371,6 +391,13 @@ pub enum RecordActor { tool: String, 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 { + coach: String, + coach_id: String, + }, } impl RecordActor { @@ -379,8 +406,13 @@ impl RecordActor { RecordActor::Athlete => "athlete", RecordActor::Agent { .. } => "agent", RecordActor::Tool { .. } => "tool", + RecordActor::Coach { .. } => "coach", } } + + pub fn is_coach(&self) -> bool { + matches!(self, RecordActor::Coach { .. }) + } } /// The author of an authored record. @@ -401,6 +433,11 @@ pub enum AuthoredRecordAuthor { tool_version: String, calculation_version: String, }, + /// A human coach (D255), with the same fields as the coach actor. + Coach { + coach: String, + coach_id: String, + }, } impl AuthoredRecordAuthor { @@ -409,8 +446,13 @@ impl AuthoredRecordAuthor { AuthoredRecordAuthor::Athlete => "athlete", AuthoredRecordAuthor::Agent { .. } => "agent", AuthoredRecordAuthor::Tool { .. } => "tool", + AuthoredRecordAuthor::Coach { .. } => "coach", } } + + pub fn is_coach(&self) -> bool { + matches!(self, AuthoredRecordAuthor::Coach { .. }) + } } fn field(name: &'static str, schema: SchemaRef, optional: bool) -> Field { @@ -437,6 +479,14 @@ fn tool_actor_fields() -> Vec { ] } +fn coach_actor_fields() -> Vec { + vec![ + field("author_type", literal("coach"), false), + field("coach", text(), false), + field("coach_id", coach_id(), false), + ] +} + /// The athlete actor shape. pub fn athlete_actor() -> SchemaRef { static SCHEMA: LazyLock<&'static Schema> = @@ -458,6 +508,13 @@ pub fn tool_actor() -> SchemaRef { &SCHEMA } +/// The coach shape, for an actor and for an author (D255). +pub fn coach_actor() -> SchemaRef { + static SCHEMA: LazyLock<&'static Schema> = + LazyLock::new(|| leak(Schema::new(Kind::Object { fields: coach_actor_fields() }))); + &SCHEMA +} + /// The agent author shape: an agent actor with its model. pub fn agent_author() -> SchemaRef { static SCHEMA: LazyLock<&'static Schema> = LazyLock::new(|| { @@ -484,7 +541,12 @@ impl Shape for RecordActor { static SCHEMA: LazyLock = LazyLock::new(|| { Schema::new(Kind::Discriminated { key: "author_type", - options: vec![("athlete", athlete_actor()), ("agent", agent_actor()), ("tool", tool_actor())], + options: vec![ + ("athlete", athlete_actor()), + ("agent", agent_actor()), + ("tool", tool_actor()), + ("coach", coach_actor()), + ], }) }); &SCHEMA @@ -496,7 +558,12 @@ impl Shape for AuthoredRecordAuthor { static SCHEMA: LazyLock = LazyLock::new(|| { Schema::new(Kind::Discriminated { key: "author_type", - options: vec![("athlete", athlete_actor()), ("agent", agent_author()), ("tool", tool_author())], + options: vec![ + ("athlete", athlete_actor()), + ("agent", agent_author()), + ("tool", tool_author()), + ("coach", coach_actor()), + ], }) }); &SCHEMA diff --git a/src/model/package.rs b/src/model/package.rs index b37f4d03..a5dffe6c 100644 --- a/src/model/package.rs +++ b/src/model/package.rs @@ -16,14 +16,14 @@ use crate::json::{self, Value}; use crate::{model_enum, model_object}; /// The software, record, and database version (D152). -pub const ATHLETIC_STANDARD_VERSION: &str = "2.1.2"; +pub const ATHLETIC_STANDARD_VERSION: &str = "2.1.3"; /// 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"]; +pub const ACCEPTED_RECORD_VERSIONS: &[&str] = &["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3"]; /// Package versions `ath import` restores. 2.1.x and 2.0.0 packages share the /// same fields; later minor versions only add optional fields. -pub const IMPORTABLE_PACKAGE_VERSIONS: &[&str] = &["2.0.0", "2.1.0", "2.1.1", "2.1.2"]; +pub const IMPORTABLE_PACKAGE_VERSIONS: &[&str] = &["2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3"]; model_enum! { pub enum RecordFormatVersion { @@ -32,6 +32,7 @@ model_enum! { V2_1_0 = "2.1.0", V2_1_1 = "2.1.1", V2_1_2 = "2.1.2", + V2_1_3 = "2.1.3", } } @@ -469,6 +470,25 @@ fn refine_package(value: &Value, issues: &mut Vec) { ); } } + coach_version_issues(value, issues); +} + +/// A coach author or actor first appears in 2.1.3 (D255). A package that +/// declares an earlier version cannot contain one, because a program of that +/// version does not know the variant. +fn coach_version_issues(value: &Value, issues: &mut Vec) { + let declared = text(value, "athleticstandard_version"); + if !RecordFormatVersion::parse(declared).is_some_and(|version| version < RecordFormatVersion::V2_1_3) { + return; + } + let message = format!("A coach author needs Athletic Standard 2.1.3 or later; this package declares {declared}"); + for list in ["records", "record_revisions", "record_deletions"] { + for (index, item) in array(value, list).iter().enumerate() { + for path in coach_paths(item) { + issue(issues, at(&[list], index, path), &message); + } + } + } } fn refine_series_file(value: &Value, issues: &mut Vec) { diff --git a/src/model/record.rs b/src/model/record.rs index da4029db..beb0a932 100644 --- a/src/model/record.rs +++ b/src/model/record.rs @@ -121,6 +121,51 @@ impl RecordType { } } +/// The record types a coach may author and change (D255). A coach writes +/// advice, like an agent. A coach never writes a measured record or an +/// athlete report, so the two-tier wall holds. +pub const COACH_RECORD_TYPES: &[RecordType] = + &[RecordType::CoachingNote, RecordType::TrainingPlan, RecordType::PlannedSession]; + +impl RecordType { + /// Whether a coach may author this type or change one of its records. + pub fn coach_may_write(self) -> bool { + COACH_RECORD_TYPES.contains(&self) + } +} + +/// The refusal for a coach named on any other record type. +pub fn coach_record_type_message(record_type: &str) -> String { + format!("A coach may write only coaching_note, training_plan, and planned_session records, not {record_type}") +} + +/// The refusal for a deletion by a coach. A coach cannot delete history (D255). +pub const COACH_DELETION_MESSAGE: &str = "A coach cannot delete a record"; + +/// The refusal for an actor who cannot change a record of this type. +pub fn actor_problem(actor: &RecordActor, record_type: RecordType) -> Option { + (actor.is_coach() && !record_type.coach_may_write()).then(|| coach_record_type_message(record_type.as_str())) +} + +/// Whether a JSON actor or author names a coach. +pub(crate) fn names_coach(value: Option<&Value>) -> bool { + value.and_then(|value| value.get("author_type")).and_then(Value::as_str) == Some("coach") +} + +/// The places in a record, revision, or deletion where an actor or author +/// is written: a revision's `changed_by`, a deletion's `deleted_by`, an +/// authored record's author, and a link's `created_by`. +pub(crate) const ACTOR_PATHS: &[&[&str]] = + &[&["changed_by"], &["deleted_by"], &["data", "authorship", "author"], &["data", "created_by"]]; + +/// The actor paths of `value` that name a coach. +pub(crate) fn coach_paths(value: &Value) -> impl Iterator + '_ { + ACTOR_PATHS + .iter() + .copied() + .filter(move |path| names_coach(path.iter().try_fold(value, |current, key| current.get(*key)))) +} + impl RecordData { /// The measured-record source, when the type has one. pub fn source_id(&self) -> Option<&str> { @@ -328,6 +373,13 @@ model_object! { deleted_at: String = utc_timestamp(), deleted_by: RecordActor, } + refine(refine_deletion_actor) +} + +fn refine_deletion_actor(value: &Value, issues: &mut Vec) { + if names_coach(value.get("deleted_by")) { + custom(issues, &["deleted_by"], COACH_DELETION_MESSAGE); + } } model_object! { @@ -358,6 +410,17 @@ fn refine_record_extensions(value: &Value, issues: &mut Vec) { } } +/// A coach may author or change only the types in `COACH_RECORD_TYPES`. +fn refine_coach_actor(value: &Value, issues: &mut Vec) { + let record_type = value.get("record_type").and_then(Value::as_str).unwrap_or_default(); + if RecordType::parse(record_type).is_some_and(RecordType::coach_may_write) { + return; + } + for path in coach_paths(value) { + custom(issues, path, coach_record_type_message(record_type)); + } +} + fn refine_previous_revision(value: &Value, issues: &mut Vec) { let revision = value.get("revision").and_then(Value::as_f64); let previous = value.get("previous_revision"); @@ -390,7 +453,7 @@ pub fn current_record_variant(record_type: RecordType) -> SchemaRef { Field { name: "record_type", schema: literal(record_type.as_str()), optional: false }, Field { name: "data", schema: data_schema(*record_type), optional: false }, ]; - leak(Schema::new(Kind::Object { fields }).refine(refine_record_extensions)) + leak(Schema::new(Kind::Object { fields }).refine(refine_record_extensions).refine(refine_coach_actor)) }) .collect() }); @@ -417,7 +480,8 @@ pub fn revision_variant(record_type: RecordType) -> SchemaRef { leak( Schema::new(Kind::Object { fields }) .refine(refine_previous_revision) - .refine(refine_record_extensions), + .refine(refine_record_extensions) + .refine(refine_coach_actor), ) }) .collect() diff --git a/src/package/restore.rs b/src/package/restore.rs index 143b7327..007840b6 100644 --- a/src/package/restore.rs +++ b/src/package/restore.rs @@ -649,6 +649,12 @@ fn restore_in( "UPDATE database_state SET current_revision = ?1 WHERE singleton_id = 1", [loaded.database_revision as i64], )?; + // A restored database starts a new change log. The triggers logged every + // restored revision under one database revision that the package does not + // have. A device that knew an older log gets a complete package (D263). + if layout.has_table("internal_change_log") { + tx.execute("DELETE FROM internal_change_log", [])?; + } Ok(()) } diff --git a/src/store/contract.rs b/src/store/contract.rs index 00992bc4..69a09c20 100644 --- a/src/store/contract.rs +++ b/src/store/contract.rs @@ -3,8 +3,8 @@ //! `spec/sql/contract.json` declares what direct SQL clients may rely on: the //! schema step, the ordered migration files, header pragmas, stable views and //! their columns, writable and internal tables, collection replacement rules, -//! transaction recipes, and enforcement triggers. This module reads that file -//! and checks two things: +//! transaction recipes, enforcement triggers, and the internal triggers that +//! keep the change log. This module reads that file and checks two things: //! //! - The parts that follow from code agree with it: the migration chain, the //! schema step, the application ID, the trigger names in the published SQL, @@ -42,6 +42,16 @@ pub struct SqlContract { pub internal_tables: Vec, pub collection_replacement: CollectionReplacement, pub enforcement_triggers: Vec, + /// Triggers that maintain internal tables, such as the change log (SQL + /// schema 7). They enforce nothing. + pub internal_triggers: Vec, +} + +impl SqlContract { + /// Every trigger the contract lists, enforcement triggers first. + pub fn all_triggers(&self) -> Vec { + self.enforcement_triggers.iter().chain(&self.internal_triggers).cloned().collect() + } } #[derive(Debug, Clone, Deserialize)] @@ -134,8 +144,9 @@ pub fn verify_contract_metadata(contract: &SqlContract) -> Vec { if required != vec![("foreign_keys", "ON"), ("busy_timeout", busy.as_str())] { problems.push(format!("contract required pragmas are {required:?}")); } - if contract.enforcement_triggers != published_trigger_names() { - problems.push("contract enforcement triggers do not match the published migration SQL".to_string()); + if contract.all_triggers() != published_trigger_names() { + problems + .push("contract enforcement and internal triggers do not match the published migration SQL".to_string()); } let writable: BTreeSet<&str> = contract.stable_writable_tables.iter().map(String::as_str).collect(); for record_type in RecordType::ALL { @@ -213,9 +224,9 @@ pub fn verify_live_schema(store: &Store, contract: &SqlContract) -> Result = contract.enforcement_triggers.iter().cloned().collect(); + let listed_triggers: BTreeSet = contract.all_triggers().into_iter().collect(); for trigger in listed_triggers.difference(&triggers) { - problems.push(format!("enforcement trigger {trigger} is missing")); + problems.push(format!("trigger {trigger} is missing")); } for trigger in triggers.difference(&listed_triggers) { problems.push(format!("trigger {trigger} is not in the contract")); diff --git a/src/store/encode.rs b/src/store/encode.rs index c07f6d54..1d3ee4f9 100644 --- a/src/store/encode.rs +++ b/src/store/encode.rs @@ -457,7 +457,10 @@ impl Layout { } pub fn has_table(self, table: &str) -> bool { - !(self.sql_schema_version < 3 && table == "workout_route_points") + let before_step_3 = self.sql_schema_version < 3 && table == "workout_route_points"; + let before_step_7 = self.sql_schema_version < 7 + && matches!(table, "internal_change_log" | "internal_write_receipts" | "internal_access_state"); + !(before_step_3 || before_step_7) } } diff --git a/src/store/migrate.rs b/src/store/migrate.rs index 35849ff9..9812e573 100644 --- a/src/store/migrate.rs +++ b/src/store/migrate.rs @@ -17,7 +17,7 @@ use crate::files; use crate::model::time; /// The SQL schema step this software writes. -pub const SQL_SCHEMA_VERSION: u32 = 6; +pub const SQL_SCHEMA_VERSION: u32 = 7; /// One published migration step. pub struct MigrationStep { @@ -65,6 +65,12 @@ pub const MIGRATION_CHAIN: &[MigrationStep] = &[ description: "Upgrade the database to software version 2.1.2. Adds the nullable athlete_reports.workout_session_id link to a workout session. No existing row changes.", sql: include_str!("../../spec/sql/migrations/006-version-2-1-2.sql"), }, + MigrationStep { + version: 7, + file: "migrations/007-version-2-1-3.sql", + description: "Upgrade the database to software version 2.1.3. No athlete-owned table or column changes. Adds internal tables for the change log, host write receipts, and the access epoch.", + sql: include_str!("../../spec/sql/migrations/007-version-2-1-3.sql"), + }, ]; /// What a migration would do, shown before any change. diff --git a/src/store/mod.rs b/src/store/mod.rs index 676b13b4..da370a79 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -38,7 +38,7 @@ 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"]; +pub const READABLE_DATABASE_VERSIONS: &[&str] = &["1.0.0", "2.0.0", "2.1.0", "2.1.1", "2.1.2", "2.1.3"]; /// The default database file name in a working directory. pub const DEFAULT_FILENAME: &str = "athlete.ath.sqlite"; diff --git a/src/store/write.rs b/src/store/write.rs index 51d4f728..f6318f18 100644 --- a/src/store/write.rs +++ b/src/store/write.rs @@ -201,6 +201,17 @@ fn checked_record(record: CurrentRecord) -> Result { Ok(CurrentRecord::from_value(&record.to_value())?) } +/// Refuse an actor who cannot change a record of this type: a coach changes +/// only coaching notes, training plans, and planned sessions (D255). +fn checked_actor(actor: &RecordActor, record_type: RecordType) -> Result<()> { + match actor_problem(actor, record_type) { + Some(message) => { + Err(Error::Invalid(ValidationError::single(vec![PathSegment::Key("changed_by".into())], message))) + } + None => Ok(()), + } +} + #[allow(clippy::too_many_arguments)] fn insert_revision( tx: &Transaction<'_>, @@ -247,6 +258,7 @@ fn insert_record(tx: &Transaction<'_>, layout: Layout, create: NewRecord, now: & data: create.data, })?; let record_type = record.record_type(); + checked_actor(&create.changed_by, record_type)?; let record_json = record.data.to_json(); tx.prepare_cached( "INSERT INTO records (record_id, record_type, current_revision, created_at, is_deleted) VALUES (?1, ?2, 1, ?3, 0)", @@ -356,6 +368,7 @@ fn correct_record(tx: &Transaction<'_>, layout: Layout, correction: Correction, extensions, data: correction.data, })?; + checked_actor(&correction.changed_by, record.record_type())?; let record_json = record.data.to_json(); insert_revision( tx, @@ -386,6 +399,12 @@ fn delete_record(tx: &Transaction<'_>, deletion: Deletion, now: &str) -> Result< if current.is_deleted { return Err(Error::refused(format!("Record is already deleted: {record_id}"))); } + if deletion.deleted_by.is_coach() { + return Err(Error::Invalid(ValidationError::single( + vec![PathSegment::Key("deleted_by".into())], + COACH_DELETION_MESSAGE, + ))); + } let deleted_at = checked_timestamp(deletion.deleted_at, now, "deleted_at")?; if time::parse_utc_timestamp(&deleted_at) < time::parse_utc_timestamp(¤t.became_known_at) { return Err(Error::refused("Deletion time cannot precede the current revision knowledge time")); diff --git a/tests/cli_golden.rs b/tests/cli_golden.rs index a734a116..65719197 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 6 (D211, D227). Steps 5 and -//! 6 are removed from native migration plans, and a source, target, or -//! required step 5 or 6 reads 4. +//! - The native program writes SQL schema step 7 (D211, D227, D254). Steps +//! 5 to 7 are removed from native migration plans, and a source, target, +//! or required step 5, 6, or 7 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,11 +216,13 @@ fn manifest_hashes(text: &str) -> String { out.join("\n") } -/// The native program writes SQL schema step 6 (2.1.1 added step 5, 2.1.2 -/// step 6); 2.1.0 wrote step 4. +/// The native program writes SQL schema step 7 (2.1.1 added step 5, 2.1.2 +/// step 6, 2.1.3 step 7); 2.1.0 wrote step 4. fn step_five_as_four(text: &str) -> String { let mut out = text.to_string(); - for file in ["migrations/005-version-2-1-1.sql", "migrations/006-version-2-1-2.sql"] { + for file in + ["migrations/005-version-2-1-1.sql", "migrations/006-version-2-1-2.sql", "migrations/007-version-2-1-3.sql"] + { let marker = format!("\"migration_file\": \"{file}\""); while let Some(position) = out.find(&marker) { let object = out[..position].rfind('{').expect("the step object opens"); @@ -229,7 +231,7 @@ fn step_five_as_four(text: &str) -> String { out.replace_range(start..end, ""); } } - for step in ["5", "6"] { + for step in ["5", "6", "7"] { 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 0b203d41..b65ae53f 100644 --- a/tests/migration.rs +++ b/tests/migration.rs @@ -342,15 +342,15 @@ fn foreign_and_mismatched_headers_are_refused_without_change() { direct(&path) .execute_batch( "PRAGMA journal_mode = DELETE; - UPDATE database_metadata SET sql_schema_version = 7; - PRAGMA user_version = 7;", + UPDATE database_metadata SET sql_schema_version = 8; + PRAGMA user_version = 8;", ) .unwrap(); let error = inspect_migration(&path, None).unwrap_err().to_string(); assert_eq!( error, format!( - "Database SQL schema 7 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 8 is newer than supported schema {SQL_SCHEMA_VERSION}. A newer ath wrote this database. Update ath to open it, for example with ath --update." ) ); } @@ -382,8 +382,9 @@ fn rollback_means_restoring_the_verified_backup() { /// Runs the 2.1.0 TypeScript `ath` from the reference checkout that /// `ATH_REFERENCE_CHECKOUT` names, with its `node_modules`. The old program -/// must refuse a migrated 2.1.1 database and leave it unchanged. It must read -/// the restored backup. The release performance workflow runs this test. +/// must refuse a migrated database of the current version and leave it +/// unchanged. It must read the restored backup. The release performance +/// workflow runs this test. #[test] #[ignore = "needs ATH_REFERENCE_CHECKOUT: a 2.1.0 checkout with node_modules"] fn the_2_1_0_program_refuses_a_migrated_database() { @@ -427,7 +428,11 @@ fn the_2_1_0_program_refuses_a_migrated_database() { ] { let (code, output) = old(&args); assert_eq!(code, Some(1), "{args:?}: {output}"); - assert!(output.contains("Unsupported Athletic Standard database version: 2.1.1"), "{args:?}: {output}"); + let refusal = format!( + "Unsupported Athletic Standard database version: {}", + athleticstandard::model::package::ATHLETIC_STANDARD_VERSION + ); + assert!(output.contains(&refusal), "{args:?}: {output}"); } assert_eq!(file_hash(&path), before, "the old program changed the migrated database"); @@ -441,7 +446,8 @@ fn the_2_1_0_program_refuses_a_migrated_database() { /// The migrated athlete tables equal what the 2.1.0 migration wrote, row for /// row. 2.1.1 adds step 5, which changes no athlete row. 2.1.2 adds step 6, -/// which adds one empty column and changes no athlete row. +/// which adds one empty column and changes no athlete row. 2.1.3 adds step 7, +/// which adds three internal tables and changes no athlete row. #[test] fn migrated_tables_match_the_2_1_0_migration() { let golden = golden("migration.json"); @@ -461,15 +467,22 @@ 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 two steps earlier. + // 2.1.0 planned the same steps, ending three 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() + 2, "{name}"); + assert_eq!(preview.planned_steps.len(), old_steps.len() + 3, "{name}"); let added: Vec<&str> = preview.planned_steps[old_steps.len()..].iter().map(|step| step.migration_file.as_str()).collect(); - assert_eq!(added, ["migrations/005-version-2-1-1.sql", "migrations/006-version-2-1-2.sql"]); + assert_eq!( + added, + [ + "migrations/005-version-2-1-1.sql", + "migrations/006-version-2-1-2.sql", + "migrations/007-version-2-1-3.sql" + ] + ); let mut store = open_for_migration(&path); execute_confirmed_migration(&mut store, &MigrationOptions::default()).unwrap(); diff --git a/tests/model_vectors.rs b/tests/model_vectors.rs index 82fdfc76..42d749cf 100644 --- a/tests/model_vectors.rs +++ b/tests/model_vectors.rs @@ -44,6 +44,16 @@ fn as_2_1_2_issue(text: String) -> String { 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. +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() @@ -88,8 +98,14 @@ 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).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) + .collect(); if actual != expected { failures.push(format!("{schema_name} / {name}:\n expected {expected:?}\n actual {actual:?}")); continue; diff --git a/tests/published_files.rs b/tests/published_files.rs index 624ab075..f034392d 100644 --- a/tests/published_files.rs +++ b/tests/published_files.rs @@ -28,6 +28,7 @@ const PUBLISHED: &[(&str, &str)] = &[ ("spec/sql/migrations/003-version-2.sql", "78f4c910f1f0fd80d0da0395ece2ab9681cbe351490d7af52752d95240041d80"), ("spec/sql/migrations/004-version-2-1.sql", "c31baa4d881d4a995912de209f902e90f4be695b5cb18e306364dc0331fa690c"), ("spec/sql/migrations/005-version-2-1-1.sql", "e393d69ba46a2f79cc40a34014e1fdf7da0cd8350a5d2dd151d88fe814ca2dbb"), + ("spec/sql/migrations/006-version-2-1-2.sql", "b9e6be1fc880929aae2a585d0cd7b9b5185f48299981a4c07997df36131b7422"), ("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"), @@ -41,6 +42,9 @@ const PUBLISHED: &[(&str, &str)] = &[ ("schema/2.1.1/athleticstandard.schema.json", "7ea68b4a96caa64c55a08639fd8fb6f24e956c74382601fa7ef06c81202ecf5b"), ("schema/2.1.1/export-manifest.schema.json", "3c8c9435f6786be3b35fe69d9565e0ca296b0ef924347f3c898cac65ef8b97ac"), ("schema/2.1.1/measurement-series.schema.json", "69814a8d043c544077d262cd66e6b4e7536b704f5a93c232980da1646460914a"), + ("schema/2.1.2/athleticstandard.schema.json", "6a5ba8b96a2f8146c173233f1ba76783b66de3c0d2d8649e31189025ae76116c"), + ("schema/2.1.2/export-manifest.schema.json", "815eb3bfb1467306709095043f664cbe3c69b0cdf873aa14707ec4064d0260aa"), + ("schema/2.1.2/measurement-series.schema.json", "d166428a39e7dbc81cd21a18be928c170f373808a4c449655d4a440d2566526f"), ]; fn repository() -> PathBuf { diff --git a/tests/published_schema.rs b/tests/published_schema.rs index ee6d6397..e516fbe0 100644 --- a/tests/published_schema.rs +++ b/tests/published_schema.rs @@ -1,7 +1,9 @@ -//! The generated JSON Schema must match the published 2.1.1 files except for -//! the version list, the schema IDs, and the optional 2.1.2 additions (D238, -//! D239). The published 2.1.1 files must still match the published 2.1.0 files -//! except for their version markers, because 2.1.1 changed no record field. +//! The generated JSON Schema must match the published 2.1.2 files except for +//! the version list, the schema IDs, and the 2.1.3 coach author (D255). The +//! published 2.1.2 files must match the published 2.1.1 files except for +//! those markers and the optional 2.1.2 additions (D238, D239). The published +//! 2.1.1 files must still match the published 2.1.0 files except for their +//! version markers, because 2.1.1 changed no record field. use athleticstandard::json::{self, Value}; use athleticstandard::model::{json_schema, package}; @@ -69,6 +71,29 @@ fn remove_2_1_2_additions(value: &mut Value) -> usize { removed } +/// Remove exactly the 2.1.3 addition: the coach option of every actor and +/// author union. Returns how many it removed. +fn remove_2_1_3_additions(value: &mut Value) -> usize { + let mut removed = 0; + match value { + Value::Array(items) => { + let before = items.len(); + items.retain(|item| item["properties"]["author_type"]["const"].as_str() != Some("coach")); + removed += before - items.len(); + for item in items.iter_mut() { + removed += remove_2_1_3_additions(item); + } + } + Value::Object(map) => { + for item in map.values_mut() { + removed += remove_2_1_3_additions(item); + } + } + _ => {} + } + removed +} + fn first_difference(expected: &str, actual: &str, name: &str) { if expected != actual { let out = std::env::temp_dir().join(format!("generated-{name}")); @@ -78,13 +103,13 @@ fn first_difference(expected: &str, actual: &str, name: &str) { } } -/// Compare a generated document with the published 2.1.1 file. `additions` is -/// how many 2.1.2 additions the document must contain. +/// Compare a generated document with the published 2.1.2 file. `additions` is +/// how many 2.1.3 coach options the document must contain. fn compare(generated: Value, name: &str, additions: usize) { let mut generated = generated; - rewrite_versions(&mut generated, package::ATHLETIC_STANDARD_VERSION, "2.1.1"); - assert_eq!(remove_2_1_2_additions(&mut generated), additions, "{name}: the 2.1.2 additions"); - first_difference(&json::to_pretty(&published("2.1.1", name)), &json::to_pretty(&generated), name); + rewrite_versions(&mut generated, package::ATHLETIC_STANDARD_VERSION, "2.1.2"); + assert_eq!(remove_2_1_3_additions(&mut generated), additions, "{name}: the 2.1.3 additions"); + first_difference(&json::to_pretty(&published("2.1.2", name)), &json::to_pretty(&generated), name); } #[test] @@ -94,9 +119,11 @@ fn package_schema_matches_published_layout() { package::ATHLETIC_STANDARD_VERSION ); // Each record shape appears twice in the package schema, once for current - // records and once for retained revisions. Each copy has the three - // strength-set fields, the report type, and the report's workout link. - let additions = 2 * (3 + 1 + 1); + // records and once for retained revisions. Each copy of the ten authored + // types has a coach author, and each copy of the result link a coach + // `created_by`. Each of the 23 revision shapes has a coach `changed_by`, + // and the deletion shape a coach `deleted_by`. + let additions = 2 * (10 + 1) + 23 + 1; compare( json_schema::document(package::package_schema(), &id, "Athletic Standard portable package document"), "athleticstandard.schema.json", @@ -117,7 +144,8 @@ fn series_schema_matches_published_layout() { "Athletic Standard measurement-series file", ), "measurement-series.schema.json", - 0, + // The sample revision's `changed_by` and the deletion's `deleted_by`. + 2, ); } @@ -135,6 +163,20 @@ fn manifest_schema_matches_published_layout() { ); } +#[test] +fn the_published_2_1_2_files_match_2_1_1_except_versions_and_additions() { + for (name, additions) in [ + ("athleticstandard.schema.json", 2 * (3 + 1 + 1)), + ("measurement-series.schema.json", 0), + ("export-manifest.schema.json", 0), + ] { + let mut document = published("2.1.2", name); + rewrite_versions(&mut document, "2.1.2", "2.1.1"); + assert_eq!(remove_2_1_2_additions(&mut document), additions, "{name}: the 2.1.2 additions"); + first_difference(&json::to_pretty(&published("2.1.1", name)), &json::to_pretty(&document), name); + } +} + #[test] fn the_published_2_1_1_files_match_2_1_0_except_versions() { for name in ["athleticstandard.schema.json", "measurement-series.schema.json", "export-manifest.schema.json"] { diff --git a/tests/record_2_1_3.rs b/tests/record_2_1_3.rs new file mode 100644 index 00000000..6f7c25e2 --- /dev/null +++ b/tests/record_2_1_3.rs @@ -0,0 +1,597 @@ +//! The 2.1.3 additions (D254, D255, D261–D263): the coach author and its +//! rules, the version a package with a coach must declare, and the three +//! internal tables of migration step 7. The change log is checked against +//! the database revision each write commits. + +mod demo_support; +// The maintenance helpers own this program's temporary folders. +mod maintenance_support; + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use athleticstandard::json::{self, Value}; +use athleticstandard::model::package::ATHLETIC_STANDARD_VERSION; +use athleticstandard::model::{registry, ErasureReasonCode, RecordActor, RecordData, RecordType}; +use athleticstandard::package::{ + apply_package_import, erase_record, export_package, preview_erasure, preview_package_import, ExportOptions, + MANIFEST_DOCUMENT, PACKAGE_DOCUMENT, +}; +use athleticstandard::store::check::check_database; +use athleticstandard::store::contract; +use athleticstandard::store::migrate::{execute_confirmed_migration, MigrationOptions}; +use athleticstandard::store::write::StaleStyle; +use athleticstandard::store::{ + Changes, Correction, CreateOptions, Deletion, ExtensionsUpdate, NewRecord, OpenOptions, Store, SQL_SCHEMA_VERSION, +}; +use rusqlite::Connection; +use serde_json::json; + +const COACH_ID: &str = "6f1c2e4a-3b5d-4c7e-9f80-1a2b3c4d5e6f"; +const NOTE: &str = "01890f3e-e7d3-7cc0-88c8-0000000000c1"; +const OTHER_NOTE: &str = "01890f3e-e7d3-7cc0-88c8-0000000000c2"; +const GOAL: &str = "01890f3e-e7d3-7cc0-88c8-0000000000c3"; +const REPORT: &str = "01890f3e-e7d3-7cc0-88c8-0000000000c4"; +/// The demo's workout, a measured record. +const WORKOUT: &str = "01890f3e-e7d3-7cc0-88c8-00000000000a"; +const WRITTEN: &str = "2026-11-20T12:00:00.000Z"; +const CORRECTED: &str = "2026-11-20T13:00:00.000Z"; +const DELETED: &str = "2026-11-20T14:00:00.000Z"; +const ERASED: &str = "2026-11-20T15:00:00.000Z"; +const INTERNAL_TABLES: [&str; 3] = ["internal_change_log", "internal_write_receipts", "internal_access_state"]; + +fn coach_json() -> serde_json::Value { + json!({ "author_type": "coach", "coach": "Example Coach", "coach_id": COACH_ID }) +} + +fn coach() -> RecordActor { + serde_json::from_value(coach_json()).unwrap() +} + +fn athlete() -> RecordActor { + serde_json::from_value(json!({ "author_type": "athlete" })).unwrap() +} + +fn value(data: serde_json::Value) -> Value { + json::parse(&data.to_string()).unwrap() +} + +fn issues(schema: &str, data: serde_json::Value) -> Vec { + registry::shape(schema).unwrap().issues(&value(data)).iter().map(|issue| issue.to_json().to_string()).collect() +} + +fn authorship(author: serde_json::Value) -> serde_json::Value { + json!({ "author": author, "authored_at": WRITTEN, "evidence": [], "content_version": 1, "status": "active" }) +} + +fn note_data(author: serde_json::Value, note: &str) -> serde_json::Value { + json!({ "authorship": authorship(author), "title": "Deload week", "note": note }) +} + +fn goal_data(author: serde_json::Value) -> serde_json::Value { + json!({ "authorship": authorship(author), "title": "Row 2000 m under eight minutes" }) +} + +fn record(record_type: &str, record_id: &str, data: serde_json::Value) -> serde_json::Value { + json!({ + "record_id": record_id, + "created_at": WRITTEN, + "current_revision": 1, + "is_deleted": false, + "record_type": record_type, + "data": data, + }) +} + +fn report_data() -> serde_json::Value { + json!({ + "report_type": "note", + "reported_at": WRITTEN, + "input_reported_at": { "timestamp_missing_reason": "not_applicable", "utc_offset_missing_reason": "not_applicable" }, + "reported_via": "text", + "note": "Legs felt heavy.", + }) +} + +fn new_record(record_type: RecordType, record_id: &str, data: serde_json::Value, actor: RecordActor) -> NewRecord { + NewRecord { + record_id: Some(record_id.to_string()), + created_at: Some(WRITTEN.to_string()), + ..NewRecord::new(RecordData::decode(record_type, &value(data)).unwrap(), actor) + } +} + +fn note(record_id: &str, text: &str) -> NewRecord { + new_record(RecordType::CoachingNote, record_id, note_data(coach_json(), text), coach()) +} + +fn new_store(directory: &Path) -> (PathBuf, Store) { + let path = directory.join("athlete.ath.sqlite"); + let store = Store::create(&path, CreateOptions::default()).unwrap(); + (path, store) +} + +fn inspect(path: &Path) -> Connection { + Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap() +} + +/// Change-log rows as (database revision, record ID, record revision, kind). +fn change_log(path: &Path) -> Vec<(u64, String, u64, String)> { + let connection = inspect(path); + let mut statement = connection + .prepare( + "SELECT database_revision, record_id, record_revision, change_kind FROM internal_change_log + ORDER BY database_revision, record_id, change_kind, record_revision", + ) + .unwrap(); + statement + .query_map([], |row| Ok((row.get::<_, i64>(0)? as u64, row.get(1)?, row.get::<_, i64>(2)? as u64, row.get(3)?))) + .unwrap() + .map(Result::unwrap) + .collect() +} + +fn row(database_revision: u64, record_id: &str, record_revision: u64, kind: &str) -> (u64, String, u64, String) { + (database_revision, record_id.to_string(), record_revision, kind.to_string()) +} + +fn count(path: &Path, table: &str) -> i64 { + inspect(path).query_row(&format!("SELECT count(*) FROM {table}"), [], |row| row.get(0)).unwrap() +} + +fn access_rows(path: &Path) -> Vec<(i64, i64)> { + let connection = inspect(path); + let mut statement = connection.prepare("SELECT singleton_id, access_epoch FROM internal_access_state").unwrap(); + statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?))).unwrap().map(Result::unwrap).collect() +} + +/// Every file below `directory`, by relative path with `/` separators. +fn files_below(directory: &Path) -> BTreeMap> { + fn walk(root: &Path, directory: &Path, out: &mut BTreeMap>) { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(root, &path, out); + } else { + let relative = path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"); + out.insert(relative, fs::read(&path).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + walk(directory, directory, &mut out); + out +} + +#[test] +fn a_coach_note_survives_export_and_restore_byte_for_byte() { + let directory = maintenance_support::temporary_dir("ath-record-2-1-3-round-trip-"); + let (_, mut store) = new_store(&directory); + store + .apply(Changes { creates: vec![note(NOTE, "Keep every session easy this week.")], ..Changes::default() }) + .unwrap(); + let corrected = RecordData::decode( + RecordType::CoachingNote, + &value(note_data(coach_json(), "Keep every session easy, and sleep eight hours.")), + ) + .unwrap(); + store + .apply(Changes { + corrections: vec![Correction { + record_id: NOTE.into(), + expected_revision: 1, + data: corrected, + extensions: ExtensionsUpdate::Keep, + changed_by: coach(), + became_known_at: Some(CORRECTED.into()), + became_known_at_basis: athleticstandard::model::BecameKnownAtBasis::LocalWrite, + stale_style: StaleStyle::Revision, + }], + ..Changes::default() + }) + .unwrap(); + + let first = directory.join("first"); + export_package(&store, &first, &ExportOptions::default()).unwrap(); + let document = json::parse(&fs::read_to_string(first.join(PACKAGE_DOCUMENT)).unwrap()).unwrap(); + assert_eq!(document["athleticstandard_version"], ATHLETIC_STANDARD_VERSION); + assert_eq!(document["records"][0]["data"]["authorship"]["author"], value(coach_json())); + for revision in document["record_revisions"].as_array().unwrap() { + assert_eq!(revision["changed_by"], value(coach_json())); + } + + // The package holds the record, its history, and nothing internal. + let package = files_below(&first); + assert_eq!(package.keys().collect::>(), [PACKAGE_DOCUMENT, MANIFEST_DOCUMENT]); + let keys: Vec<&String> = document.as_object().unwrap().keys().collect(); + assert_eq!( + keys, + [ + "athleticstandard_version", + "database_id", + "database_revision", + "measurement_series_files", + "record_deletions", + "record_erasure_markers", + "record_import_keys", + "record_revisions", + "records" + ] + ); + for (file, bytes) in &package { + let text = String::from_utf8_lossy(bytes); + for word in INTERNAL_TABLES.iter().copied().chain(["access_epoch", "request_digest", "change_kind"]) { + assert!(!text.contains(word), "{file} names {word}"); + } + } + + // Restore into an empty database, then export again. + let restored_path = directory.join("restored.ath.sqlite"); + let mut restored = Store::create(&restored_path, CreateOptions::default()).unwrap(); + let preview = preview_package_import(&restored, &first).unwrap(); + assert!(preview.restore && !preview.is_unrepresentable(), "{preview:?}"); + apply_package_import(&mut restored, &preview, &[]).unwrap(); + let second = directory.join("second"); + export_package(&restored, &second, &ExportOptions::default()).unwrap(); + assert_eq!(files_below(&second), package, "the second export differs"); + let kept = restored.revisions(NOTE).unwrap(); + assert_eq!(kept.iter().map(|revision| revision.changed_by.clone()).collect::>(), [coach(), coach()]); + drop(restored); + + // A restore starts a new change log and keeps the other internal tables + // as a new database has them. + assert!(change_log(&restored_path).is_empty()); + assert_eq!(count(&restored_path, "internal_write_receipts"), 0); + assert_eq!(access_rows(&restored_path), [(1, 0)]); + drop(store); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn a_coach_writes_only_notes_plans_and_planned_sessions() { + // The shapes: a coach author on the three types passes. + assert_eq!(issues("CoachingNoteRecord", record("coaching_note", NOTE, note_data(coach_json(), "Easy."))), [""; 0]); + let plan = json!({ "authorship": authorship(coach_json()), "title": "Base block" }); + assert_eq!(issues("TrainingPlanRecord", record("training_plan", NOTE, plan)), [""; 0]); + + // On any other authored type it is refused. + let goal = issues("GoalRecord", record("goal", GOAL, goal_data(coach_json()))); + assert_eq!(goal.len(), 1, "{goal:?}"); + assert!(goal[0].contains(r#""path":["data","authorship","author"]"#), "{goal:?}"); + assert!( + goal[0].contains("A coach may write only coaching_note, training_plan, and planned_session records, not goal"), + "{goal:?}" + ); + let review = json!({ + "authorship": authorship(coach_json()), + "period_start": "2026-11-01", + "period_end": "2026-11-14", + "summary": "Two steady weeks.", + }); + let review = issues("SavedTrainingReviewRecord", record("saved_training_review", GOAL, review)); + assert!(review.len() == 1 && review[0].contains("not saved_training_review"), "{review:?}"); + + // A coach cannot be the actor of an athlete report's revision. + let revision = json!({ + "record_id": REPORT, + "revision": 1, + "previous_revision": null, + "became_known_at": WRITTEN, + "became_known_at_basis": "local_write", + "changed_by": coach_json(), + "record_type": "athlete_report", + "data": report_data(), + }); + let refused = issues("AthleteReportRevision", revision.clone()); + assert!(refused.len() == 1 && refused[0].contains(r#""path":["changed_by"]"#), "{refused:?}"); + assert!(refused[0].contains("not athlete_report"), "{refused:?}"); + let mut by_athlete = revision; + by_athlete["changed_by"] = json!({ "author_type": "athlete" }); + assert_eq!(issues("AthleteReportRevision", by_athlete), [""; 0]); + + // The store refuses the same writes and writes nothing. + let directory = maintenance_support::temporary_dir("ath-record-2-1-3-wall-"); + let path = demo_support::write(&directory); + let mut store = Store::open(&path, OpenOptions::default()).unwrap(); + let before = store.database_revision().unwrap(); + let refuse = |store: &mut Store, changes: Changes| store.apply(changes).unwrap_err().to_string(); + + let report = new_record(RecordType::AthleteReport, REPORT, report_data(), coach()); + assert_eq!( + refuse(&mut store, Changes { creates: vec![report], ..Changes::default() }), + "changed_by: A coach may write only coaching_note, training_plan, and planned_session records, not athlete_report" + ); + let goal = new_record(RecordType::Goal, GOAL, goal_data(coach_json()), athlete()); + assert_eq!( + refuse(&mut store, Changes { creates: vec![goal], ..Changes::default() }), + "data.authorship.author: A coach may write only coaching_note, training_plan, and planned_session records, not goal" + ); + let workout = store.get_record(WORKOUT).unwrap().unwrap(); + let correction = Correction { + record_id: WORKOUT.into(), + expected_revision: workout.current_revision, + data: workout.data.clone(), + extensions: ExtensionsUpdate::Keep, + changed_by: coach(), + became_known_at: Some(WRITTEN.into()), + became_known_at_basis: athleticstandard::model::BecameKnownAtBasis::LocalWrite, + stale_style: StaleStyle::Revision, + }; + assert_eq!( + refuse(&mut store, Changes { corrections: vec![correction], ..Changes::default() }), + "changed_by: A coach may write only coaching_note, training_plan, and planned_session records, not workout_session" + ); + assert_eq!(store.database_revision().unwrap(), before, "a refused write writes nothing"); + assert!(store.get_record(REPORT).unwrap().is_none() && store.get_record(GOAL).unwrap().is_none()); + drop(store); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn a_coach_needs_a_name_and_a_lowercase_uuid() { + for schema in ["RecordActor", "AuthoredRecordAuthor"] { + assert_eq!(issues(schema, coach_json()), [""; 0], "{schema}"); + // Any UUID version is accepted: the host chooses the ID. + let mut version_seven = coach_json(); + version_seven["coach_id"] = json!(NOTE); + assert_eq!(issues(schema, version_seven), [""; 0], "{schema}"); + for (field, bad) in [ + ("coach_id", json!("6F1C2E4A-3B5D-4C7E-9F80-1A2B3C4D5E6F")), + ("coach_id", json!("6f1c2e4a3b5d4c7e9f801a2b3c4d5e6f")), + ("coach_id", json!("coach@example.com")), + ("coach_id", json!("")), + ("coach", json!("")), + ("coach", json!(7)), + ] { + let mut actor = coach_json(); + actor[field] = bad.clone(); + let found = issues(schema, actor); + assert_eq!(found.len(), 1, "{schema} {field} {bad}: {found:?}"); + assert!(found[0].contains(&format!(r#""path":["{field}"]"#)), "{found:?}"); + } + let mut missing = coach_json(); + missing.as_object_mut().unwrap().remove("coach_id"); + assert!(!issues(schema, missing).is_empty(), "{schema}"); + let mut extra = coach_json(); + extra["email"] = json!("coach@example.com"); + assert!(issues(schema, extra)[0].contains("Unrecognized key"), "{schema}"); + } +} + +#[test] +fn a_coach_cannot_delete_a_record() { + let deletion = + json!({ "record_id": NOTE, "record_revision": 1, "deleted_at": DELETED, "deleted_by": coach_json() }); + let found = issues("RecordDeletion", deletion); + assert!(found.len() == 1 && found[0].contains("A coach cannot delete a record"), "{found:?}"); + + let directory = maintenance_support::temporary_dir("ath-record-2-1-3-delete-"); + let (_, mut store) = new_store(&directory); + store.apply(Changes { creates: vec![note(NOTE, "Easy week.")], ..Changes::default() }).unwrap(); + let before = store.database_revision().unwrap(); + let error = store + .apply(Changes { + deletions: vec![Deletion { + record_id: NOTE.into(), + expected_revision: 1, + deleted_by: coach(), + deleted_at: Some(DELETED.into()), + }], + ..Changes::default() + }) + .unwrap_err() + .to_string(); + assert_eq!(error, "deleted_by: A coach cannot delete a record"); + assert_eq!(store.database_revision().unwrap(), before); + assert!(!store.get_record(NOTE).unwrap().unwrap().is_deleted); + drop(store); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn a_package_with_a_coach_declares_2_1_3_or_later() { + let directory = maintenance_support::temporary_dir("ath-record-2-1-3-version-"); + let (_, mut store) = new_store(&directory); + store.apply(Changes { creates: vec![note(NOTE, "Easy week.")], ..Changes::default() }).unwrap(); + let package = directory.join("package"); + export_package(&store, &package, &ExportOptions::default()).unwrap(); + drop(store); + + let text = fs::read_to_string(package.join(PACKAGE_DOCUMENT)).unwrap(); + let document: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(issues("AthleticStandardPackage", document.clone()), [""; 0]); + for older in ["2.1.2", "2.1.0", "1.0.0"] { + let mut declared = document.clone(); + declared["athleticstandard_version"] = json!(older); + let found = issues("AthleticStandardPackage", declared); + let message = format!("A coach author needs Athletic Standard 2.1.3 or later; this package declares {older}"); + // The note's author, and its revision's actor and author. + assert_eq!(found.len(), 3, "{older}: {found:?}"); + assert!(found[0].contains(r#""path":["records",0,"data","authorship","author"]"#), "{found:?}"); + assert!(found[1].contains(r#""path":["record_revisions",0,"changed_by"]"#), "{found:?}"); + assert!(found[2].contains(r#""path":["record_revisions",0,"data","authorship","author"]"#), "{found:?}"); + assert!(found.iter().all(|issue| issue.contains(&message)), "{found:?}"); + } + + // `ath import` refuses the older declaration and names the reason. + let older = text.replacen( + &format!("\"athleticstandard_version\": \"{ATHLETIC_STANDARD_VERSION}\""), + "\"athleticstandard_version\": \"2.1.2\"", + 1, + ); + assert_ne!(older, text); + fs::write(package.join(PACKAGE_DOCUMENT), older).unwrap(); + fs::remove_file(package.join(MANIFEST_DOCUMENT)).unwrap(); + let destination = Store::create(directory.join("destination.ath.sqlite"), CreateOptions::default()).unwrap(); + let preview = preview_package_import(&destination, &package).unwrap(); + assert!(preview.is_unrepresentable()); + assert!( + preview.unrepresentable_records.iter().any(|line| line + == "records.0.data.authorship.author: A coach author needs Athletic Standard 2.1.3 or later; this package declares 2.1.2"), + "{:?}", + preview.unrepresentable_records + ); + drop(destination); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn a_new_database_has_the_three_internal_tables() { + let directory = maintenance_support::temporary_dir("ath-record-2-1-3-new-"); + let (path, store) = new_store(&directory); + assert_eq!(store.metadata().sql_schema_version, SQL_SCHEMA_VERSION); + assert_eq!(SQL_SCHEMA_VERSION, 7); + drop(store); + assert!(change_log(&path).is_empty()); + assert_eq!(count(&path, "internal_write_receipts"), 0); + assert_eq!(access_rows(&path), [(1, 0)]); + fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn a_2_1_2_database_migrates_to_step_7_with_empty_internal_tables() { + // A 2.1.2 program runs the published steps 5 and 6 on the 2.1.0 demo. + let path = + maintenance_support::copy_fixture(&maintenance_support::demo_fixture(), "ath-record-2-1-3-step-6-", true); + let migrations = maintenance_support::repository().join("spec/sql/migrations"); + let direct = maintenance_support::direct(&path); + direct.execute_batch("PRAGMA journal_mode = DELETE; BEGIN IMMEDIATE;").unwrap(); + for file in ["005-version-2-1-1.sql", "006-version-2-1-2.sql"] { + direct.execute_batch(&fs::read_to_string(migrations.join(file)).unwrap()).unwrap(); + } + direct.execute_batch("PRAGMA user_version = 6; COMMIT;").unwrap(); + drop(direct); + assert_eq!(maintenance_support::stored_versions(&path), ("2.1.2".to_string(), 6)); + let revision = maintenance_support::database_revision(&path); + let has_table = |name: &str| -> bool { + inspect(&path) + .query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", [name], |row| { + row.get::<_, i64>(0) + }) + .unwrap() + == 1 + }; + assert!(INTERNAL_TABLES.iter().all(|table| !has_table(table))); + + let mut store = Store::open(&path, OpenOptions { read_only: false, allow_outdated_schema: true }).unwrap(); + let result = execute_confirmed_migration(&mut store, &MigrationOptions::default()).unwrap(); + assert!(result.migrated); + let steps: Vec = result.preview.planned_steps.iter().map(|step| step.target_sql_schema_version).collect(); + assert_eq!(steps, [7]); + assert_eq!(store.metadata().sql_schema_version, 7); + assert_eq!(store.metadata().athleticstandard_version, "2.1.3"); + let report = check_database(&store).unwrap(); + assert!(report.valid && report.issues.is_empty(), "{:?}", report.issues); + let published = contract::published_contract().unwrap(); + assert_eq!(contract::verify_live_schema(&store, &published).unwrap(), Vec::::new()); + drop(store); + + assert!(INTERNAL_TABLES.iter().all(|table| has_table(table))); + assert!(change_log(&path).is_empty(), "the migration logs no change"); + assert_eq!(count(&path, "internal_write_receipts"), 0); + assert_eq!(access_rows(&path), [(1, 0)]); + assert_eq!(maintenance_support::database_revision(&path), revision, "the migration changes no record"); +} + +#[test] +fn the_change_log_names_the_revision_each_write_committed() { + let directory = maintenance_support::temporary_dir("ath-record-2-1-3-log-"); + let (path, mut store) = new_store(&directory); + + let created = store + .apply(Changes { + creates: vec![note(NOTE, "Easy week."), note(OTHER_NOTE, "Rest on Sunday.")], + ..Changes::default() + }) + .unwrap() + .database_revision; + assert_eq!(created, 1); + assert_eq!(change_log(&path), [row(1, NOTE, 1, "revision"), row(1, OTHER_NOTE, 1, "revision")]); + + let corrected = + RecordData::decode(RecordType::CoachingNote, &value(note_data(coach_json(), "Easy week, then test."))).unwrap(); + let corrected = store + .apply(Changes { + corrections: vec![Correction { + record_id: NOTE.into(), + expected_revision: 1, + data: corrected, + extensions: ExtensionsUpdate::Keep, + changed_by: athlete(), + became_known_at: Some(CORRECTED.into()), + became_known_at_basis: athleticstandard::model::BecameKnownAtBasis::LocalWrite, + stale_style: StaleStyle::Revision, + }], + ..Changes::default() + }) + .unwrap() + .database_revision; + assert_eq!(corrected, 2); + + let deleted = store + .apply(Changes { + deletions: vec![Deletion { + record_id: NOTE.into(), + expected_revision: 2, + deleted_by: athlete(), + deleted_at: Some(DELETED.into()), + }], + ..Changes::default() + }) + .unwrap() + .database_revision; + assert_eq!(deleted, 3); + assert_eq!(store.database_revision().unwrap(), 3); + assert_eq!( + change_log(&path), + [ + row(1, NOTE, 1, "revision"), + row(1, OTHER_NOTE, 1, "revision"), + row(2, NOTE, 2, "revision"), + row(3, NOTE, 2, "deletion"), + ] + ); + + // An erasure leaves one value-free row, as it leaves one marker. The + // erased record's earlier rows go with its history. + let preview = preview_erasure(&store, NOTE, 2).unwrap(); + let erased = erase_record(&mut store, &preview, ErasureReasonCode::AthleteRequest, Some(ERASED)).unwrap(); + assert_eq!(erased.database_revision, 4); + assert_eq!(change_log(&path), [row(1, OTHER_NOTE, 1, "revision"), row(4, NOTE, 0, "erasure")]); + drop(store); + + // A direct writer that follows the published soft-delete recipe is + // logged under the revision its transaction commits. + let direct = maintenance_support::direct(&path); + direct + .execute_batch(&format!( + "BEGIN IMMEDIATE; + PRAGMA defer_foreign_keys = ON; + INSERT INTO record_deletions (record_id, record_revision, deleted_at, deleted_by_json) + VALUES ('{OTHER_NOTE}', 1, '{DELETED}', '{{\"author_type\":\"athlete\"}}'); + UPDATE records SET is_deleted = 1 WHERE record_id = '{OTHER_NOTE}'; + UPDATE database_state SET current_revision = current_revision + 1 WHERE singleton_id = 1; + COMMIT;" + )) + .unwrap(); + drop(direct); + assert_eq!(maintenance_support::database_revision(&path), 5); + assert_eq!( + change_log(&path), + [row(1, OTHER_NOTE, 1, "revision"), row(4, NOTE, 0, "erasure"), row(5, OTHER_NOTE, 1, "deletion")] + ); + + // The log holds IDs and numbers only. + let connection = inspect(&path); + let columns: Vec = connection + .prepare("SELECT name FROM pragma_table_info('internal_change_log') ORDER BY cid") + .unwrap() + .query_map([], |row| row.get(0)) + .unwrap() + .map(Result::unwrap) + .collect(); + assert_eq!(columns, ["database_revision", "record_id", "record_revision", "change_kind"]); + drop(connection); + fs::remove_dir_all(directory).unwrap(); +} diff --git a/tests/record_lifecycle.rs b/tests/record_lifecycle.rs index 445ba393..8f59f699 100644 --- a/tests/record_lifecycle.rs +++ b/tests/record_lifecycle.rs @@ -387,7 +387,9 @@ fn stored_rows(path: &Path) -> BTreeMap> { let connection = inspect(path); let mut out = BTreeMap::new(); for table in table_names(&connection) { - if table == "database_metadata" || table == "database_state" { + // The change log records how each copy was written, as the database + // revision does; a restore starts a new one. + if table == "database_metadata" || table == "database_state" || table == "internal_change_log" { continue; } let mut statement = connection.prepare(&format!("SELECT * FROM {table}")).unwrap(); @@ -410,6 +412,8 @@ fn stored_rows(path: &Path) -> BTreeMap> { } /// Tables, other than the erasure markers, with a text cell that names `id`. +/// The change log's erasure row is value-free like the marker, so only its +/// other rows count. fn tables_naming(path: &Path, id: &str) -> Vec { let connection = inspect(path); let mut found = Vec::new(); @@ -417,7 +421,12 @@ fn tables_naming(path: &Path, id: &str) -> Vec { if table == "record_erasure_markers" { continue; } - let mut statement = connection.prepare(&format!("SELECT * FROM {table}")).unwrap(); + let query = if table == "internal_change_log" { + "SELECT * FROM internal_change_log WHERE change_kind <> 'erasure'".to_string() + } else { + format!("SELECT * FROM {table}") + }; + let mut statement = connection.prepare(&query).unwrap(); let columns = statement.column_count(); let mut rows = statement.query([]).unwrap(); while let Some(row) = rows.next().unwrap() { diff --git a/tests/skill_install.rs b/tests/skill_install.rs index fb05222a..28d5cbdc 100644 --- a/tests/skill_install.rs +++ b/tests/skill_install.rs @@ -107,10 +107,11 @@ fn coaching_skills_are_installed_only_when_named() { // An older installed coaching skill is refreshed by a default install. let file = installed(dir.path(), "hyrox"); - let older = fs::read_to_string(&file).unwrap().replace("version: \"2.1.2\"", "version: \"2.1.1\""); + let current = format!("version: \"{}\"", athleticstandard::model::package::ATHLETIC_STANDARD_VERSION); + let older = fs::read_to_string(&file).unwrap().replace(¤t, "version: \"2.1.1\""); fs::write(&file, older).unwrap(); install_skill(dir.path()).unwrap(); - assert!(fs::read_to_string(&file).unwrap().contains("version: \"2.1.2\"")); + assert!(fs::read_to_string(&file).unwrap().contains(¤t)); assert!(!installed(dir.path(), "crossfit").exists(), "still not installed by default"); } diff --git a/tools/public-data-allowlist.json b/tools/public-data-allowlist.json index d14e19b6..8ab4d69e 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": "83d1094e734ba4e67ef4a7c8ab4e07b83c593cd6695823a7c759dd27391eae2e" + "sha256": "e73071197c4757a1254c56392b46d1025d3c7fb56b248cbaada74b0e6fbc2c7f" }, { "path": "examples/demo-athlete/attachments/01890f3e-e7d3-7cc0-88c8-00000000000e.png", From f3343386e78cffd536916151c93743c8fe9e192d Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 23 Nov 2026 17:34:11 -0600 Subject: [PATCH 03/26] Record D268: a remote write runs on a local working copy. The libSQL backend runs each operation on a local working copy with the library unchanged, records the changed rows with the SQLite session extension, and commits them to the server in one guarded transaction. This keeps one code path for the record rules and avoids a network round trip for every statement. Step 2 is marked done. Co-Authored-By: Claude Opus 5.5 --- build-history/v2.1.3/decisions.md | 57 ++++++++++++++++++++++++++ build-history/v2.1.3/progress.md | 21 ++++++++-- build-history/v2.1.3/spec.md | 68 +++++++++++++++++++------------ 3 files changed, 117 insertions(+), 29 deletions(-) diff --git a/build-history/v2.1.3/decisions.md b/build-history/v2.1.3/decisions.md index 417f08ec..11ce7369 100644 --- a/build-history/v2.1.3/decisions.md +++ b/build-history/v2.1.3/decisions.md @@ -370,3 +370,60 @@ Rejected alternatives: the copy would be lost or duplicated. - Let the destination activate after a timeout. Rejected because a timer cannot prove the source stopped. + +## D268. A remote write runs on a local working copy and commits as one changeset + +The libSQL backend does not send the library's SQL statements to the server one at a +time. The host keeps a working copy of each active athlete's database on local +temporary disk. The library runs every operation against that copy, unchanged. +SQLite's session extension records the rows a write changed. The host then commits +those row changes to the remote database in one transaction. The transaction first +checks that the remote database revision and access epoch still equal the values the +working copy started from. If either has moved, the host refreshes the copy and runs +the request again. The receipt makes the second run safe (D261). + +The host sends rows in a fixed order: deletions with children first, then insertions +with parents first, then updates, with the database revision raised last. That is the +order the store itself writes in. Foreign keys are deferred to commit. All 43 tables +have primary keys, which the session extension requires. Every trigger before 2.1.3 +only checks rows and never writes them. The 2.1.3 change-log triggers compute the same +rows on the server as on the working copy, so the server builds its own change log. + +A working copy is a cache. The host builds it by copying every table from the server, +keeps it current from `internal_replication_log`, a log of committed changesets kept in +the remote database, and may delete it at any time. Host copies keep no durable state. +An erasure deletes the replication log in the same transaction, because the log holds +earlier row values, and every working copy older than the erasure is rebuilt. Idle +working copies are deleted after a set time and when the host starts. + +This supersedes the part of D257 that routes the store's SQL calls through one +interface with two backends. The native backend is the library's own store. D257's +choice of the libSQL protocol and its rejected alternatives stand. Spec sections 5.1, +5.2 and 6.1 describe the result. + +The reasons come from the build: + +- The library calls SQLite in about 340 places, including streamed reads during + export. Routing each one through a network interface changes all of them, and every + statement becomes a network round trip. An import of the 100,000-record workload + would need hundreds of thousands of round trips. +- The record rules run in one place, unchanged. Experiments 3 and 5 showed that rows + written by the library and sent to a SQLite-compatible engine export byte for byte + like the original ([experiments](appendix/hosting-experiments.md)). +- The server checks every row again: its STRICT types, triggers and foreign keys run + on each replayed row. +- Reads are local, so calculations and views also work in remote mode. + +Rejected alternatives: + +- Route every SQL call through an interface, as D257 first said. Rejected for the + reasons above. +- Replay the SQL text recorded by a statement trace. Rejected because functions such as + the current time give different results on replay, and trigger statements appear in + the trace. +- Use libSQL embedded replicas for the working copy. Rejected as the only mechanism + because writes would still need a second path, and it ties the backend to one + replication protocol. The changeset works with any SQLite-compatible server. +- Rebuild a stale working copy from scratch every time. Rejected as the only path + because several host copies serving one athlete would each copy the whole database + after every write by another copy. It remains the fallback when the log has a gap. diff --git a/build-history/v2.1.3/progress.md b/build-history/v2.1.3/progress.md index c5d1f7c9..8278471c 100644 --- a/build-history/v2.1.3/progress.md +++ b/build-history/v2.1.3/progress.md @@ -1,13 +1,13 @@ # v2.1.3 progress -Status: **planned; not built**. The plan is [spec.md](spec.md). +Status: **in progress; not released**. The plan is [spec.md](spec.md). | Step | What | Status | |---|---|---| | 1 | Plan, decisions D254–D267, storage study, hosting experiments | done | -| 2 | Version 2.1.3, migration 007, coach authorship | not started | -| 3 | Storage interface with the native backend behind it | not started | -| 4 | libSQL remote backend and the qualification suite | not started | +| 2 | Version 2.1.3, migration 007, coach authorship | done | +| 3 | Changeset capture in the library (D268) | not started | +| 4 | libSQL remote backend: working copies, guarded commits, replication log, qualification suite | not started | | 5 | `ath-host` native directory mode: connect, read, write, attachments, refresh, restore | not started | | 6 | Sign-in and grants | not started | | 7 | Remote mode with object storage and several host copies | not started | @@ -18,3 +18,16 @@ Status: **planned; not built**. The plan is [spec.md](spec.md). The experiments in step 1 ran on 2.1.2 with synthetic data on one machine ([hosting-experiments.md](appendix/hosting-experiments.md)). No live provider, region, or network latency has been measured yet. Steps 4 and 7 do that. + +Step 2 notes: + +- An erasure removes that record's earlier rows from `internal_change_log` and leaves one + `erasure` row with no values, so the log never outlives an erasure. +- The change-log triggers are listed under a new `internal_triggers` key in + `spec/sql/contract.json`, because they enforce nothing. +- Records carry no version, so the 2.1.3 gate on coach authors runs on the package + document, in Rust and in Zod. +- A 2.1.2 program refuses a step-7 database by its version check ("Unsupported Athletic + Standard database version: 2.1.3"). This was checked by hand with a 2.1.2 build. + +D268 changes how the libSQL backend writes. Steps 3 and 4 follow it. diff --git a/build-history/v2.1.3/spec.md b/build-history/v2.1.3/spec.md index 58171dbe..553c0800 100644 --- a/build-history/v2.1.3/spec.md +++ b/build-history/v2.1.3/spec.md @@ -118,30 +118,47 @@ complete package export replace the verified backup (D258). ## 5. Storage -### 5.1 The storage interface (D257) +### 5.1 Two backends (D257, D268) -The store's SQL calls go through one internal interface in `src/store/`. It covers what -the store uses today: execute, query, prepared statements, immediate write transactions, -and batches. About 340 call sites in 31 files move behind it. - -| Backend | Opens | Used by | Built into | +| Backend | Where the athlete database lives | How a write reaches it | Built into | |---|---|---|---| -| Native | A local SQLite file through bundled rusqlite. | The CLI, the npm executable, and the host's directory mode. | Every build. | -| libSQL remote | A database on a server that speaks the libSQL protocol, through the `libsql` crate. | The host only. | `ath-host` only, behind the `libsql-remote` Cargo feature. | +| Native | A local SQLite file, opened through bundled rusqlite. | The library writes it directly. | Every build. | +| libSQL remote | A database on a server that speaks the libSQL protocol. | The library writes a local working copy. The host commits the changed rows to the server in one transaction. | `ath-host` only, behind its `libsql-remote` Cargo feature. | + +The library stays synchronous and keeps one code path. It gains a way to run a write +while recording its changed rows with SQLite's session extension. That is behind the +library's `changesets` Cargo feature, which only `ath-host` turns on. The CLI gains no +network code and no dependency. + +### 5.2 The libSQL backend (D258, D268) + +**Working copies.** The host keeps a working copy of each active athlete's database on +local temporary disk. It builds the copy by copying every table from the server. It +keeps the copy current from `internal_replication_log` in the remote database. It +rebuilds the copy when the log has a gap, deletes idle copies after a set time, and +deletes all copies when it starts. + +**A write.** + +1. Bring the working copy to the server's current database revision. +2. Run the library operation on the copy while recording its changeset. +3. On the server, in one transaction: check the database revision and access epoch, + apply deletions (children first), insertions (parents first), then updates, with + the database revision raised last; append the changeset to the replication log. +4. If the check fails, discard the copy's change, refresh, and run the request again. + The receipt makes the second run safe. -The library stays synchronous. The host runs storage work on blocking worker threads -and drives the libSQL client there. The CLI gains no network code and no dependency. +An erasure deletes the replication log in the same transaction. -### 5.2 Differences on a libSQL server (D258) +**Differences from local SQLite.** -- `application_id` and `user_version` are read but never written. The metadata table is - authoritative (D93). -- `journal_mode` and `busy_timeout` are skipped. The server manages both. -- Each write is one interactive transaction on one connection. The backend refuses to - open a database where a dangling reference is not rejected. -- The SQLite online backup API is not used. Section 4.2 says what replaces it. -- Large imports send rows in batches inside one transaction. Every statement is a - network round trip. +- `application_id` and `user_version` are read but never written on the server. The + metadata table is authoritative (D93). +- `journal_mode` and `busy_timeout` are not sent. The server manages both. +- The backend refuses to open a database where a dangling reference is not rejected. +- The SQLite online backup API is not used on the server. Section 4.2 says what + replaces it before a migration. +- A large write is sent in batches inside its one transaction. ### 5.3 Attachments (D259) @@ -170,7 +187,7 @@ access check. | Athletes per host | Limited by disk size. | Limited by the provider. | | Backups | Litestream, attachment copies, scheduled package export. | Provider restore, attachment bucket copy, scheduled package export. | | Per-athlete keys | Not in 2.1.3. | Where the provider supports them. | -| Each operation | In process. | Network round trips. | +| Each operation | In process. | In process on a working copy, plus a few round trips to commit. | | Vendor needed | No. | No, if you run a libSQL server yourself. | The [study](appendix/hosted-storage-options.md) section 6 gives the questions to ask. @@ -193,9 +210,10 @@ own a set of athletes. The directory names the machine that serves each athlete, request for another machine's athlete is forwarded or redirected. Only one machine accepts writes for an athlete at a time (D267). -**Remote mode.** Host copies hold no record data. Any copy can serve any athlete. The -libSQL server orders writes to each database. Revision checks, receipts, and the access -epoch handle races between copies (D261, D262). +**Remote mode.** Host copies keep no durable record data, only working copies that can +be deleted at any time (D268). Any copy can serve any athlete. The libSQL server orders +writes to each database. The revision check, receipts, and the access epoch handle +races between copies (D261, D262). ### 6.2 Sign-in (D260) @@ -376,8 +394,8 @@ successful sign-in alone does not finish a step. |---|---|---| | 1 | This plan, D254–D267, and the storage study. | Approved. | | 2 | Version 2.1.3, migration 007, coach authorship. | A coach-authored note survives export and restore. A 2.1.2 program refuses the database. All existing tests pass. | -| 3 | The storage interface, with the native backend behind it. | Every existing test passes with no change in CLI behavior. | -| 4 | The libSQL remote backend and the qualification suite. | The suite passes against a local libSQL server in continuous integration. | +| 3 | Changeset capture in the library (D268). | A write recorded as a changeset and applied to an empty copy gives the same export, byte for byte. Every existing test passes with no change in CLI behavior. | +| 4 | The libSQL remote backend: working copies, guarded commits, the replication log, and the qualification suite. | The suite passes against a local libSQL server in continuous integration. | | 5 | `ath-host` in native directory mode: owner connect, read, write with receipts, attachments, device refresh, restore. | An owner saves a report with a photo on one device and opens both on another. | | 6 | Sign-in and grants: both recipes, three grants, access epoch, roster. | Two coaches, two apps, two athletes. A revocation during a queued write blocks it. | | 7 | Remote mode with the object store, and several host copies. | Steps 5 and 6 pass in remote mode. A named run of the suite passes against one provider. | From ff0267e091e76ca52b9f06e294532a7bab6aa49e Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 23 Nov 2026 17:46:04 -0600 Subject: [PATCH 04/26] Record a write's row changes and replay them on another copy. Store::capture runs any library operation unchanged and records, in order, every row it inserted, updated, or deleted, using temporary triggers on the writing connection. replay_statements turns that record into plain SQL that any SQLite-compatible server can run; replay and commit_replicated run it in one transaction that first checks the database revision and access epoch. build_working_copy fills a new database from another database's rows. Migration 007 gains internal_replication_log, which a host keeps in a remote database so other working copies can catch up; erasing a record empties it. The new code is behind the changesets feature (D268). Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 9 + SPEC.md | 9 +- build-history/v2.1.3/progress.md | 15 +- build-history/v2.1.3/spec.md | 9 +- examples/demo-athlete/athlete.ath.sqlite | Bin 512000 -> 520192 bytes spec/sql/contract.json | 9 +- spec/sql/migrations/007-version-2-1-3.sql | 18 + src/store/mod.rs | 2 + src/store/replica.rs | 708 ++++++++++++++++++++++ tests/replica.rs | 343 +++++++++++ tools/public-data-allowlist.json | 2 +- 11 files changed, 1114 insertions(+), 10 deletions(-) create mode 100644 src/store/replica.rs create mode 100644 tests/replica.rs diff --git a/Cargo.toml b/Cargo.toml index 5ebc3e2d..e93687e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,15 @@ ureq = "2.12" uuid = { version = "1.29", features = ["v7"] } zip = "2.2" +[[test]] +name = "replica" +required-features = ["changesets"] + +[features] +# Record the rows a write changes and replay them on another copy (D268). +# Only the host program turns this on. +changesets = [] + [profile.release] lto = "thin" codegen-units = 4 diff --git a/SPEC.md b/SPEC.md index 5281e57e..00cf812d 100644 --- a/SPEC.md +++ b/SPEC.md @@ -34,7 +34,7 @@ skills, are in [`build-history/v2.1.2/spec.md`](build-history/v2.1.2/spec.md). Version 2.1.3 adds one author variant: a human coach can author and change coaching notes, training plans, and planned sessions (sections 4.3 and 5.1). A version 2.1.2 -database upgrades with `ath migrate` to SQL schema step 7, which adds three internal +database upgrades with `ath migrate` to SQL schema step 7, which adds four internal 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). @@ -927,6 +927,7 @@ lists them under `internal_tables`, with a note for each. | `internal_change_log` | step 7 | One row for each record revision, deletion, and erasure, with the database revision that committed it | | `internal_write_receipts` | step 7 | One row for each write request a host accepted, with a keyed digest of the request and its result | | `internal_access_state` | step 7 | One row with the access epoch, which revoking a host grant raises | +| `internal_replication_log` | step 7 | In a database a host keeps on a remote server: the changeset of each committed write, so other working copies can catch up. Empty on a local file | Triggers fill `internal_change_log` in the same transaction as the change, so a direct SQL writer that follows the published recipes is included. A row names the @@ -937,6 +938,10 @@ marker does (section 4.5). A restore into an empty database starts a new log. `i A database that never connects to a host keeps an empty receipt table and an access epoch of 0. +`internal_replication_log` holds earlier row values, so a trigger deletes every row +when any record is erased. A host that finds a gap in the log rebuilds its working +copy instead of catching up. + ## 8. Portable JSON package An export directory may contain: @@ -1174,7 +1179,7 @@ and live database metadata all carry that version. A minor version only adds optional fields. A patch version adds no field. Versions 2.1.2 and 2.1.3 are recorded exceptions. Version 2.1.2 (D227) adds optional fields and the `session_effort` report type, and removes or changes nothing. Version 2.1.3 -(D254) adds one author variant and three internal tables, and removes or changes +(D254) adds one author variant and four internal tables, and removes or changes nothing. A `2.0.0` record has no `field_basis` and stays valid, and every 2.1.1 and 2.1.2 record is valid 2.1.3 data. A package with a coach author declares 2.1.3 or later. `ath migrate` moves a `2.0.0`, `2.1.0`, `2.1.1`, or `2.1.2` database to diff --git a/build-history/v2.1.3/progress.md b/build-history/v2.1.3/progress.md index 8278471c..d7cd0295 100644 --- a/build-history/v2.1.3/progress.md +++ b/build-history/v2.1.3/progress.md @@ -6,7 +6,7 @@ Status: **in progress; not released**. The plan is [spec.md](spec.md). |---|---|---| | 1 | Plan, decisions D254–D267, storage study, hosting experiments | done | | 2 | Version 2.1.3, migration 007, coach authorship | done | -| 3 | Changeset capture in the library (D268) | not started | +| 3 | Changeset capture in the library (D268) | done | | 4 | libSQL remote backend: working copies, guarded commits, replication log, qualification suite | not started | | 5 | `ath-host` native directory mode: connect, read, write, attachments, refresh, restore | not started | | 6 | Sign-in and grants | not started | @@ -31,3 +31,16 @@ Step 2 notes: Standard database version: 2.1.3"). This was checked by hand with a 2.1.2 build. D268 changes how the libSQL backend writes. Steps 3 and 4 follow it. + +Step 3 notes: + +- Changes are recorded with temporary triggers on the writing connection, not with + SQLite's session extension. The session extension needs `bindgen` and `libclang` in + every build, including the release builds for each platform. Temporary triggers need + nothing extra, keep the exact order of the writes, and roll back with the transaction. +- A changeset is JSON. No replicated column holds a binary value, so JSON carries every + value exactly. +- `tests/replica.rs` runs with `--features changesets`. Step 4 adds the host to the + workspace, which turns the feature on for the default `cargo test`. +- Migration 007 gained `internal_replication_log`, with the revision each changeset + started from, and a trigger that empties it when a record is erased. diff --git a/build-history/v2.1.3/spec.md b/build-history/v2.1.3/spec.md index 553c0800..b93a8f78 100644 --- a/build-history/v2.1.3/spec.md +++ b/build-history/v2.1.3/spec.md @@ -85,7 +85,7 @@ constraint, so no table is rebuilt. ### 4.2 Migration 007 -`007-version-2-1-3.sql` sets the metadata to 2.1.3 and SQL schema 7. It adds three +`007-version-2-1-3.sql` sets the metadata to 2.1.3 and SQL schema 7. It adds four internal tables and changes no athlete-owned row (D211): - `internal_change_log`: one row for each record revision, deletion, and erasure, with @@ -97,10 +97,13 @@ internal tables and changes no athlete-owned row (D211): revisions. It holds no request body and no health values (D261). - `internal_access_state`: one row holding the access epoch (D262). Revoking a grant raises it. +- `internal_replication_log`: in a database a host keeps on a remote server, the + changeset of each committed write, with the revision it started from (D268). An + erasure deletes every row. It stays empty on a local file. -None of the three is exported in a package. All are listed in `spec/sql/contract.json` +None of the four is exported in a package. All are listed in `spec/sql/contract.json` as internal, like `internal_pending_file_operations`. A local database that never -connects to a host uses only the change log. +connects to a host uses only the change log and the access row. On the native backend, the migration keeps the preview, verified backup, confirmation, and rollback rules (D124, D211). On the libSQL backend, a provider restore point and a diff --git a/examples/demo-athlete/athlete.ath.sqlite b/examples/demo-athlete/athlete.ath.sqlite index 350d88d864a0998d8d1f942ce51de07edc0b876f..6d90c70b042fc8423b0ffee02f1d657a9cfd2dcf 100644 GIT binary patch delta 1005 zcmZozAm8vneu6x2Jp%&7Ow_UA;O0LG5~-Y6Ai@GAjcPl&3Gdz$QHXz-2aR)}+MZ)cDC8SQOpBtfJJi z%wnLS3U;;%1`3XTE()l^HVP?;K$n0t!IWz1a49GxXC&sOrxvG{Ojo$ZtSAcSYC>f5 zb8|CGCePrP-OhKB&7YHnfq{A9bk759_SS5TENtLlX!L1hW|#K0;V!aLBORZWdHfXJ=`QZe*Koe1Xl3 zu?ifn(;F_Z^|4}$Io671-A0z_iMQCS7|S7Qff35L{lG0YKSm>3c{LQ9SBGB`0><4^ L=Ity6?0@0`nB`n_ delta 264 zcmZp8Am6Y+eu6x2Edv5XP1LdB;Nm|A63LrbATn9uL;A+o_xPqS_{qe|3KYyO+kBbd zB7w1XGf%-|et{ZspjfpKkf`DT5|z#W>)Zd=GXgOa5HkZY3lOtz|6k9>>cGs!;JTgt z0NXEqBcNJ727N}(dF+QdLs<{8C$aozwq{zz$j2AM6VDaP!_S}(R00Ey(TyzA9oyN> z7%Qghb+e02?`vo8+y3Pun?EN@vu-2P^nwm{tLeJk?Bdg-F0k=!Ki|Rb$Hf$c04*#E=>00Smae*gdg diff --git a/spec/sql/contract.json b/spec/sql/contract.json index 1d86465a..1e787a17 100644 --- a/spec/sql/contract.json +++ b/spec/sql/contract.json @@ -200,7 +200,8 @@ "internal_pending_file_operations", "internal_change_log", "internal_write_receipts", - "internal_access_state" + "internal_access_state", + "internal_replication_log" ], "internal_table_notes": { "database_metadata": "Written once at creation and by each migration step. Holds the application marker, versions, database ID, and creation time.", @@ -209,7 +210,8 @@ "internal_pending_file_operations": "Written only by the ath program, from SQL schema 5. Holds recovery state for attachment files that a SQL transaction cannot include: operation IDs, kinds, relative paths, and times. It holds no health values. It is not athlete-owned history and is never exported in a JSON package. Direct writers must not write it.", "internal_change_log": "Maintained only by the triggers listed in internal_triggers, from SQL schema 7. Holds one row for each record revision, deletion, and erasure: the database revision that committed it, the record ID, the record revision (0 for an erasure), and the kind of change. It holds no health values and has no foreign keys. An erasure removes the record's earlier rows and leaves one erasure row, which names no revision. A restore into an empty database starts a new log. It is not athlete-owned history and is never exported in a JSON package. Direct writers must not write it; the triggers record their changes.", "internal_write_receipts": "Written only by a host through the Athletic Standard library, from SQL schema 7. Holds one row for each accepted host write request: the signed-in person, the app, the request ID, the operation, a keyed digest of the request, the resulting IDs and revisions, the database revision, and the time. It holds no request body and no health values. It is never exported in a JSON package. Direct writers must not write it.", - "internal_access_state": "Written by migration step 7 and by a host through the Athletic Standard library. Holds one row with the access epoch, which revoking a grant raises. It is 0 in a database that never connected to a host. It is never exported in a JSON package. Direct writers must not write it." + "internal_access_state": "Written by migration step 7 and by a host through the Athletic Standard library. Holds one row with the access epoch, which revoking a grant raises. It is 0 in a database that never connected to a host. It is never exported in a JSON package. Direct writers must not write it.", + "internal_replication_log": "Written only by a host through the Athletic Standard library, from SQL schema 7, in a database the host keeps on a remote libSQL server. Holds one row for each committed write: the database revision it committed, the revision it started from, the changeset of the rows the write changed (JSON, in the order the write made them), and the time. A host uses it to bring another working copy up to date (D268). It holds earlier row values, so the trigger internal_replication_log_erasure deletes every row when a record is erased. On a local file it stays empty. It is never exported in a JSON package. Direct writers must not write it." }, "collection_replacement": { "description": "On every create or correction, ordered child collections and link tables are replaced from the full payload. Delete existing child rows for the parent record_id, then insert the payload order. Omitted children are removed. An empty collection deletes all prior child rows.", @@ -329,6 +331,7 @@ "internal_triggers": [ "internal_change_log_revision_insert", "internal_change_log_deletion_insert", - "internal_change_log_erasure_insert" + "internal_change_log_erasure_insert", + "internal_replication_log_erasure" ] } diff --git a/spec/sql/migrations/007-version-2-1-3.sql b/spec/sql/migrations/007-version-2-1-3.sql index 63070d52..c65bc4ad 100644 --- a/spec/sql/migrations/007-version-2-1-3.sql +++ b/spec/sql/migrations/007-version-2-1-3.sql @@ -78,6 +78,24 @@ BEGIN ); END; +-- internal_replication_log is used only in a database that a host keeps on a +-- remote libSQL server (D268). Each row is the changeset of one committed +-- write: the row changes it made, in order, as JSON, so another host copy can bring its working copy up to date. +-- It holds earlier row values, so an erasure deletes the whole log in the same +-- transaction. On a local file it stays empty. +CREATE TABLE internal_replication_log ( + database_revision INTEGER PRIMARY KEY CHECK (database_revision >= 1), + base_revision INTEGER NOT NULL CHECK (base_revision >= 0 AND base_revision < database_revision), + changeset TEXT NOT NULL CHECK (json_valid(changeset)), + committed_at TEXT NOT NULL +) STRICT; + +CREATE TRIGGER internal_replication_log_erasure +AFTER INSERT ON record_erasure_markers +BEGIN + DELETE FROM internal_replication_log; +END; + CREATE TABLE internal_write_receipts ( principal_id TEXT NOT NULL, client_id TEXT NOT NULL, diff --git a/src/store/mod.rs b/src/store/mod.rs index da370a79..fc717d99 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -15,6 +15,8 @@ pub mod pending; pub mod query; pub mod read; pub mod repair; +#[cfg(feature = "changesets")] +pub mod replica; pub mod stats; pub mod write; diff --git a/src/store/replica.rs b/src/store/replica.rs new file mode 100644 index 00000000..fd4300a5 --- /dev/null +++ b/src/store/replica.rs @@ -0,0 +1,708 @@ +//! Recording the rows a write changes and replaying them on another copy of the +//! same database (D268). +//! +//! A host that keeps an athlete's database on a remote libSQL server runs every +//! library operation on a local working copy. [`Store::capture`] records, in order, +//! every row the operation inserted, updated, or deleted. It does this with +//! temporary triggers that live only on this connection and only while the +//! operation runs, so the operation itself is unchanged. A change rolled back inside +//! the operation is rolled back from the record too, because the record is a +//! temporary table in the same transaction. +//! +//! [`Store::replay_statements`] turns the record into ordinary SQL statements that +//! any SQLite-compatible server can run in the same order. [`Store::replay`] runs +//! them on a local database, guarded the way a server transaction is guarded, so a +//! working copy can catch up and tests can stand in for a server. +//! +//! Tables in [`NOT_REPLAYED`] are never recorded: the receiving database's own +//! triggers rebuild the change log, and the other two describe one copy only. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use rusqlite::types::{ToSqlOutput, ValueRef}; +use rusqlite::{Connection, ToSql}; +use serde_json::Value; + +use super::{CreateOptions, Store}; +use crate::error::{Error, Result}; + +/// Tables a capture never records and a replay never sends. +pub const NOT_REPLAYED: &[&str] = + &["internal_change_log", "internal_pending_file_operations", "internal_replication_log"]; + +/// Tables a working copy never copies from the server. +pub const NOT_COPIED: &[&str] = &["internal_pending_file_operations", "internal_replication_log"]; + +/// One SQLite value. +#[derive(Debug, Clone, PartialEq)] +pub enum SqlValue { + Null, + Integer(i64), + Real(f64), + Text(String), +} + +impl SqlValue { + fn from_ref(value: ValueRef<'_>) -> rusqlite::Result { + Ok(match value { + ValueRef::Null => SqlValue::Null, + ValueRef::Integer(number) => SqlValue::Integer(number), + ValueRef::Real(number) => SqlValue::Real(number), + ValueRef::Text(bytes) => SqlValue::Text(std::str::from_utf8(bytes)?.to_string()), + ValueRef::Blob(_) => { + return Err(rusqlite::Error::InvalidColumnType(0, "a binary value".into(), rusqlite::types::Type::Blob)) + } + }) + } + + fn from_json(value: &Value) -> Result { + Ok(match value { + Value::Null => SqlValue::Null, + Value::String(text) => SqlValue::Text(text.clone()), + Value::Number(number) => match number.as_i64() { + Some(integer) if !number.to_string().contains(['.', 'e', 'E']) => SqlValue::Integer(integer), + _ => SqlValue::Real( + number.as_f64().ok_or_else(|| Error::other("A changeset holds an unreadable number"))?, + ), + }, + _ => return Err(Error::other("A changeset holds a value that is not a SQLite value")), + }) + } + + fn to_json(&self) -> Value { + match self { + SqlValue::Null => Value::Null, + SqlValue::Integer(number) => Value::from(*number), + SqlValue::Real(number) => serde_json::Number::from_f64(*number).map(Value::Number).unwrap_or(Value::Null), + SqlValue::Text(text) => Value::String(text.clone()), + } + } +} + +impl ToSql for SqlValue { + fn to_sql(&self) -> rusqlite::Result> { + Ok(match self { + SqlValue::Null => ToSqlOutput::Borrowed(ValueRef::Null), + SqlValue::Integer(number) => ToSqlOutput::Borrowed(ValueRef::Integer(*number)), + SqlValue::Real(number) => ToSqlOutput::Borrowed(ValueRef::Real(*number)), + SqlValue::Text(text) => ToSqlOutput::Borrowed(ValueRef::Text(text.as_bytes())), + }) + } +} + +/// What a recorded change did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChangeKind { + Insert, + Update, + Delete, +} + +impl ChangeKind { + fn name(self) -> &'static str { + match self { + ChangeKind::Insert => "insert", + ChangeKind::Update => "update", + ChangeKind::Delete => "delete", + } + } + + fn parse(name: &str) -> Result { + match name { + "insert" => Ok(ChangeKind::Insert), + "update" => Ok(ChangeKind::Update), + "delete" => Ok(ChangeKind::Delete), + _ => Err(Error::other(format!("A changeset holds an unknown kind of change: {name}"))), + } + } +} + +/// One row change. `key` holds the old primary-key values for an update or a +/// deletion. `row` holds every column's new value for an insertion or an update. +#[derive(Debug, Clone, PartialEq)] +pub struct Change { + pub table: String, + pub kind: ChangeKind, + pub key: Vec, + pub row: Vec, +} + +/// The row changes one or more committed writes made, in the order they made them. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Changeset(pub Vec); + +impl Changeset { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The changeset as JSON text, as `internal_replication_log` stores it. + pub fn to_json(&self) -> String { + Value::Array( + self.0 + .iter() + .map(|change| { + serde_json::json!([ + change.table, + change.kind.name(), + change.key.iter().map(SqlValue::to_json).collect::>(), + change.row.iter().map(SqlValue::to_json).collect::>(), + ]) + }) + .collect(), + ) + .to_string() + } + + /// Read JSON text written by [`Changeset::to_json`]. + pub fn from_json(text: &str) -> Result { + let value: Value = + serde_json::from_str(text).map_err(|error| Error::other(format!("A changeset is not JSON: {error}")))?; + let entries = value.as_array().ok_or_else(|| Error::other("A changeset must be a JSON array"))?; + let mut changes = Vec::with_capacity(entries.len()); + for entry in entries { + let parts = entry + .as_array() + .filter(|parts| parts.len() == 4) + .ok_or_else(|| Error::other("A change must have four parts"))?; + let table = parts[0].as_str().ok_or_else(|| Error::other("A change must name its table"))?.to_string(); + let kind = ChangeKind::parse(parts[1].as_str().unwrap_or_default())?; + let values = |part: &Value| -> Result> { + part.as_array() + .ok_or_else(|| Error::other("A change's values must be an array"))? + .iter() + .map(SqlValue::from_json) + .collect() + }; + changes.push(Change { table, kind, key: values(&parts[2])?, row: values(&parts[3])? }); + } + Ok(Changeset(changes)) + } +} + +/// One SQL statement with positional parameters. +/// +/// An insertion or an update must change exactly one row. A deletion may change +/// none, because deleting a parent row earlier can already have removed it. +#[derive(Debug, Clone, PartialEq)] +pub struct ReplayStatement { + pub kind: ChangeKind, + pub table: String, + pub sql: String, + pub params: Vec, +} + +impl ReplayStatement { + /// Whether `changed_rows` is the result this statement must have. + pub fn accepts(&self, changed_rows: u64) -> bool { + match self.kind { + ChangeKind::Delete => changed_rows <= 1, + ChangeKind::Insert | ChangeKind::Update => changed_rows == 1, + } + } +} + +/// The value an operation returned, the rows it changed, and the state it started +/// from. A server commits the changeset only while its database revision is +/// `base_revision` and its access epoch is `access_epoch`. +#[derive(Debug, Clone)] +pub struct Captured { + pub value: T, + pub changeset: Changeset, + pub base_revision: u64, + pub new_revision: u64, + pub access_epoch: u64, +} + +/// A table's columns in declared order and its primary-key columns. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TableShape { + pub name: String, + pub columns: Vec, + pub primary_key: Vec, +} + +/// Every row of one table, with columns in declared order. +#[derive(Debug, Clone, PartialEq)] +pub struct TableRows { + pub table: String, + pub columns: Vec, + pub rows: Vec>, +} + +const CAPTURE_TABLE: &str = "temp.ath_captured_changes"; + +impl Store { + /// The access epoch. Revoking a grant raises it (D262). + pub fn access_epoch(&self) -> Result { + access_epoch(&self.connection) + } + + /// Raise the access epoch in its own write transaction and return the new value. + pub fn raise_access_epoch(&mut self) -> Result { + self.transaction(|tx| { + let changed = tx.execute( + "UPDATE internal_access_state SET access_epoch = access_epoch + 1 WHERE singleton_id = 1", + [], + )?; + if changed != 1 { + return Err(Error::other("The access state row is missing")); + } + access_epoch(tx) + }) + } + + /// Run `operation` and record, in order, every row it changed. + /// + /// The operation runs unchanged, with the same transactions and checks it has + /// without recording. If it fails, nothing is returned. + pub fn capture(&mut self, operation: impl FnOnce(&mut Store) -> Result) -> Result> { + if self.read_only { + return Err(Error::refused("This database was opened read-only")); + } + if !self.connection.is_autocommit() { + return Err(Error::other("A recorded operation must start outside a transaction")); + } + let base_revision = self.database_revision()?; + let access_epoch = self.access_epoch()?; + let shapes = self.table_shapes()?; + self.connection.execute_batch(&capture_triggers(&shapes))?; + let outcome = operation(self); + let recorded = read_capture(&self.connection, &shapes); + let removed = self.connection.execute_batch(&remove_capture_triggers(&shapes)); + let value = outcome?; + let changeset = recorded?; + removed?; + Ok(Captured { value, changeset, base_revision, new_revision: self.database_revision()?, access_epoch }) + } + + /// The tables of this database, each after every table it references through + /// a foreign key that is checked immediately. + pub fn table_shapes(&self) -> Result> { + table_shapes(&self.connection) + } + + /// Turn a changeset into SQL statements, in the order the changes were made. + pub fn replay_statements(&self, changeset: &Changeset) -> Result> { + let shapes: BTreeMap = + self.table_shapes()?.into_iter().map(|shape| (shape.name.clone(), shape)).collect(); + let mut statements = Vec::with_capacity(changeset.0.len()); + for change in &changeset.0 { + if NOT_REPLAYED.contains(&change.table.as_str()) { + continue; + } + let shape = shapes + .get(&change.table) + .ok_or_else(|| Error::other(format!("A changeset names an unknown table: {}", change.table)))?; + let width = shape.columns.len(); + let key_width = shape.primary_key.len(); + let fits = match change.kind { + ChangeKind::Insert => change.row.len() == width && change.key.is_empty(), + ChangeKind::Update => change.row.len() == width && change.key.len() == key_width, + ChangeKind::Delete => change.row.is_empty() && change.key.len() == key_width, + }; + if !fits { + return Err(Error::other(format!("A changeset does not match the columns of {}", change.table))); + } + let table = quote(&shape.name); + let (sql, params) = match change.kind { + ChangeKind::Insert => { + let names = shape.columns.iter().map(|name| quote(name)).collect::>().join(", "); + let marks = (1..=width).map(|n| format!("?{n}")).collect::>().join(", "); + (format!("INSERT INTO {table} ({names}) VALUES ({marks})"), change.row.clone()) + } + ChangeKind::Update => { + let set = shape + .columns + .iter() + .enumerate() + .map(|(index, name)| format!("{} = ?{}", quote(name), index + 1)) + .collect::>() + .join(", "); + let condition = key_condition(shape, width + 1); + let mut params = change.row.clone(); + params.extend(change.key.iter().cloned()); + (format!("UPDATE {table} SET {set} WHERE {condition}"), params) + } + ChangeKind::Delete => { + (format!("DELETE FROM {table} WHERE {}", key_condition(shape, 1)), change.key.clone()) + } + }; + statements.push(ReplayStatement { kind: change.kind, table: shape.name.clone(), sql, params }); + } + Ok(statements) + } + + /// Apply a changeset recorded on another copy, the way a server applies it: in one + /// immediate transaction that first checks the database revision and access epoch. + pub fn replay(&mut self, base_revision: u64, access_epoch: u64, changeset: &Changeset) -> Result<()> { + let statements = self.replay_statements(changeset)?; + self.transaction(|tx| { + let revision = super::database_revision(tx)?; + let epoch = self::access_epoch(tx)?; + if revision != base_revision || epoch != access_epoch { + return Err(Error::stale(format!( + "The database moved on: revision {revision} and access epoch {epoch}, expected {base_revision} and {access_epoch}" + ))); + } + run_statements(tx, &statements) + }) + } + + /// Commit a changeset the way a server does, and keep it in + /// `internal_replication_log` so other working copies can catch up (D268). + /// + /// The log row is written before the changes, so an erasure in the changeset + /// deletes it with the rest of the log. The transaction fails unless the database + /// ends at `new_revision`. + pub fn commit_replicated( + &mut self, + base_revision: u64, + new_revision: u64, + access_epoch: u64, + changeset: &Changeset, + committed_at: &str, + ) -> Result<()> { + let statements = self.replay_statements(changeset)?; + let text = changeset.to_json(); + self.transaction(|tx| { + let revision = super::database_revision(tx)?; + let epoch = self::access_epoch(tx)?; + if revision != base_revision || epoch != access_epoch { + return Err(Error::stale(format!( + "The database moved on: revision {revision} and access epoch {epoch}, expected {base_revision} and {access_epoch}" + ))); + } + tx.execute( + "INSERT INTO internal_replication_log (database_revision, base_revision, changeset, committed_at) + VALUES (?1, ?2, ?3, ?4)", + rusqlite::params![new_revision as i64, base_revision as i64, text, committed_at], + )?; + run_statements(tx, &statements)?; + let ended = super::database_revision(tx)?; + if ended != new_revision { + return Err(Error::other(format!("The changeset ended at revision {ended}, not {new_revision}"))); + } + Ok(()) + }) + } + + /// The logged changesets that bring a copy at `revision` up to date, in order, + /// as (base revision, new revision, changeset). `None` means the log has a gap, + /// so the copy must be rebuilt. + pub fn replication_log_after(&self, revision: u64) -> Result>> { + let current = self.database_revision()?; + let mut statement = self.connection.prepare( + "SELECT base_revision, database_revision, changeset FROM internal_replication_log + WHERE database_revision > ?1 ORDER BY database_revision", + )?; + let rows: Vec<(i64, i64, String)> = statement + .query_map([revision as i64], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))? + .collect::>()?; + let mut at = revision; + let mut entries = Vec::with_capacity(rows.len()); + for (base, new, text) in rows { + if base as u64 != at { + return Ok(None); + } + entries.push((base as u64, new as u64, Changeset::from_json(&text)?)); + at = new as u64; + } + Ok((at == current).then_some(entries)) + } + + /// Every row of `table`, in primary-key order. + pub fn table_rows(&self, table: &str) -> Result { + let shape = self + .table_shapes()? + .into_iter() + .find(|shape| shape.name == table) + .ok_or_else(|| Error::not_found(format!("No table named {table}")))?; + read_rows(&self.connection, &shape) + } + + /// Build a working copy at `path` from every row of a database (D268). + /// + /// The copy is created with the current schema, emptied, and filled in one + /// transaction, parents before children. `database_metadata` comes from the + /// rows, so the copy has the source's database ID. The change log is written + /// last, from the rows, so the triggers add no entries of their own. + pub fn build_working_copy(path: impl AsRef, tables: &[TableRows]) -> Result { + let mut store = Store::create(path, CreateOptions::default())?; + let shapes = store.table_shapes()?; + let given: BTreeMap<&str, &TableRows> = tables.iter().map(|rows| (rows.table.as_str(), rows)).collect(); + for name in given.keys() { + if !shapes.iter().any(|shape| shape.name == *name) { + return Err(Error::other(format!("A working copy was given rows for an unknown table: {name}"))); + } + } + store.transaction(|tx| { + for shape in shapes.iter().rev() { + tx.execute(&format!("DELETE FROM {}", quote(&shape.name)), [])?; + } + let ordered = shapes + .iter() + .filter(|shape| shape.name != "internal_change_log") + .chain(shapes.iter().filter(|shape| shape.name == "internal_change_log")); + for shape in ordered { + if NOT_COPIED.contains(&shape.name.as_str()) { + continue; + } + if shape.name == "internal_change_log" { + tx.execute("DELETE FROM internal_change_log", [])?; + } + let Some(rows) = given.get(shape.name.as_str()) else { + continue; + }; + if rows.columns != shape.columns { + return Err(Error::other(format!("The columns given for {} do not match", shape.name))); + } + let names = shape.columns.iter().map(|name| quote(name)).collect::>().join(", "); + let marks = (1..=shape.columns.len()).map(|n| format!("?{n}")).collect::>().join(", "); + let mut insert = + tx.prepare(&format!("INSERT INTO {} ({names}) VALUES ({marks})", quote(&shape.name)))?; + for row in &rows.rows { + if row.len() != shape.columns.len() { + return Err(Error::other(format!("A row for {} has the wrong number of values", shape.name))); + } + insert.execute(rusqlite::params_from_iter(row.iter()))?; + } + } + Ok(()) + })?; + store.reload_metadata()?; + Ok(store) + } +} + +fn run_statements(connection: &Connection, statements: &[ReplayStatement]) -> Result<()> { + for statement in statements { + let changed = connection.execute(&statement.sql, rusqlite::params_from_iter(statement.params.iter()))? as u64; + if !statement.accepts(changed) { + return Err(Error::stale(format!( + "A replayed change to {} changed {changed} rows: {}", + statement.table, statement.sql + ))); + } + } + Ok(()) +} + +fn access_epoch(connection: &Connection) -> Result { + let epoch: i64 = + connection + .query_row("SELECT access_epoch FROM internal_access_state WHERE singleton_id = 1", [], |row| row.get(0))?; + Ok(epoch as u64) +} + +fn quote(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn trigger_name(table: &str, kind: ChangeKind) -> String { + quote(&format!("ath_capture_{table}_{}", kind.name())) +} + +fn captured_tables(shapes: &[TableShape]) -> impl Iterator { + shapes.iter().filter(|shape| !NOT_REPLAYED.contains(&shape.name.as_str())) +} + +fn capture_triggers(shapes: &[TableShape]) -> String { + let mut sql = format!( + "CREATE TEMP TABLE IF NOT EXISTS {CAPTURE_TABLE} ( + position INTEGER PRIMARY KEY, + table_name TEXT NOT NULL, + change_kind TEXT NOT NULL, + old_key TEXT NOT NULL, + new_row TEXT NOT NULL + ); + DELETE FROM {CAPTURE_TABLE};\n" + ); + for shape in captured_tables(shapes) { + let table = quote(&shape.name); + let name_literal = shape.name.replace('\'', "''"); + let row = |prefix: &str| { + format!( + "json_array({})", + shape.columns.iter().map(|c| format!("{prefix}.{}", quote(c))).collect::>().join(", ") + ) + }; + let key = format!( + "json_array({})", + shape.primary_key.iter().map(|c| format!("OLD.{}", quote(c))).collect::>().join(", ") + ); + for (kind, old_key, new_row) in [ + (ChangeKind::Insert, "'[]'".to_string(), row("NEW")), + (ChangeKind::Update, key.clone(), row("NEW")), + (ChangeKind::Delete, key.clone(), "'[]'".to_string()), + ] { + let event = match kind { + ChangeKind::Insert => "INSERT", + ChangeKind::Update => "UPDATE", + ChangeKind::Delete => "DELETE", + }; + sql.push_str(&format!( + "CREATE TEMP TRIGGER {} AFTER {event} ON main.{table} BEGIN + INSERT INTO {CAPTURE_TABLE} (table_name, change_kind, old_key, new_row) + VALUES ('{name_literal}', '{}', {old_key}, {new_row}); + END;\n", + trigger_name(&shape.name, kind), + kind.name(), + )); + } + } + sql +} + +fn remove_capture_triggers(shapes: &[TableShape]) -> String { + let mut sql = String::new(); + for shape in captured_tables(shapes) { + for kind in [ChangeKind::Insert, ChangeKind::Update, ChangeKind::Delete] { + sql.push_str(&format!("DROP TRIGGER IF EXISTS temp.{};\n", trigger_name(&shape.name, kind))); + } + } + sql.push_str(&format!("DELETE FROM {CAPTURE_TABLE};\n")); + sql +} + +fn read_capture(connection: &Connection, shapes: &[TableShape]) -> Result { + let known: BTreeSet<&str> = shapes.iter().map(|shape| shape.name.as_str()).collect(); + let mut statement = connection + .prepare(&format!("SELECT table_name, change_kind, old_key, new_row FROM {CAPTURE_TABLE} ORDER BY position"))?; + let rows: Vec<(String, String, String, String)> = statement + .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)))? + .collect::>()?; + let mut changes = Vec::with_capacity(rows.len()); + for (table, kind, old_key, new_row) in rows { + if !known.contains(table.as_str()) { + return Err(Error::other(format!("A capture recorded an unknown table: {table}"))); + } + let values = |text: &str| -> Result> { + let value: Value = serde_json::from_str(text) + .map_err(|error| Error::other(format!("A captured row is not JSON: {error}")))?; + value + .as_array() + .ok_or_else(|| Error::other("A captured row is not an array"))? + .iter() + .map(SqlValue::from_json) + .collect() + }; + changes.push(Change { table, kind: ChangeKind::parse(&kind)?, key: values(&old_key)?, row: values(&new_row)? }); + } + Ok(Changeset(changes)) +} + +fn key_condition(shape: &TableShape, first_parameter: usize) -> String { + shape + .primary_key + .iter() + .enumerate() + .map(|(index, name)| format!("{} = ?{}", quote(name), first_parameter + index)) + .collect::>() + .join(" AND ") +} + +fn read_rows(connection: &Connection, shape: &TableShape) -> Result { + let names = shape.columns.iter().map(|name| quote(name)).collect::>().join(", "); + let order = shape.primary_key.iter().map(|name| quote(name)).collect::>().join(", "); + let mut statement = connection.prepare(&format!("SELECT {names} FROM {} ORDER BY {order}", quote(&shape.name)))?; + let width = shape.columns.len(); + let rows = statement + .query_map([], |row| (0..width).map(|column| SqlValue::from_ref(row.get_ref(column)?)).collect())? + .collect::>>>()?; + Ok(TableRows { table: shape.name.clone(), columns: shape.columns.clone(), rows }) +} + +/// User tables in creation order, then sorted so a table comes after every table it +/// references through a foreign key that is checked immediately. A foreign key +/// declared `DEFERRABLE INITIALLY DEFERRED` does not order tables, which breaks the +/// one cycle in the schema: `records.current_revision` refers to `record_revisions`. +fn table_shapes(connection: &Connection) -> Result> { + let mut statement = connection.prepare( + "SELECT name, sql FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY rowid", + )?; + let tables: Vec<(String, String)> = + statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?.collect::>()?; + let names: BTreeSet = tables.iter().map(|(name, _)| name.clone()).collect(); + let parents: BTreeMap> = tables + .iter() + .map(|(name, sql)| { + let found = immediate_references(sql) + .into_iter() + .filter(|parent| parent != name && names.contains(parent)) + .collect(); + (name.clone(), found) + }) + .collect(); + let mut ordered: Vec = Vec::new(); + let mut placed: BTreeSet = BTreeSet::new(); + while ordered.len() < tables.len() { + let next = tables + .iter() + .map(|(name, _)| name) + .find(|name| !placed.contains(*name) && parents[*name].iter().all(|parent| placed.contains(parent))) + .ok_or_else(|| Error::other("The schema's immediate foreign keys form a cycle"))? + .clone(); + placed.insert(next.clone()); + ordered.push(next); + } + let mut shapes = Vec::new(); + for name in ordered { + let mut info = connection.prepare(&format!("PRAGMA table_info({})", quote(&name)))?; + let mut columns: Vec<(String, i64)> = info + .query_map([], |row| Ok((row.get::<_, String>(1)?, row.get::<_, i64>(5)?)))? + .collect::>()?; + let all: Vec = columns.iter().map(|(column, _)| column.clone()).collect(); + columns.retain(|(_, key)| *key > 0); + columns.sort_by_key(|(_, key)| *key); + if columns.is_empty() { + return Err(Error::other(format!("{name} has no primary key, so its rows cannot be replayed"))); + } + shapes.push(TableShape { + name, + columns: all, + primary_key: columns.into_iter().map(|(column, _)| column).collect(), + }); + } + Ok(shapes) +} + +/// The tables `sql` references, leaving out references declared +/// `DEFERRABLE INITIALLY DEFERRED`. +fn immediate_references(sql: &str) -> Vec { + let upper = sql.to_ascii_uppercase(); + let mut found = Vec::new(); + let mut from = 0; + while let Some(offset) = upper[from..].find("REFERENCES ") { + let start = from + offset + "REFERENCES ".len(); + let name: String = sql[start..] + .trim_start() + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '"') + .filter(|c| *c != '"') + .collect(); + let clause = &upper[start..start + clause_end(&upper[start..])]; + if !clause.contains("DEFERRABLE INITIALLY DEFERRED") { + found.push(name); + } + from = start; + } + found +} + +/// The end of a REFERENCES clause: the next comma or closing parenthesis outside +/// the referenced column list. +fn clause_end(text: &str) -> usize { + let mut depth = 0i32; + for (index, c) in text.char_indices() { + match c { + '(' => depth += 1, + ')' if depth == 0 => return index, + ')' => depth -= 1, + ',' if depth == 0 => return index, + _ => {} + } + } + text.len() +} diff --git a/tests/replica.rs b/tests/replica.rs new file mode 100644 index 00000000..14cdf285 --- /dev/null +++ b/tests/replica.rs @@ -0,0 +1,343 @@ +//! D268: a write recorded on one copy and replayed on another leaves both copies the +//! same. A working copy built from a database's rows exports like the database; every +//! kind of write replays to the same rows and the same export; a replay from an old +//! revision or an old access epoch is refused; and an erasure clears the replication log. + +// The maintenance helpers own this program's temporary folders. +mod maintenance_support; + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use athleticstandard::json::{self, Value}; +use athleticstandard::model::{BecameKnownAtBasis, ErasureReasonCode, RecordActor, RecordData, RecordType}; +use athleticstandard::package::{erase_record, export_package, preview_erasure, ExportOptions}; +use athleticstandard::store::replica::{Changeset, TableRows, NOT_COPIED}; +use athleticstandard::store::write::StaleStyle; +use athleticstandard::store::{Changes, Correction, Deletion, ExtensionsUpdate, NewRecord, OpenOptions, Store}; +use serde_json::json; + +const NOTE: &str = "01890f3e-e7d3-7cc0-88c8-0000000000d1"; +const OTHER: &str = "01890f3e-e7d3-7cc0-88c8-0000000000d2"; +const WRITTEN: &str = "2026-11-21T08:00:00.000Z"; + +/// One labelled write applied to a store. +type Step = (&'static str, Box); + +fn demo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/demo-athlete") +} + +fn copy_folder(from: &Path, to: &Path) { + fs::create_dir_all(to).unwrap(); + for entry in fs::read_dir(from).unwrap() { + let path = entry.unwrap().path(); + let target = to.join(path.file_name().unwrap()); + if path.is_dir() { + copy_folder(&path, &target); + } else { + fs::copy(&path, &target).unwrap(); + } + } +} + +/// A copy of the demo record in `directory/name`. +fn demo(directory: &Path, name: &str) -> Store { + let folder = directory.join(name); + copy_folder(&demo_root(), &folder); + Store::open(folder.join("athlete.ath.sqlite"), OpenOptions::default()).unwrap() +} + +fn all_rows(store: &Store) -> Vec { + store + .table_shapes() + .unwrap() + .into_iter() + .filter(|shape| !NOT_COPIED.contains(&shape.name.as_str())) + .map(|shape| store.table_rows(&shape.name).unwrap()) + .collect() +} + +/// A working copy of `source` in `directory/name`, with its attachment files. +fn working_copy(source: &Store, directory: &Path, name: &str) -> Store { + let folder = directory.join(name); + fs::create_dir_all(&folder).unwrap(); + let attachments = source.path().parent().unwrap().join("attachments"); + if attachments.is_dir() { + copy_folder(&attachments, &folder.join("attachments")); + } + Store::build_working_copy(folder.join("athlete.ath.sqlite"), &all_rows(source)).unwrap() +} + +fn exported(store: &Store, directory: &Path, name: &str) -> BTreeMap> { + let output = directory.join(name); + export_package(store, &output, &ExportOptions::default()).unwrap(); + let mut files = BTreeMap::new(); + for entry in fs::read_dir(&output).unwrap() { + let path = entry.unwrap().path(); + if path.is_file() { + files.insert(path.file_name().unwrap().to_string_lossy().into_owned(), fs::read(&path).unwrap()); + } + } + files +} + +fn assert_same(left: &Store, right: &Store, directory: &Path, label: &str) { + assert_eq!(left.database_revision().unwrap(), right.database_revision().unwrap(), "{label}: revision"); + assert_eq!(left.metadata().database_id, right.metadata().database_id, "{label}: database ID"); + assert_eq!(all_rows(left), all_rows(right), "{label}: rows"); + assert_eq!( + exported(left, directory, &format!("{label}-left")), + exported(right, directory, &format!("{label}-right")), + "{label}: export" + ); +} + +fn athlete() -> RecordActor { + serde_json::from_value(json!({ "author_type": "athlete" })).unwrap() +} + +fn note_data(text: &str) -> Value { + json::parse( + &json!({ + "authorship": { + "author": { "author_type": "coach", "coach": "Example Coach", "coach_id": "6f1c2e4a-3b5d-4c7e-9f80-1a2b3c4d5e6f" }, + "authored_at": WRITTEN, + "evidence": [], + "content_version": 1, + "status": "active" + }, + "title": "Deload week", + "note": text + }) + .to_string(), + ) + .unwrap() +} + +fn coach() -> RecordActor { + serde_json::from_value( + json!({ "author_type": "coach", "coach": "Example Coach", "coach_id": "6f1c2e4a-3b5d-4c7e-9f80-1a2b3c4d5e6f" }), + ) + .unwrap() +} + +fn create(record_id: &str, text: &str) -> Changes { + Changes { + creates: vec![NewRecord { + record_id: Some(record_id.into()), + created_at: Some(WRITTEN.into()), + ..NewRecord::new(RecordData::decode(RecordType::CoachingNote, ¬e_data(text)).unwrap(), coach()) + }], + ..Changes::default() + } +} + +fn correct(record_id: &str, revision: u64, text: &str) -> Changes { + Changes { + corrections: vec![Correction { + record_id: record_id.into(), + expected_revision: revision, + data: RecordData::decode(RecordType::CoachingNote, ¬e_data(text)).unwrap(), + extensions: ExtensionsUpdate::Keep, + changed_by: coach(), + became_known_at: Some(WRITTEN.into()), + became_known_at_basis: BecameKnownAtBasis::LocalWrite, + stale_style: StaleStyle::Revision, + }], + ..Changes::default() + } +} + +#[test] +fn a_working_copy_exports_like_its_source() { + let directory = maintenance_support::temporary_dir("ath-replica-copy-"); + let source = demo(&directory, "source"); + let copy = working_copy(&source, &directory, "copy"); + assert_same(&source, ©, &directory, "built"); +} + +#[test] +fn every_kind_of_write_replays_to_the_same_database() { + let directory = maintenance_support::temporary_dir("ath-replica-writes-"); + let mut source = demo(&directory, "source"); + let mut copy = working_copy(&source, &directory, "copy"); + + let steps: Vec = vec![ + ( + "create", + Box::new(|store: &mut Store| { + store.apply(create(NOTE, "Keep every session easy.")).unwrap(); + }), + ), + ( + "create two in one write", + Box::new(|store: &mut Store| { + let mut changes = create(OTHER, "Sleep eight hours."); + changes.corrections = correct(NOTE, 1, "Keep every session easy, and walk daily.").corrections; + store.apply(changes).unwrap(); + }), + ), + ( + "delete", + Box::new(|store: &mut Store| { + store + .apply(Changes { + deletions: vec![Deletion { + record_id: OTHER.into(), + expected_revision: 1, + deleted_by: athlete(), + deleted_at: Some(WRITTEN.into()), + }], + ..Changes::default() + }) + .unwrap(); + }), + ), + ( + "erase", + Box::new(|store: &mut Store| { + let preview = preview_erasure(store, NOTE, 2).unwrap(); + erase_record(store, &preview, ErasureReasonCode::AthleteRequest, Some(WRITTEN)).unwrap(); + }), + ), + ]; + for (label, step) in steps { + let captured = source.capture(|store| { + step(store); + Ok(()) + }); + let captured = captured.unwrap(); + assert!(!captured.changeset.is_empty(), "{label}: something was recorded"); + assert_eq!(captured.base_revision, copy.database_revision().unwrap()); + copy.replay(captured.base_revision, captured.access_epoch, &captured.changeset).unwrap(); + assert_same(&source, ©, &directory, label); + } +} + +#[test] +fn a_replay_from_an_old_revision_or_epoch_is_refused() { + let directory = maintenance_support::temporary_dir("ath-replica-guard-"); + let mut source = demo(&directory, "source"); + let mut copy = working_copy(&source, &directory, "copy"); + let captured = source.capture(|store| store.apply(create(NOTE, "First."))).unwrap(); + + let stale = copy.replay(captured.base_revision + 1, captured.access_epoch, &captured.changeset).unwrap_err(); + assert_eq!(stale.code(), "stale", "{stale}"); + copy.raise_access_epoch().unwrap(); + let revoked = copy.replay(captured.base_revision, captured.access_epoch, &captured.changeset).unwrap_err(); + assert_eq!(revoked.code(), "stale", "{revoked}"); + assert_eq!(copy.database_revision().unwrap(), captured.base_revision, "nothing was applied"); +} + +#[test] +fn a_failed_operation_returns_its_error_and_records_nothing_later() { + let directory = maintenance_support::temporary_dir("ath-replica-failed-"); + let mut source = demo(&directory, "source"); + source.apply(create(NOTE, "First.")).unwrap(); + let failed = source.capture(|store| store.apply(correct(NOTE, 7, "Stale."))); + assert!(failed.is_err()); + // A later capture records only its own write. + let captured = source.capture(|store| store.apply(correct(NOTE, 1, "Second."))).unwrap(); + let tables: Vec<&str> = captured.changeset.0.iter().map(|change| change.table.as_str()).collect(); + assert!(tables.contains(&"record_revisions") && tables.contains(&"database_state"), "{tables:?}"); + assert_eq!(tables.iter().filter(|table| **table == "record_revisions").count(), 1, "{tables:?}"); +} + +#[test] +fn a_changeset_survives_its_json_form() { + let directory = maintenance_support::temporary_dir("ath-replica-json-"); + let mut source = demo(&directory, "source"); + let captured = source.capture(|store| store.apply(create(NOTE, "A note with \"quotes\" and ünïcode."))).unwrap(); + let text = captured.changeset.to_json(); + assert_eq!(Changeset::from_json(&text).unwrap(), captured.changeset); +} + +#[test] +fn tables_come_after_the_tables_they_reference() { + let directory = maintenance_support::temporary_dir("ath-replica-order-"); + let source = demo(&directory, "source"); + let order: Vec = source.table_shapes().unwrap().into_iter().map(|shape| shape.name).collect(); + let position = |name: &str| order.iter().position(|table| table == name).unwrap(); + assert!(position("records") < position("record_revisions")); + assert!(position("records") < position("workout_sessions")); + assert!(position("record_revisions") < position("record_deletions")); + for shape in source.table_shapes().unwrap() { + assert!(!shape.primary_key.is_empty(), "{} has a primary key", shape.name); + } +} + +#[test] +fn a_server_keeps_a_contiguous_log_and_an_erasure_clears_it() { + let directory = maintenance_support::temporary_dir("ath-replica-log-"); + let mut working = demo(&directory, "working"); + let mut server = working_copy(&working, &directory, "server"); + let start = server.database_revision().unwrap(); + + for (record_id, text) in [(NOTE, "One."), (OTHER, "Two.")] { + let captured = working.capture(|store| store.apply(create(record_id, text))).unwrap(); + server + .commit_replicated( + captured.base_revision, + captured.new_revision, + captured.access_epoch, + &captured.changeset, + WRITTEN, + ) + .unwrap(); + } + let entries = server.replication_log_after(start).unwrap().expect("the log is contiguous"); + assert_eq!(entries.len(), 2); + + // A second working copy at the start catches up from the log. + let mut late = demo(&directory, "late"); + for (base, _, changeset) in &entries { + late.replay(*base, late.access_epoch().unwrap(), changeset).unwrap(); + } + assert_same(&server, &late, &directory, "caught up"); + + // A wrong new revision is refused and leaves the server unchanged. + let captured = working.capture(|store| store.apply(correct(NOTE, 1, "Three."))).unwrap(); + let refused = server + .commit_replicated( + captured.base_revision, + captured.new_revision + 1, + captured.access_epoch, + &captured.changeset, + WRITTEN, + ) + .unwrap_err(); + assert!(refused.to_string().contains("ended at revision"), "{refused}"); + server + .commit_replicated( + captured.base_revision, + captured.new_revision, + captured.access_epoch, + &captured.changeset, + WRITTEN, + ) + .unwrap(); + + let captured = working + .capture(|store| { + let preview = preview_erasure(store, NOTE, 2)?; + erase_record(store, &preview, ErasureReasonCode::AthleteRequest, Some(WRITTEN)).map(|_| ()) + }) + .unwrap(); + server + .commit_replicated( + captured.base_revision, + captured.new_revision, + captured.access_epoch, + &captured.changeset, + WRITTEN, + ) + .unwrap(); + assert!( + server.replication_log_after(start).unwrap().is_none(), + "the erasure cleared the log, so a copy at the start must be rebuilt" + ); + assert_eq!(server.replication_log_after(server.database_revision().unwrap()).unwrap(), Some(Vec::new())); + assert_same(&working, &server, &directory, "erased"); +} diff --git a/tools/public-data-allowlist.json b/tools/public-data-allowlist.json index 8ab4d69e..32bc9f99 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": "e73071197c4757a1254c56392b46d1025d3c7fb56b248cbaada74b0e6fbc2c7f" + "sha256": "8906d31992ad5467d54741fac5fe3f35654a9b00b439246eb4cd9517fc4264bb" }, { "path": "examples/demo-athlete/attachments/01890f3e-e7d3-7cc0-88c8-00000000000e.png", From e50a1c0ab25c1d1174077f4783063bce1605e057 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 23 Nov 2026 18:07:29 -0600 Subject: [PATCH 05/26] Keep host receipts, the access epoch, and the change log in the library. A write can carry a host request receipt, stored in the same transaction, and can require the access epoch it read before a grant check (D261, D262). Store::changes_since reads the change log and says when it no longer reaches back far enough (D263). The replay rules gain what a server needs: the change log replays with INSERT OR IGNORE so the server's own triggers and the sender agree; the access epoch stays on the server; schema_scripts builds an empty database without the two header settings a libSQL server makes read-only (D258). A capture now survives a package restore, which changes temp_store. Co-Authored-By: Claude Opus 5.5 --- src/store/hosting.rs | 176 +++++++++++++++++++++++++++++++++++++++++++ src/store/mod.rs | 1 + src/store/replica.rs | 63 +++++++++++----- src/store/write.rs | 17 ++++- tests/replica.rs | 49 +++++++++++- 5 files changed, 283 insertions(+), 23 deletions(-) create mode 100644 src/store/hosting.rs diff --git a/src/store/hosting.rs b/src/store/hosting.rs new file mode 100644 index 00000000..9e29f7ba --- /dev/null +++ b/src/store/hosting.rs @@ -0,0 +1,176 @@ +//! What a host keeps inside an athlete's database: write receipts, the access epoch, +//! and the change log (D261–D263). The tables come from migration step 7. A database +//! that never connects to a host leaves the receipts empty and the epoch at 0. + +use rusqlite::{OptionalExtension, Transaction}; + +use super::{Applied, Store}; +use crate::error::{Error, Result}; +use crate::model::time; + +/// The host request that made a change. The digest is a keyed hash of the request +/// body; the body itself is never stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WriteReceipt { + pub principal_id: String, + pub client_id: String, + pub request_id: String, + pub operation: String, + pub request_digest: String, +} + +/// A receipt as stored, with the result the request had. +#[derive(Debug, Clone, PartialEq)] +pub struct StoredReceipt { + pub operation: String, + pub request_digest: String, + /// `{"database_revision": N, "records": [{"record_id": …, "revision": …}]}` + pub result: serde_json::Value, + pub database_revision: u64, +} + +/// One change-log entry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LoggedChange { + pub database_revision: u64, + pub record_id: String, + /// 0 for an erasure. + pub record_revision: u64, + /// `revision`, `deletion`, or `erasure`. + pub kind: String, +} + +/// The changes after a database revision. When `complete` is false the log does not +/// reach back that far, so a copy at `from` needs a full package instead (D263). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChangesSince { + pub from: u64, + pub to: u64, + pub complete: bool, + pub changes: Vec, +} + +pub(crate) fn check_access_epoch(tx: &Transaction<'_>, expected: u64) -> Result<()> { + let epoch: i64 = + tx.query_row("SELECT access_epoch FROM internal_access_state WHERE singleton_id = 1", [], |row| row.get(0))?; + if epoch as u64 != expected { + return Err(Error::stale( + "Access to this record changed while the request was waiting; check the grant and try again", + )); + } + Ok(()) +} + +pub(crate) fn insert_receipt(tx: &Transaction<'_>, receipt: &WriteReceipt, applied: &Applied) -> Result<()> { + let result = serde_json::json!({ + "database_revision": applied.database_revision, + "records": applied + .records + .iter() + .map(|record| serde_json::json!({ "record_id": record.record_id, "revision": record.current_revision })) + .collect::>(), + }); + tx.execute( + "INSERT INTO internal_write_receipts + (principal_id, client_id, request_id, operation, request_digest, result_json, database_revision, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + rusqlite::params![ + receipt.principal_id, + receipt.client_id, + receipt.request_id, + receipt.operation, + receipt.request_digest, + result.to_string(), + applied.database_revision as i64, + time::now_utc(), + ], + ) + .map_err(|error| match error { + rusqlite::Error::SqliteFailure(failure, _) if failure.code == rusqlite::ErrorCode::ConstraintViolation => { + Error::stale("This request ID was already used") + } + other => other.into(), + })?; + Ok(()) +} + +impl Store { + /// The receipt for a request, if the request was accepted before. + pub fn find_receipt(&self, principal_id: &str, client_id: &str, request_id: &str) -> Result> { + let row: Option<(String, String, String, i64)> = self + .connection() + .query_row( + "SELECT operation, request_digest, result_json, database_revision FROM internal_write_receipts + WHERE principal_id = ?1 AND client_id = ?2 AND request_id = ?3", + [principal_id, client_id, request_id], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + ) + .optional()?; + row.map(|(operation, request_digest, result, database_revision)| { + Ok(StoredReceipt { + operation, + request_digest, + result: serde_json::from_str(&result) + .map_err(|error| Error::other(format!("A stored receipt is not JSON: {error}")))?, + database_revision: database_revision as u64, + }) + }) + .transpose() + } + + /// The access epoch. Revoking a grant raises it (D262). + pub fn current_access_epoch(&self) -> Result { + let epoch: i64 = self.connection().query_row( + "SELECT access_epoch FROM internal_access_state WHERE singleton_id = 1", + [], + |row| row.get(0), + )?; + Ok(epoch as u64) + } + + /// Raise the access epoch in its own write transaction and return the new value. + /// The database revision does not change: no record changed. + pub fn raise_access_epoch(&mut self) -> Result { + self.transaction(|tx| { + let changed = tx.execute( + "UPDATE internal_access_state SET access_epoch = access_epoch + 1 WHERE singleton_id = 1", + [], + )?; + if changed != 1 { + return Err(Error::other("The access state row is missing")); + } + let epoch: i64 = + tx.query_row("SELECT access_epoch FROM internal_access_state WHERE singleton_id = 1", [], |row| { + row.get(0) + })?; + Ok(epoch as u64) + }) + } + + /// The logged changes after `revision`, in order (D263). + pub fn changes_since(&self, revision: u64) -> Result { + let to = self.database_revision()?; + if revision > to { + return Err(Error::stale(format!("Revision {revision} is newer than this database's revision {to}"))); + } + let mut statement = self.connection().prepare( + "SELECT database_revision, record_id, record_revision, change_kind FROM internal_change_log + WHERE database_revision > ?1 ORDER BY database_revision, record_id, change_kind, record_revision", + )?; + let changes: Vec = statement + .query_map([revision as i64], |row| { + Ok(LoggedChange { + database_revision: row.get::<_, i64>(0)? as u64, + record_id: row.get(1)?, + record_revision: row.get::<_, i64>(2)? as u64, + kind: row.get(3)?, + }) + })? + .collect::>()?; + let oldest: Option = + self.connection() + .query_row("SELECT min(database_revision) FROM internal_change_log", [], |row| row.get(0))?; + let complete = revision == to || oldest.is_some_and(|oldest| revision + 1 >= oldest as u64); + Ok(ChangesSince { from: revision, to, complete, changes }) + } +} diff --git a/src/store/mod.rs b/src/store/mod.rs index fc717d99..24a8f680 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -10,6 +10,7 @@ pub mod backup; pub mod check; pub mod contract; pub mod encode; +pub mod hosting; pub mod migrate; pub mod pending; pub mod query; diff --git a/src/store/replica.rs b/src/store/replica.rs index fd4300a5..5052b2c3 100644 --- a/src/store/replica.rs +++ b/src/store/replica.rs @@ -14,8 +14,15 @@ //! them on a local database, guarded the way a server transaction is guarded, so a //! working copy can catch up and tests can stand in for a server. //! -//! Tables in [`NOT_REPLAYED`] are never recorded: the receiving database's own -//! triggers rebuild the change log, and the other two describe one copy only. +//! Tables in [`NOT_REPLAYED`] are never recorded. Pending file work and the +//! replication log describe one copy only. The access epoch lives on the server: a +//! host raises it there directly and checks it when it commits (D262). +//! +//! The change log is replayed with `INSERT OR IGNORE`. The receiving database's +//! triggers write the same rows as the sending copy's triggers did, because both +//! compute the revision from `database_state` before it is raised. Replaying the +//! rows as well keeps deletions that the sender made, such as a restore starting a +//! new log. use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; @@ -29,7 +36,10 @@ use crate::error::{Error, Result}; /// Tables a capture never records and a replay never sends. pub const NOT_REPLAYED: &[&str] = - &["internal_change_log", "internal_pending_file_operations", "internal_replication_log"]; + &["internal_pending_file_operations", "internal_replication_log", "internal_access_state"]; + +/// Tables whose rows the receiving database's triggers also write. +pub const TRIGGER_WRITTEN: &[&str] = &["internal_change_log"]; /// Tables a working copy never copies from the server. pub const NOT_COPIED: &[&str] = &["internal_pending_file_operations", "internal_replication_log"]; @@ -198,6 +208,7 @@ impl ReplayStatement { pub fn accepts(&self, changed_rows: u64) -> bool { match self.kind { ChangeKind::Delete => changed_rows <= 1, + ChangeKind::Insert if TRIGGER_WRITTEN.contains(&self.table.as_str()) => changed_rows <= 1, ChangeKind::Insert | ChangeKind::Update => changed_rows == 1, } } @@ -236,21 +247,7 @@ const CAPTURE_TABLE: &str = "temp.ath_captured_changes"; impl Store { /// The access epoch. Revoking a grant raises it (D262). pub fn access_epoch(&self) -> Result { - access_epoch(&self.connection) - } - - /// Raise the access epoch in its own write transaction and return the new value. - pub fn raise_access_epoch(&mut self) -> Result { - self.transaction(|tx| { - let changed = tx.execute( - "UPDATE internal_access_state SET access_epoch = access_epoch + 1 WHERE singleton_id = 1", - [], - )?; - if changed != 1 { - return Err(Error::other("The access state row is missing")); - } - access_epoch(tx) - }) + self.current_access_epoch() } /// Run `operation` and record, in order, every row it changed. @@ -267,6 +264,10 @@ impl Store { let base_revision = self.database_revision()?; let access_epoch = self.access_epoch()?; let shapes = self.table_shapes()?; + // Changing `temp_store` deletes every temporary table and trigger. A package + // restore sets it to MEMORY, so set it first: the restore's change is then no + // change, and the capture survives it. + self.connection.pragma_update(None, "temp_store", "MEMORY")?; self.connection.execute_batch(&capture_triggers(&shapes))?; let outcome = operation(self); let recorded = read_capture(&self.connection, &shapes); @@ -310,7 +311,9 @@ impl Store { ChangeKind::Insert => { let names = shape.columns.iter().map(|name| quote(name)).collect::>().join(", "); let marks = (1..=width).map(|n| format!("?{n}")).collect::>().join(", "); - (format!("INSERT INTO {table} ({names}) VALUES ({marks})"), change.row.clone()) + let verb = + if TRIGGER_WRITTEN.contains(&shape.name.as_str()) { "INSERT OR IGNORE" } else { "INSERT" }; + (format!("{verb} INTO {table} ({names}) VALUES ({marks})"), change.row.clone()) } ChangeKind::Update => { let set = shape @@ -476,6 +479,28 @@ impl Store { } } +/// The SQL scripts that create an empty database at the current schema, in order, +/// for a server that keeps the database instead of a local file (D258). They are +/// the published migrations with the metadata row between the first and the rest, +/// as a new local file gets them. The two SQLite header settings a local file has are +/// left out: a libSQL server makes them read-only, and `database_metadata` is +/// authoritative (D93). +pub fn schema_scripts(database_id: &str, created_at: &str) -> Vec { + let literal = |text: &str| format!("'{}'", text.replace('\'', "''")); + let chain = super::migrate::MIGRATION_CHAIN; + let mut scripts = vec![chain[0].sql.to_string()]; + scripts.push(format!( + "INSERT INTO database_metadata (singleton_id, application_marker, sql_schema_version, athleticstandard_version, database_id, created_at) + VALUES (1, {}, 1, '1.0.0', {}, {}); + INSERT INTO database_state (singleton_id, current_revision) VALUES (1, 0);", + literal(super::SQLITE_APPLICATION_MARKER), + literal(database_id), + literal(created_at), + )); + scripts.extend(chain[1..].iter().map(|step| step.sql.to_string())); + scripts +} + fn run_statements(connection: &Connection, statements: &[ReplayStatement]) -> Result<()> { for statement in statements { let changed = connection.execute(&statement.sql, rusqlite::params_from_iter(statement.params.iter()))? as u64; diff --git a/src/store/write.rs b/src/store/write.rs index f6318f18..85e81b19 100644 --- a/src/store/write.rs +++ b/src/store/write.rs @@ -90,6 +90,11 @@ pub struct Changes { pub corrections: Vec, pub deletions: Vec, pub import_keys: Vec, + /// Refuse unless the access epoch is this value. A host sets it for a write made + /// under a grant, so a write ordered after a revocation fails (D262). + pub expected_access_epoch: Option, + /// Record the host request that made this change, in the same transaction (D261). + pub receipt: Option, } impl Changes { @@ -122,10 +127,18 @@ impl Store { /// Apply a change inside an existing transaction. Package restore and imports /// call this when they own a larger transaction. -pub(crate) fn apply_in(tx: &Transaction<'_>, layout: Layout, changes: Changes) -> Result { +pub(crate) fn apply_in(tx: &Transaction<'_>, layout: Layout, mut changes: Changes) -> Result { + if let Some(expected) = changes.expected_access_epoch { + super::hosting::check_access_epoch(tx, expected)?; + } + let receipt = changes.receipt.take(); let records = write_in(tx, layout, changes)?; let database_revision = advance_database_revision(tx)?; - Ok(Applied { records, database_revision }) + let applied = Applied { records, database_revision }; + if let Some(receipt) = receipt { + super::hosting::insert_receipt(tx, &receipt, &applied)?; + } + Ok(applied) } /// Advance the database revision once for a complete logical change. diff --git a/tests/replica.rs b/tests/replica.rs index 14cdf285..1edbdb99 100644 --- a/tests/replica.rs +++ b/tests/replica.rs @@ -12,8 +12,10 @@ use std::path::{Path, PathBuf}; use athleticstandard::json::{self, Value}; use athleticstandard::model::{BecameKnownAtBasis, ErasureReasonCode, RecordActor, RecordData, RecordType}; -use athleticstandard::package::{erase_record, export_package, preview_erasure, ExportOptions}; -use athleticstandard::store::replica::{Changeset, TableRows, NOT_COPIED}; +use athleticstandard::package::{ + apply_package_import, erase_record, export_package, preview_erasure, preview_package_import, ExportOptions, +}; +use athleticstandard::store::replica::{schema_scripts, Changeset, TableRows, NOT_COPIED}; use athleticstandard::store::write::StaleStyle; use athleticstandard::store::{Changes, Correction, Deletion, ExtensionsUpdate, NewRecord, OpenOptions, Store}; use serde_json::json; @@ -341,3 +343,46 @@ fn a_server_keeps_a_contiguous_log_and_an_erasure_clears_it() { assert_eq!(server.replication_log_after(server.database_revision().unwrap()).unwrap(), Some(Vec::new())); assert_same(&working, &server, &directory, "erased"); } + +#[test] +fn the_schema_scripts_build_the_same_schema_as_a_new_file() { + let directory = maintenance_support::temporary_dir("ath-replica-schema-"); + let made = Store::create(directory.join("made.ath.sqlite"), Default::default()).unwrap(); + let scripted = directory.join("scripted.ath.sqlite"); + let connection = rusqlite::Connection::open(&scripted).unwrap(); + for script in schema_scripts(&made.metadata().database_id, &made.metadata().created_at) { + connection.execute_batch(&script).unwrap(); + } + let read = |connection: &rusqlite::Connection, sql: &str| -> String { + connection.query_row(sql, [], |row| row.get(0)).unwrap() + }; + let made_connection = rusqlite::Connection::open(made.path()).unwrap(); + for sql in [ + "SELECT json_group_array(json_array(name, sql)) FROM (SELECT name, coalesce(sql, '') AS sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY name)", + "SELECT json_array(application_marker, sql_schema_version, athleticstandard_version, database_id, created_at) FROM database_metadata", + "SELECT json_array(current_revision) FROM database_state", + "SELECT json_array(access_epoch) FROM internal_access_state", + ] { + assert_eq!(read(&made_connection, sql), read(&connection, sql), "{sql}"); + } +} + +#[test] +fn a_package_restore_into_an_empty_record_replays() { + let directory = maintenance_support::temporary_dir("ath-replica-restore-"); + let source = demo(&directory, "source"); + let package = directory.join("package"); + export_package(&source, &package, &ExportOptions::default()).unwrap(); + + let mut empty = Store::create(directory.join("empty").join("athlete.ath.sqlite"), Default::default()).unwrap(); + let mut copy = working_copy(&empty, &directory, "copy"); + let captured = empty + .capture(|store| { + let preview = preview_package_import(store, &package)?; + apply_package_import(store, &preview, &[]).map(|_| ()) + }) + .unwrap(); + copy_folder(&directory.join("empty").join("attachments"), &directory.join("copy").join("attachments")); + copy.replay(captured.base_revision, copy.access_epoch().unwrap(), &captured.changeset).unwrap(); + assert_same(&empty, ©, &directory, "restored"); +} From 37f8e2089b6d1990f8fcb213361e22840eac500b Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 23 Nov 2026 18:07:40 -0600 Subject: [PATCH 06/26] Add ath-host, an optional program that serves many athletes' records. ath-host is a second package in the workspace. It checks OpenID Connect access tokens, keeps a directory of people, athlete records, grant offers, and grants, and serves version 1 of the host API: owner reads, writes, uploads, export, and change lists; grant offers and revocation; and a coach roster, workout summaries, notes, and programs under the three grants (D260-D262). Every write carries an Idempotency-Key and a receipt. In directory mode each athlete has a native SQLite file. In remote mode each athlete has a database on a libSQL server and attachments in an S3-compatible bucket; the host runs every operation on a working copy and commits the recorded rows in one guarded transaction (D268). The tests run both modes, using a local file in place of the server. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1497 +++++++++++++++++++++++++++++- Cargo.toml | 5 + build-history/v2.1.3/progress.md | 26 +- host/Cargo.toml | 37 + host/src/api.rs | 1057 +++++++++++++++++++++ host/src/auth.rs | 153 +++ host/src/config.rs | 152 +++ host/src/db.rs | 252 +++++ host/src/directory.rs | 565 +++++++++++ host/src/error.rs | 100 ++ host/src/lib.rs | 60 ++ host/src/main.rs | 110 +++ host/src/moves.rs | 9 + host/src/objects.rs | 94 ++ host/src/package_zip.rs | 55 ++ host/src/storage.rs | 647 +++++++++++++ host/tests/host_api.rs | 420 +++++++++ host/tests/support/mod.rs | 259 ++++++ 18 files changed, 5470 insertions(+), 28 deletions(-) create mode 100644 host/Cargo.toml create mode 100644 host/src/api.rs create mode 100644 host/src/auth.rs create mode 100644 host/src/config.rs create mode 100644 host/src/db.rs create mode 100644 host/src/directory.rs create mode 100644 host/src/error.rs create mode 100644 host/src/lib.rs create mode 100644 host/src/main.rs create mode 100644 host/src/moves.rs create mode 100644 host/src/objects.rs create mode 100644 host/src/package_zip.rs create mode 100644 host/src/storage.rs create mode 100644 host/tests/host_api.rs create mode 100644 host/tests/support/mod.rs diff --git a/Cargo.lock b/Cargo.lock index dd0ff54b..7b850e4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -78,6 +78,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + [[package]] name = "arbitrary" version = "1.5.0" @@ -87,6 +93,39 @@ dependencies = [ "derive_arbitrary", ] +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "athleticstandard" version = "2.1.3" @@ -107,18 +146,121 @@ dependencies = [ "zip", ] +[[package]] +name = "athleticstandard-host" +version = "2.1.3" +dependencies = [ + "athleticstandard", + "axum", + "chrono", + "jsonwebtoken", + "libsql", + "rusqlite", + "rusty-s3", + "serde", + "serde_json", + "sha2", + "tokio", + "ureq", + "url", + "uuid", + "zip", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http 1.5.0", + "http-body 1.1.0", + "http-body-util", + "hyper 1.13.0", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower 0.5.3", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http 1.5.0", + "http-body 1.1.0", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" @@ -141,6 +283,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ "hybrid-array", + "zeroize", ] [[package]] @@ -155,6 +298,15 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +dependencies = [ + "serde", +] + [[package]] name = "bzip2" version = "0.5.2" @@ -211,7 +363,7 @@ checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" dependencies = [ "chrono", "chrono-tz-build", - "phf", + "phf 0.12.1", "uncased", ] @@ -222,8 +374,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7d8d1efd5109b9c1cd3b7966bd071cdfb53bb6eb0b22a473a68c2f70a11a1eb" dependencies = [ "parse-zoneinfo", - "phf_codegen", - "phf_shared", + "phf_codegen 0.12.1", + "phf_shared 0.12.1", "uncased", ] @@ -278,6 +430,12 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" @@ -296,12 +454,28 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -350,6 +524,23 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crypto-bigint" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "serdect", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -366,7 +557,56 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "crypto-primes" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f" +dependencies = [ + "crypto-bigint", + "rand_core 0.10.1", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", + "subtle", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -375,6 +615,17 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" @@ -412,6 +663,8 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", + "zeroize", ] [[package]] @@ -425,6 +678,71 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der", + "digest 0.11.3", + "elliptic-curve", + "rfc6979", + "signature", + "spki", + "zeroize", +] + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct", + "crypto-bigint", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff", + "group", + "hybrid-array", + "pem-rfc7468", + "pkcs8", + "rand_core 0.10.1", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -459,6 +777,22 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -476,6 +810,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" @@ -484,19 +824,78 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -509,8 +908,13 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", + "futures-io", + "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -559,6 +963,37 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff", + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "h2" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 0.2.12", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", ] [[package]] @@ -595,12 +1030,166 @@ dependencies = [ ] [[package]] -name = "hybrid-array" -version = "0.4.15" +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "http" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" +dependencies = [ + "bytes", + "http 0.2.12", + "pin-project-lite", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http 1.5.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http 1.5.0", + "http-body 1.1.0", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", +] + +[[package]] +name = "hyper" +version = "0.14.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http 0.2.12", + "http-body 0.4.6", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2 0.5.10", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http 1.5.0", + "http-body 1.1.0", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "399c78f9338483cb7e630c8474b07268983c6bd5acee012e4211f9f7bb21b070" +dependencies = [ + "futures-util", + "http 0.2.12", + "hyper 0.14.32", + "log", + "rustls 0.22.4", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "webpki-roots 0.26.11", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http 1.5.0", + "http-body 1.1.0", + "hyper 1.13.0", + "pin-project-lite", + "tokio", + "tower-service", ] [[package]] @@ -750,18 +1339,83 @@ dependencies = [ "generic-array", ] +[[package]] +name = "instant-xml" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0201956651e8e4b5a78978dd2840bbb3797227a262a74f47b3576ef053b53bb" +dependencies = [ + "instant-xml-macros", + "xmlparser", +] + +[[package]] +name = "instant-xml-macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f38f6d268cc5e23813c7b2b5bae70317626bf4a95c6de1136b96a221c45148f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jiff" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e77cbfb9fff4798e283c2d69dff39fc2c45e7da017e5ce95b654e46ea41236" +dependencies = [ + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9067a0b23e5be3147d56b2dcf652b18e6b1364caca93fb157653b6fbcab23a9" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -783,12 +1437,92 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "12.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f347a975eb5fa8f5c4eadce6c1152c11c326cf32cf839fb64ff12d5cb8f4ce8b" +dependencies = [ + "base64 0.23.1", + "ed25519-dalek", + "getrandom 0.4.3", + "hmac 0.13.0", + "js-sys", + "p256", + "p384", + "pem", + "rsa", + "serde", + "serde_json", + "sha2", + "signature", + "simple_asn1", + "zeroize", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libsql" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bca1704194048f0f0bbc8a8e05ba85c0c67628b03bd59346dd2fdd946a1588" +dependencies = [ + "async-stream", + "async-trait", + "base64 0.21.7", + "bitflags", + "bytes", + "fallible-iterator", + "futures", + "http 0.2.12", + "hyper 0.14.32", + "hyper-rustls", + "libsql-hrana", + "libsql-sqlite3-parser", + "serde", + "serde_json", + "thiserror 1.0.69", + "tokio", + "tokio-util", + "tower 0.4.13", + "tracing", +] + +[[package]] +name = "libsql-hrana" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ceb7fa4a6b75b9eeffe2a375bde04ee8f48910d135a83ffd4191ddfd346c25c" +dependencies = [ + "base64 0.21.7", + "bytes", + "prost", + "serde", +] + +[[package]] +name = "libsql-sqlite3-parser" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15a90128c708356af8f7d767c9ac2946692c9112b4f74f07b99a01a60680e413" +dependencies = [ + "bitflags", + "cc", + "fallible-iterator", + "indexmap", + "log", + "memchr", + "phf 0.11.3", + "phf_codegen 0.11.3", + "phf_shared 0.11.3", + "uncased", +] + [[package]] name = "libsqlite3-sys" version = "0.40.0" @@ -839,12 +1573,34 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -855,12 +1611,42 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -882,6 +1668,39 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primefield", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa", + "elliptic-curve", + "fiat-crypto", + "primefield", + "primeorder", + "sha2", +] + [[package]] name = "parse-zoneinfo" version = "0.4.1" @@ -895,7 +1714,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", - "hmac", + "hmac 0.12.1", +] + +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64 0.23.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", ] [[package]] @@ -904,6 +1742,15 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared 0.11.3", +] + [[package]] name = "phf" version = "0.12.1" @@ -911,7 +1758,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" dependencies = [ "phf_macros", - "phf_shared", + "phf_shared 0.12.1", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", ] [[package]] @@ -920,8 +1777,18 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "efbdcb6f01d193b17f0b9c3360fa7e0e620991b193ff08702f78b3ce365d7e61" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.12.1", + "phf_shared 0.12.1", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand", ] [[package]] @@ -931,7 +1798,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cbb1126afed61dd6368748dae63b1ee7dc480191c6262a3b4ff1e29d86a6c5b" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.12.1", ] [[package]] @@ -940,14 +1807,24 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d713258393a82f091ead52047ca779d37e5766226d009de21696c4e667044368" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.12.1", + "phf_shared 0.12.1", "proc-macro2", "quote", "syn 2.0.119", "uncased", ] +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", + "uncased", +] + [[package]] name = "phf_shared" version = "0.12.1" @@ -958,18 +1835,73 @@ dependencies = [ "uncased", ] +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6250dd7321adbe93d12b750aee0ced159fd13e77f625edcdf1cb6f83cd99f650" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -985,6 +1917,33 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.2", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -994,6 +1953,29 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "prost" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "quick-xml" version = "0.37.5" @@ -1024,6 +2006,37 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint", + "hmac 0.13.0", +] + [[package]] name = "ring" version = "0.17.14" @@ -1038,13 +2051,34 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rsa" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699" +dependencies = [ + "const-oid", + "crypto-bigint", + "crypto-common 0.2.2", + "crypto-primes", + "digest 0.11.3", + "hmac 0.13.0", + "pkcs1", + "pkcs8", + "rand_core 0.10.1", + "sha2", + "signature", + "spki", + "zeroize", +] + [[package]] name = "rsqlite-vfs" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" dependencies = [ - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -1062,6 +2096,15 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.6" @@ -1075,6 +2118,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" +dependencies = [ + "log", + "ring", + "rustls-pki-types", + "rustls-webpki 0.102.8", + "subtle", + "zeroize", +] + [[package]] name = "rustls" version = "0.23.46" @@ -1085,11 +2142,33 @@ dependencies = [ "once_cell", "ring", "rustls-pki-types", - "rustls-webpki", + "rustls-webpki 0.103.17", "subtle", "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5" +dependencies = [ + "openssl-probe", + "rustls-pemfile", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "rustls-pki-types" version = "1.16.0" @@ -1099,6 +2178,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-webpki" +version = "0.102.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustls-webpki" version = "0.103.17" @@ -1116,12 +2206,89 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-s3" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c091b4ca9c4d51c1a959fa746cc74f5a612a2242070a4ae7b14e22b04c71f8c" +dependencies = [ + "base64 0.23.1", + "hmac 0.13.0", + "instant-xml", + "jiff", + "md-5", + "percent-encoding", + "serde", + "serde_json", + "sha2", + "url", + "zeroize", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "ryu-js" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der", + "hybrid-array", + "subtle", + "zeroize", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1167,6 +2334,39 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "sha1" version = "0.10.7" @@ -1195,12 +2395,44 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.21", + "time", +] + [[package]] name = "siphasher" version = "1.0.4" @@ -1219,6 +2451,36 @@ version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "sqlite-wasm-rs" version = "0.6.3" @@ -1269,6 +2531,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + [[package]] name = "synstructure" version = "0.14.0" @@ -1303,13 +2571,33 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -1334,6 +2622,7 @@ dependencies = [ "powerfmt", "serde_core", "time-core", + "time-macros", ] [[package]] @@ -1342,6 +2631,16 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.5" @@ -1352,6 +2651,127 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.6.5", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls 0.22.4", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "futures-core", + "futures-util", + "pin-project", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -1385,21 +2805,23 @@ version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" dependencies = [ - "base64", + "base64 0.22.1", "flate2", "log", "once_cell", - "rustls", + "rustls 0.23.46", "rustls-pki-types", + "serde", + "serde_json", "url", "webpki-roots 0.26.11", ] [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -1430,9 +2852,9 @@ checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "uuid" -version = "1.29.2" +version = "1.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -1451,6 +2873,15 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -1675,12 +3106,30 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + [[package]] name = "xz2" version = "0.1.7" @@ -1802,7 +3251,7 @@ dependencies = [ "deflate64", "flate2", "getrandom 0.3.4", - "hmac", + "hmac 0.12.1", "indexmap", "lzma-rs", "memchr", diff --git a/Cargo.toml b/Cargo.toml index e93687e3..8d3c4c93 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,11 @@ description = "Athletic Standard: a local-first SQLite record of an athlete's tr license = "MIT" publish = false +[workspace] +members = [".", "host"] +default-members = [".", "host"] +resolver = "2" + [lib] name = "athleticstandard" path = "src/lib.rs" diff --git a/build-history/v2.1.3/progress.md b/build-history/v2.1.3/progress.md index d7cd0295..aa2788c2 100644 --- a/build-history/v2.1.3/progress.md +++ b/build-history/v2.1.3/progress.md @@ -7,10 +7,10 @@ Status: **in progress; not released**. The plan is [spec.md](spec.md). | 1 | Plan, decisions D254–D267, storage study, hosting experiments | done | | 2 | Version 2.1.3, migration 007, coach authorship | done | | 3 | Changeset capture in the library (D268) | done | -| 4 | libSQL remote backend: working copies, guarded commits, replication log, qualification suite | not started | -| 5 | `ath-host` native directory mode: connect, read, write, attachments, refresh, restore | not started | -| 6 | Sign-in and grants | not started | -| 7 | Remote mode with object storage and several host copies | not started | +| 4 | libSQL remote backend: working copies, guarded commits, replication log, qualification suite | built; live run pending | +| 5 | `ath-host` native directory mode: connect, read, write, attachments, refresh, restore | done | +| 6 | Sign-in and grants | done; provider recipes in step 9 | +| 7 | Remote mode with object storage and several host copies | done with a stand-in server; live run pending | | 8 | Moves and backups | not started | | 9 | Clients, starter, `docs/hosting.md`, container and setup guide | not started | | 10 | Scale and fault runs, release evidence | not started | @@ -44,3 +44,21 @@ Step 3 notes: workspace, which turns the feature on for the default `cargo test`. - Migration 007 gained `internal_replication_log`, with the revision each changeset started from, and a trigger that empties it when a record is erased. + +Steps 4 to 7 notes: + +- `ath-host` is a second package in the workspace (`host/`). The `ath` CLI does not + depend on it. The libSQL client lives only in the host. +- Remote mode follows D268: the library runs every operation on a working copy, and + the host commits the recorded rows to the server in one guarded transaction. The + same commit code runs against a local SQLite file standing in for the server + (`local_server` storage), which is how the tests run without a network. +- Host copies that share athletes' databases also share the host directory. In remote + mode it is a libSQL database; in the stand-in mode it is a file in the shared folder. +- `host/tests/host_api.rs` covers, in both modes: a report with a photo saved and + opened on another device; retries and request-ID conflicts; a coach who sees and + adds only what was granted; a program; a revocation that blocks a waiting write; and + two host copies sharing one record, including catching up from the replication log + and rebuilding after an erasure. +- Not yet run: the remote backend against a real libSQL server, and sign-in through a + real provider. Tokens in the tests are signed by a fixed test-only key. diff --git a/host/Cargo.toml b/host/Cargo.toml new file mode 100644 index 00000000..945a4fd6 --- /dev/null +++ b/host/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "athleticstandard-host" +version = "2.1.3" +edition = "2021" +rust-version = "1.95" +description = "ath-host: an optional program that serves many athletes' Athletic Standard records over HTTPS" +license = "MIT" +publish = false + +[[bin]] +name = "ath-host" +path = "src/main.rs" + +[lib] +name = "ath_host" +path = "src/lib.rs" + +[dependencies] +athleticstandard = { path = "..", features = ["changesets"] } +axum = "0.8.9" +chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } +jsonwebtoken = { version = "12.0.0", features = ["rust_crypto"] } +libsql = { version = "0.10.0", default-features = false, features = ["remote", "tls"] } +rusqlite = { version = "0.42", features = ["bundled"] } +rusty-s3 = "0.12.0" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +sha2 = "0.11" +tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "signal", "sync", "time", "fs"] } +ureq = { version = "2.12", features = ["json"] } +url = "2.5.9" +uuid = { version = "1.29.3", features = ["v4", "v7"] } +zip = "2.2" + +[dev-dependencies] +jsonwebtoken = { version = "12.0.0", features = ["rust_crypto"] } +ureq = { version = "2.12", features = ["json"] } diff --git a/host/src/api.rs b/host/src/api.rs new file mode 100644 index 00000000..e03fefc3 --- /dev/null +++ b/host/src/api.rs @@ -0,0 +1,1057 @@ +//! Version 1 of the host API (spec section 6.5, D266). +//! +//! Every request carries an OAuth access token. The host checks the token, then the +//! caller's relation to the athlete: owner, coach with a grant through this app, or +//! nothing. A caller with no relation gets `not_found`, the same as for a record that +//! does not exist. Every write carries an `Idempotency-Key`; a repeated request with +//! the same body returns the original result (D261). + +use std::path::PathBuf; +use std::sync::Arc; + +use athleticstandard::json; +use athleticstandard::model::{BecameKnownAtBasis, ErasureReasonCode, RecordActor, RecordData, RecordType}; +use athleticstandard::package::{ + apply_with_attachments, erase_record, export_package, preview_erasure, ExportOptions, PreparedAttachment, +}; +use athleticstandard::store::hosting::WriteReceipt; +use athleticstandard::store::read::ListOptions; +use athleticstandard::store::write::StaleStyle; +use athleticstandard::store::{Changes, Correction, Deletion, ExtensionsUpdate, NewRecord, Store}; +use axum::body::Bytes; +use axum::extract::{FromRequestParts, Path, Query, State}; +use axum::http::request::Parts; +use axum::http::{header, HeaderMap, HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{delete, get, post, put}; +use axum::{Json, Router}; +use serde::Deserialize; +use serde_json::{json as j, Value}; +use sha2::{Digest, Sha256}; + +use crate::auth::Verifier; +use crate::config::Config; +use crate::directory::{hex, now, Athlete, Directory, Grant, Permission, Principal}; +use crate::error::{ApiError, ApiResult}; +use crate::storage::Storage; + +pub struct AppState { + pub config: Config, + pub directory: Directory, + pub storage: Storage, + pub verifier: Verifier, + /// The key that makes receipt digests (D261). It never leaves the host. + pub receipt_key: String, +} + +pub type Shared = Arc; + +pub fn router(state: Shared) -> Router { + let body_limit = state.config.limits.body_bytes; + Router::new() + .route("/.well-known/oauth-protected-resource", get(protected_resource)) + .route("/v1/capabilities", get(capabilities)) + .route("/v1/me", get(me)) + .route("/v1/athletes", get(list_athletes).post(create_athlete)) + .route("/v1/athletes/{id}", get(athlete_summary)) + .route("/v1/athletes/{id}/package", put(put_package)) + .route("/v1/athletes/{id}/export", get(export)) + .route("/v1/athletes/{id}/changes", get(changes)) + .route("/v1/athletes/{id}/records", get(list_records).post(create_record)) + .route("/v1/athletes/{id}/records/{record_id}", get(get_record)) + .route("/v1/athletes/{id}/records/{record_id}/corrections", post(correct_record)) + .route("/v1/athletes/{id}/records/{record_id}/deletion", post(delete_record)) + .route("/v1/athletes/{id}/records/{record_id}/erasure", post(erase)) + .route("/v1/athletes/{id}/uploads", post(upload)) + .route("/v1/athletes/{id}/attachments/{record_id}", get(download_attachment)) + .route("/v1/athletes/{id}/grant-offers", post(create_grant_offer)) + .route("/v1/athletes/{id}/grants", get(list_grants)) + .route("/v1/athletes/{id}/grants/{grant_id}", delete(revoke_grant)) + .route("/v1/grant-offers/accept", post(accept_grant_offer)) + .route("/v1/roster", get(roster)) + .route("/v1/athletes/{id}/workouts", get(workout_summaries)) + .route("/v1/athletes/{id}/notes", post(add_note)) + .route("/v1/athletes/{id}/programs", post(add_program)) + .merge(crate::moves::routes()) + .layer(axum::extract::DefaultBodyLimit::max(body_limit)) + .with_state(state) +} + +// ---- The caller ------------------------------------------------------------- + +/// A signed-in caller: the person and the app the token was issued to. +pub struct Caller { + pub principal: Principal, + pub client_id: String, +} + +impl FromRequestParts for Caller { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, state: &Shared) -> Result { + let token = parts + .headers + .get(header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.strip_prefix("Bearer ")) + .ok_or_else(|| ApiError::sign_in_required("Sign in and send the access token as a Bearer token"))?; + let verified = state.verifier.verify(token.trim()).await?; + let principal = state + .directory + .principal(&verified.issuer, &verified.subject, verified.name.as_deref()) + .await + .map_err(|error| ApiError::internal("directory", error))?; + Ok(Caller { principal, client_id: verified.client_id }) + } +} + +/// How the caller relates to one athlete's record. +enum Relation { + Owner(Athlete), + Coach(Athlete, Grant), +} + +async fn relation(state: &AppState, caller: &Caller, resource_id: &str) -> ApiResult { + let athlete = state + .directory + .athlete(resource_id) + .await + .map_err(|error| ApiError::internal("directory", error))? + .filter(|athlete| athlete.state != "retired") + .ok_or_else(ApiError::not_found)?; + if athlete.owner_principal_id == caller.principal.principal_id { + return Ok(Relation::Owner(athlete)); + } + match state + .directory + .active_grant(resource_id, &caller.principal.principal_id, &caller.client_id) + .await + .map_err(|error| ApiError::internal("directory", error))? + { + Some(grant) => Ok(Relation::Coach(athlete, grant)), + None => Err(ApiError::not_found()), + } +} + +async fn owner(state: &AppState, caller: &Caller, resource_id: &str) -> ApiResult { + match relation(state, caller, resource_id).await? { + Relation::Owner(athlete) => Ok(athlete), + Relation::Coach(..) => Err(ApiError::permission_denied("Only the athlete can do this")), + } +} + +/// The coach's grant for `permission`, with the access epoch read before the grant +/// check (D262): a write committed after a revocation then fails. +async fn coach_grant( + state: &AppState, + caller: &Caller, + resource_id: &str, + permission: Permission, +) -> ApiResult<(Grant, u64)> { + let epoch = state.storage.access_epoch(resource_id).await.map_err(hide_missing)?; + match relation(state, caller, resource_id).await? { + Relation::Coach(_, grant) if grant.allows(permission) => Ok((grant, epoch)), + Relation::Coach(..) => Err(ApiError::permission_denied("Your access to this athlete does not include this")), + Relation::Owner(_) => Err(ApiError::permission_denied("Use the owner operations for your own record")), + } +} + +fn hide_missing(error: ApiError) -> ApiError { + if error.code == "not_found" { + ApiError::not_found() + } else { + error + } +} + +fn not_moving(athlete: &Athlete) -> ApiResult<()> { + if athlete.state == "frozen" { + return Err(ApiError::moving()); + } + Ok(()) +} + +// ---- Receipts ---------------------------------------------------------------- + +fn idempotency_key(headers: &HeaderMap) -> ApiResult { + let key = headers + .get("idempotency-key") + .and_then(|value| value.to_str().ok()) + .map(str::trim) + .filter(|key| !key.is_empty() && key.len() <= 200) + .ok_or_else(|| ApiError::invalid("Send an Idempotency-Key header of 1 to 200 characters with every write"))?; + Ok(key.to_string()) +} + +fn receipt(state: &AppState, caller: &Caller, operation: &str, request_id: String, body: &[u8]) -> WriteReceipt { + let mut digest = Sha256::new(); + digest.update(state.receipt_key.as_bytes()); + digest.update([0]); + digest.update(operation.as_bytes()); + digest.update([0]); + digest.update(body); + WriteReceipt { + principal_id: caller.principal.principal_id.clone(), + client_id: caller.client_id.clone(), + request_id, + operation: operation.to_string(), + request_digest: hex(&digest.finalize()), + } +} + +enum Outcome { + Done(Value), + Conflict, +} + +/// Run one write with a receipt. `build` makes the change; it runs again if the server +/// moved on. A repeated request returns the stored result. +async fn write_with_receipt( + state: &AppState, + resource_id: &str, + guard_epoch: Option, + receipt: WriteReceipt, + attachments: Vec, + build: impl Fn(&Store) -> athleticstandard::Result + Send + Sync + 'static, +) -> ApiResult { + let outcome = state + .storage + .write(resource_id, guard_epoch, move |store, epoch| { + if let Some(found) = store.find_receipt(&receipt.principal_id, &receipt.client_id, &receipt.request_id)? { + if found.request_digest != receipt.request_digest || found.operation != receipt.operation { + return Ok(Outcome::Conflict); + } + return Ok(Outcome::Done(found.result)); + } + let mut changes = build(store)?; + changes.receipt = Some(receipt.clone()); + changes.expected_access_epoch = epoch; + let applied = if attachments.is_empty() { + store.apply(changes)? + } else { + let actor = changes.creates.first().map(|create| create.changed_by.clone()).unwrap_or(RecordActor::Athlete); + let prepared = athleticstandard::package::prepare_attachments(store, &attachments, &actor, &now())?; + let mut changes = changes; + let ids: Vec = prepared.iter().map(|attachment| attachment.record_id.clone()).collect(); + link_attachments(&mut changes, &ids)?; + changes.creates.splice(0..0, prepared.iter().map(PreparedAttachment::new_record)); + apply_with_attachments(store, &prepared, changes)? + }; + Ok(Outcome::Done(j!({ + "database_revision": applied.database_revision, + "records": applied.records.iter().map(|record| j!({ "record_id": record.record_id, "revision": record.current_revision })).collect::>(), + }))) + }) + .await?; + match outcome { + Outcome::Done(value) => Ok(value), + Outcome::Conflict => Err(ApiError::request_conflict()), + } +} + +fn link_attachments(changes: &mut Changes, ids: &[String]) -> athleticstandard::Result<()> { + let create = changes + .creates + .first_mut() + .ok_or_else(|| athleticstandard::Error::refused("attachments need a record to belong to"))?; + match &mut create.data { + RecordData::AthleteReport(data) => data.attachment_ids.get_or_insert_with(Vec::new).extend(ids.iter().cloned()), + RecordData::NutritionEntry(data) => { + data.attachment_ids.get_or_insert_with(Vec::new).extend(ids.iter().cloned()) + } + _ => { + return Err(athleticstandard::Error::refused( + "attachments belong to an athlete report or a nutrition entry", + )) + } + } + Ok(()) +} + +// ---- Helpers -------------------------------------------------------------------- + +fn to_json(value: &json::Value) -> Value { + serde_json::from_str(&json::to_string(value)).unwrap_or(Value::Null) +} + +fn from_json(value: &Value) -> ApiResult { + json::parse(&value.to_string()) + .map_err(|error| ApiError::invalid(format!("The request is not valid JSON: {error}"))) +} + +fn decode(record_type: RecordType, data: &Value) -> ApiResult { + RecordData::decode(record_type, &from_json(data)?).map_err(|error| ApiError::invalid(error.to_string())) +} + +fn body_json(body: &[u8]) -> ApiResult { + serde_json::from_slice(body).map_err(|error| ApiError::invalid(format!("The request body is not valid: {error}"))) +} + +fn coach_author(caller: &Caller, grant: &Grant) -> Value { + let name = grant + .coach_label + .clone() + .or_else(|| caller.principal.display_name.clone()) + .unwrap_or_else(|| "Coach".to_string()); + j!({ "author_type": "coach", "coach": name, "coach_id": caller.principal.coach_id }) +} + +fn coach_actor(caller: &Caller, grant: &Grant) -> ApiResult { + serde_json::from_value(coach_author(caller, grant)).map_err(|error| ApiError::internal("coach author", error)) +} + +fn staged_upload(state: &AppState, resource_id: &str, upload_id: &str) -> ApiResult { + if upload_id.len() != 32 || !upload_id.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(ApiError::invalid("An upload ID is 32 hexadecimal characters")); + } + let path = state.storage.staging().join("uploads").join(resource_id).join(upload_id); + if !path.is_file() { + return Err(ApiError::invalid(format!("There is no upload {upload_id}"))); + } + Ok(path) +} + +// ---- Discovery ------------------------------------------------------------------- + +async fn protected_resource(State(state): State) -> Json { + Json(j!({ + "resource": state.config.public_url, + "authorization_servers": [state.verifier.issuer()], + "bearer_methods_supported": ["header"], + "resource_name": "Athletic Standard host", + })) +} + +async fn capabilities(State(state): State) -> Json { + Json(j!({ + "api_version": 1, + "athleticstandard_version": athleticstandard::model::package::ATHLETIC_STANDARD_VERSION, + "storage": if state.storage.is_remote() { "libsql" } else { "directory" }, + "permissions": ["read_workout_summaries", "add_coach_notes", "add_programming"], + "operator_disclosure": state.config.operator_disclosure, + "open_enrollment": state.config.open_enrollment, + })) +} + +async fn me(State(state): State, caller: Caller) -> ApiResult> { + let owned = state + .directory + .athletes_owned_by(&caller.principal.principal_id) + .await + .map_err(|e| ApiError::internal("directory", e))?; + Ok(Json(j!({ + "principal_id": caller.principal.principal_id, + "client_id": caller.client_id, + "coach_id": caller.principal.coach_id, + "athletes": owned.iter().map(|athlete| athlete.resource_id.clone()).collect::>(), + }))) +} + +// ---- Owner: records ----------------------------------------------------------------- + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct NewAthlete { + #[serde(default)] + display_name: Option, + #[serde(default)] + invitation: Option, +} + +async fn create_athlete( + State(state): State, + caller: Caller, + body: Bytes, +) -> ApiResult<(StatusCode, Json)> { + let request: NewAthlete = + if body.is_empty() { NewAthlete { display_name: None, invitation: None } } else { body_json(&body)? }; + let invited = match &request.invitation { + Some(code) => state + .directory + .use_athlete_invitation(code, &caller.principal.principal_id) + .await + .map_err(|e| ApiError::internal("directory", e))?, + None => false, + }; + if !invited && !state.config.open_enrollment { + return Err(ApiError::permission_denied("This host needs an invitation to create a record")); + } + let athlete = state + .directory + .create_athlete(&caller.principal.principal_id, request.display_name.as_deref()) + .await + .map_err(|e| ApiError::internal("directory", e))?; + let revision = state.storage.create(&athlete.resource_id).await?; + Ok(( + StatusCode::CREATED, + Json( + j!({ "athlete_id": athlete.resource_id, "database_revision": revision, "operator_disclosure": state.config.operator_disclosure }), + ), + )) +} + +async fn list_athletes(State(state): State, caller: Caller) -> ApiResult> { + let owned = state + .directory + .athletes_owned_by(&caller.principal.principal_id) + .await + .map_err(|e| ApiError::internal("directory", e))?; + Ok(Json( + j!({ "athletes": owned.iter().map(|a| j!({ "athlete_id": a.resource_id, "display_name": a.display_name, "state": a.state })).collect::>() }), + )) +} + +async fn athlete_summary( + State(state): State, + caller: Caller, + Path(id): Path, +) -> ApiResult> { + let relation = relation(&state, &caller, &id).await?; + let (athlete, role) = match &relation { + Relation::Owner(athlete) => (athlete, "owner"), + Relation::Coach(athlete, _) => (athlete, "coach"), + }; + let mut summary = j!({ "athlete_id": athlete.resource_id, "role": role, "state": athlete.state, "operator_disclosure": state.config.operator_disclosure }); + if let Relation::Owner(_) = relation { + let revision = state.storage.read(&id, |store| store.database_revision()).await?; + summary["database_revision"] = j!(revision); + } + Ok(Json(summary)) +} + +/// Connect an existing record: restore a complete package (a zip of the package +/// folder) into an athlete's empty record. +async fn put_package( + State(state): State, + caller: Caller, + Path(id): Path, + body: Bytes, +) -> ApiResult> { + let athlete = owner(&state, &caller, &id).await?; + not_moving(&athlete)?; + let folder = state.storage.staging().join("packages").join(uuid::Uuid::new_v4().simple().to_string()); + crate::package_zip::unpack(&body, &folder) + .map_err(|error| ApiError::invalid(format!("The package is not a readable zip: {error}")))?; + let restore_from = folder.clone(); + let result = state + .storage + .write(&id, None, move |store, _| { + let preview = athleticstandard::package::preview_package_import(store, &restore_from)?; + if !preview.restore { + return Err(athleticstandard::Error::refused("A package can only be restored into an empty record")); + } + athleticstandard::package::apply_package_import(store, &preview, &[])?; + store.database_revision() + }) + .await; + let _ = std::fs::remove_dir_all(&folder); + Ok(Json(j!({ "database_revision": result? }))) +} + +async fn export(State(state): State, caller: Caller, Path(id): Path) -> ApiResult { + owner(&state, &caller, &id).await?; + let (bytes, digest) = export_zip(&state, &id).await?; + let mut response = (StatusCode::OK, bytes).into_response(); + response.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/zip")); + response.headers_mut().insert("x-manifest-digest", HeaderValue::from_str(&digest).expect("hex digest")); + Ok(response) +} + +/// The complete package as a zip, and the SHA-256 of its manifest (D263). +pub async fn export_zip(state: &AppState, id: &str) -> ApiResult<(Vec, String)> { + state.storage.ensure_attachment_files(id).await?; + let exports = state.storage.staging().join("exports"); + std::fs::create_dir_all(&exports).map_err(|error| ApiError::internal("creating the export folder", error))?; + let folder = exports.join(uuid::Uuid::new_v4().simple().to_string()); + let output = folder.clone(); + let result = state + .storage + .read(id, move |store| { + export_package(store, &output, &ExportOptions::default())?; + Ok(()) + }) + .await; + let packed = result.and_then(|_| { + let digest = std::fs::read(folder.join(athleticstandard::package::MANIFEST_DOCUMENT)) + .map(|bytes| hex(&Sha256::digest(&bytes))) + .map_err(|error| ApiError::internal("reading the manifest", error))?; + let bytes = + crate::package_zip::pack(&folder).map_err(|error| ApiError::internal("packing an export", error))?; + Ok((bytes, digest)) + }); + let _ = std::fs::remove_dir_all(&folder); + packed +} + +#[derive(Deserialize)] +struct Since { + since: u64, +} + +async fn changes( + State(state): State, + caller: Caller, + Path(id): Path, + Query(since): Query, +) -> ApiResult> { + owner(&state, &caller, &id).await?; + let found = state.storage.read(&id, move |store| store.changes_since(since.since)).await?; + Ok(Json(j!({ + "from": found.from, + "to": found.to, + "complete": found.complete, + "changes": found.changes.iter().map(|change| j!({ + "database_revision": change.database_revision, + "record_id": change.record_id, + "record_revision": change.record_revision, + "kind": change.kind, + })).collect::>(), + }))) +} + +#[derive(Deserialize)] +struct ListQuery { + #[serde(default)] + record_type: Option, + #[serde(default)] + limit: Option, +} + +async fn list_records( + State(state): State, + caller: Caller, + Path(id): Path, + Query(query): Query, +) -> ApiResult> { + owner(&state, &caller, &id).await?; + let record_type = match &query.record_type { + Some(name) => { + Some(RecordType::parse(name).ok_or_else(|| ApiError::invalid(format!("Unknown record type: {name}")))?) + } + None => None, + }; + let limit = query.limit.unwrap_or(state.config.limits.page_size).clamp(1, state.config.limits.page_size); + let records = state + .storage + .read(&id, move |store| store.list_records(&ListOptions { record_type, include_deleted: false, limit })) + .await?; + Ok(Json(j!({ "records": records.iter().map(|record| to_json(&record.to_value())).collect::>() }))) +} + +async fn get_record( + State(state): State, + caller: Caller, + Path((id, record_id)): Path<(String, String)>, +) -> ApiResult> { + owner(&state, &caller, &id).await?; + let lookup = record_id.clone(); + let (record, revisions) = + state.storage.read(&id, move |store| Ok((store.get_record(&lookup)?, store.revisions(&lookup)?))).await?; + let record = record.ok_or_else(ApiError::not_found)?; + Ok(Json(j!({ + "record": to_json(&record.to_value()), + "revisions": revisions.iter().map(|revision| to_json(&revision.to_value())).collect::>(), + }))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CreateRequest { + record_type: String, + data: Value, + #[serde(default)] + record_id: Option, + #[serde(default)] + attachments: Vec, +} + +async fn create_record( + State(state): State, + caller: Caller, + Path(id): Path, + headers: HeaderMap, + body: Bytes, +) -> ApiResult<(StatusCode, Json)> { + let athlete = owner(&state, &caller, &id).await?; + not_moving(&athlete)?; + let request: CreateRequest = body_json(&body)?; + let record_type = RecordType::parse(&request.record_type) + .ok_or_else(|| ApiError::invalid(format!("Unknown record type: {}", request.record_type)))?; + let data = decode(record_type, &request.data)?; + let uploads = + request.attachments.iter().map(|upload| staged_upload(&state, &id, upload)).collect::>>()?; + let receipt = receipt(&state, &caller, "create_record", idempotency_key(&headers)?, &body); + let record_id = request.record_id.clone(); + let result = write_with_receipt(&state, &id, None, receipt, uploads, move |_| { + Ok(Changes { + creates: vec![NewRecord { + record_id: record_id.clone(), + ..NewRecord::new(data.clone(), RecordActor::Athlete) + }], + ..Changes::default() + }) + }) + .await?; + Ok((StatusCode::CREATED, Json(result))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct CorrectionRequest { + expected_revision: u64, + data: Value, +} + +async fn correct_record( + State(state): State, + caller: Caller, + Path((id, record_id)): Path<(String, String)>, + headers: HeaderMap, + body: Bytes, +) -> ApiResult> { + let athlete = owner(&state, &caller, &id).await?; + not_moving(&athlete)?; + let request: CorrectionRequest = body_json(&body)?; + let receipt = receipt(&state, &caller, "correct_record", idempotency_key(&headers)?, &body); + let data = request.data.clone(); + let result = write_with_receipt(&state, &id, None, receipt, Vec::new(), move |store| { + let current = store + .get_record(&record_id)? + .ok_or_else(|| athleticstandard::Error::not_found(format!("No record {record_id}")))?; + let data = RecordData::decode( + current.record_type(), + &json::parse(&data.to_string()).map_err(|e| athleticstandard::Error::refused(e.to_string()))?, + )?; + Ok(Changes { + corrections: vec![Correction { + record_id: record_id.clone(), + expected_revision: request.expected_revision, + data, + extensions: ExtensionsUpdate::Keep, + changed_by: RecordActor::Athlete, + became_known_at: None, + became_known_at_basis: BecameKnownAtBasis::LocalWrite, + stale_style: StaleStyle::Revision, + }], + ..Changes::default() + }) + }) + .await?; + Ok(Json(result)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct DeletionRequest { + expected_revision: u64, +} + +async fn delete_record( + State(state): State, + caller: Caller, + Path((id, record_id)): Path<(String, String)>, + headers: HeaderMap, + body: Bytes, +) -> ApiResult> { + let athlete = owner(&state, &caller, &id).await?; + not_moving(&athlete)?; + let request: DeletionRequest = body_json(&body)?; + let receipt = receipt(&state, &caller, "delete_record", idempotency_key(&headers)?, &body); + let result = write_with_receipt(&state, &id, None, receipt, Vec::new(), move |_| { + Ok(Changes { + deletions: vec![Deletion { + record_id: record_id.clone(), + expected_revision: request.expected_revision, + deleted_by: RecordActor::Athlete, + deleted_at: None, + }], + ..Changes::default() + }) + }) + .await?; + Ok(Json(result)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ErasureRequest { + expected_revision: u64, + reason_code: String, +} + +/// Privacy erasure (D107). The library's erasure runs on its own transaction; it has +/// no receipt, and a repeated request finds nothing left to erase. +async fn erase( + State(state): State, + caller: Caller, + Path((id, record_id)): Path<(String, String)>, + body: Bytes, +) -> ApiResult> { + let athlete = owner(&state, &caller, &id).await?; + not_moving(&athlete)?; + let request: ErasureRequest = body_json(&body)?; + let reason: ErasureReasonCode = serde_json::from_value(Value::String(request.reason_code.clone())) + .map_err(|_| ApiError::invalid(format!("Unknown erasure reason: {}", request.reason_code)))?; + let revision = state + .storage + .write(&id, None, move |store, _| { + let preview = preview_erasure(store, &record_id, request.expected_revision)?; + Ok(erase_record(store, &preview, reason, None)?.database_revision) + }) + .await?; + Ok(Json(j!({ "database_revision": revision }))) +} + +async fn upload( + State(state): State, + caller: Caller, + Path(id): Path, + body: Bytes, +) -> ApiResult<(StatusCode, Json)> { + let athlete = owner(&state, &caller, &id).await?; + not_moving(&athlete)?; + if body.is_empty() { + return Err(ApiError::invalid("An upload needs a body")); + } + let media_type = athleticstandard::files::attachments::sniff_media_type(&body) + .ok_or_else(|| ApiError::refused("An attachment must be a PNG, JPEG, WebP, or PDF file"))?; + let upload_id = uuid::Uuid::new_v4().simple().to_string(); + let folder = state.storage.staging().join("uploads").join(&id); + std::fs::create_dir_all(&folder).map_err(|e| ApiError::internal("staging an upload", e))?; + std::fs::write(folder.join(&upload_id), &body).map_err(|e| ApiError::internal("staging an upload", e))?; + Ok(( + StatusCode::CREATED, + Json( + j!({ "upload_id": upload_id, "byte_count": body.len(), "sha256": hex(&Sha256::digest(&body)), "media_type": media_type }), + ), + )) +} + +async fn download_attachment( + State(state): State, + caller: Caller, + Path((id, record_id)): Path<(String, String)>, +) -> ApiResult { + owner(&state, &caller, &id).await?; + let lookup = record_id.clone(); + let record = + state.storage.read(&id, move |store| store.get_record(&lookup)).await?.ok_or_else(ApiError::not_found)?; + let RecordData::Attachment(data) = &record.data else { + return Err(ApiError::not_found()); + }; + let name = athleticstandard::files::attachments::stored_attachment_name(&record.record_id, data); + let bytes = state.storage.attachment_bytes(&id, &name).await?; + let mut response = (StatusCode::OK, bytes).into_response(); + if let Ok(value) = HeaderValue::from_str(&data.media_type.to_string()) { + response.headers_mut().insert(header::CONTENT_TYPE, value); + } + Ok(response) +} + +// ---- Owner: grants (D262) --------------------------------------------------------- + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OfferRequest { + permissions: Vec, + client_id: String, + #[serde(default)] + coach_label: Option, + #[serde(default)] + valid_seconds: Option, +} + +async fn create_grant_offer( + State(state): State, + caller: Caller, + Path(id): Path, + body: Bytes, +) -> ApiResult<(StatusCode, Json)> { + owner(&state, &caller, &id).await?; + let request: OfferRequest = body_json(&body)?; + if request.permissions.is_empty() { + return Err(ApiError::invalid("Choose at least one permission")); + } + let mut permissions = request.permissions.clone(); + permissions.sort(); + permissions.dedup(); + let offer = state + .directory + .create_grant_offer( + &id, + &permissions, + &request.client_id, + request.coach_label.as_deref(), + &caller.principal.principal_id, + request.valid_seconds.unwrap_or(7 * 24 * 3600).clamp(60, 30 * 24 * 3600), + ) + .await + .map_err(|e| ApiError::internal("directory", e))?; + Ok(( + StatusCode::CREATED, + Json( + j!({ "code": offer.code, "expires_at": offer.expires_at, "permissions": permissions, "client_id": request.client_id }), + ), + )) +} + +async fn list_grants(State(state): State, caller: Caller, Path(id): Path) -> ApiResult> { + owner(&state, &caller, &id).await?; + let grants = state.directory.grants_for_athlete(&id).await.map_err(|e| ApiError::internal("directory", e))?; + Ok(Json(j!({ "grants": grants }))) +} + +/// Revoke a grant: mark it revoked, then raise the access epoch (D262). A coach write +/// that read the epoch before this point and commits after it fails. +async fn revoke_grant( + State(state): State, + caller: Caller, + Path((id, grant_id)): Path<(String, String)>, +) -> ApiResult> { + owner(&state, &caller, &id).await?; + let revoked = state.directory.revoke(&id, &grant_id).await.map_err(|e| ApiError::internal("directory", e))?; + if !revoked { + return Err(ApiError::not_found()); + } + let epoch = state.storage.raise_access_epoch(&id).await?; + Ok(Json(j!({ "revoked": grant_id, "access_epoch": epoch }))) +} + +// ---- Coach ------------------------------------------------------------------------- + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct AcceptRequest { + code: String, +} + +async fn accept_grant_offer(State(state): State, caller: Caller, body: Bytes) -> ApiResult> { + let request: AcceptRequest = body_json(&body)?; + let grant = state + .directory + .accept_grant_offer(&request.code, &caller.principal, &caller.client_id) + .await + .map_err(|e| ApiError::internal("directory", e))? + .ok_or_else(ApiError::not_found)?; + Ok(Json(j!({ "grant": grant }))) +} + +async fn roster(State(state): State, caller: Caller) -> ApiResult> { + let roster = state + .directory + .roster(&caller.principal.principal_id, &caller.client_id) + .await + .map_err(|e| ApiError::internal("directory", e))?; + Ok(Json(j!({ + "athletes": roster.iter().map(|(athlete, grant)| j!({ + "athlete_id": athlete.resource_id, + "display_name": athlete.display_name, + "permissions": grant.permissions, + "grant_id": grant.grant_id, + })).collect::>(), + }))) +} + +#[derive(Deserialize)] +struct WorkoutQuery { + #[serde(default)] + limit: Option, + #[serde(default)] + after: Option, +} + +/// Workout summaries under the read grant: record ID, revision, start, end, and +/// activity type. Nothing else from the workout (D262). +async fn workout_summaries( + State(state): State, + caller: Caller, + Path(id): Path, + Query(query): Query, +) -> ApiResult> { + let (_, _) = coach_grant(&state, &caller, &id, Permission::ReadWorkoutSummaries).await?; + let limit = query.limit.unwrap_or(state.config.limits.page_size).clamp(1, state.config.limits.page_size) as usize; + let mut summaries: Vec<(String, String, Value)> = state + .storage + .read(&id, |store| { + let records = store.list_records(&ListOptions { + record_type: Some(RecordType::WorkoutSession), + include_deleted: false, + limit: 10_000, + })?; + Ok(records + .into_iter() + .filter_map(|record| match &record.data { + RecordData::WorkoutSession(data) => Some(( + data.start_at.clone(), + record.record_id.clone(), + j!({ + "record_id": record.record_id, + "revision": record.current_revision, + "start_at": data.start_at, + "end_at": data.end_at, + "activity_type": data.activity_type, + }), + )), + _ => None, + }) + .collect()) + }) + .await?; + summaries.sort_by(|left, right| (&right.0, &right.1).cmp(&(&left.0, &left.1))); + let start = match &query.after { + Some(after) => summaries + .iter() + .position(|(_, record_id, _)| record_id == after) + .map(|index| index + 1) + .unwrap_or(summaries.len()), + None => 0, + }; + let page: Vec = summaries.iter().skip(start).take(limit).map(|(_, _, summary)| summary.clone()).collect(); + let next = if start + page.len() < summaries.len() { + page.last().map(|summary| summary["record_id"].clone()) + } else { + None + }; + Ok(Json(j!({ "workouts": page, "next": next }))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct NoteRequest { + note: String, + #[serde(default)] + title: Option, + #[serde(default)] + applies_from: Option, + #[serde(default)] + applies_to: Option, + #[serde(default)] + evidence: Vec, +} + +#[derive(Deserialize, Clone)] +#[serde(deny_unknown_fields)] +struct EvidenceRequest { + record_id: String, + revision: u64, +} + +async fn add_note( + State(state): State, + caller: Caller, + Path(id): Path, + headers: HeaderMap, + body: Bytes, +) -> ApiResult<(StatusCode, Json)> { + let (grant, epoch) = coach_grant(&state, &caller, &id, Permission::AddCoachNotes).await?; + let athlete = state + .directory + .athlete(&id) + .await + .map_err(|e| ApiError::internal("directory", e))? + .ok_or_else(ApiError::not_found)?; + not_moving(&athlete)?; + let request: NoteRequest = body_json(&body)?; + if !request.evidence.is_empty() && !grant.allows(Permission::ReadWorkoutSummaries) { + return Err(ApiError::permission_denied("Evidence must be a workout you can read")); + } + let mut data = j!({ + "authorship": { "author": coach_author(&caller, &grant), "authored_at": now(), "evidence": request.evidence.iter().map(|e| j!({ "record_id": e.record_id, "revision": e.revision })).collect::>(), "content_version": 1, "status": "active" }, + "note": request.note, + }); + for (field, value) in + [("title", &request.title), ("applies_from", &request.applies_from), ("applies_to", &request.applies_to)] + { + if let Some(value) = value { + data[field] = j!(value); + } + } + let record = decode(RecordType::CoachingNote, &data)?; + let actor = coach_actor(&caller, &grant)?; + let evidence = request.evidence.clone(); + let receipt = receipt(&state, &caller, "add_note", idempotency_key(&headers)?, &body); + let result = write_with_receipt(&state, &id, Some(epoch), receipt, Vec::new(), move |store| { + check_evidence(store, &evidence)?; + Ok(Changes { creates: vec![NewRecord::new(record.clone(), actor.clone())], ..Changes::default() }) + }) + .await?; + Ok((StatusCode::CREATED, Json(result))) +} + +/// Evidence must name the current revision of a workout the read grant shows. +fn check_evidence(store: &Store, evidence: &[EvidenceRequest]) -> athleticstandard::Result<()> { + for reference in evidence { + let visible = store.get_record(&reference.record_id)?.is_some_and(|record| { + !record.is_deleted + && record.record_type() == RecordType::WorkoutSession + && record.current_revision == reference.revision + }); + if !visible { + return Err(athleticstandard::Error::refused(format!( + "Evidence {} at revision {} is not a current workout you can read", + reference.record_id, reference.revision + ))); + } + } + Ok(()) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ProgramRequest { + plan: Value, + #[serde(default)] + sessions: Vec, +} + +/// A training plan and its planned sessions, created together (D262). Sessions start +/// as planned; the coach cannot mark one completed or link a completed workout. +async fn add_program( + State(state): State, + caller: Caller, + Path(id): Path, + headers: HeaderMap, + body: Bytes, +) -> ApiResult<(StatusCode, Json)> { + let (grant, epoch) = coach_grant(&state, &caller, &id, Permission::AddProgramming).await?; + let athlete = state + .directory + .athlete(&id) + .await + .map_err(|e| ApiError::internal("directory", e))? + .ok_or_else(ApiError::not_found)?; + not_moving(&athlete)?; + let request: ProgramRequest = body_json(&body)?; + let authorship = j!({ "author": coach_author(&caller, &grant), "authored_at": now(), "evidence": [], "content_version": 1, "status": "active" }); + let mut plan = request.plan.as_object().cloned().ok_or_else(|| ApiError::invalid("plan must be an object"))?; + if plan.contains_key("authorship") { + return Err(ApiError::invalid("The host writes the authorship")); + } + plan.insert("authorship".into(), authorship.clone()); + let plan_id = athleticstandard::ids::new_record_id(); + let plan_data = decode(RecordType::TrainingPlan, &Value::Object(plan))?; + let mut sessions = Vec::new(); + for session in &request.sessions { + let mut session = + session.as_object().cloned().ok_or_else(|| ApiError::invalid("each session must be an object"))?; + for forbidden in ["authorship", "training_plan_id", "completion_status", "completed_workout_session_id"] { + if session.contains_key(forbidden) { + return Err(ApiError::invalid(format!("A coach cannot set {forbidden}"))); + } + } + session.insert("authorship".into(), authorship.clone()); + session.insert("training_plan_id".into(), j!(plan_id)); + session.insert("completion_status".into(), j!("planned")); + sessions.push(decode(RecordType::PlannedSession, &Value::Object(session))?); + } + let actor = coach_actor(&caller, &grant)?; + let receipt = receipt(&state, &caller, "add_program", idempotency_key(&headers)?, &body); + let result = write_with_receipt(&state, &id, Some(epoch), receipt, Vec::new(), move |_| { + let mut creates = + vec![NewRecord { record_id: Some(plan_id.clone()), ..NewRecord::new(plan_data.clone(), actor.clone()) }]; + creates.extend(sessions.iter().map(|session| NewRecord::new(session.clone(), actor.clone()))); + Ok(Changes { creates, ..Changes::default() }) + }) + .await?; + Ok((StatusCode::CREATED, Json(result))) +} diff --git a/host/src/auth.rs b/host/src/auth.rs new file mode 100644 index 00000000..ba22ced5 --- /dev/null +++ b/host/src/auth.rs @@ -0,0 +1,153 @@ +//! Checking an OAuth access token from the configured OpenID Connect provider (D260). +//! +//! The host checks the issuer, the signature against the provider's published keys, +//! the expiry, the audience, and the client. It accepts only signature algorithms +//! with a public key, so a shared secret can never sign a token for it. The person is +//! identified by issuer and subject, never by email address. + +use std::time::{Duration, Instant}; + +use jsonwebtoken::jwk::JwkSet; +use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation}; +use serde::Deserialize; +use tokio::sync::RwLock; + +use crate::config::SignInConfig; +use crate::error::{ApiError, ApiResult}; + +const ACCEPTED: &[Algorithm] = &[ + Algorithm::RS256, + Algorithm::RS384, + Algorithm::RS512, + Algorithm::PS256, + Algorithm::PS384, + Algorithm::PS512, + Algorithm::ES256, + Algorithm::ES384, + Algorithm::EdDSA, +]; + +/// How long published keys are trusted before they are read again. +const KEY_LIFETIME: Duration = Duration::from_secs(600); +/// The shortest gap between two reads caused by an unknown key ID. +const REFRESH_GAP: Duration = Duration::from_secs(30); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Verified { + pub issuer: String, + pub subject: String, + pub client_id: String, + pub name: Option, +} + +#[derive(Debug, Deserialize)] +struct Claims { + iss: String, + sub: String, + #[serde(default)] + azp: Option, + #[serde(default)] + client_id: Option, + #[serde(default)] + name: Option, +} + +pub struct Verifier { + config: SignInConfig, + keys: RwLock>, +} + +impl Verifier { + pub fn new(config: SignInConfig) -> Verifier { + Verifier { config, keys: RwLock::new(None) } + } + + pub fn issuer(&self) -> &str { + &self.config.issuer + } + + pub async fn verify(&self, token: &str) -> ApiResult { + let header = decode_header(token).map_err(|_| ApiError::sign_in_required("The access token cannot be read"))?; + if !ACCEPTED.contains(&header.alg) { + return Err(ApiError::sign_in_required("The access token uses a signature this host does not accept")); + } + let key = self.key(header.kid.as_deref()).await?; + let mut validation = Validation::new(header.alg); + validation.set_issuer(&[&self.config.issuer]); + validation.set_audience(&[&self.config.audience]); + validation.set_required_spec_claims(&["exp", "iss", "sub", "aud"]); + validation.leeway = 30; + let data = decode::(token, &key, &validation) + .map_err(|error| ApiError::sign_in_required(format!("The access token was refused: {error}")))?; + let claims = data.claims; + let client_id = claims + .azp + .or(claims.client_id) + .ok_or_else(|| ApiError::sign_in_required("The access token does not name the app it was issued to"))?; + if !self.config.allowed_clients.is_empty() && !self.config.allowed_clients.contains(&client_id) { + return Err(ApiError::sign_in_required("This host does not accept tokens issued to this app")); + } + Ok(Verified { issuer: claims.iss, subject: claims.sub, client_id, name: claims.name }) + } + + async fn key(&self, kid: Option<&str>) -> ApiResult { + if let Some(key) = self.cached_key(kid, KEY_LIFETIME).await? { + return Ok(key); + } + let fresh_enough = matches!(&*self.keys.read().await, Some((read_at, _)) if read_at.elapsed() < REFRESH_GAP); + if !fresh_enough { + let set = self.fetch().await?; + *self.keys.write().await = Some((Instant::now(), set)); + } + self.cached_key(kid, Duration::MAX) + .await? + .ok_or_else(|| ApiError::sign_in_required("The access token was signed with a key this host does not know")) + } + + async fn cached_key(&self, kid: Option<&str>, lifetime: Duration) -> ApiResult> { + let keys = self.keys.read().await; + let Some((read_at, set)) = &*keys else { + return Ok(None); + }; + if read_at.elapsed() > lifetime { + return Ok(None); + } + let jwk = match kid { + Some(kid) => set.find(kid), + None if set.keys.len() == 1 => set.keys.first(), + None => None, + }; + match jwk { + Some(jwk) => DecodingKey::from_jwk(jwk).map(Some).map_err(|error| ApiError::internal("signing key", error)), + None => Ok(None), + } + } + + async fn fetch(&self) -> ApiResult { + let issuer = self.config.issuer.trim_end_matches('/').to_string(); + let configured = self.config.jwks_uri.clone(); + tokio::task::spawn_blocking(move || -> Result { + let jwks_uri = match configured { + Some(uri) => uri, + None => { + let discovery: serde_json::Value = ureq::get(&format!("{issuer}/.well-known/openid-configuration")) + .timeout(Duration::from_secs(10)) + .call() + .map_err(|error| error.to_string())? + .into_json() + .map_err(|error| error.to_string())?; + discovery["jwks_uri"].as_str().ok_or("the discovery document names no jwks_uri")?.to_string() + } + }; + ureq::get(&jwks_uri) + .timeout(Duration::from_secs(10)) + .call() + .map_err(|error| error.to_string())? + .into_json::() + .map_err(|error| error.to_string()) + }) + .await + .map_err(|error| ApiError::internal("reading signing keys", error))? + .map_err(|error| ApiError::internal("reading signing keys", error)) + } +} diff --git a/host/src/config.rs b/host/src/config.rs new file mode 100644 index 00000000..ed1aca9f --- /dev/null +++ b/host/src/config.rs @@ -0,0 +1,152 @@ +//! The host's configuration: a JSON file. Secrets are never in the file. The file +//! names environment variables that hold them. + +use std::path::{Path, PathBuf}; + +use serde::Deserialize; + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + /// Address and port to listen on, such as `0.0.0.0:8080`. + pub listen: String, + /// The address clients use, such as `https://records.example.org`. It is the + /// resource identifier in the protected-resource metadata (RFC 9728). + pub public_url: String, + /// The host's own folder: its directory database, staging files, and, for the + /// directory backend, every athlete's database. + pub data_directory: PathBuf, + pub storage: StorageConfig, + pub sign_in: SignInConfig, + /// Text shown to an athlete when they connect: who runs this host and its storage + /// (D264). + pub operator_disclosure: String, + /// When true, any signed-in person can create their own record. When false, a + /// person needs an invitation from `ath-host invite`. + #[serde(default)] + pub open_enrollment: bool, + #[serde(default)] + pub limits: Limits, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum StorageConfig { + /// Native SQLite files in `data_directory/athletes/` (D257). + Directory, + /// One database per athlete on a server that speaks the libSQL protocol, with + /// attachments in an S3-compatible bucket (D257, D259, D268). + Libsql { + /// The database address for one athlete, with `{database}` where the database + /// name goes, such as `libsql://{database}-myorg.turso.io`. + url_template: String, + /// The host's directory database. + directory_url: String, + /// Environment variable holding the token for every database. + token_env: String, + provision: Provision, + attachments: S3Config, + }, + /// Test stand-in for a server: each athlete's "server" database is a local file + /// in this folder, committed to with the same guarded transaction (D268). + LocalServer { directory: PathBuf, attachments: S3Config }, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum Provision { + /// The operator creates each database before use. + Existing, + /// Turso's Platform API creates each database. + Turso { organization: String, group: String, platform_token_env: String }, + /// A self-run libSQL server with namespaces creates each database through its + /// admin address. + SqldAdmin { admin_url: String }, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct S3Config { + /// Such as `https://.r2.cloudflarestorage.com` or `https://s3.amazonaws.com`. + pub endpoint: String, + pub bucket: String, + pub region: String, + pub access_key_env: String, + pub secret_key_env: String, + /// Path-style addresses (`endpoint/bucket/key`). Most S3-compatible services + /// accept them. + #[serde(default = "yes")] + pub path_style: bool, +} + +fn yes() -> bool { + true +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignInConfig { + /// The OpenID Connect issuer, exactly as it appears in tokens (D260). + pub issuer: String, + /// The audience tokens for this API must name. + pub audience: String, + /// Where to read signing keys. When absent, the issuer's discovery document says. + #[serde(default)] + pub jwks_uri: Option, + /// Client IDs this host accepts. When empty, any client the provider issued a + /// token to is accepted; grants still name the client. + #[serde(default)] + pub allowed_clients: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Limits { + /// Largest request body, such as an uploaded package or attachment. + #[serde(default = "Limits::default_body_bytes")] + pub body_bytes: usize, + /// Largest number of records in one list page. + #[serde(default = "Limits::default_page_size")] + pub page_size: u32, + /// How long an idle working copy is kept, in seconds (D268). + #[serde(default = "Limits::default_working_copy_idle_seconds")] + pub working_copy_idle_seconds: u64, +} + +impl Limits { + fn default_body_bytes() -> usize { + 64 * 1024 * 1024 + } + fn default_page_size() -> u32 { + 200 + } + fn default_working_copy_idle_seconds() -> u64 { + 15 * 60 + } +} + +impl Default for Limits { + fn default() -> Self { + Limits { + body_bytes: Limits::default_body_bytes(), + page_size: Limits::default_page_size(), + working_copy_idle_seconds: Limits::default_working_copy_idle_seconds(), + } + } +} + +impl Config { + pub fn read(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|error| format!("cannot read {}: {error}", path.display()))?; + let mut config: Config = serde_json::from_str(&text) + .map_err(|error| format!("{} is not a valid configuration: {error}", path.display()))?; + if config.data_directory.is_relative() { + config.data_directory = path.parent().unwrap_or(Path::new(".")).join(&config.data_directory); + } + Ok(config) + } + + pub fn secret(name: &str) -> Result { + std::env::var(name).map_err(|_| format!("the environment variable {name} is not set")) + } +} diff --git a/host/src/db.rs b/host/src/db.rs new file mode 100644 index 00000000..9c12464d --- /dev/null +++ b/host/src/db.rs @@ -0,0 +1,252 @@ +//! One small SQL client for the host's own data: a local SQLite file, or a database on +//! a server that speaks the libSQL protocol. The host uses it for its directory and, +//! in remote mode, to commit changesets to athletes' databases (D268). Record rules +//! never run here; the library runs them on a working copy. + +use std::path::Path; +use std::sync::Arc; + +use athleticstandard::store::replica::SqlValue; +use tokio::sync::{Mutex, OwnedMutexGuard}; + +pub type Row = Vec; + +#[derive(Debug)] +pub struct DbError(pub String); + +impl std::fmt::Display for DbError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for DbError {} + +impl From for DbError { + fn from(error: rusqlite::Error) -> DbError { + DbError(error.to_string()) + } +} + +impl From for DbError { + fn from(error: libsql::Error) -> DbError { + DbError(error.to_string()) + } +} + +pub type DbResult = Result; + +#[derive(Clone)] +pub enum Db { + Local(Arc>), + Remote(Arc), +} + +impl Db { + /// A local SQLite file, created if absent, with foreign keys on and WAL. + pub fn open_local(path: &Path) -> DbResult { + let connection = rusqlite::Connection::open(path)?; + connection.busy_timeout(std::time::Duration::from_secs(5))?; + connection.pragma_update(None, "foreign_keys", "ON")?; + connection.pragma_update(None, "journal_mode", "WAL")?; + Ok(Db::Local(Arc::new(Mutex::new(connection)))) + } + + /// A database on a libSQL server. + pub async fn open_remote(url: &str, token: &str) -> DbResult { + let database = libsql::Builder::new_remote(url.to_string(), token.to_string()).build().await?; + Ok(Db::Remote(Arc::new(database))) + } + + pub async fn execute(&self, sql: &str, params: Vec) -> DbResult { + match self { + Db::Local(connection) => { + let connection = connection.lock().await; + Ok(connection.execute(sql, rusqlite::params_from_iter(params.iter()))? as u64) + } + Db::Remote(database) => { + let connection = database.connect()?; + Ok(connection.execute(sql, libsql::params_from_iter(params.into_iter().map(to_libsql))).await?) + } + } + } + + pub async fn execute_batch(&self, sql: &str) -> DbResult<()> { + match self { + Db::Local(connection) => Ok(connection.lock().await.execute_batch(sql)?), + Db::Remote(database) => { + database.connect()?.execute_batch(sql).await?; + Ok(()) + } + } + } + + pub async fn query(&self, sql: &str, params: Vec) -> DbResult> { + match self { + Db::Local(connection) => query_local(&*connection.lock().await, sql, ¶ms), + Db::Remote(database) => query_remote(&database.connect()?, sql, params).await, + } + } + + /// An immediate write transaction with foreign keys enforced and deferred to + /// commit. Dropping it without `commit` rolls it back. + pub async fn transaction(&self) -> DbResult { + match self { + Db::Local(connection) => { + let guard = connection.clone().lock_owned().await; + guard.execute_batch("BEGIN IMMEDIATE; PRAGMA defer_foreign_keys = ON;")?; + Ok(Tx::Local { guard: Some(guard) }) + } + Db::Remote(database) => { + let connection = database.connect()?; + connection.execute("PRAGMA foreign_keys = ON", ()).await?; + let enforced = query_remote(&connection, "PRAGMA foreign_keys", Vec::new()).await?; + if enforced.first().and_then(|row| row.first()) != Some(&SqlValue::Integer(1)) { + return Err(DbError("The server does not enforce foreign keys on this connection (D258)".into())); + } + let transaction = connection.transaction_with_behavior(libsql::TransactionBehavior::Immediate).await?; + transaction.execute("PRAGMA defer_foreign_keys = ON", ()).await?; + Ok(Tx::Remote { transaction: Some(transaction), _connection: connection }) + } + } + } +} + +pub enum Tx { + Local { guard: Option> }, + Remote { transaction: Option, _connection: libsql::Connection }, +} + +impl Tx { + pub async fn execute(&mut self, sql: &str, params: Vec) -> DbResult { + match self { + Tx::Local { guard } => { + let connection = guard.as_ref().expect("open transaction"); + Ok(connection.execute(sql, rusqlite::params_from_iter(params.iter()))? as u64) + } + Tx::Remote { transaction, .. } => { + let transaction = transaction.as_ref().expect("open transaction"); + Ok(transaction.execute(sql, libsql::params_from_iter(params.into_iter().map(to_libsql))).await?) + } + } + } + + pub async fn query(&mut self, sql: &str, params: Vec) -> DbResult> { + match self { + Tx::Local { guard } => query_local(guard.as_ref().expect("open transaction"), sql, ¶ms), + Tx::Remote { transaction, .. } => { + let transaction = transaction.as_ref().expect("open transaction"); + let mut rows = + transaction.query(sql, libsql::params_from_iter(params.into_iter().map(to_libsql))).await?; + collect_remote(&mut rows).await + } + } + } + + pub async fn commit(mut self) -> DbResult<()> { + match &mut self { + Tx::Local { guard } => { + let connection = guard.take().expect("open transaction"); + connection.execute_batch("COMMIT")?; + Ok(()) + } + Tx::Remote { transaction, .. } => { + transaction.take().expect("open transaction").commit().await?; + Ok(()) + } + } + } +} + +impl Drop for Tx { + fn drop(&mut self) { + if let Tx::Local { guard: Some(connection) } = self { + let _ = connection.execute_batch("ROLLBACK"); + } + // A libSQL transaction dropped without commit is rolled back by the client. + } +} + +/// The first value of the first row as an integer. +pub fn first_integer(rows: &[Row]) -> Option { + match rows.first().and_then(|row| row.first()) { + Some(SqlValue::Integer(value)) => Some(*value), + _ => None, + } +} + +pub fn text(value: &SqlValue) -> Option<&str> { + match value { + SqlValue::Text(text) => Some(text), + _ => None, + } +} + +pub fn integer(value: &SqlValue) -> Option { + match value { + SqlValue::Integer(value) => Some(*value), + _ => None, + } +} + +fn query_local(connection: &rusqlite::Connection, sql: &str, params: &[SqlValue]) -> DbResult> { + let mut statement = connection.prepare(sql)?; + let width = statement.column_count(); + let rows = statement + .query_map(rusqlite::params_from_iter(params.iter()), |row| { + (0..width) + .map(|column| { + Ok(match row.get_ref(column)? { + rusqlite::types::ValueRef::Null => SqlValue::Null, + rusqlite::types::ValueRef::Integer(value) => SqlValue::Integer(value), + rusqlite::types::ValueRef::Real(value) => SqlValue::Real(value), + rusqlite::types::ValueRef::Text(bytes) => { + SqlValue::Text(String::from_utf8_lossy(bytes).into_owned()) + } + rusqlite::types::ValueRef::Blob(_) => { + return Err(rusqlite::Error::InvalidColumnType( + column, + "binary value".into(), + rusqlite::types::Type::Blob, + )) + } + }) + }) + .collect() + })? + .collect::>>()?; + Ok(rows) +} + +async fn query_remote(connection: &libsql::Connection, sql: &str, params: Vec) -> DbResult> { + let mut rows = connection.query(sql, libsql::params_from_iter(params.into_iter().map(to_libsql))).await?; + collect_remote(&mut rows).await +} + +async fn collect_remote(rows: &mut libsql::Rows) -> DbResult> { + let width = rows.column_count(); + let mut out = Vec::new(); + while let Some(row) = rows.next().await? { + let mut values = Vec::with_capacity(width as usize); + for column in 0..width { + values.push(match row.get_value(column)? { + libsql::Value::Null => SqlValue::Null, + libsql::Value::Integer(value) => SqlValue::Integer(value), + libsql::Value::Real(value) => SqlValue::Real(value), + libsql::Value::Text(value) => SqlValue::Text(value), + libsql::Value::Blob(_) => return Err(DbError("A host query returned a binary value".into())), + }); + } + out.push(values); + } + Ok(out) +} + +fn to_libsql(value: SqlValue) -> libsql::Value { + match value { + SqlValue::Null => libsql::Value::Null, + SqlValue::Integer(value) => libsql::Value::Integer(value), + SqlValue::Real(value) => libsql::Value::Real(value), + SqlValue::Text(value) => libsql::Value::Text(value), + } +} diff --git a/host/src/directory.rs b/host/src/directory.rs new file mode 100644 index 00000000..5111cddc --- /dev/null +++ b/host/src/directory.rs @@ -0,0 +1,565 @@ +//! The host's directory: signed-in people, the athlete records they own, grant offers, +//! grants, and invitations (D256, D260, D262). It is a separate database from every +//! athlete's record. Grants are history-free host state; the record keeps only +//! authorship (D255). + +use athleticstandard::store::replica::SqlValue; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::db::{first_integer, text, Db, DbError, DbResult, Row}; + +const SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS host_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +) STRICT; +CREATE TABLE IF NOT EXISTS principals ( + principal_id TEXT PRIMARY KEY, + issuer TEXT NOT NULL, + subject TEXT NOT NULL, + display_name TEXT, + coach_id TEXT NOT NULL UNIQUE, + created_at TEXT NOT NULL, + UNIQUE (issuer, subject) +) STRICT; +CREATE TABLE IF NOT EXISTS athletes ( + resource_id TEXT PRIMARY KEY, + owner_principal_id TEXT NOT NULL REFERENCES principals (principal_id), + display_name TEXT, + state TEXT NOT NULL CHECK (state IN ('active', 'frozen', 'retired')), + created_at TEXT NOT NULL +) STRICT; +CREATE INDEX IF NOT EXISTS athletes_owner_idx ON athletes (owner_principal_id); +CREATE TABLE IF NOT EXISTS invitations ( + code_hash TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('athlete', 'grant')), + resource_id TEXT REFERENCES athletes (resource_id), + permissions TEXT, + client_id TEXT, + coach_label TEXT, + created_by TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_by TEXT, + used_at TEXT +) STRICT; +CREATE TABLE IF NOT EXISTS grants ( + grant_id TEXT PRIMARY KEY, + resource_id TEXT NOT NULL REFERENCES athletes (resource_id), + coach_principal_id TEXT NOT NULL REFERENCES principals (principal_id), + client_id TEXT NOT NULL, + permissions TEXT NOT NULL, + coach_label TEXT, + created_at TEXT NOT NULL, + revoked_at TEXT +) STRICT; +CREATE INDEX IF NOT EXISTS grants_coach_idx ON grants (coach_principal_id, client_id); +CREATE INDEX IF NOT EXISTS grants_resource_idx ON grants (resource_id); +CREATE TABLE IF NOT EXISTS transfers ( + transfer_id TEXT PRIMARY KEY, + resource_id TEXT NOT NULL, + direction TEXT NOT NULL CHECK (direction IN ('outgoing', 'incoming')), + destination TEXT, + manifest_digest TEXT, + activation_hash TEXT, + state TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +) STRICT; +"; + +/// The three grants (D262). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Permission { + ReadWorkoutSummaries, + AddCoachNotes, + AddProgramming, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Principal { + pub principal_id: String, + pub issuer: String, + pub subject: String, + pub display_name: Option, + /// The opaque ID written into coach authorship (D255). + pub coach_id: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Athlete { + pub resource_id: String, + pub owner_principal_id: String, + pub display_name: Option, + pub state: String, + pub created_at: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Grant { + pub grant_id: String, + pub resource_id: String, + pub coach_principal_id: String, + pub client_id: String, + pub permissions: Vec, + pub coach_label: Option, + pub created_at: String, + pub revoked_at: Option, +} + +impl Grant { + pub fn allows(&self, permission: Permission) -> bool { + self.revoked_at.is_none() && self.permissions.contains(&permission) + } +} + +/// An offer an athlete made: a code a coach accepts with a named app. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Offer { + pub code: String, + pub expires_at: String, +} + +#[derive(Clone)] +pub struct Directory { + db: Db, +} + +pub fn now() -> String { + chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) +} + +fn later(seconds: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(seconds)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true) +} + +pub fn hash_code(code: &str) -> String { + hex(&Sha256::digest(code.as_bytes())) +} + +pub fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +/// A code with 244 random bits, safe to show once and store only as a hash. +pub fn new_code() -> String { + format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple()) +} + +fn t(value: &str) -> SqlValue { + SqlValue::Text(value.to_string()) +} + +fn opt(value: Option<&str>) -> SqlValue { + value.map(t).unwrap_or(SqlValue::Null) +} + +fn get_text(row: &Row, index: usize) -> String { + row.get(index).and_then(text).unwrap_or_default().to_string() +} + +fn get_opt(row: &Row, index: usize) -> Option { + row.get(index).and_then(text).map(str::to_string) +} + +fn permissions_text(permissions: &[Permission]) -> String { + serde_json::to_string(permissions).expect("permissions serialize") +} + +fn parse_permissions(text: &str) -> Vec { + serde_json::from_str(text).unwrap_or_default() +} + +fn athlete(row: &Row) -> Athlete { + Athlete { + resource_id: get_text(row, 0), + owner_principal_id: get_text(row, 1), + display_name: get_opt(row, 2), + state: get_text(row, 3), + created_at: get_text(row, 4), + } +} + +const ATHLETE_COLUMNS: &str = "resource_id, owner_principal_id, display_name, state, created_at"; +const GRANT_COLUMNS: &str = + "grant_id, resource_id, coach_principal_id, client_id, permissions, coach_label, created_at, revoked_at"; + +fn grant(row: &Row) -> Grant { + Grant { + grant_id: get_text(row, 0), + resource_id: get_text(row, 1), + coach_principal_id: get_text(row, 2), + client_id: get_text(row, 3), + permissions: parse_permissions(&get_text(row, 4)), + coach_label: get_opt(row, 5), + created_at: get_text(row, 6), + revoked_at: get_opt(row, 7), + } +} + +impl Directory { + pub async fn open(db: Db) -> DbResult { + db.execute_batch(SCHEMA).await?; + Ok(Directory { db }) + } + + pub fn db(&self) -> &Db { + &self.db + } + + /// The principal for a verified issuer and subject, created on first sight. The ID + /// is derived from the issuer and subject, never from an email address (D260). + pub async fn principal(&self, issuer: &str, subject: &str, display_name: Option<&str>) -> DbResult { + let principal_id = format!("p_{}", &hex(&Sha256::digest(format!("{issuer}\n{subject}").as_bytes()))[..32]); + self.db + .execute( + "INSERT INTO principals (principal_id, issuer, subject, display_name, coach_id, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT (principal_id) DO UPDATE SET display_name = coalesce(excluded.display_name, principals.display_name)", + vec![t(&principal_id), t(issuer), t(subject), opt(display_name), t(&uuid::Uuid::new_v4().to_string()), t(&now())], + ) + .await?; + let rows = self + .db + .query( + "SELECT principal_id, issuer, subject, display_name, coach_id FROM principals WHERE principal_id = ?1", + vec![t(&principal_id)], + ) + .await?; + let row = rows.first().ok_or_else(|| DbError("principal was not stored".into()))?; + Ok(Principal { + principal_id: get_text(row, 0), + issuer: get_text(row, 1), + subject: get_text(row, 2), + display_name: get_opt(row, 3), + coach_id: get_text(row, 4), + }) + } + + pub async fn create_athlete(&self, owner_principal_id: &str, display_name: Option<&str>) -> DbResult { + let resource_id = format!("ath_{}", uuid::Uuid::new_v4().simple()); + self.db + .execute( + &format!("INSERT INTO athletes ({ATHLETE_COLUMNS}) VALUES (?1, ?2, ?3, 'active', ?4)"), + vec![t(&resource_id), t(owner_principal_id), opt(display_name), t(&now())], + ) + .await?; + self.athlete(&resource_id).await?.ok_or_else(|| DbError("athlete was not stored".into())) + } + + pub async fn athlete(&self, resource_id: &str) -> DbResult> { + let rows = self + .db + .query(&format!("SELECT {ATHLETE_COLUMNS} FROM athletes WHERE resource_id = ?1"), vec![t(resource_id)]) + .await?; + Ok(rows.first().map(athlete)) + } + + pub async fn athletes_owned_by(&self, principal_id: &str) -> DbResult> { + let rows = self + .db + .query( + &format!("SELECT {ATHLETE_COLUMNS} FROM athletes WHERE owner_principal_id = ?1 AND state <> 'retired' ORDER BY created_at, resource_id"), + vec![t(principal_id)], + ) + .await?; + Ok(rows.iter().map(athlete).collect()) + } + + pub async fn all_athletes(&self) -> DbResult> { + let rows = self + .db + .query( + &format!("SELECT {ATHLETE_COLUMNS} FROM athletes WHERE state <> 'retired' ORDER BY resource_id"), + Vec::new(), + ) + .await?; + Ok(rows.iter().map(athlete).collect()) + } + + pub async fn set_athlete_state(&self, resource_id: &str, from: &str, to: &str) -> DbResult { + let changed = self + .db + .execute( + "UPDATE athletes SET state = ?3 WHERE resource_id = ?1 AND state = ?2", + vec![t(resource_id), t(from), t(to)], + ) + .await?; + Ok(changed == 1) + } + + /// An invitation that lets one person create their own record, used once. + pub async fn create_athlete_invitation(&self, created_by: &str, valid_seconds: i64) -> DbResult { + let code = new_code(); + let expires_at = later(valid_seconds); + self.db + .execute( + "INSERT INTO invitations (code_hash, kind, created_by, created_at, expires_at) VALUES (?1, 'athlete', ?2, ?3, ?4)", + vec![t(&hash_code(&code)), t(created_by), t(&now()), t(&expires_at)], + ) + .await?; + Ok(Offer { code, expires_at }) + } + + /// Use an athlete invitation. False when it is unknown, used, or expired. + pub async fn use_athlete_invitation(&self, code: &str, principal_id: &str) -> DbResult { + let changed = self + .db + .execute( + "UPDATE invitations SET used_by = ?2, used_at = ?3 + WHERE code_hash = ?1 AND kind = 'athlete' AND used_at IS NULL AND expires_at > ?3", + vec![t(&hash_code(code)), t(principal_id), t(&now())], + ) + .await?; + Ok(changed == 1) + } + + /// A grant offer for one athlete's record: the permissions, the app it must be + /// accepted through, and a label the athlete gave the coach. + pub async fn create_grant_offer( + &self, + resource_id: &str, + permissions: &[Permission], + client_id: &str, + coach_label: Option<&str>, + created_by: &str, + valid_seconds: i64, + ) -> DbResult { + let code = new_code(); + let expires_at = later(valid_seconds); + self.db + .execute( + "INSERT INTO invitations (code_hash, kind, resource_id, permissions, client_id, coach_label, created_by, created_at, expires_at) + VALUES (?1, 'grant', ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + vec![ + t(&hash_code(&code)), + t(resource_id), + t(&permissions_text(permissions)), + t(client_id), + opt(coach_label), + t(created_by), + t(&now()), + t(&expires_at), + ], + ) + .await?; + Ok(Offer { code, expires_at }) + } + + /// Accept a grant offer as `coach` through `client_id`. `None` when the offer is + /// unknown, used, expired, made for another app, or made by the coach themselves. + pub async fn accept_grant_offer(&self, code: &str, coach: &Principal, client_id: &str) -> DbResult> { + let mut transaction = self.db.transaction().await?; + let rows = transaction + .query( + "SELECT resource_id, permissions, client_id, coach_label, created_by FROM invitations + WHERE code_hash = ?1 AND kind = 'grant' AND used_at IS NULL AND expires_at > ?2", + vec![t(&hash_code(code)), t(&now())], + ) + .await?; + let Some(row) = rows.first() else { + return Ok(None); + }; + if get_text(row, 2) != client_id || get_text(row, 4) == coach.principal_id { + return Ok(None); + } + let grant_id = format!("grant_{}", uuid::Uuid::new_v4().simple()); + transaction + .execute( + "UPDATE invitations SET used_by = ?2, used_at = ?3 WHERE code_hash = ?1", + vec![t(&hash_code(code)), t(&coach.principal_id), t(&now())], + ) + .await?; + transaction + .execute( + &format!("INSERT INTO grants ({GRANT_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL)"), + vec![ + t(&grant_id), + t(&get_text(row, 0)), + t(&coach.principal_id), + t(client_id), + t(&get_text(row, 1)), + opt(get_opt(row, 3).as_deref()), + t(&now()), + ], + ) + .await?; + transaction.commit().await?; + self.grant(&grant_id).await + } + + pub async fn grant(&self, grant_id: &str) -> DbResult> { + let rows = self + .db + .query(&format!("SELECT {GRANT_COLUMNS} FROM grants WHERE grant_id = ?1"), vec![t(grant_id)]) + .await?; + Ok(rows.first().map(grant)) + } + + pub async fn grants_for_athlete(&self, resource_id: &str) -> DbResult> { + let rows = self + .db + .query( + &format!("SELECT {GRANT_COLUMNS} FROM grants WHERE resource_id = ?1 ORDER BY created_at, grant_id"), + vec![t(resource_id)], + ) + .await?; + Ok(rows.iter().map(grant).collect()) + } + + /// The coach's current grant for this athlete through this app. + pub async fn active_grant( + &self, + resource_id: &str, + coach_principal_id: &str, + client_id: &str, + ) -> DbResult> { + let rows = self + .db + .query( + &format!( + "SELECT {GRANT_COLUMNS} FROM grants + WHERE resource_id = ?1 AND coach_principal_id = ?2 AND client_id = ?3 AND revoked_at IS NULL + ORDER BY created_at DESC LIMIT 1" + ), + vec![t(resource_id), t(coach_principal_id), t(client_id)], + ) + .await?; + Ok(rows.first().map(grant)) + } + + /// Athletes who granted this coach access through this app, with the grant. + pub async fn roster(&self, coach_principal_id: &str, client_id: &str) -> DbResult> { + let rows = self + .db + .query( + &format!( + "SELECT {}, {} FROM grants g JOIN athletes a ON a.resource_id = g.resource_id + WHERE g.coach_principal_id = ?1 AND g.client_id = ?2 AND g.revoked_at IS NULL AND a.state <> 'retired' + ORDER BY a.resource_id", + ATHLETE_COLUMNS.split(", ").map(|c| format!("a.{c}")).collect::>().join(", "), + GRANT_COLUMNS.split(", ").map(|c| format!("g.{c}")).collect::>().join(", "), + ), + vec![t(coach_principal_id), t(client_id)], + ) + .await?; + Ok(rows.iter().map(|row| (athlete(&row[..5].to_vec()), grant(&row[5..].to_vec()))).collect()) + } + + /// Mark a grant revoked. The caller raises the access epoch afterwards (D262). + pub async fn revoke(&self, resource_id: &str, grant_id: &str) -> DbResult { + let changed = self + .db + .execute( + "UPDATE grants SET revoked_at = ?3 WHERE resource_id = ?1 AND grant_id = ?2 AND revoked_at IS NULL", + vec![t(resource_id), t(grant_id), t(&now())], + ) + .await?; + Ok(changed == 1) + } + + pub async fn setting(&self, key: &str) -> DbResult> { + let rows = self.db.query("SELECT value FROM host_settings WHERE key = ?1", vec![t(key)]).await?; + Ok(rows.first().and_then(|row| get_opt(row, 0))) + } + + /// Store a setting once. False when it was already set. + pub async fn set_setting_once(&self, key: &str, value: &str) -> DbResult { + let changed = self + .db + .execute("INSERT OR IGNORE INTO host_settings (key, value) VALUES (?1, ?2)", vec![t(key), t(value)]) + .await?; + Ok(changed == 1) + } + + pub async fn count(&self, table: &str) -> DbResult { + let rows = self.db.query(&format!("SELECT count(*) FROM {table}"), Vec::new()).await?; + Ok(first_integer(&rows).unwrap_or(0)) + } + + // ---- Moves between hosts (D267) ------------------------------------------ + + pub async fn record_transfer( + &self, + transfer_id: &str, + resource_id: &str, + direction: &str, + destination: Option<&str>, + state: &str, + ) -> DbResult<()> { + self.db + .execute( + "INSERT INTO transfers (transfer_id, resource_id, direction, destination, state, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)", + vec![t(transfer_id), t(resource_id), t(direction), opt(destination), t(state), t(&now())], + ) + .await?; + Ok(()) + } + + pub async fn transfer(&self, transfer_id: &str) -> DbResult> { + let rows = self + .db + .query( + "SELECT transfer_id, resource_id, direction, destination, manifest_digest, activation_hash, state FROM transfers WHERE transfer_id = ?1", + vec![t(transfer_id)], + ) + .await?; + Ok(rows.first().map(|row| Transfer { + transfer_id: get_text(row, 0), + resource_id: get_text(row, 1), + direction: get_text(row, 2), + destination: get_opt(row, 3), + manifest_digest: get_opt(row, 4), + activation_hash: get_opt(row, 5), + state: get_text(row, 6), + })) + } + + pub async fn update_transfer( + &self, + transfer_id: &str, + from_state: &str, + to_state: &str, + manifest_digest: Option<&str>, + activation_hash: Option<&str>, + ) -> DbResult { + let changed = self + .db + .execute( + "UPDATE transfers SET state = ?3, manifest_digest = coalesce(?4, manifest_digest), + activation_hash = coalesce(?5, activation_hash), updated_at = ?6 + WHERE transfer_id = ?1 AND state = ?2", + vec![t(transfer_id), t(from_state), t(to_state), opt(manifest_digest), opt(activation_hash), t(&now())], + ) + .await?; + Ok(changed == 1) + } + + pub async fn open_transfer_for(&self, resource_id: &str) -> DbResult> { + let rows = self + .db + .query( + "SELECT transfer_id FROM transfers WHERE resource_id = ?1 AND state NOT IN ('aborted', 'activated', 'retired') ORDER BY created_at DESC LIMIT 1", + vec![t(resource_id)], + ) + .await?; + match rows.first().and_then(|row| get_opt(row, 0)) { + Some(id) => self.transfer(&id).await, + None => Ok(None), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Transfer { + pub transfer_id: String, + pub resource_id: String, + pub direction: String, + pub destination: Option, + pub manifest_digest: Option, + pub activation_hash: Option, + pub state: String, +} diff --git a/host/src/error.rs b/host/src/error.rs new file mode 100644 index 00000000..a64911bf --- /dev/null +++ b/host/src/error.rs @@ -0,0 +1,100 @@ +//! The errors the API returns. Every error is JSON with a stable code (spec section +//! 6.5). A request about an athlete the caller has no relation to gets the same +//! `not_found` answer as a request about an athlete that does not exist. + +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use axum::Json; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApiError { + pub status: StatusCode, + pub code: &'static str, + pub message: String, +} + +pub type ApiResult = std::result::Result; + +impl ApiError { + pub fn new(status: StatusCode, code: &'static str, message: impl Into) -> ApiError { + ApiError { status, code, message: message.into() } + } + + pub fn sign_in_required(message: impl Into) -> ApiError { + ApiError::new(StatusCode::UNAUTHORIZED, "sign_in_required", message) + } + + pub fn permission_denied(message: impl Into) -> ApiError { + ApiError::new(StatusCode::FORBIDDEN, "permission_denied", message) + } + + pub fn not_found() -> ApiError { + ApiError::new(StatusCode::NOT_FOUND, "not_found", "There is no such resource, or it is not shared with you") + } + + pub fn stale(message: impl Into) -> ApiError { + ApiError::new(StatusCode::CONFLICT, "stale", message) + } + + pub fn request_conflict() -> ApiError { + ApiError::new( + StatusCode::CONFLICT, + "request_conflict", + "This Idempotency-Key was already used for a different request", + ) + } + + pub fn moving() -> ApiError { + ApiError::new( + StatusCode::CONFLICT, + "host_moving", + "This record is moving to another host and accepts no changes", + ) + } + + pub fn limit(message: impl Into) -> ApiError { + ApiError::new(StatusCode::PAYLOAD_TOO_LARGE, "limit_reached", message) + } + + pub fn invalid(message: impl Into) -> ApiError { + ApiError::new(StatusCode::BAD_REQUEST, "invalid", message) + } + + pub fn refused(message: impl Into) -> ApiError { + ApiError::new(StatusCode::UNPROCESSABLE_ENTITY, "refused", message) + } + + /// An error whose details stay in the host's own log. The response names no + /// file path, credential, or record value. + pub fn internal(context: &str, error: impl std::fmt::Display) -> ApiError { + eprintln!("ath-host: {context}: {error}"); + ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", "The host could not finish this request") + } +} + +impl std::fmt::Display for ApiError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} ({}): {}", self.code, self.status.as_u16(), self.message) + } +} + +impl std::error::Error for ApiError {} + +impl From for ApiError { + fn from(error: athleticstandard::Error) -> ApiError { + match error.code() { + "invalid" => ApiError::invalid(error.to_string()), + "not_found" => ApiError::not_found(), + "stale" => ApiError::stale(error.to_string()), + "refused" => ApiError::refused(error.to_string()), + _ => ApiError::internal("library", error), + } + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let body = serde_json::json!({ "error": { "code": self.code, "message": self.message } }); + (self.status, Json(body)).into_response() + } +} diff --git a/host/src/lib.rs b/host/src/lib.rs new file mode 100644 index 00000000..bcd5229b --- /dev/null +++ b/host/src/lib.rs @@ -0,0 +1,60 @@ +//! `ath-host`: an optional program that serves many athletes' Athletic Standard records +//! over HTTPS (build-history/v2.1.3/spec.md). Every record operation goes through the +//! Athletic Standard library. The host adds sign-in, grants, receipts, and storage. + +pub mod api; +pub mod auth; +pub mod config; +pub mod db; +pub mod directory; +pub mod error; +pub mod moves; +pub mod objects; +pub mod package_zip; +pub mod storage; + +use std::sync::Arc; + +use crate::api::AppState; +use crate::config::{Config, StorageConfig}; +use crate::db::Db; +use crate::directory::Directory; + +pub fn version() -> &'static str { + env!("CARGO_PKG_VERSION") +} + +/// Open the directory the configuration names. +pub async fn open_directory(config: &Config) -> Result { + std::fs::create_dir_all(&config.data_directory) + .map_err(|error| format!("cannot create the data folder: {error}"))?; + let db = match &config.storage { + StorageConfig::Libsql { directory_url, token_env, .. } => { + Db::open_remote(directory_url, &Config::secret(token_env)?).await.map_err(|error| error.to_string())? + } + StorageConfig::Directory => { + Db::open_local(&config.data_directory.join("host.sqlite")).map_err(|error| error.to_string())? + } + // Host copies that share athletes' databases share the directory too. + StorageConfig::LocalServer { directory, .. } => { + std::fs::create_dir_all(directory).map_err(|error| error.to_string())?; + Db::open_local(&directory.join("host-directory.sqlite")).map_err(|error| error.to_string())? + } + }; + Directory::open(db).await.map_err(|error| error.to_string()) +} + +/// Everything a running host needs. +pub async fn state(config: Config) -> Result, String> { + let directory = open_directory(&config).await?; + directory.set_setting_once("receipt_key", &directory::new_code()).await.map_err(|error| error.to_string())?; + let receipt_key = directory + .setting("receipt_key") + .await + .map_err(|error| error.to_string())? + .ok_or("the receipt key is missing")?; + let storage = storage::Storage::new(&config)?; + storage.clear_working_copies(); + let verifier = auth::Verifier::new(config.sign_in.clone()); + Ok(Arc::new(AppState { config, directory, storage, verifier, receipt_key })) +} diff --git a/host/src/main.rs b/host/src/main.rs new file mode 100644 index 00000000..63459a17 --- /dev/null +++ b/host/src/main.rs @@ -0,0 +1,110 @@ +//! `ath-host serve`, `setup`, `invite`, and `version`. + +use std::path::PathBuf; +use std::time::Duration; + +fn usage() -> ! { + eprintln!( + "usage: + ath-host serve --config + ath-host setup --config --issuer --subject [--name ] + ath-host invite --config [--days ] + ath-host version" + ); + std::process::exit(2) +} + +fn option(args: &[String], name: &str) -> Option { + args.iter().position(|arg| arg == name).and_then(|index| args.get(index + 1)).cloned() +} + +fn config(args: &[String]) -> ath_host::config::Config { + let path = PathBuf::from(option(args, "--config").unwrap_or_else(|| usage())); + ath_host::config::Config::read(&path).unwrap_or_else(|error| fail(&error)) +} + +fn fail(message: &str) -> ! { + eprintln!("ath-host: {message}"); + std::process::exit(1) +} + +#[tokio::main] +async fn main() { + let args: Vec = std::env::args().skip(1).collect(); + match args.first().map(String::as_str) { + Some("version") | Some("--version") => println!("ath-host {}", ath_host::version()), + Some("serve") => serve(config(&args)).await, + Some("setup") => setup(config(&args), &args).await, + Some("invite") => invite(config(&args), &args).await, + _ => usage(), + } +} + +async fn serve(config: ath_host::config::Config) { + std::fs::create_dir_all(&config.data_directory).unwrap_or_else(|error| fail(&error.to_string())); + // One host process owns a data folder: in directory mode it holds the records. + let lock = std::fs::File::create(config.data_directory.join(".ath-host.lock")) + .unwrap_or_else(|error| fail(&error.to_string())); + if lock.try_lock().is_err() { + fail("another ath-host is using this data folder"); + } + let listen = config.listen.clone(); + let state = ath_host::state(config).await.unwrap_or_else(|error| fail(&error)); + let sweeper = state.clone(); + tokio::spawn(async move { + loop { + tokio::time::sleep(Duration::from_secs(60)).await; + sweeper.storage.sweep_idle(); + } + }); + let listener = tokio::net::TcpListener::bind(&listen) + .await + .unwrap_or_else(|error| fail(&format!("cannot listen on {listen}: {error}"))); + eprintln!("ath-host {} listening on {listen}", ath_host::version()); + axum::serve(listener, ath_host::api::router(state)) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await + .unwrap_or_else(|error| fail(&error.to_string())); + drop(lock); +} + +/// Claim the first owner, once, on the machine (D260): create their record. +async fn setup(config: ath_host::config::Config, args: &[String]) { + let issuer = option(args, "--issuer").unwrap_or_else(|| usage()); + let subject = option(args, "--subject").unwrap_or_else(|| usage()); + let state = ath_host::state(config).await.unwrap_or_else(|error| fail(&error)); + let claimed = state + .directory + .set_setting_once("first_owner", &format!("{issuer}\n{subject}")) + .await + .unwrap_or_else(|error| fail(&error.to_string())); + if !claimed { + fail("this host already has its first owner; use ath-host invite for more athletes"); + } + let principal = state + .directory + .principal(&issuer, &subject, option(args, "--name").as_deref()) + .await + .unwrap_or_else(|error| fail(&error.to_string())); + let athlete = state + .directory + .create_athlete(&principal.principal_id, option(args, "--name").as_deref()) + .await + .unwrap_or_else(|error| fail(&error.to_string())); + state.storage.create(&athlete.resource_id).await.unwrap_or_else(|error| fail(&error.to_string())); + println!("{}", athlete.resource_id); +} + +/// An invitation code that lets one person create their own record. +async fn invite(config: ath_host::config::Config, args: &[String]) { + let days: i64 = option(args, "--days").map(|days| days.parse().unwrap_or_else(|_| usage())).unwrap_or(7); + let state = ath_host::state(config).await.unwrap_or_else(|error| fail(&error)); + let offer = state + .directory + .create_athlete_invitation("operator", days.clamp(1, 90) * 24 * 3600) + .await + .unwrap_or_else(|error| fail(&error.to_string())); + println!("{}\nexpires {}", offer.code, offer.expires_at); +} diff --git a/host/src/moves.rs b/host/src/moves.rs new file mode 100644 index 00000000..96559779 --- /dev/null +++ b/host/src/moves.rs @@ -0,0 +1,9 @@ +//! Moving a record between hosts (D267). Built in step 8. + +use axum::Router; + +use crate::api::Shared; + +pub fn routes() -> Router { + Router::new() +} diff --git a/host/src/objects.rs b/host/src/objects.rs new file mode 100644 index 00000000..cdb16f47 --- /dev/null +++ b/host/src/objects.rs @@ -0,0 +1,94 @@ +//! Attachment files in an S3-compatible bucket (D259). Every request is a short-lived +//! signed URL, so any service that speaks the S3 protocol works: Amazon S3, +//! Cloudflare R2, Railway buckets, Supabase Storage, MinIO, and others. Keys are +//! `/attachments/`. The stored name contains the record ID, +//! so different files never share a key. + +use std::time::Duration; + +use rusty_s3::actions::{DeleteObject, GetObject, PutObject}; +use rusty_s3::{Bucket, Credentials, S3Action, UrlStyle}; + +use crate::config::{Config, S3Config}; +use crate::error::{ApiError, ApiResult}; + +const SIGNED_FOR: Duration = Duration::from_secs(300); + +#[derive(Clone)] +pub struct ObjectStore { + bucket: Bucket, + credentials: Credentials, +} + +impl ObjectStore { + pub fn new(config: &S3Config) -> Result { + let endpoint = config.endpoint.parse().map_err(|error| format!("the bucket endpoint is not a URL: {error}"))?; + let style = if config.path_style { UrlStyle::Path } else { UrlStyle::VirtualHost }; + let bucket = Bucket::new(endpoint, style, config.bucket.clone(), config.region.clone()) + .map_err(|error| format!("the bucket settings are not usable: {error}"))?; + let credentials = + Credentials::new(Config::secret(&config.access_key_env)?, Config::secret(&config.secret_key_env)?); + Ok(ObjectStore { bucket, credentials }) + } + + pub fn key(resource_id: &str, stored_name: &str) -> String { + format!("{resource_id}/attachments/{stored_name}") + } + + pub async fn put(&self, key: &str, bytes: Vec) -> ApiResult<()> { + let url = PutObject::new(&self.bucket, Some(&self.credentials), key).sign(SIGNED_FOR); + blocking("storing an attachment", move || { + ureq::put(url.as_str()) + .timeout(Duration::from_secs(120)) + .send_bytes(&bytes) + .map(|_| ()) + .map_err(|error| error.to_string()) + }) + .await + } + + /// The object's bytes, or `None` when there is no such object. + pub async fn get(&self, key: &str) -> ApiResult>> { + let url = GetObject::new(&self.bucket, Some(&self.credentials), key).sign(SIGNED_FOR); + blocking("reading an attachment", move || { + match ureq::get(url.as_str()).timeout(Duration::from_secs(120)).call() { + Ok(response) => { + let mut bytes = Vec::new(); + std::io::Read::read_to_end(&mut response.into_reader(), &mut bytes) + .map_err(|error| error.to_string())?; + Ok(Some(bytes)) + } + Err(ureq::Error::Status(404, _)) => Ok(None), + Err(error) => Err(error.to_string()), + } + }) + .await + } + + pub async fn delete(&self, key: &str) -> ApiResult<()> { + let url = DeleteObject::new(&self.bucket, Some(&self.credentials), key).sign(SIGNED_FOR); + blocking("removing an attachment", move || { + match ureq::delete(url.as_str()).timeout(Duration::from_secs(60)).call() { + Ok(_) | Err(ureq::Error::Status(404, _)) => Ok(()), + Err(error) => Err(error.to_string()), + } + }) + .await + } + + /// A short-lived link a client can download the object from. Issue it only after + /// the permission check (D259). + pub fn download_link(&self, key: &str) -> String { + GetObject::new(&self.bucket, Some(&self.credentials), key).sign(SIGNED_FOR).to_string() + } +} + +async fn blocking( + context: &'static str, + work: impl FnOnce() -> Result + Send + 'static, +) -> ApiResult { + tokio::task::spawn_blocking(work) + .await + .map_err(|error| ApiError::internal(context, error))? + .map_err(|error| ApiError::internal(context, error)) +} diff --git a/host/src/package_zip.rs b/host/src/package_zip.rs new file mode 100644 index 00000000..a569b1f7 --- /dev/null +++ b/host/src/package_zip.rs @@ -0,0 +1,55 @@ +//! A package folder as one zip file, for upload and download. Unpacking refuses any +//! entry that would land outside the target folder. + +use std::io::{Read, Write}; +use std::path::{Component, Path}; + +pub fn pack(folder: &Path) -> Result, String> { + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let mut stack = vec![folder.to_path_buf()]; + let mut files = Vec::new(); + while let Some(directory) = stack.pop() { + for entry in std::fs::read_dir(&directory).map_err(|error| error.to_string())? { + let path = entry.map_err(|error| error.to_string())?.path(); + if path.is_dir() { + stack.push(path); + } else { + files.push(path); + } + } + } + files.sort(); + for path in files { + let name = path.strip_prefix(folder).map_err(|error| error.to_string())?.to_string_lossy().replace('\\', "/"); + writer.start_file(name, options).map_err(|error| error.to_string())?; + writer + .write_all(&std::fs::read(&path).map_err(|error| error.to_string())?) + .map_err(|error| error.to_string())?; + } + Ok(writer.finish().map_err(|error| error.to_string())?.into_inner()) +} + +pub fn unpack(bytes: &[u8], folder: &Path) -> Result<(), String> { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|error| error.to_string())?; + std::fs::create_dir_all(folder).map_err(|error| error.to_string())?; + for index in 0..archive.len() { + let mut entry = archive.by_index(index).map_err(|error| error.to_string())?; + if entry.is_dir() { + continue; + } + let name = entry.name().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}")); + } + let target = folder.join(relative); + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let mut contents = Vec::new(); + entry.read_to_end(&mut contents).map_err(|error| error.to_string())?; + std::fs::write(&target, contents).map_err(|error| error.to_string())?; + } + Ok(()) +} diff --git a/host/src/storage.rs b/host/src/storage.rs new file mode 100644 index 00000000..be97278b --- /dev/null +++ b/host/src/storage.rs @@ -0,0 +1,647 @@ +//! Where athletes' databases live and how the host reads and writes them (D256, D257, +//! D268). +//! +//! **Directory mode.** Each athlete has a private folder in `data/athletes/` with an +//! ordinary database and its attachments. One host process owns the data folder; a +//! lock per athlete orders that athlete's writes. +//! +//! **Remote mode.** Each athlete has a database on a libSQL server (or, for tests, a +//! local file standing in for one) and attachments in an S3-compatible bucket. The +//! host keeps a working copy in `data/working/`. Every operation runs on the working +//! copy through the library, unchanged. A write's row changes are then committed to +//! the server in one transaction that first checks the database revision and access +//! epoch. If the check fails, the copy is discarded and the request runs again. + +use std::collections::{BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use athleticstandard::store::replica::{ + schema_scripts, Changeset, ReplayStatement, SqlValue, TableRows, TableShape, NOT_COPIED, +}; +use athleticstandard::store::{CreateOptions, OpenOptions, Store}; +use tokio::sync::{Mutex, OwnedMutexGuard}; + +use crate::config::{Config, Provision, StorageConfig}; +use crate::db::{first_integer, integer, text, Db}; +use crate::error::{ApiError, ApiResult}; +use crate::objects::ObjectStore; + +/// How many times a write runs again after the server moved on. +const ATTEMPTS: usize = 3; + +pub struct Storage { + data: PathBuf, + mode: Mode, + locks: std::sync::Mutex>>>, +} + +enum Mode { + Directory, + Remote(Box), +} + +struct Remote { + servers: Servers, + objects: ObjectStore, + shapes: Vec, + idle: Duration, + connections: Mutex>, + last_used: std::sync::Mutex>, +} + +enum Servers { + Libsql { url_template: String, token: String, provision: Provision }, + Local { directory: PathBuf }, +} + +impl Storage { + pub fn new(config: &Config) -> Result { + let data = config.data_directory.clone(); + std::fs::create_dir_all(data.join("staging")) + .map_err(|error| format!("cannot create the data folder: {error}"))?; + let mode = match &config.storage { + StorageConfig::Directory => { + std::fs::create_dir_all(data.join("athletes")).map_err(|error| error.to_string())?; + Mode::Directory + } + StorageConfig::Libsql { url_template, token_env, provision, attachments, .. } => { + Mode::Remote(Box::new(Remote::new( + &data, + Servers::Libsql { + url_template: url_template.clone(), + token: Config::secret(token_env)?, + provision: provision.clone(), + }, + ObjectStore::new(attachments)?, + config.limits.working_copy_idle_seconds, + )?)) + } + StorageConfig::LocalServer { directory, attachments } => { + std::fs::create_dir_all(directory).map_err(|error| error.to_string())?; + Mode::Remote(Box::new(Remote::new( + &data, + Servers::Local { directory: directory.clone() }, + ObjectStore::new(attachments)?, + config.limits.working_copy_idle_seconds, + )?)) + } + }; + Ok(Storage { data, mode, locks: std::sync::Mutex::new(HashMap::new()) }) + } + + pub fn is_remote(&self) -> bool { + matches!(self.mode, Mode::Remote(_)) + } + + pub fn staging(&self) -> PathBuf { + self.data.join("staging") + } + + /// The athlete's folder: the record in directory mode, the working copy in remote + /// mode. + fn folder(&self, resource_id: &str) -> PathBuf { + match self.mode { + Mode::Directory => self.data.join("athletes").join(resource_id), + Mode::Remote(_) => self.data.join("working").join(resource_id), + } + } + + fn database(&self, resource_id: &str) -> PathBuf { + self.folder(resource_id).join("athlete.ath.sqlite") + } + + async fn lock(&self, resource_id: &str) -> OwnedMutexGuard<()> { + let lock = self.locks.lock().expect("lock map").entry(resource_id.to_string()).or_default().clone(); + lock.lock_owned().await + } + + /// Create a new, empty record for a new athlete. + pub async fn create(&self, resource_id: &str) -> ApiResult { + let _guard = self.lock(resource_id).await; + match &self.mode { + Mode::Directory => { + let folder = self.folder(resource_id); + std::fs::create_dir_all(&folder) + .map_err(|error| ApiError::internal("creating a record folder", error))?; + let path = self.database(resource_id); + blocking(move || Store::create(&path, CreateOptions::default())?.database_revision()).await + } + Mode::Remote(remote) => { + let server = remote.provision(resource_id).await?; + let database_id = athleticstandard::ids::new_record_id(); + let created_at = crate::directory::now(); + for script in schema_scripts(&database_id, &created_at) { + server + .execute_batch(&script) + .await + .map_err(|error| ApiError::internal("creating a database", error))?; + } + remote.current(self, resource_id).await + } + } + } + + /// Run a read on the athlete's record. + pub async fn read( + &self, + resource_id: &str, + read: impl FnOnce(&Store) -> athleticstandard::Result + Send + 'static, + ) -> ApiResult { + let _guard = self.lock(resource_id).await; + if let Mode::Remote(remote) = &self.mode { + remote.current(self, resource_id).await?; + } + let path = self.database(resource_id); + blocking(move || { + let store = Store::open(&path, OpenOptions::default())?; + read(&store) + }) + .await + } + + /// Run a write. `guard_epoch` is the access epoch read before the grant check, for + /// a write made under a grant (D262). The write is given it so the library can + /// check it in directory mode; in remote mode the server check uses it. + pub async fn write( + &self, + resource_id: &str, + guard_epoch: Option, + write: impl Fn(&mut Store, Option) -> athleticstandard::Result + Send + Sync + 'static, + ) -> ApiResult { + let write = Arc::new(write); + match &self.mode { + Mode::Directory => { + let _guard = self.lock(resource_id).await; + let path = self.database(resource_id); + let value = blocking(move || { + let mut store = Store::open(&path, OpenOptions::default())?; + write(&mut store, guard_epoch) + }) + .await?; + Ok(value) + } + Mode::Remote(remote) => { + for attempt in 1..=ATTEMPTS { + let _guard = self.lock(resource_id).await; + remote.current(self, resource_id).await?; + let (_, epoch) = remote.revision_and_epoch(resource_id).await?; + if let Some(expected) = guard_epoch { + if expected != epoch { + return Err(ApiError::stale( + "Access to this record changed while the request was waiting; check the grant and try again", + )); + } + } + let path = self.database(resource_id); + let attachments = path.parent().expect("record folder").join("attachments"); + let before = file_names(&attachments); + let write = write.clone(); + let captured = blocking(move || { + let mut store = Store::open(&path, OpenOptions::default())?; + let captured = store.capture(|store| write(store, None))?; + let statements = store.replay_statements(&captured.changeset)?; + Ok((captured, statements)) + }) + .await; + let (captured, statements) = match captured { + Ok(result) => result, + Err(error) => { + // The library rolled the operation back; the copy is intact. + return Err(error); + } + }; + if captured.changeset.is_empty() { + return Ok(captured.value); + } + let after = file_names(&attachments); + let outcome = async { + for name in after.difference(&before) { + let bytes = std::fs::read(attachments.join(name)) + .map_err(|error| ApiError::internal("reading a new attachment", error))?; + remote.objects.put(&ObjectStore::key(resource_id, name), bytes).await?; + } + remote + .commit( + resource_id, + captured.base_revision, + captured.new_revision, + guard_epoch.unwrap_or(epoch), + &captured.changeset, + &statements, + ) + .await?; + for name in before.difference(&after) { + remote.objects.delete(&ObjectStore::key(resource_id, name)).await?; + } + Ok::<(), ApiError>(()) + } + .await; + match outcome { + Ok(()) => return Ok(captured.value), + Err(error) => { + // The copy is ahead of the server. Discard it. + remote.discard(self, resource_id); + if error.code == "stale" && attempt < ATTEMPTS && guard_epoch.is_none() { + continue; + } + return Err(error); + } + } + } + Err(ApiError::stale("The record kept changing; try again")) + } + } + } + + /// The access epoch: in the record in directory mode, on the server in remote mode. + pub async fn access_epoch(&self, resource_id: &str) -> ApiResult { + match &self.mode { + Mode::Directory => self.read(resource_id, |store| store.current_access_epoch()).await, + Mode::Remote(remote) => Ok(remote.revision_and_epoch(resource_id).await?.1), + } + } + + /// Raise the access epoch after a grant is revoked (D262). + pub async fn raise_access_epoch(&self, resource_id: &str) -> ApiResult { + let _guard = self.lock(resource_id).await; + match &self.mode { + Mode::Directory => { + let path = self.database(resource_id); + blocking(move || Store::open(&path, OpenOptions::default())?.raise_access_epoch()).await + } + Mode::Remote(remote) => { + let server = remote.server(resource_id).await?; + server + .execute( + "UPDATE internal_access_state SET access_epoch = access_epoch + 1 WHERE singleton_id = 1", + Vec::new(), + ) + .await + .map_err(|error| ApiError::internal("raising the access epoch", error))?; + Ok(remote.revision_and_epoch(resource_id).await?.1) + } + } + } + + /// Make sure every attachment file the record names is in the local folder, so + /// export and download work. In directory mode they always are. + pub async fn ensure_attachment_files(&self, resource_id: &str) -> ApiResult<()> { + let Mode::Remote(remote) = &self.mode else { + return Ok(()); + }; + let path = self.database(resource_id); + let names = self + .read(resource_id, move |store| { + let records = store.list_records(&athleticstandard::store::read::ListOptions { + record_type: Some(athleticstandard::model::RecordType::Attachment), + include_deleted: true, + limit: 10_000, + })?; + Ok(records + .into_iter() + .filter_map(|record| match &record.data { + athleticstandard::model::RecordData::Attachment(data) => { + Some(athleticstandard::files::attachments::stored_attachment_name(&record.record_id, data)) + } + _ => None, + }) + .collect::>()) + }) + .await?; + let folder = path.parent().expect("record folder").join("attachments"); + for name in names { + let target = folder.join(&name); + if target.exists() { + continue; + } + let bytes = remote.objects.get(&ObjectStore::key(resource_id, &name)).await?.ok_or_else(|| { + ApiError::internal("reading an attachment", format!("missing object for {resource_id}")) + })?; + std::fs::create_dir_all(&folder) + .map_err(|error| ApiError::internal("creating an attachment folder", error))?; + std::fs::write(&target, bytes).map_err(|error| ApiError::internal("writing an attachment", error))?; + } + Ok(()) + } + + /// The bytes of one attachment file, after the permission check. + pub async fn attachment_bytes(&self, resource_id: &str, stored_name: &str) -> ApiResult> { + self.ensure_attachment_files(resource_id).await?; + let path = self.folder(resource_id).join("attachments").join(stored_name); + std::fs::read(&path).map_err(|_| ApiError::not_found()) + } + + /// Delete idle working copies (D268). Directory mode keeps every record. + pub fn sweep_idle(&self) { + if let Mode::Remote(remote) = &self.mode { + let idle: Vec = remote + .last_used + .lock() + .expect("last-used map") + .iter() + .filter(|(_, used)| used.elapsed() > remote.idle) + .map(|(id, _)| id.clone()) + .collect(); + for id in idle { + if let Ok(lock) = + self.locks.lock().expect("lock map").entry(id.clone()).or_default().clone().try_lock_owned() + { + remote.discard(self, &id); + drop(lock); + } + } + } + } + + /// Remove every working copy, as the host does when it starts (D268). + pub fn clear_working_copies(&self) { + if self.is_remote() { + let _ = std::fs::remove_dir_all(self.data.join("working")); + } + } +} + +impl Remote { + fn new(data: &Path, servers: Servers, objects: ObjectStore, idle_seconds: u64) -> Result { + let working = data.join("working"); + std::fs::create_dir_all(&working).map_err(|error| error.to_string())?; + let template = data.join("staging").join("schema-template.ath.sqlite"); + let _ = std::fs::remove_file(&template); + let store = Store::create(&template, CreateOptions::default()).map_err(|error| error.to_string())?; + let shapes = store.table_shapes().map_err(|error| error.to_string())?; + drop(store); + let _ = std::fs::remove_file(&template); + Ok(Remote { + servers, + objects, + shapes, + idle: Duration::from_secs(idle_seconds), + connections: Mutex::new(HashMap::new()), + last_used: std::sync::Mutex::new(HashMap::new()), + }) + } + + fn database_name(resource_id: &str) -> String { + resource_id.replace('_', "-") + } + + async fn server(&self, resource_id: &str) -> ApiResult { + if let Some(db) = self.connections.lock().await.get(resource_id) { + return Ok(db.clone()); + } + let db = match &self.servers { + Servers::Local { directory } => { + let path = directory.join(format!("{}.sqlite", Remote::database_name(resource_id))); + if !path.exists() { + return Err(ApiError::not_found()); + } + Db::open_local(&path).map_err(|error| ApiError::internal("opening a server database", error))? + } + Servers::Libsql { url_template, token, .. } => { + let url = url_template.replace("{database}", &Remote::database_name(resource_id)); + Db::open_remote(&url, token) + .await + .map_err(|error| ApiError::internal("opening a server database", error))? + } + }; + self.connections.lock().await.insert(resource_id.to_string(), db.clone()); + Ok(db) + } + + /// Create the athlete's database on the server. + async fn provision(&self, resource_id: &str) -> ApiResult { + let name = Remote::database_name(resource_id); + match &self.servers { + Servers::Local { directory } => { + let path = directory.join(format!("{name}.sqlite")); + Db::open_local(&path).map_err(|error| ApiError::internal("creating a server database", error))?; + } + Servers::Libsql { provision, .. } => { + let provision = provision.clone(); + let name = name.clone(); + tokio::task::spawn_blocking(move || provision_database(&provision, &name)) + .await + .map_err(|error| ApiError::internal("creating a server database", error))? + .map_err(|error| ApiError::internal("creating a server database", error))?; + } + } + self.server(resource_id).await + } + + async fn revision_and_epoch(&self, resource_id: &str) -> ApiResult<(u64, u64)> { + let server = self.server(resource_id).await?; + let rows = server + .query( + "SELECT (SELECT current_revision FROM database_state WHERE singleton_id = 1), + (SELECT access_epoch FROM internal_access_state WHERE singleton_id = 1)", + Vec::new(), + ) + .await + .map_err(|error| ApiError::internal("reading the server revision", error))?; + let row = rows.first().ok_or_else(|| ApiError::internal("reading the server revision", "no row"))?; + match (row.first().and_then(integer), row.get(1).and_then(integer)) { + (Some(revision), Some(epoch)) => Ok((revision as u64, epoch as u64)), + _ => Err(ApiError::internal("reading the server revision", "the database is not initialized")), + } + } + + /// Bring the working copy to the server's revision and return that revision. + async fn current(&self, storage: &Storage, resource_id: &str) -> ApiResult { + self.last_used.lock().expect("last-used map").insert(resource_id.to_string(), Instant::now()); + let (revision, _) = self.revision_and_epoch(resource_id).await?; + let path = storage.database(resource_id); + if path.exists() { + let copy_path = path.clone(); + let copy_revision = + blocking(move || Store::open(©_path, OpenOptions::default())?.database_revision()).await; + match copy_revision { + Ok(copy) if copy == revision => return Ok(revision), + Ok(copy) if copy < revision => { + if let Some(entries) = self.log_after(resource_id, copy, revision).await? { + let copy_path = path.clone(); + let caught_up = blocking(move || { + let mut store = Store::open(©_path, OpenOptions::default())?; + for (base, _, changeset) in &entries { + let epoch = store.access_epoch()?; + store.replay(*base, epoch, changeset)?; + } + store.database_revision() + }) + .await; + if caught_up.as_ref().is_ok_and(|reached| *reached == revision) { + return Ok(revision); + } + } + } + _ => {} + } + } + self.rebuild(storage, resource_id).await?; + Ok(revision) + } + + async fn log_after( + &self, + resource_id: &str, + revision: u64, + current: u64, + ) -> ApiResult>> { + let server = self.server(resource_id).await?; + let rows = server + .query( + "SELECT base_revision, database_revision, changeset FROM internal_replication_log + WHERE database_revision > ?1 ORDER BY database_revision", + vec![SqlValue::Integer(revision as i64)], + ) + .await + .map_err(|error| ApiError::internal("reading the replication log", error))?; + let mut at = revision; + let mut entries = Vec::new(); + for row in rows { + let (Some(base), Some(new), Some(json)) = + (row.first().and_then(integer), row.get(1).and_then(integer), row.get(2).and_then(text)) + else { + return Ok(None); + }; + if base as u64 != at { + return Ok(None); + } + entries.push((base as u64, new as u64, Changeset::from_json(json)?)); + at = new as u64; + } + Ok((at == current).then_some(entries)) + } + + async fn rebuild(&self, storage: &Storage, resource_id: &str) -> ApiResult<()> { + let server = self.server(resource_id).await?; + let mut tables = Vec::new(); + for shape in &self.shapes { + if NOT_COPIED.contains(&shape.name.as_str()) { + continue; + } + let columns = shape.columns.iter().map(|column| format!("\"{column}\"")).collect::>().join(", "); + let order = shape.primary_key.iter().map(|column| format!("\"{column}\"")).collect::>().join(", "); + let rows = server + .query(&format!("SELECT {columns} FROM \"{}\" ORDER BY {order}", shape.name), Vec::new()) + .await + .map_err(|error| ApiError::internal("copying a server database", error))?; + tables.push(TableRows { table: shape.name.clone(), columns: shape.columns.clone(), rows }); + } + let folder = storage.folder(resource_id); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).map_err(|error| ApiError::internal("creating a working copy", error))?; + let path = storage.database(resource_id); + blocking(move || Store::build_working_copy(&path, &tables).map(|_| ())).await + } + + fn discard(&self, storage: &Storage, resource_id: &str) { + let _ = std::fs::remove_dir_all(storage.folder(resource_id)); + self.last_used.lock().expect("last-used map").remove(resource_id); + } + + /// Commit a changeset to the server in one transaction (D268). + async fn commit( + &self, + resource_id: &str, + base_revision: u64, + new_revision: u64, + access_epoch: u64, + changeset: &Changeset, + statements: &[ReplayStatement], + ) -> ApiResult<()> { + let server = self.server(resource_id).await?; + let failed = |error: crate::db::DbError| ApiError::internal("committing to the server", error); + let mut transaction = server.transaction().await.map_err(failed)?; + let rows = transaction + .query( + "SELECT (SELECT current_revision FROM database_state WHERE singleton_id = 1), + (SELECT access_epoch FROM internal_access_state WHERE singleton_id = 1)", + Vec::new(), + ) + .await + .map_err(failed)?; + let row = rows.first().cloned().unwrap_or_default(); + let (revision, epoch) = (row.first().and_then(integer), row.get(1).and_then(integer)); + if revision != Some(base_revision as i64) || epoch != Some(access_epoch as i64) { + return Err(ApiError::stale("The record changed on the server; the request will run again")); + } + transaction + .execute( + "INSERT INTO internal_replication_log (database_revision, base_revision, changeset, committed_at) VALUES (?1, ?2, ?3, ?4)", + vec![ + SqlValue::Integer(new_revision as i64), + SqlValue::Integer(base_revision as i64), + SqlValue::Text(changeset.to_json()), + SqlValue::Text(crate::directory::now()), + ], + ) + .await + .map_err(failed)?; + for statement in statements { + let changed = transaction.execute(&statement.sql, statement.params.clone()).await.map_err(failed)?; + if !statement.accepts(changed) { + return Err(ApiError::stale(format!("A change to {} did not apply on the server", statement.table))); + } + } + let ended = first_integer( + &transaction + .query("SELECT current_revision FROM database_state WHERE singleton_id = 1", Vec::new()) + .await + .map_err(failed)?, + ); + if ended != Some(new_revision as i64) { + return Err(ApiError::internal("committing to the server", "the changeset ended at another revision")); + } + transaction.commit().await.map_err(failed) + } +} + +/// Create one database on the server. Runs on a blocking thread. +fn provision_database(provision: &Provision, name: &str) -> Result<(), String> { + match provision { + Provision::Existing => Ok(()), + Provision::Turso { organization, group, platform_token_env } => { + let token = Config::secret(platform_token_env)?; + let response = ureq::post(&format!("https://api.turso.tech/v1/organizations/{organization}/databases")) + .set("Authorization", &format!("Bearer {token}")) + .timeout(Duration::from_secs(60)) + .send_json(serde_json::json!({ "name": name, "group": group })); + match response { + Ok(_) | Err(ureq::Error::Status(409, _)) => Ok(()), + Err(error) => Err(format!("Turso did not create the database: {error}")), + } + } + Provision::SqldAdmin { admin_url } => { + let response = ureq::post(&format!("{}/v1/namespaces/{name}/create", admin_url.trim_end_matches('/'))) + .timeout(Duration::from_secs(60)) + .send_json(serde_json::json!({})); + match response { + Ok(_) | Err(ureq::Error::Status(409, _)) => Ok(()), + Err(error) => Err(format!("the libSQL server did not create the namespace: {error}")), + } + } + } +} + +fn file_names(folder: &Path) -> BTreeSet { + std::fs::read_dir(folder) + .map(|entries| { + entries + .filter_map(|entry| entry.ok()) + .filter(|entry| entry.path().is_file()) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .collect() + }) + .unwrap_or_default() +} + +async fn blocking( + work: impl FnOnce() -> athleticstandard::Result + Send + 'static, +) -> ApiResult { + tokio::task::spawn_blocking(work) + .await + .map_err(|error| ApiError::internal("a worker thread", error))? + .map_err(ApiError::from) +} diff --git a/host/tests/host_api.rs b/host/tests/host_api.rs new file mode 100644 index 00000000..a2f847b3 --- /dev/null +++ b/host/tests/host_api.rs @@ -0,0 +1,420 @@ +//! The host API end to end, in directory mode and in remote mode with a stand-in +//! server and bucket (spec 2.1.3 build steps 5–7). + +mod support; + +use std::collections::BTreeSet; + +use athleticstandard::model::RecordType; +use athleticstandard::store::read::ListOptions; +use athleticstandard::store::{Changes, NewRecord}; +use serde_json::json; +use support::*; + +struct Setup { + hosts: Vec, + _bucket: Option, +} + +fn directory_host() -> Setup { + let jwks = key_server(); + Setup { hosts: vec![host(config(&temporary("ath-host-dir-"), Mode::Directory, &jwks))], _bucket: None } +} + +/// `copies` host processes sharing one stand-in server and one bucket. +fn remote_hosts(copies: usize) -> Setup { + let jwks = key_server(); + let (bucket_url, bucket) = bucket_server(); + let server = temporary("ath-host-server-"); + let hosts = (0..copies) + .map(|_| { + host(config( + &temporary("ath-host-remote-"), + Mode::LocalServer { server: &server, bucket: &bucket_url }, + &jwks, + )) + }) + .collect(); + Setup { hosts, _bucket: Some(bucket) } +} + +fn create_athlete(host: &Host, owner: &str) -> String { + let reply = call("POST", &format!("{}/v1/athletes", host.url), owner, Some(json!({})), None); + assert_eq!(reply.status, 201, "{}", reply.json); + reply.json["athlete_id"].as_str().unwrap().to_string() +} + +fn athlete_url(host: &Host, id: &str, rest: &str) -> String { + format!("{}/v1/athletes/{id}{rest}", host.url) +} + +// ---- Step 5: an owner saves a report with a photo and opens both elsewhere -------- + +fn report_with_photo(host: &Host) { + let owner = token("athlete-1", ATHLETE_APP); + let id = create_athlete(host, &owner); + + let uploaded = send_bytes("POST", &athlete_url(host, &id, "/uploads"), &owner, &demo_photo()); + assert_eq!(uploaded.status, 201, "{}", uploaded.json); + let upload_id = uploaded.json["upload_id"].as_str().unwrap().to_string(); + + let request = + json!({ "record_type": "athlete_report", "data": report("Felt strong."), "attachments": [upload_id] }); + let created = call("POST", &athlete_url(host, &id, "/records"), &owner, Some(request.clone()), Some("report-1")); + assert_eq!(created.status, 201, "{}", created.json); + assert_eq!(created.json["records"].as_array().unwrap().len(), 2, "the attachment and the report"); + + // A retry after a lost reply returns the same result and writes nothing new. + let again = call("POST", &athlete_url(host, &id, "/records"), &owner, Some(request), Some("report-1")); + assert_eq!(again.json, created.json); + // The same key with a different body is a conflict. + let other = json!({ "record_type": "athlete_report", "data": report("Something else.") }); + let conflict = call("POST", &athlete_url(host, &id, "/records"), &owner, Some(other), Some("report-1")); + assert_eq!((conflict.status, conflict.json["error"]["code"].as_str()), (409, Some("request_conflict"))); + // A write without a key is refused. + let unkeyed = call( + "POST", + &athlete_url(host, &id, "/records"), + &owner, + Some(json!({ "record_type": "athlete_report", "data": report("x") })), + None, + ); + assert_eq!(unkeyed.status, 400); + + let exported = call("GET", &athlete_url(host, &id, "/export"), &owner, None, None); + assert_eq!(exported.status, 200); + assert_eq!(exported.headers.get("x-manifest-digest").map(String::len), Some(64)); + let (_, device) = open_on_another_device(&exported.bytes); + let reports = device + .list_records(&ListOptions { record_type: Some(RecordType::AthleteReport), include_deleted: false, limit: 100 }) + .unwrap(); + assert_eq!(reports.len(), 1); + let attachments = device + .list_records(&ListOptions { record_type: Some(RecordType::Attachment), include_deleted: false, limit: 100 }) + .unwrap(); + assert_eq!(attachments.len(), 1); + let athleticstandard::model::RecordData::Attachment(data) = &attachments[0].data else { panic!() }; + let name = athleticstandard::files::attachments::stored_attachment_name(&attachments[0].record_id, data); + let copied = std::fs::read(device.path().parent().unwrap().join("attachments").join(name)).unwrap(); + assert_eq!(copied, demo_photo(), "the photo arrived byte for byte"); + + let download = + call("GET", &athlete_url(host, &id, &format!("/attachments/{}", attachments[0].record_id)), &owner, None, None); + assert_eq!((download.status, download.bytes.clone()), (200, demo_photo())); + + let changes = call("GET", &athlete_url(host, &id, "/changes?since=0"), &owner, None, None); + assert_eq!(changes.json["complete"], json!(true)); + assert_eq!(changes.json["changes"].as_array().unwrap().len(), 2); + + // Someone else cannot tell the record exists. + let stranger = token("athlete-2", ATHLETE_APP); + for path in ["", "/export", "/records", "/changes?since=0"] { + assert_eq!(call("GET", &athlete_url(host, &id, path), &stranger, None, None).status, 404, "{path}"); + } +} + +#[test] +fn directory_mode_saves_a_report_with_a_photo() { + report_with_photo(&directory_host().hosts[0]); +} + +#[test] +fn remote_mode_saves_a_report_with_a_photo() { + let setup = remote_hosts(1); + report_with_photo(&setup.hosts[0]); + let objects = setup._bucket.as_ref().unwrap().objects.lock().unwrap(); + assert_eq!(objects.len(), 1, "the photo is in the bucket"); +} + +// ---- Step 6: a coach sees and adds only what was granted -------------------------- + +fn coach_flow(host: &Host) { + let owner = token("athlete-1", ATHLETE_APP); + let id = create_athlete(host, &owner); + let restored = send_bytes("PUT", &athlete_url(host, &id, "/package"), &owner, &demo_package_zip()); + assert_eq!(restored.status, 200, "{}", restored.json); + let other_owner = token("athlete-2", ATHLETE_APP); + let other_id = create_athlete(host, &other_owner); + + let offer = call( + "POST", + &athlete_url(host, &id, "/grant-offers"), + &owner, + Some( + json!({ "permissions": ["read_workout_summaries", "add_coach_notes"], "client_id": COACH_APP, "coach_label": "Coach Sam" }), + ), + None, + ); + assert_eq!(offer.status, 201, "{}", offer.json); + let code = offer.json["code"].as_str().unwrap(); + + // The offer is for the coach app; another app cannot accept it. + let coach_elsewhere = token("coach-1", ATHLETE_APP); + assert_eq!( + call( + "POST", + &format!("{}/v1/grant-offers/accept", host.url), + &coach_elsewhere, + Some(json!({ "code": code })), + None + ) + .status, + 404 + ); + let coach = token("coach-1", COACH_APP); + let accepted = + call("POST", &format!("{}/v1/grant-offers/accept", host.url), &coach, Some(json!({ "code": code })), None); + assert_eq!(accepted.status, 200, "{}", accepted.json); + // A code works once. + assert_eq!( + call("POST", &format!("{}/v1/grant-offers/accept", host.url), &coach, Some(json!({ "code": code })), None) + .status, + 404 + ); + + let roster = call("GET", &format!("{}/v1/roster", host.url), &coach, None, None); + let listed: Vec<&str> = + roster.json["athletes"].as_array().unwrap().iter().map(|a| a["athlete_id"].as_str().unwrap()).collect(); + assert_eq!(listed, vec![id.as_str()]); + + let workouts = call("GET", &athlete_url(host, &id, "/workouts"), &coach, None, None); + assert_eq!(workouts.status, 200, "{}", workouts.json); + let list = workouts.json["workouts"].as_array().unwrap(); + assert!(!list.is_empty()); + for summary in list { + let keys: BTreeSet<&str> = summary.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys, BTreeSet::from(["record_id", "revision", "start_at", "end_at", "activity_type"])); + } + let workout = &list[0]; + + let note = json!({ "note": "Review pacing at the next session.", "evidence": [{ "record_id": workout["record_id"], "revision": workout["revision"] }] }); + let added = call("POST", &athlete_url(host, &id, "/notes"), &coach, Some(note.clone()), Some("note-1")); + assert_eq!(added.status, 201, "{}", added.json); + assert_eq!(call("POST", &athlete_url(host, &id, "/notes"), &coach, Some(note), Some("note-1")).json, added.json); + let bad_evidence = json!({ "note": "x", "evidence": [{ "record_id": workout["record_id"], "revision": 99 }] }); + assert_eq!(call("POST", &athlete_url(host, &id, "/notes"), &coach, Some(bad_evidence), Some("note-2")).status, 422); + + // Not granted: programming, owner reads, the other athlete, the other app. + let program = json!({ "plan": { "title": "Base block" }, "sessions": [] }); + assert_eq!( + call("POST", &athlete_url(host, &id, "/programs"), &coach, Some(program), Some("program-1")).status, + 403 + ); + assert_eq!(call("GET", &athlete_url(host, &id, "/export"), &coach, None, None).status, 403); + assert_eq!(call("GET", &athlete_url(host, &id, "/records"), &coach, None, None).status, 403); + assert_eq!(call("GET", &athlete_url(host, &other_id, "/workouts"), &coach, None, None).status, 404); + assert_eq!(call("GET", &athlete_url(host, &id, "/workouts"), &coach_elsewhere, None, None).status, 404); + + // The note keeps its coach author, with the host's coach ID. + let me = call("GET", &format!("{}/v1/me", host.url), &coach, None, None); + let note_id = added.json["records"][0]["record_id"].as_str().unwrap(); + let stored = call("GET", &athlete_url(host, &id, &format!("/records/{note_id}")), &owner, None, None); + let author = &stored.json["record"]["data"]["authorship"]["author"]; + assert_eq!(author["author_type"], json!("coach")); + assert_eq!(author["coach"], json!("Coach Sam")); + assert_eq!(author["coach_id"], me.json["coach_id"]); + assert_eq!(stored.json["revisions"][0]["changed_by"]["author_type"], json!("coach")); + + // Revoking stops the next request. + let grants = call("GET", &athlete_url(host, &id, "/grants"), &owner, None, None); + let grant_id = grants.json["grants"][0]["grant_id"].as_str().unwrap().to_string(); + let revoked = call("DELETE", &athlete_url(host, &id, &format!("/grants/{grant_id}")), &owner, None, None); + assert_eq!(revoked.status, 200, "{}", revoked.json); + assert_eq!(call("GET", &athlete_url(host, &id, "/workouts"), &coach, None, None).status, 404); + assert_eq!( + call("POST", &athlete_url(host, &id, "/notes"), &coach, Some(json!({ "note": "late" })), Some("note-3")).status, + 404 + ); + assert!(call("GET", &format!("{}/v1/roster", host.url), &coach, None, None).json["athletes"] + .as_array() + .unwrap() + .is_empty()); +} + +#[test] +fn directory_mode_coach_sees_only_what_was_granted() { + coach_flow(&directory_host().hosts[0]); +} + +#[test] +fn remote_mode_coach_sees_only_what_was_granted() { + coach_flow(&remote_hosts(1).hosts[0]); +} + +fn programming(host: &Host) { + let owner = token("athlete-1", ATHLETE_APP); + let id = create_athlete(host, &owner); + let offer = call( + "POST", + &athlete_url(host, &id, "/grant-offers"), + &owner, + Some(json!({ "permissions": ["add_programming"], "client_id": COACH_APP })), + None, + ); + let coach = token("coach-1", COACH_APP); + call( + "POST", + &format!("{}/v1/grant-offers/accept", host.url), + &coach, + Some(json!({ "code": offer.json["code"] })), + None, + ); + let program = json!({ + "plan": { "title": "Base block", "objective": "Build an aerobic base" }, + "sessions": [ + { "title": "Easy row", "scheduled_date": "2026-12-01", "blocks": [{ "block_type": "main", "title": "30 minutes easy" }] }, + { "title": "Intervals", "scheduled_date": "2026-12-03", "blocks": [{ "block_type": "main", "title": "6 x 500 m" }] } + ] + }); + let added = call("POST", &athlete_url(host, &id, "/programs"), &coach, Some(program), Some("program-1")); + assert_eq!(added.status, 201, "{}", added.json); + assert_eq!(added.json["records"].as_array().unwrap().len(), 3); + let forbidden = json!({ "plan": { "title": "x" }, "sessions": [{ "title": "Done", "scheduled_date": "2026-12-01", "blocks": [], "completion_status": "completed" }] }); + assert_eq!( + call("POST", &athlete_url(host, &id, "/programs"), &coach, Some(forbidden), Some("program-2")).status, + 400 + ); + // The coach cannot write notes or read workouts with only programming. + assert_eq!( + call("POST", &athlete_url(host, &id, "/notes"), &coach, Some(json!({ "note": "x" })), Some("n")).status, + 403 + ); + assert_eq!(call("GET", &athlete_url(host, &id, "/workouts"), &coach, None, None).status, 403); +} + +#[test] +fn directory_mode_coach_adds_a_program() { + programming(&directory_host().hosts[0]); +} + +#[test] +fn remote_mode_coach_adds_a_program() { + programming(&remote_hosts(1).hosts[0]); +} + +/// A write that read the access epoch before a revocation and commits after it fails +/// (D262), in both modes. +fn revocation_blocks_a_waiting_write(host: &Host) { + let owner = token("athlete-1", ATHLETE_APP); + let id = create_athlete(host, &owner); + let storage = &host.state.storage; + let epoch = runtime().block_on(storage.access_epoch(&id)).unwrap(); + runtime().block_on(storage.raise_access_epoch(&id)).unwrap(); + let note = athleticstandard::model::RecordData::decode( + RecordType::AthleteReport, + &athleticstandard::json::parse(&report("written under an old grant").to_string()).unwrap(), + ) + .unwrap(); + let result = runtime().block_on(storage.write(&id, Some(epoch), move |store, epoch| { + store.apply(Changes { + expected_access_epoch: epoch, + creates: vec![NewRecord::new(note.clone(), athleticstandard::model::RecordActor::Athlete)], + ..Changes::default() + }) + })); + let error = result.expect_err("the write is refused"); + assert_eq!(error.code, "stale", "{error}"); + let count = runtime() + .block_on(storage.read(&id, |store| { + store.list_records(&ListOptions { + record_type: Some(RecordType::AthleteReport), + include_deleted: false, + limit: 10, + }) + })) + .unwrap() + .len(); + assert_eq!(count, 0, "nothing was written"); +} + +#[test] +fn directory_mode_revocation_blocks_a_waiting_write() { + revocation_blocks_a_waiting_write(&directory_host().hosts[0]); +} + +#[test] +fn remote_mode_revocation_blocks_a_waiting_write() { + revocation_blocks_a_waiting_write(&remote_hosts(1).hosts[0]); +} + +// ---- Step 7: several host copies share one record -------------------------------- + +#[test] +fn two_host_copies_share_a_record() { + let setup = remote_hosts(2); + let (a, b) = (&setup.hosts[0], &setup.hosts[1]); + let owner = token("athlete-1", ATHLETE_APP); + let id = create_athlete(a, &owner); + + let first = call( + "POST", + &athlete_url(a, &id, "/records"), + &owner, + Some(json!({ "record_type": "athlete_report", "data": report("From host A.") })), + Some("a-1"), + ); + assert_eq!(first.status, 201, "{}", first.json); + // B builds its working copy from the server and sees A's write. + let listed = call("GET", &athlete_url(b, &id, "/records?record_type=athlete_report"), &owner, None, None); + assert_eq!(listed.json["records"].as_array().unwrap().len(), 1); + + // B writes; A catches up from the replication log. + let second = call( + "POST", + &athlete_url(b, &id, "/records"), + &owner, + Some(json!({ "record_type": "athlete_report", "data": report("From host B.") })), + Some("b-1"), + ); + assert_eq!(second.status, 201, "{}", second.json); + let third = call( + "POST", + &athlete_url(a, &id, "/records"), + &owner, + Some(json!({ "record_type": "athlete_report", "data": report("A again.") })), + Some("a-2"), + ); + assert_eq!(third.status, 201, "{}", third.json); + for host in [a, b] { + let listed = call("GET", &athlete_url(host, &id, "/records?record_type=athlete_report"), &owner, None, None); + assert_eq!(listed.json["records"].as_array().unwrap().len(), 3); + } + // A retry sent to the other copy returns the original result. + let retried = call( + "POST", + &athlete_url(b, &id, "/records"), + &owner, + Some(json!({ "record_type": "athlete_report", "data": report("From host A.") })), + Some("a-1"), + ); + assert_eq!(retried.json, first.json); + + // A photo saved through A downloads through B. + let uploaded = send_bytes("POST", &athlete_url(a, &id, "/uploads"), &owner, &demo_photo()); + let with_photo = json!({ "record_type": "athlete_report", "data": report("Photo."), "attachments": [uploaded.json["upload_id"]] }); + let created = call("POST", &athlete_url(a, &id, "/records"), &owner, Some(with_photo), Some("a-3")); + assert_eq!(created.status, 201, "{}", created.json); + let attachment_id = created.json["records"][0]["record_id"].as_str().unwrap(); + let download = call("GET", &athlete_url(b, &id, &format!("/attachments/{attachment_id}")), &owner, None, None); + assert_eq!((download.status, download.bytes), (200, demo_photo())); + + // Exports from both copies are identical. + let export_a = call("GET", &athlete_url(a, &id, "/export"), &owner, None, None); + let export_b = call("GET", &athlete_url(b, &id, "/export"), &owner, None, None); + assert_eq!(export_a.headers.get("x-manifest-digest"), export_b.headers.get("x-manifest-digest")); + + // An erasure through B clears the log; A rebuilds and no longer has the report. + let report_id = first.json["records"][0]["record_id"].as_str().unwrap(); + let erased = call( + "POST", + &athlete_url(b, &id, &format!("/records/{report_id}/erasure")), + &owner, + Some(json!({ "expected_revision": 1, "reason_code": "athlete_request" })), + None, + ); + assert_eq!(erased.status, 200, "{}", erased.json); + let after = call("GET", &athlete_url(a, &id, &format!("/records/{report_id}")), &owner, None, None); + assert_eq!(after.status, 404); + let listed = call("GET", &athlete_url(a, &id, "/records?record_type=athlete_report"), &owner, None, None); + assert_eq!(listed.json["records"].as_array().unwrap().len(), 3); +} diff --git a/host/tests/support/mod.rs b/host/tests/support/mod.rs new file mode 100644 index 00000000..88e0dd8c --- /dev/null +++ b/host/tests/support/mod.rs @@ -0,0 +1,259 @@ +//! Test servers for the host: a sign-in key server, a stand-in S3 bucket, and the host +//! itself, each on a free local port. The signing key is a fixed, test-only Ed25519 +//! key built from a seed below; it signs nothing outside these tests. + +#![allow(dead_code)] + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use ath_host::config::{Config, Limits, S3Config, SignInConfig, StorageConfig}; +use axum::body::Bytes; +use axum::extract::{Path as UrlPath, State}; +use axum::http::StatusCode; +use axum::routing::get; +use axum::{Json, Router}; +use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; +use serde_json::{json, Value}; + +/// The test key's 32-byte seed and public key. +const SEED: &str = "4828f8020207fb11233d01b011c5937bede2b268a8603620b80bf97e050503d0"; +const PUBLIC_X: &str = "itrbr0O5BuqdMUzuGWjVxNLAdQjldIGhKq8Rxhhr3_A"; +pub const ISSUER: &str = "https://sign-in.test"; +pub const AUDIENCE: &str = "https://host.test"; +pub const ATHLETE_APP: &str = "athlete-app"; +pub const COACH_APP: &str = "coach-app"; + +pub fn runtime() -> &'static tokio::runtime::Runtime { + static RUNTIME: std::sync::OnceLock = std::sync::OnceLock::new(); + RUNTIME.get_or_init(|| tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap()) +} + +fn serve(router: Router) -> SocketAddr { + runtime().block_on(async { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + address + }) +} + +/// A key server publishing the test key. +pub fn key_server() -> String { + let jwks = json!({ "keys": [{ "kty": "OKP", "crv": "Ed25519", "x": PUBLIC_X, "kid": "test-key", "alg": "EdDSA", "use": "sig" }] }); + let address = serve(Router::new().route("/jwks.json", get(move || async move { Json(jwks.clone()) }))); + format!("http://{address}/jwks.json") +} + +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() +} + +/// An access token for `subject`, issued to `client`. +pub fn token(subject: &str, client: &str) -> String { + token_with( + json!({ "iss": ISSUER, "sub": subject, "aud": AUDIENCE, "azp": client, "name": subject, "exp": far_future() }), + ) +} + +pub fn token_with(claims: Value) -> 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()); + encode(&header, &claims, &EncodingKey::from_ed_der(&der)).unwrap() +} + +pub fn far_future() -> u64 { + (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()) + 3600 +} + +/// A stand-in S3 bucket: path-style PUT, GET, and DELETE, keeping objects in memory. +/// It ignores signatures; the host's signing is covered by the library it uses. +#[derive(Clone, Default)] +pub struct Bucket { + pub objects: Arc>>>, +} + +pub fn bucket_server() -> (String, Bucket) { + let bucket = Bucket::default(); + async fn put(State(bucket): State, UrlPath(key): UrlPath, body: Bytes) -> StatusCode { + bucket.objects.lock().unwrap().insert(key, body.to_vec()); + StatusCode::OK + } + async fn get_object(State(bucket): State, UrlPath(key): UrlPath) -> Result, StatusCode> { + bucket.objects.lock().unwrap().get(&key).cloned().ok_or(StatusCode::NOT_FOUND) + } + async fn remove(State(bucket): State, UrlPath(key): UrlPath) -> StatusCode { + bucket.objects.lock().unwrap().remove(&key); + StatusCode::NO_CONTENT + } + let router = + Router::new().route("/test-bucket/{*key}", get(get_object).put(put).delete(remove)).with_state(bucket.clone()); + let address = serve(router); + (format!("http://{address}"), bucket) +} + +pub fn temporary(prefix: &str) -> PathBuf { + // The library refuses paths through a symbolic link, and the system's temporary + // folder is often one, so use its real path. + let root = std::fs::canonicalize(std::env::temp_dir()).unwrap(); + let path = root.join(format!("{prefix}{}", uuid::Uuid::new_v4().simple())); + std::fs::create_dir_all(&path).unwrap(); + path +} + +pub enum Mode<'a> { + Directory, + /// A local stand-in server folder shared by every host copy, and a bucket address. + LocalServer { + server: &'a Path, + bucket: &'a str, + }, +} + +pub fn config(data: &Path, mode: Mode<'_>, jwks: &str) -> Config { + std::env::set_var("ATH_TEST_S3_KEY", "test"); + std::env::set_var("ATH_TEST_S3_SECRET", "test-secret"); + let storage = match mode { + Mode::Directory => StorageConfig::Directory, + Mode::LocalServer { server, bucket } => StorageConfig::LocalServer { + directory: server.to_path_buf(), + attachments: S3Config { + endpoint: bucket.to_string(), + bucket: "test-bucket".into(), + region: "test".into(), + access_key_env: "ATH_TEST_S3_KEY".into(), + secret_key_env: "ATH_TEST_S3_SECRET".into(), + path_style: true, + }, + }, + }; + Config { + listen: "127.0.0.1:0".into(), + public_url: AUDIENCE.into(), + data_directory: data.to_path_buf(), + storage, + sign_in: SignInConfig { + issuer: ISSUER.into(), + audience: AUDIENCE.into(), + jwks_uri: Some(jwks.into()), + allowed_clients: Vec::new(), + }, + operator_disclosure: "Test host run by the test suite, storing records on this machine.".into(), + open_enrollment: true, + limits: Limits::default(), + } +} + +pub struct Host { + pub url: String, + pub state: ath_host::api::Shared, +} + +pub fn host(config: Config) -> Host { + let state = runtime().block_on(ath_host::state(config)).unwrap(); + let address = serve(ath_host::api::router(state.clone())); + Host { url: format!("http://{address}"), state } +} + +/// A response's status and JSON body (or raw bytes). +pub struct Reply { + pub status: u16, + pub json: Value, + pub bytes: Vec, + pub headers: HashMap, +} + +pub fn call(method: &str, url: &str, token: &str, body: Option, key: Option<&str>) -> Reply { + let mut request = ureq::request(method, url).set("Authorization", &format!("Bearer {token}")); + if let Some(key) = key { + request = request.set("Idempotency-Key", key); + } + let response = match body { + Some(body) => request.send_json(body), + None => request.call(), + }; + reply(response) +} + +pub fn send_bytes(method: &str, url: &str, token: &str, bytes: &[u8]) -> Reply { + reply(ureq::request(method, url).set("Authorization", &format!("Bearer {token}")).send_bytes(bytes)) +} + +fn reply(response: Result) -> Reply { + let response = match response { + Ok(response) => response, + Err(ureq::Error::Status(_, response)) => response, + Err(error) => panic!("request failed: {error}"), + }; + let status = response.status(); + let headers = response + .headers_names() + .into_iter() + .filter_map(|name| response.header(&name).map(|v| (name, v.to_string()))) + .collect(); + let mut bytes = Vec::new(); + std::io::Read::read_to_end(&mut response.into_reader(), &mut bytes).unwrap(); + let json = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + Reply { status, json, bytes, headers } +} + +pub fn demo_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/demo-athlete") +} + +/// The demo record's complete package as a zip. +pub fn demo_package_zip() -> Vec { + let folder = temporary("ath-host-demo-package-"); + let copy = folder.join("record"); + copy_folder(&demo_root(), ©); + let store = athleticstandard::store::Store::open(copy.join("athlete.ath.sqlite"), Default::default()).unwrap(); + let package = folder.join("package"); + athleticstandard::package::export_package(&store, &package, &Default::default()).unwrap(); + ath_host::package_zip::pack(&package).unwrap() +} + +pub fn demo_photo() -> Vec { + std::fs::read(demo_root().join("attachments/01890f3e-e7d3-7cc0-88c8-00000000000e.png")).unwrap() +} + +pub fn copy_folder(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let path = entry.unwrap().path(); + let target = to.join(path.file_name().unwrap()); + if path.is_dir() { + copy_folder(&path, &target); + } else { + std::fs::copy(&path, &target).unwrap(); + } + } +} + +/// An athlete report as an owner would log it. +pub fn report(note: &str) -> Value { + json!({ + "report_type": "note", + "reported_at": "2026-11-21T08:00:00.000Z", + "input_reported_at": { "timestamp_missing_reason": "not_applicable", "utc_offset_missing_reason": "not_applicable" }, + "reported_via": "text", + "note": note, + }) +} + +/// Restore an exported zip into a new local database, as a second device would, and +/// return the store. +pub fn open_on_another_device(zip: &[u8]) -> (PathBuf, athleticstandard::store::Store) { + let folder = temporary("ath-host-device-"); + let package = folder.join("package"); + ath_host::package_zip::unpack(zip, &package).unwrap(); + let path = folder.join("device").join("athlete.ath.sqlite"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut store = athleticstandard::store::Store::create(&path, Default::default()).unwrap(); + let preview = athleticstandard::package::preview_package_import(&store, &package).unwrap(); + athleticstandard::package::apply_package_import(&mut store, &preview, &[]).unwrap(); + (path, store) +} From 42ceb505cf8cfedb7feb747f16ed5540d2196390 Mon Sep 17 00:00:00 2001 From: Michael Whitham Date: Mon, 23 Nov 2026 18:14:47 -0600 Subject: [PATCH 07/26] Move a record between hosts and back up one athlete at a time. A move has one writer at every step (D267): the source freezes the record and records the package digest, the destination keeps the uploaded package staged, the source retires its writer and issues a single-use activation code, and the destination activates only after the source confirms that code for the destination's address and the same digest. ath-host backup writes each athlete's package after a trial restore; ath-host restore replaces one athlete's record, applies every erasure recorded since, and raises the access epoch (D264). Erasures are noted before they are applied and finished when the host starts. An ignored test runs every host scenario against a real libSQL server. Co-Authored-By: Claude Opus 5.5 --- build-history/v2.1.3/progress.md | 20 ++- host/src/api.rs | 57 ++++++- host/src/backup.rs | 109 ++++++++++++++ host/src/directory.rs | 113 +++++++++++++- host/src/lib.rs | 1 + host/src/main.rs | 31 ++++ host/src/moves.rs | 248 ++++++++++++++++++++++++++++++- host/src/storage.rs | 34 +++++ host/tests/host_api.rs | 56 ++++++- host/tests/moves.rs | 239 +++++++++++++++++++++++++++++ host/tests/support/mod.rs | 54 +++++-- 11 files changed, 935 insertions(+), 27 deletions(-) create mode 100644 host/src/backup.rs create mode 100644 host/tests/moves.rs diff --git a/build-history/v2.1.3/progress.md b/build-history/v2.1.3/progress.md index aa2788c2..3d0cca06 100644 --- a/build-history/v2.1.3/progress.md +++ b/build-history/v2.1.3/progress.md @@ -11,7 +11,7 @@ Status: **in progress; not released**. The plan is [spec.md](spec.md). | 5 | `ath-host` native directory mode: connect, read, write, attachments, refresh, restore | done | | 6 | Sign-in and grants | done; provider recipes in step 9 | | 7 | Remote mode with object storage and several host copies | done with a stand-in server; live run pending | -| 8 | Moves and backups | not started | +| 8 | Moves and backups | done; Litestream recipe untested | | 9 | Clients, starter, `docs/hosting.md`, container and setup guide | not started | | 10 | Scale and fault runs, release evidence | not started | @@ -62,3 +62,21 @@ Steps 4 to 7 notes: and rebuilding after an erasure. - Not yet run: the remote backend against a real libSQL server, and sign-in through a real provider. Tokens in the tests are signed by a fixed test-only key. + +Step 8 notes: + +- A move is driven by the owner's app: `move/freeze` on the source, the package + uploaded to an `incoming` record on the destination, `move/retire` on the source, + then `move/activate` on the destination, which asks the source to confirm the + single-use code for its own address and the digest of the package it holds (D267). +- `ath-host backup` writes each athlete's package as a zip after a trial restore and + check. `ath-host restore` replaces one athlete's record in directory mode, then + applies every erasure recorded since and raises the access epoch. In remote mode, use + the provider's restore for that athlete's database. +- Every erasure is noted in the host directory before it is applied. The host finishes + unfinished erasures when it starts (D264). +- The Litestream recipe is documented but not run: no Litestream binary was run in + this build. +- `host_api.rs` has an ignored qualification test that runs every scenario against a + real libSQL server with two host copies and prints timings. It needs a server + address and token in `ATH_QUALIFY_*` variables. diff --git a/host/src/api.rs b/host/src/api.rs index e03fefc3..8f6966bb 100644 --- a/host/src/api.rs +++ b/host/src/api.rs @@ -133,7 +133,7 @@ async fn relation(state: &AppState, caller: &Caller, resource_id: &str) -> ApiRe } } -async fn owner(state: &AppState, caller: &Caller, resource_id: &str) -> ApiResult { +pub(crate) async fn owner(state: &AppState, caller: &Caller, resource_id: &str) -> ApiResult { match relation(state, caller, resource_id).await? { Relation::Owner(athlete) => Ok(athlete), Relation::Coach(..) => Err(ApiError::permission_denied("Only the athlete can do this")), @@ -164,8 +164,10 @@ fn hide_missing(error: ApiError) -> ApiError { } } -fn not_moving(athlete: &Athlete) -> ApiResult<()> { - if athlete.state == "frozen" { +/// Writes are refused while a record is frozen for a move or staged as an incoming +/// move (D267). +pub(crate) fn not_moving(athlete: &Athlete) -> ApiResult<()> { + if athlete.state == "frozen" || athlete.state == "staged" { return Err(ApiError::moving()); } Ok(()) @@ -283,7 +285,7 @@ fn decode(record_type: RecordType, data: &Value) -> ApiResult { RecordData::decode(record_type, &from_json(data)?).map_err(|error| ApiError::invalid(error.to_string())) } -fn body_json(body: &[u8]) -> ApiResult { +pub(crate) fn body_json(body: &[u8]) -> ApiResult { serde_json::from_slice(body).map_err(|error| ApiError::invalid(format!("The request body is not valid: {error}"))) } @@ -356,6 +358,10 @@ struct NewAthlete { display_name: Option, #[serde(default)] invitation: Option, + /// A record arriving from another host: it accepts its package and stays hidden + /// until the move activates it (D267). + #[serde(default)] + incoming: bool, } async fn create_athlete( @@ -363,8 +369,11 @@ async fn create_athlete( caller: Caller, body: Bytes, ) -> ApiResult<(StatusCode, Json)> { - let request: NewAthlete = - if body.is_empty() { NewAthlete { display_name: None, invitation: None } } else { body_json(&body)? }; + let request: NewAthlete = if body.is_empty() { + NewAthlete { display_name: None, invitation: None, incoming: false } + } else { + body_json(&body)? + }; let invited = match &request.invitation { Some(code) => state .directory @@ -378,7 +387,11 @@ async fn create_athlete( } let athlete = state .directory - .create_athlete(&caller.principal.principal_id, request.display_name.as_deref()) + .create_athlete_in( + &caller.principal.principal_id, + request.display_name.as_deref(), + if request.incoming { "staged" } else { "active" }, + ) .await .map_err(|e| ApiError::internal("directory", e))?; let revision = state.storage.create(&athlete.resource_id).await?; @@ -428,7 +441,9 @@ async fn put_package( body: Bytes, ) -> ApiResult> { let athlete = owner(&state, &caller, &id).await?; - not_moving(&athlete)?; + if athlete.state == "frozen" { + return Err(ApiError::moving()); + } let folder = state.storage.staging().join("packages").join(uuid::Uuid::new_v4().simple().to_string()); crate::package_zip::unpack(&body, &folder) .map_err(|error| ApiError::invalid(format!("The package is not a readable zip: {error}")))?; @@ -692,6 +707,11 @@ async fn erase( let request: ErasureRequest = body_json(&body)?; let reason: ErasureReasonCode = serde_json::from_value(Value::String(request.reason_code.clone())) .map_err(|_| ApiError::invalid(format!("Unknown erasure reason: {}", request.reason_code)))?; + let intent = state + .directory + .record_erasure_intent(&id, &record_id, &request.reason_code) + .await + .map_err(|e| ApiError::internal("directory", e))?; let revision = state .storage .write(&id, None, move |store, _| { @@ -699,9 +719,30 @@ async fn erase( Ok(erase_record(store, &preview, reason, None)?.database_revision) }) .await?; + state.directory.complete_erasure_intent(&intent).await.map_err(|e| ApiError::internal("directory", e))?; Ok(Json(j!({ "database_revision": revision }))) } +/// Apply an erasure again: after a failure, or after a restore from an older backup +/// (D264). It erases whatever revision the record has. `false` when the record is not +/// there any more. +pub async fn erase_again(state: &AppState, resource_id: &str, record_id: &str, reason_code: &str) -> ApiResult { + let reason: ErasureReasonCode = serde_json::from_value(Value::String(reason_code.to_string())) + .map_err(|_| ApiError::invalid(format!("Unknown erasure reason: {reason_code}")))?; + let record_id = record_id.to_string(); + state + .storage + .write(resource_id, None, move |store, _| { + let Some(current) = store.get_record(&record_id)? else { + return Ok(false); + }; + let preview = preview_erasure(store, &record_id, current.current_revision)?; + erase_record(store, &preview, reason, None)?; + Ok(true) + }) + .await +} + async fn upload( State(state): State, caller: Caller, diff --git a/host/src/backup.rs b/host/src/backup.rs new file mode 100644 index 00000000..9edc28d9 --- /dev/null +++ b/host/src/backup.rs @@ -0,0 +1,109 @@ +//! Backups and restores of one athlete at a time (D264). +//! +//! A backup is each athlete's complete package as a zip, checked by restoring it into +//! an empty database before it is kept. A restore replaces one athlete's record from +//! such a package, then applies every erasure recorded since, and raises the access +//! epoch so a write that started before the restore cannot commit after it. + +use std::path::{Path, PathBuf}; + +use athleticstandard::store::{CreateOptions, Store}; + +use crate::api::{erase_again, export_zip, AppState}; +use crate::error::{ApiError, ApiResult}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BackedUp { + pub athlete_id: String, + pub file: PathBuf, + pub manifest_digest: String, +} + +/// Back up every athlete that is not retired into `output//