diff --git a/AGENTS.md b/AGENTS.md index d87d0351..65baea1b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ Read these before making decisions — they are the project's memory and outrank 5. **`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. 6. **`build-history/*/progress.md`** — what's done and what's next. 7. **`docs/connections.md`** — per-provider data research (what WHOOP/Oura/Garmin/Apple Health each provide via which path). -8. **`SPEC.md`** — the public field-level format reference. Normative Zod for v1 is in `src/v1/schema.ts` (`SPEC.md`); `src/schema.ts` is legacy 0.x. JSON Schema is generated from these sources. +8. **`SPEC.md`** — the public field-level format reference. **Today** v1 Zod in `src/v1/schema.ts` is normative (D8, D83); `src/schema.ts` is legacy 0.x. JSON Schema is generated from Zod. Proposed D130–D131 move normative records into `ath-core` with generated JSON Schema and TypeScript types; hand-maintained Zod stops at npm **2.0.0** (record format version can stay 1.0.0). See **`build-history/v1.0.0/appendix/rust-adoption.md`** and the inventory/coverage tables beside it. 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 @@ -26,8 +26,8 @@ describe released 0.x behavior. ## Hard rules - **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. -- **Schemas are the source of truth.** After changing `src/v1/schema.ts`, run `pnpm generate:json-schema` and `pnpm generate:v1-fixture` and commit the regenerated outputs. After changing legacy `src/schema.ts`, run `pnpm generate:json-schema` and `pnpm generate:fixture` and commit the regenerated outputs. After changing a command or its help in `src/program.ts` or `src/help.ts`, run `pnpm generate:skill-cli` and commit `skill/references/cli.md` (D80). +- **`build-history/` is append-only.** A new version folder (`v0.2.0/`, `v1.0.0/`, …) is created only when a plan changes the record format (`athleticstandard_version`). Other plans go in the current format folder's `appendix/`. 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. +- **Schemas are the source of truth (today).** After changing `src/v1/schema.ts`, run `pnpm generate:json-schema` and `pnpm generate:v1-fixture` and commit the regenerated outputs. After changing legacy `src/schema.ts`, run `pnpm generate:json-schema` and `pnpm generate:fixture` and commit the regenerated outputs. After changing storage SQL authored in TypeScript, run `pnpm generate:sql-contract` and commit `spec/sql/`. After changing a command or its help in `src/program.ts` or `src/help.ts`, run `pnpm generate:skill-cli` and commit `skill/references/cli.md` (D80). Once D131 is approved and the Rust model ships, regenerate JSON Schema and TypeScript from Rust instead of extending normative Zod. - **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 `scripts/check-public-data.ts`. diff --git a/build-history/README.md b/build-history/README.md index 344b7894..339566fd 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -4,9 +4,12 @@ This folder is the permanent record of what we decided to build and why. ## The rule -Every plan we execute gets its spec written into a versioned subfolder here **before or as** the build happens. Within a version, all decisions go in that version's `decisions.md` — append new D-numbers, don't rewrite earlier ones. Supporting research goes in `appendix/` in the same version folder and is linked from the D-number. If a later build is a new plan, it gets a new version folder; the old one stays as-is. +Every plan we execute gets its spec written into a versioned subfolder here **before or as** the build happens when that plan **changes the record format** (`athleticstandard_version`). Plans that do not change the record format go in the current format folder's `appendix/` (and link decisions from that folder's `decisions.md`). Within a version, all decisions go in that version's `decisions.md` — append new D-numbers, don't rewrite earlier ones. Supporting research goes in `appendix/` in the same version folder and is linked from the D-number. A new version folder is created only when a plan changes the record format; the old folder stays as-is. -Folders are named for the format version they describe — the same version that appears in `athleticstandard_version` and in the npm package. A plan that revises the format gets a folder matching the version it produces. +Folders are named for the **record format version** they describe — the same version +that appears in `athleticstandard_version`. The npm package version and +`sql_schema_version` are versioned separately (see contribution readiness §4.1). A +plan that revises the record format gets a folder matching the version it produces. D-numbers run continuously across version folders. D25 follows D24 even though it lives in a different folder, so a decision can be cited by number alone. diff --git a/build-history/v1.0.0/appendix/rust-adoption.md b/build-history/v1.0.0/appendix/rust-adoption.md new file mode 100644 index 00000000..5a80827a --- /dev/null +++ b/build-history/v1.0.0/appendix/rust-adoption.md @@ -0,0 +1,287 @@ +# Rust adoption plan (proposed) + +**Status:** proposed. Draft decisions D130–D132 live in +`build-history/v1.0.0/decisions.md`. Tables: +[`rust-capability-inventory.md`](rust-capability-inventory.md), +[`rust-calculation-coverage.md`](rust-calculation-coverage.md). + +**Goal:** Put all athlete-record rules in one Rust library (`ath-core`). Node and iOS +use thin bindings. Keep the npm name `athleticstandard` and the `ath` command. Do not +add a local HTTP service (D121). Do not add MCP (D7). + +There is one cutover to Rust. No engine switch, no TypeScript fallback, and no +compatibility layer that keeps two rule sets alive. + +--- + +## 1. Where the repo stands today + +Checks on `main` (representative): + +| Check | Result | +|---|---| +| `pnpm check:public-data` | pass | +| `pnpm typecheck` | pass | +| `pnpm test` | pass | +| `pnpm build` | pass | + +**In code today:** v1 SQLite through TypeScript and `@libsql/client` (D93), Zod in +`src/v1/schema.ts` as the normative record model (D8, D83), SQL under `spec/sql/` +produced by `pnpm generate:sql-contract` from TypeScript migration strings, provider +parsers that still touch the legacy 0.x shape in places, and calculations in +`src/db/calculate.ts`. + +**Pull requests to coordinate with:** + +- [#20](https://github.com/mwhitham/ath/pull/20) — this plan and D130–D132 only. +- [#25](https://github.com/mwhitham/ath/pull/25) — migrate, import checks, structured + logging, docs. **Land #25 before the Rust build PR.** It targets npm **1.1.0**. +- [#15](https://github.com/mwhitham/ath/pull/15) — about seven README link lines only; + decisions and appendix text are already on `main` (D129). + +**After the owner approves this plan:** one implementation PR on `main`. That PR carries +prerequisites and the start of `ath-core`. + +**Verification today:** reuse Vitest (`tests/v1-cli-writes.test.ts`, +`tests/v1-export-import.test.ts`, `tests/v1-direct-sql.test.ts`, provider import tests). +CR5 calls for shared behavior fixtures under `spec/conformance/`; that directory is not +in the repo yet and will be added in the build PR. + +**iPhone proof app:** when built, it should live at `apps/verification-ios/` and use the +Swift package from `ath-uniffi`. One app, one place. + +--- + +## 2. One core, thin shells + +| Piece | Job | +|---|---| +| **ath-core** | Records, validation, storage, history, conflicts, imports, calculations, packages, attachments, deletion, erasure | +| **ath-node** | napi-rs bindings; heavy work off the Node event loop | +| **ath-uniffi** | UniFFI bindings; Swift first | +| **TypeScript CLI** | Args, help, Skill, credentials, model calls | +| **Swift app** | UI, files, permissions (verification app above) | + +Use **rusqlite** with bundled SQLite inside `ath-core`. Match pragmas and triggers from +the SQL contract. + +--- + +## 3. One rule set + +End state: + +- One record model. +- One implementation of behavior. +- Supported writes through **typed operations on the core**. + +Remove legacy pieces only after tests prove parity for that migration step: + +- 0.x model (`src/schema.ts`) on import paths. +- Hand-maintained TypeScript validation and calculations that duplicate Rust. +- TypeScript string migrations as the SQL authoring path (see §5). +- Old writers and the TypeScript engine. + +No engine-selection flags and no automatic fallback to TypeScript. + +TypeScript may remain temporarily during the build. Each temporary path has a removal +step in the inventory table. + +--- + +## 4. Rust owns the record model + +Rust types and validators define valid records. JSON Schema and TypeScript types are +**generated** from that model. + +The inventory lists each Zod rule and whether Rust keeps, fixes, or drops it. + +JSON Schema must express every rule it can. Rules JSON Schema cannot express stay in +Rust and in docs. Host languages do not keep a second handwritten validator. + +Test timestamps, units, optional vs null, extensions, and serialization across Rust, +Node, Swift, and portable packages. + +**npm 1.1.0** ([#25](https://github.com/mwhitham/ath/pull/25)) still uses Zod. A later +**1.x** release deprecates the Zod-based normative exports with a warning and names the +generated replacement (D126). **npm 2.0.0** removes them (D131). **athleticstandard_version** +stays **1.0.0** for the record format unless a separate format change is approved. +**sql_schema_version** stays **1** unless a new SQL migration is added. Those numbers are +independent of the npm major version. + +--- + +## 5. SQL files and the public API + +**Today:** `src/db/migrations/*.ts` is the authoring source. `pnpm generate:sql-contract` +writes `spec/sql/migrations/*.sql`. The npm `files` list does **not** include `spec/`, +so shipping SQL to Node at runtime requires a **packaging change** (for example include +`spec/sql` in the tarball or embed SQL only in native binaries). + +**Target:** plain SQL in `spec/sql/migrations/` is the canonical definition. Rust embeds +the same bytes. Node either embeds them or reads them from shipped files after packaging +is fixed. + +Retire `pnpm generate:sql-contract` at the **Records and lifecycle** migration step, +when edits go to SQL files and drift checks compare SQL to a fresh database (see +inventory). + +Keep foreign keys, constraints, and triggers unless a concrete change improves +correctness. + +**Writes (D132):** official products use core operations. SQLite stays readable. Triggers +still enforce the two-tier wall. Third parties may still open the file with SQLite (D116), +but the project no longer promises that someone can recreate the **full revision protocol** +using only the old direct-write recipes in `spec/sql/README.md` (**D132** narrows **D125**). + +No opaque `execute(JSON)` API. + +Blocking work must not run on the Node event loop or the iOS main thread; bindings call +into Rust on a worker thread. + +--- + +## 6. Capabilities to keep + +Everything in the inventory, including the two-tier wall, sources, revisions, imports, +export/restore, attachments, erasure, conflicts, and explained calculations. + +Attachments must commit or roll back with the database. + +Fix bugs when found. Do not treat old bugs as compatibility. + +--- + +## 7. Calculations + +See [`rust-calculation-coverage.md`](rust-calculation-coverage.md). The wide calculation +library comes **after** the foundation proof. + +Use `performance/` workloads only to spot serious regressions or memory problems. Do not +sell Rust on speed. + +RMSSD and SDNN stay separate. Vendor scores stay labeled as vendor results. + +Each result should identify its method, inputs, and missing-data behavior (coverage +appendix). + +--- + +## 8. Import completeness + +Parsers should land in the canonical Rust model without routing through `src/schema.ts`. + +Imports need a **receipt**: imported, unchanged, corrected, skipped, invalid, and missing +fields, with reasons. + +**Owner-reported import issues** (Oura readiness, sleep scores, contributors, SpO₂, +invalid rows after reimport) are not reproduced in public tests yet. Treat them as targets +for synthetic regressions in the build. + +--- + +## 9. Work in the approved build PR + +| Item | Notes | +|---|---| +| Inventory and coverage tables | This appendix | +| D130–D132 and guidance | `decisions.md`, `AGENTS.md`, `progress.md` | +| SQL canonical path + packaging | Ship or embed SQL; align with §5 | +| Behavior fixtures | `spec/conformance/` (CR5) | +| Rust workspace | `ath-core`, `ath-node`, `ath-uniffi`, CI | +| Calculation contract | Coverage appendix | +| Dead code | e.g. unused `importExport`; milestones in inventory | + +Defer: catalog infrastructure, extra database backends, D115 internal workspace split, generic +extension frameworks beyond the v1 envelope. + +**CORE_API_VERSION** is decided (D128) but not implemented (CR8 pending). The Rust plan +does not change what D128 covers. + +--- + +## 10. Foundation proof (CLI + iPhone) + +1. Installed CLI creates a database and a measurement. +2. iPhone app opens it and corrects the measurement. +3. CLI reads the correction and history. + +Also prove reopen, source rules, bad input rejection, stale edits, unsupported versions, +and no change after refused writes. + +Must run in the **iPhone Simulator** on macOS with Xcode. Linux CI cannot pass this gate. + +**Status:** **BLOCKED** here (no Xcode / iOS Simulator). + +Do not start the wide port until this proof passes. + +--- + +## 11. Migration steps + +| Step | Done when | +|---|---| +| Foundation | Core, bindings, shared model, basic storage, iPhone round trip | +| Records and lifecycle | Validation, queries, history, corrections, deletion, erasure | +| Provider imports | Parsing, field checks, repeat imports, corrections | +| Portable packages | Import/export, conflicts, attachments, samples | +| Existing calculations | Rust parity + reference tests | +| Expanded calculations | Coverage table batches | +| Cutover | TypeScript engine removed; release artifacts verified | + +Record-format version and SQL schema version stay separate from npm versioning (see §4). + +--- + +## 12. Data + +No broad legacy system for external users. Use explicit, tested conversion on copies when +needed. Do not silently upgrade a database on open. + +--- + +## 13. Packaging and checks + +Prebuilt natives for declared Node platforms. Swift builds on declared iOS targets. + +Shared behavior fixtures (once added) run in Rust, Node, and Swift tests. + +Report PASS, FAIL, BLOCKED, or NOT IMPLEMENTED. + +--- + +## 14. Deletion checklist + +Remove only after the step above passes: + +| Artifact | Step | +|---|---| +| `src/schema.ts` on import paths | Provider imports | +| Hand-maintained `src/v1/schema.ts` as normative | Foundation complete; generated types at npm 2.0.0 | +| `src/validate.ts` (0.x only, imports `src/schema.ts`) | Provider imports / 0.x removal | +| TypeScript `INITIAL_SCHEMA_SQL` as authoring source | Records and lifecycle | +| `pnpm generate:sql-contract` | Records and lifecycle | +| `src/db/calculate.ts` engine | Existing calculations | +| 0.x `ImportPayload` routing | Provider imports | +| TypeScript migration runner replaced by Rust | Cutover | +| `src/import/index.ts#importExport` (unused) | Start of build PR | + +--- + +## Next task + +Get this plan and D130–D132 approved. Land **#25**. Then open **one build PR** that +starts `ath-core` (open database, embed SQL, first binding surface) and the prerequisite +items in §9. Public cutover waits on the iPhone simulator proof on macOS. + +--- + +## Tooling reference + +| Host | Binding | +|---|---| +| Node | napi-rs | +| Apple | UniFFI | +| Web (later) | wasm-bindgen | + +Web and Android are not blockers for the first Node + iOS release. diff --git a/build-history/v1.0.0/appendix/rust-calculation-coverage.md b/build-history/v1.0.0/appendix/rust-calculation-coverage.md new file mode 100644 index 00000000..036a51fe --- /dev/null +++ b/build-history/v1.0.0/appendix/rust-calculation-coverage.md @@ -0,0 +1,74 @@ +# Provider capability and calculation coverage + +One table for imports and calculations. **Step** names match +[`rust-adoption.md`](rust-adoption.md). + +Classification: + +- **observation** — measured value with source +- **provider_result** — vendor score or summary, attributed to the vendor +- **reproducible** — ATH recomputes with a named method +- **ath_estimate** — transparent ATH method when the vendor does not ship the value +- **unavailable** — missing inputs or method; reason stated + +| Provider capability | Input / export path | ATH representation | Method and reference | Required data | Current support | Step | +|---|---|---|---|---|---|---| +| WHOOP recovery score | CSV `physiological_cycles` | `provider_score` | provider_result | cycle row | partial import | Provider imports | +| WHOOP strain | CSV workouts / cycles | `provider_score` or session metrics | provider_result | workout/cycle | partial | Provider imports | +| WHOOP sleep performance | CSV `sleeps` | `provider_score` | provider_result | sleep row | partial | Provider imports | +| WHOOP journal entries | CSV | `athlete_report` or notes | observation / report | text fields | partial | Provider imports | +| WHOOP HRV (RMSSD) | CSV cycles | `point_measurement` `hrv_rmssd` | observation | nightly value | yes | Provider imports | +| WHOOP resting HR | CSV cycles | `point_measurement` `resting_heart_rate` | observation | nightly value | yes | Provider imports | +| WHOOP workout HR samples | CSV / API | — | unavailable — CSV has avg/max HR only; API has no continuous HR series | continuous HR | not supported | — | +| Oura readiness score | CSV export | `provider_score` | provider_result | readiness row | mapped in `src/import/oura.ts`; owner-reported real-export failures not yet reproduced | Provider imports | +| Oura sleep score | CSV export | `provider_score` | provider_result | sleep summary | mapped; owner-reported real-export failures not yet reproduced | Provider imports | +| Oura readiness contributors (nine) | CSV export | `provider_score` | provider_result | contributor columns | mapped; owner-reported real-export failures not yet reproduced | Provider imports | +| Oura SpO2 | CSV export | `point_measurement` | observation | SpO2 columns | mapped; owner-reported real-export failures not yet reproduced | Provider imports | +| Oura sleep stages | CSV export | `sleep_session` | observation | stage durations | partial | Provider imports | +| Oura HRV (RMSSD) | CSV export | `point_measurement` `hrv_rmssd` | observation | sleep summary | yes | Provider imports | +| Oura temperature deviation | CSV export | `point_measurement` | observation | temp signal | partial | Provider imports | +| Apple Health HRV (SDNN) | export.zip | `point_measurement` `hrv_sdnn` | observation | SDNN samples | yes (import) | Provider imports | +| Apple Health resting HR | export.zip | `point_measurement` | observation | daily RHR | yes | Provider imports | +| Apple Health workouts | export.zip | `workout_session` | observation | workout records | yes | Provider imports | +| Apple Health sleep analysis | export.zip | `sleep_session` | observation | segments | partial | Provider imports | +| Apple beat lists → RMSSD | export.zip | `hrv_rmssd` via `src/hrv.ts` | reproducible | beat timestamps | yes | Existing calculations | +| Summary stats | CLI `ath calculate summary` | calculation result | reproducible — `ath-runtime-v1` | points or series | yes | Existing calculations | +| Baseline | CLI baseline | calculation result | mean and SD over the requested date range (not a rolling window) | range + quantity | yes | Existing calculations | +| Trend | CLI trend | calculation result | reproducible | time series | yes | Existing calculations | +| Calendar coverage | CLI coverage | calculation result | reproducible | dates in range | yes | Existing calculations | +| Compare sources | CLI compare-sources | calculation result | reproducible | two sources | yes | Existing calculations | +| Correlation | CLI correlation | calculation result | reproducible | two quantities | yes | Existing calculations | +| Workout drift | CLI workout-drift | calculation result | reproducible | workout samples | yes | Existing calculations | +| Provider period summary | CLI provider-period-summary | calculation result | reproducible | provider periods | yes | Existing calculations | +| HRV RMSSD from RR intervals | `src/hrv.ts` | `hrv_rmssd` | reproducible — RMSSD formula | beat intervals ms | yes | Existing calculations | +| HRV SDNN daily aggregate | — | — | unavailable — no SDNN calculation in codebase | beat series | unavailable | Expanded calculations | +| HRV method-specific nightly summary | multi-sample nights | calculation result | reproducible — method registry | samples + method id | partial | Expanded calculations | +| Resting HR (defined methods) | HR time series | calculation result | reproducible — method TBD | HR samples | unavailable | Expanded calculations | +| Heart-rate zones / time in zone | workouts + max HR | calculation result | reproducible — zones documented | HR series | unavailable | Expanded calculations | +| Heart-rate recovery | post-workout HR | calculation result | reproducible | HR series | unavailable | Expanded calculations | +| Sleep duration / efficiency | sleep sessions | calculation result | reproducible | session times | partial | Expanded calculations | +| Sleep interruptions / timing / regularity | sleep sessions | calculation result | reproducible | session history | unavailable | Expanded calculations | +| Sleep stage summaries | staged sleep | calculation result | sum supplied stages only | stage minutes | partial | Expanded calculations | +| Infer sleep stages from raw sensors | — | — | unavailable — policy | raw sensors | unavailable | — | +| Training load (HR-based) | workouts + HR | calculation result | ath_estimate — method TBD | HR, duration | unavailable | Expanded calculations | +| Training load (RPE-based) | athlete report + duration | calculation result | ath_estimate | RPE, duration | unavailable | Expanded calculations | +| Strength volume | workouts | — | unavailable — no implementation | structured workout | unavailable | Expanded calculations | +| Recovery / readiness (ATH generic) | HRV + sleep + RHR | calculation result | ath_estimate — method TBD | baselines | unavailable | Expanded calculations | +| Vendor readiness as ATH-branded score | — | — | unavailable — use provider_result or a distinct ATH method name | — | n/a | — | + +## Calculation contract + +Each `ath-core` result should include method id and version, parameters, units, time +range, input revisions, exclusions, missing-data handling, and a clear unavailable reason +when inputs are not enough. + +Numerical tests use answers computed outside the code under test. RMSSD and SDNN never +share a baseline. + +## Import completeness + +Imports must emit a receipt (imported, unchanged, corrected, skipped, invalid, missing). +Silent loss of a mapped field is a failure. + +Owner-reported import failures on real exports should become public synthetic regressions +when reproduced. diff --git a/build-history/v1.0.0/appendix/rust-capability-inventory.md b/build-history/v1.0.0/appendix/rust-capability-inventory.md new file mode 100644 index 00000000..7711171e --- /dev/null +++ b/build-history/v1.0.0/appendix/rust-capability-inventory.md @@ -0,0 +1,71 @@ +# Capability and dependency inventory (Rust adoption) + +Maps today’s TypeScript code to planned `ath-core` modules and thin hosts. + +## Host shells (stay thin) + +| Area | Today | After cutover | +|---|---|---| +| CLI args, help, presentation | `src/program.ts`, `src/help.ts`, `src/cli.ts` | TypeScript CLI | +| Skill | `src/skill.ts`, `skill/` | TypeScript CLI | +| Credentials, models | `src/keyring.ts`, `src/gateway.ts`, `src/predict.ts` | TypeScript CLI | +| Progress, share | `src/progress.ts`, `src/share.ts` | TypeScript CLI | +| iOS verification app | not in repo | `apps/verification-ios/` when built | + +## ath-core + +| Capability | Today | Rust module (planned) | Notes | +|---|---|---|---| +| v1 records | `src/v1/schema.ts`, `schema/1.0.0/` | `model`, `validate` | Zod normative until npm 2.0.0; then generated from Rust | +| Legacy 0.x | `src/schema.ts` | none | Remove from import paths | +| SQLite open, migrate | `src/db/migrate.ts`, `src/db/client.ts` (D93) | `storage` | Embed SQL; packaging must ship bytes (see plan §5) | +| Writes, revisions | `src/db/records.ts`, `revision-encoding.ts` | `records` | Official write path (D132) | +| Queries | `src/db/query.ts`, views | `query` | | +| Conflicts, transactions | `src/db/conflicts.ts`, `transaction.ts` | `storage` | | +| Deletion, erasure | `src/db/erase.ts` | `lifecycle` | | +| Packages | `src/db/import-package.ts`, `export.ts` | `package` | | +| Attachments | `src/db/attachments.ts`, `attachment-ingest.ts` | `attachments` | | +| Provider import | `src/import/*`, `src/db/provider-import.ts` | `import` | Drop 0.x hop | +| Series | `src/series.ts`, `src/db/series-view.ts` | `series` | | +| Calculations | `src/db/calculate.ts`, `src/hrv.ts`, `src/stats.ts` | `calc` | | +| Check, drift | `src/db/check.ts`, `scripts/check-schema-drift.ts` | `check` | | +| Grading storage | `src/db/evidence.ts`, `prediction-grade.ts` | `grading` | Models stay in CLI | +| IDs | `src/db/uuid.ts` | `ids` | | +| SQL contract | `src/db/sql-contract.ts`, `spec/sql/` | `contract` | | + +## SQL generator timeline (plan and inventory agree) + +| Phase | SQL source | +|---|---| +| Today | TypeScript strings in `src/db/migrations/`; `pnpm generate:sql-contract` writes `spec/sql/` | +| Records and lifecycle step | Edit `spec/sql/migrations/*.sql` directly; generator removed; drift check uses SQL files | +| Rust build | `ath-core` embeds the same SQL files (or post-packaging copy in Node) | + +## Generated contracts + +| Artifact | Today | After Rust cutover (npm 2.0.0 for TS exports) | +|---|---|---| +| JSON Schema | from Zod | from Rust model | +| TypeScript types | Zod inference | generated | +| `spec/sql/` | generated from TS | canonical on disk | +| Behavior fixtures | CR5 not started | `spec/conformance/` in build PR | + +## Open pull requests + +| PR | Role | +|---|---| +| [#20](https://github.com/mwhitham/ath/pull/20) | This plan + D130–D132 | +| [#25](https://github.com/mwhitham/ath/pull/25) | Land before Rust build; npm 1.1.0 | +| [#15](https://github.com/mwhitham/ath/pull/15) | Small README link updates only | + +Implementation is **one build PR** after plan approval (not separate prerequisite PRs). + +## Temporary paths and removal + +| Path | Remove when | +|---|---| +| TypeScript engine `src/db/*` | Cutover | +| `src/schema.ts` on imports | Provider imports step | +| `pnpm generate:sql-contract` | Records and lifecycle step | +| Hand-maintained Zod as normative | Foundation + npm 2.0.0 export change | +| `src/import/index.ts#importExport` | Start of build PR | diff --git a/build-history/v1.0.0/decisions.md b/build-history/v1.0.0/decisions.md index 58b02da1..48bd0c0d 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -1286,3 +1286,112 @@ Rejected alternatives: required before the first v1 npm publish and does not depend on #15 landing first. - **Implement without recording the plan text.** Rejected because build-history must contain the approved decisions and specification before or as the build happens. + +## D130. Athletic Standard domain logic moves to one Rust core (proposed) + +The executable definition of athlete records, validation, storage operations, +provider normalization, calculations, and portable packages lives in a Rust +workspace crate (`ath-core`). The npm package `athleticstandard` and the `ath` +command remain the Node distribution via thin napi-rs bindings (`ath-node`). +Swift hosts use UniFFI (`ath-uniffi`) for a maintained library and verification +app. D121 rejected a maintained Swift library or example; this decision adds that +surface for the Rust foundation proof. + +**Supersedes (for the Rust build only):** + +- **D121** — the parts that reject a maintained Swift library or example and that + allow a future Rust core only behind unchanged existing APIs. Rust becomes the + implementation; bindings are thin and may change where D131 allows. +- **D8** — TypeScript with Zod as the single source of truth for the record model. + +**Defers (does not cancel):** + +- **D115** — the first step in D115: splitting pure logic, storage, and importers + into private workspace packages behind `athleticstandard`. The Rust build lands + `ath-core` and bindings first; the internal split waits until after that work. + Publishing scoped `@ath/*` packages remains “only after concrete need,” as D115 says. + +D121 still rejects a local HTTP service. D7 still rejects MCP. D121 already allowed +a Rust core inside npm; this decision requires that core and ends the “optional later” +reading. + +Rejected alternatives: + +- **A long-term TypeScript engine beside Rust.** Rejected because two rule sets diverge. +- **Any engine switch or TypeScript fallback at cutover.** Rejected. +- **A local HTTP service for mobile.** Rejected for the same reasons as D121. + +This follows the [Rust adoption plan](appendix/rust-adoption.md). + +## D131. Rust owns the record model; generated contracts and conformance outrank bindings (proposed) + +Rust types and validators in `ath-core` become the source for generated JSON Schema +and TypeScript data types. The public contracts are `spec/sql/`, generated JSON +Schema, and language-neutral behavior fixtures under `spec/conformance/` (CR5). + +**Supersedes:** + +- **D8** — Zod as the single source of truth for schema and implementation alignment. +- **D83** — Zod as the public definition of athlete-owned records (logical record + definition moves to Rust; SQLite and JSON still encode the same records). +- **D116** — the sentence that Zod remains the logical record definition. + +**Follows D126:** + +Normative Zod exports and hand-maintained `./schema` types stay until npm major +**2.0.0**. [Pull request #25](https://github.com/mwhitham/ath/pull/25) ships **1.1.0** +still on Zod. After 1.1.0, a later **1.x** release must deprecate those exports with a +runtime warning and a documented replacement (generated types from Rust). **2.0.0** +removes them. No compatibility facade that keeps two validators. + +**Does not change:** + +- **athleticstandard_version** (record format) stays **1.0.0** unless a separate + format decision adds a new version. +- **sql_schema_version** stays **1** unless a new SQL migration is recorded. +- **D128** — `CORE_API_VERSION` for community extension manifests. CR8 has not + implemented it yet; this decision does not narrow D128’s scope. + +The [contribution readiness plan](appendix/contribution-readiness.md) keeps four +independent version numbers (`athleticstandard_version`, `sql_schema_version`, +`CORE_API_VERSION`, npm). Binding and generated-type refactors that do not change +the record format or SQL schema still use the D126 deprecation path above. + +Rejected alternatives: + +- **Keep Zod normative after cutover.** Rejected. +- **Treat napi or UniFFI shapes as the spec.** Rejected. +- **Remove stable TypeScript exports in a minor npm release.** Rejected by D126. + +This follows the [Rust adoption plan](appendix/rust-adoption.md). + +## D132. Supported writes go through the core; narrow direct SQL (proposed) + +**D116** still allows third parties to write SQLite directly with required pragmas; +triggers and constraints still enforce critical rules when application code is bypassed. +Official Athletic Standard products and the documented integration path perform record +lifecycle work through typed operations in `ath-core`, not by following the full +direct-write recipes that **D125** published for writable tables and transaction steps +in `spec/sql/README.md`. + +**Supersedes:** + +- **D125** — treating the documented writable-table set and direct-SQL write steps as + a supported way to recreate the full revision protocol, history, conflicts, package + import, attachments, and erasure. +- **D93** — using `@libsql/client` raw parameterized SQL from the Node package as the + long-term official storage implementation, including D93’s plan that local SQLite and + a future hosted libSQL adapter share the same domain operations. Official writes move + into `ath-core` with rusqlite; Node becomes a thin binding. The hosted libSQL adapter + path in D93 is not pursued for official products under this plan. + +Stable read views remain for direct reads. Simple direct writes that triggers allow +may remain documented; they do not replace core operations for full lifecycle work. + +Rejected alternatives: + +- **Require every writer to use Node.** Rejected; direct SQLite access remains for + inspection and narrow cases. +- **Promise full lifecycle parity through direct SQL alone.** Rejected. + +This follows the [Rust adoption plan](appendix/rust-adoption.md). diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index 158c552d..74d82c26 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -14,9 +14,9 @@ Tracks the build order from `spec.md`. Update when a step lands. | 7 | Add v1 JSON package import and deterministic JSON export | ✅ done | | 8 | Migrate provider importers and dense samples using `appendix/time-and-provider-periods.md` | ✅ done | | 9 | Update checks, help, the Skill, SPEC, README, and package exports | ✅ done | -| 10 | Run functional, cross-platform, and measured performance suites | in progress — local functional and measured 100,000- and 3-million-record runs pass; cross-platform workflow pending | -| 11 | Release a prerelease for v1 package and database testing | pending | -| 12 | Release v1.0.0 after round-trip and cross-platform tests pass | pending | +| 10 | Run functional, cross-platform, and measured performance suites | partial — local functional and measured 100,000- and 3-million-record runs pass; **cross-platform workflow not run yet** | +| 11 | Release a prerelease for v1 package and database testing | pending — no npm prerelease; 1.0.0 shipped from `main` at 7cd6a09 | +| 12 | Release v1.0.0 after round-trip and cross-platform tests pass | ✅ shipped — before the cross-platform tests ran (step 10); `athleticstandard@1.0.0` on npm (2026-10-18, `main` 7cd6a09) | D101 removed the prerelease-file migration gate. Runtime implementation begins at step 2 with the v1 domain schemas. Step 2 added the typed record, revision, portable @@ -45,11 +45,11 @@ tests. The required measured runs now use 100,000 and 3 million records. Both pa all nine operations on the reference runner. Their measurements and review limits are recorded in `performance/limits.json`. -## Pre-publish contribution foundation +## Contribution foundation (CR4–CR9 after 1.0.0) -D115–D128 and section 19 of `spec.md` add work before release steps 11 and 12. -The long-form sequence is in -[`appendix/contribution-readiness.md`](appendix/contribution-readiness.md). +`spec.md` §19 (implementing D115–D128) listed CR4–CR9 as pre-publish work. **CR4–CR9 slipped past +the 1.0.0 npm release**; they were not deferred on purpose. The long-form sequence is +in [`appendix/contribution-readiness.md`](appendix/contribution-readiness.md). | Step | Deliverable | Status | |---|---|---| @@ -64,6 +64,19 @@ The long-form sequence is in | CR8 | Add internal workspace boundaries, `CORE_API_VERSION` 1.0.0, explicit public exports, and API deprecation checks | pending | | CR9 | Verify the packed v1 tarball contains every promised schema, SQL, conformance, community, and Skill file | pending | -CR1 and CR2 change the unreleased v1 schema. They must finish before v1.0.0 is -published to npm. Release steps 11 and 12 remain blocked until CR1–CR9 and the -cross-platform part of step 10 pass. +CR1–CR3 landed before athleticstandard@1.0.0 shipped. CR4–CR9 remain open. Step 10’s +cross-platform workflow is still pending. + +## Rust adoption (proposed) + +Tracked in [`appendix/rust-adoption.md`](appendix/rust-adoption.md). Draft decisions +D130–D132. `athleticstandard@1.0.0` is already on npm; this work targets a later npm +major (**2.0.0**) for dropping Zod-based exports while the record format can stay +1.0.0. Land [#25](https://github.com/mwhitham/ath/pull/25) (npm 1.1.0) before the +Rust build PR. + +| Step | Deliverable | Status | +|---|---|---| +| R0 | Plan, inventory, coverage, decisions, `AGENTS.md` | in review — PR #20 | +| R1 | Approved plan → one build PR on `main` (SQL packaging, conformance, Rust workspace, dead-code milestones) | pending approval | +| R2 | iPhone simulator CLI ↔ app round trip | **BLOCKED** — requires Xcode and iOS Simulator on macOS |