From aacb31224a3582be34f157d032de8822491eca06 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 18 Oct 2026 02:03:03 +0000 Subject: [PATCH 01/10] Add proposed Rust adoption plan (docs only) Document options for staying on TypeScript vs adding a Rust core behind the athleticstandard npm package, with draft D130 for owner approval. Document pending plans/ placement in build-history README. Signed-off-by: Cursor Agent Co-authored-by: Michael Whitham --- build-history/README.md | 6 + build-history/plans/rust-adoption.md | 336 +++++++++++++++++++++++++++ 2 files changed, 342 insertions(+) create mode 100644 build-history/plans/rust-adoption.md diff --git a/build-history/README.md b/build-history/README.md index 344b7894..62586dfb 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -10,10 +10,16 @@ Folders are named for the format version they describe — the same version that 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. +Proposed plans that do not yet have approved D-numbers live in `build-history/plans/` +until the owner accepts them. After acceptance, record the decisions in the +version folder the work produces and link the long-form plan from those +D-numbers (often in that version's `appendix/`). + ## Structure ``` build-history/ + plans/ # proposed plans awaiting owner approval (not yet versioned) v0.1.0/ spec.md # the full build specification for the first version decisions.md # the decision log: what was chosen, what was rejected, and why (D1–D24) diff --git a/build-history/plans/rust-adoption.md b/build-history/plans/rust-adoption.md new file mode 100644 index 00000000..0f719728 --- /dev/null +++ b/build-history/plans/rust-adoption.md @@ -0,0 +1,336 @@ +# Rust adoption plan (proposed) + +Status: **proposed — awaiting owner approval.** This file is not an approved +decision. No new D-number is recorded in any `decisions.md` until the owner +accepts this plan and the draft decision below. + +Placement follows the rule that plans stay **outside** a version folder until +their decisions are approved. After approval, link this plan from a new +D-number in the folder for the format version the work produces (likely +`build-history/v1.0.0/` if the npm package stays at 1.x and does not change +record content). + +## 1. Core goal + +Keep Athletic Standard easy to install (`npm i athleticstandard`, `ath` on Node +20+) and faithful to the public contracts (`spec/sql`, JSON schemas, two-tier +wall, extension envelope). If Rust is added, it must sit **behind** the same +npm package and CLI surface, not replace them. + +The question is not “should we like Rust?” It is whether a **concrete need** +justifies the maintenance cost of a second implementation language, given D121. + +## 2. What is locked today + +| Decision | What it says for Rust | +|---|---| +| **D7** | Agent interface is CLI + Skill, not MCP. Rust does not change this. Any Rust work must not add a local HTTP or MCP server as the primary interface. | +| **D8** | TypeScript was chosen for distribution (`npx`/`pnpm dlx`), Zod-first schemas, and a workload that did not need a systems language. A Rust **core** does not repeal D8 for the **npm shell**: the published package remains Node-first for install and CLI entry. | +| **D121** | No Rust core, Swift library, MCP, or HTTP service **now**. A future Rust core may ship inside npm behind existing APIs after a **concrete builder need** and the same conformance vectors. | +| **Contribution readiness** | Direct SQLite + language-neutral `spec/` are the cross-language path. Rust is explicitly “later, only on demand.” | +| **v1 spec §13** | Before a second database engine, exhaust indexes, batching, fewer text copies, chunked series, and compressed blocks — then measure again. | + +This plan does **not** assume Rust is approved. It defines when approval would +be honest and how to execute if the owner says yes. + +## 3. What must not break + +Any Rust adoption path must preserve: + +- **Published SQL contract** — `spec/sql/` (generated from `src/db/migrations/`), + triggers enforcing the two-tier wall, extension rules, and migration ordering. +- **SQLite as live record** — same file format, pragmas, and transaction recipe + documented in `spec/sql/README.md`. +- **`ath migrate`** — preview, backup, confirmation, and interactive prompt-on-open + (CR4, in progress elsewhere). This plan does not edit migrate implementation + files; Rust must call the same behavior, not fork it silently. +- **Conformance** — CR5 vectors (when landed) and existing automated tests + remain the parity gate. Rust code is wrong if vectors fail. +- **npm identity** — package name `athleticstandard`, binary `ath`, Node `>=20`, + same `package.json#exports` unless a separate semver-major API decision says + otherwise. +- **OSS thin** — no maintained Swift port, no MCP server, no “build every client + surface” unless a later, separate plan approves it. + +## 4. What would justify Rust (honest need) + +D121 blocks Rust **without demonstrated need**. Any proposal to adopt Rust should +name at least one of these **measured or reported** triggers. Vague “performance” +or “Rust is nicer” is not enough. + +1. **Release performance limits are missed after §13 remedies** — The 100k-record + CI benchmark or 3M large job fails agreed limits after indexes, batching, and + series storage options are tried in TypeScript/SQLite, and profiling shows CPU + in hot loops (import merge, series decode, baseline windows, export), not + I/O or SQLite alone. + +2. **A real builder is blocked without a native library** — Someone shipping a + non-Node app (mobile, desktop, embedded agent runtime) needs a **supported** + shared library with the same semantics as `ath`, and cannot use direct SQLite + + vectors alone within their timeline. The request must be specific (which + commands or calculations, which platform). + +3. **Security or supply-chain pressure on parsing** — A maintained importer or + decode path handles untrusted input at scale, and memory-safe native parsing + with fuzzing is judged lower risk than growing TypeScript parsers. This still + requires vectors and does not skip SQL triggers. + +4. **Contributor capacity** — At least one maintainer can own Rust toolchains, + cross-platform prebuilds, and CI for the next 12 months. Without that, defer. + +If **none** of the above is true today, the correct action is **Option A** (stay +TypeScript) and keep improving SQL and TypeScript hot paths per v1 spec §13. + +## 5. Options + +### Option A — Stay TypeScript; optimize SQLite and TypeScript only + +Keep all logic in the current repo layout. Finish CR4–CR9, land conformance +vectors, and use `performance/` benchmarks as the gate. Revisit Rust only when +§4 triggers fire. + +**Pros** + +- Matches D121 as written; no new decision required. +- One language, one toolchain, aligns with D8 distribution story. +- Zod remains normative for records; no schema drift between Rust and TS. +- Lowest CI and release complexity. + +**Cons** + +- Very large imports or series may stay slower than a tuned native core. +- Non-Node builders rely on direct SQLite + vectors, not a shared `.so`/`.dylib`. +- CPU-heavy calculations stay in Node unless moved to SQLite (views, triggers). + +### Option B — Rust library as the engine; Node CLI stays the façade + +Introduce a `crates/ath-core` (name TBD) Rust crate compiled to native addons +via **napi-rs** (or similar) and loaded from the existing `athleticstandard` +package. TypeScript keeps CLI, Skill packaging, LLM gateway hooks, and thin +wrappers. Heavy work (import merge, series math, export assembly, optional +`check` walks) moves to Rust behind stable internal FFI. + +**Pros** + +- Single npm install with prebuilt binaries per platform (napi-rs pattern). +- Strong speed and memory wins possible on hot paths without changing user + commands. +- Public API stays Node; D8 distribution story largely intact. + +**Cons** + +- Two implementations until parity is proven; ongoing sync on behavior changes. +- Release matrix: linux/macOS/windows × arm64/x64, plus musl where needed. +- Zod/JSON Schema stay in TS; Rust needs generated types or shared fixtures — + drift risk unless conformance vectors are strict. +- Debugging spans Node + native; contributors need Rust toolchain. + +### Option C — Rust only for narrow, high-value modules + +Same packaging as B, but scope Rust to **one** bounded area first, for example: + +- measurement-series decode/encode only, or +- import merge for one vendor, or +- pure calculation helpers used by `ath stats` / baselines. + +Everything else stays TypeScript. Expand only when vectors pass and §4 triggers +justify the next module. + +**Pros** + +- Smallest step that amends D121; proves CI and prebuild pipeline before a big + rewrite. +- Easier rollback: disable native addon and fall back to TS for that module. +- Lessons apply before committing to a full core port. + +**Cons** + +- Boundary design work up front (what is “pure” vs what touches SQLite). +- Two languages in production forever unless later phases expand Rust. +- Some overhead from FFI per call if modules are too granular. + +## 6. Recommendation + +**Default: Option A** until a §4 trigger is documented with evidence (benchmark +JSON, builder issue, or security review). D121 is still the right default for a +thin OSS base finishing v1 publish. + +**If the owner accepts a trigger now: start with Option C**, not a full rewrite. +First candidate module (pending owner decision §8): **measurement-series +sample decode and within-workout calculations**, because they are CPU-bound, +mostly pure, and already have clear inputs/outputs for vectors. Keep all SQLite +writes and migrations in TypeScript (or shared SQL) until CR5 vectors exist. + +**Do not choose Option B (full core)** until Option C has shipped, vectors pass, +and maintainers agree the remaining TS hot paths still fail limits. + +Option B remains the long-term shape **if** multiple modules move and maintaining +split brains in TS and Rust costs more than consolidation. + +## 7. Phased steps (only after owner approves a D-number superseding D121) + +Phase 0 — **No Rust** (current) + +- Land CR4–CR5, SQL contract drift checks, and performance baselines. +- Document current p95/p99 from `performance/results/` for the nine scenarios. + +Phase 1 — **Spike behind a flag** (Option C) + +- Add `crates/` with one crate, napi-rs wiring, and `optionalDependencies` or + prebuild download script; **no** default enable in release until vectors pass. +- Implement one module; TS retains fallback implementation. +- Extend conformance fixtures for that module (input bytes/JSON → expected + outputs). Same tests run against TS fallback and Rust path. + +Phase 2 — **Enable by default when parity proven** + +- CI runs vectors on all platforms in the release matrix. +- Turn on Rust path when prebuild exists; TS fallback remains for unsupported + platforms until prebuilds exist or owner drops support. + +Phase 3 — **Expand or consolidate** (optional) + +- Move additional hot paths per §4 evidence. +- If most logic is Rust, collapse duplicate TS implementations and document + internal API. Public npm exports unchanged. + +Phase 4 — **Standalone Rust library** (only on builder request) + +- Publish `ath-core` crate to crates.io for non-Node consumers. +- Not required for npm users; separate decision if API surface differs from FFI. + +**Explicit non-goals for early phases** + +- Rewriting SQL migrations in Rust. +- Replacing Zod with Rust as normative record schema. +- WASM in the browser unless a builder needs it (WASM is slower for file I/O + heavy work; napi-rs is the default for Node CLI). + +## 8. Risks + +| Risk | Mitigation | +|---|---| +| Behavior drift between TS and Rust | CR5 conformance vectors; property tests; TS fallback until green matrix | +| Broken `npm i` on exotic platforms | TS fallback; document supported platforms; fail with clear message | +| Schema changes require two edits | TS remains normative; Rust reads fixtures; codegen later only if justified | +| `ath migrate` divergence | Migrate stays in TS/SQL; Rust never applies migrations without shared code path | +| Violating two-tier wall in native code | DB triggers remain authoritative; Rust uses same SQL write recipes | +| Team overload | Phase 1 time-box; revert if no maintainer owns Rust CI in 90 days | +| Contradicting D121 silently | Owner must approve draft D130 (below) before Phase 1 merges | + +## 9. How existing and planned tests prove parity + +**Today** + +- `pnpm test` — unit and integration tests for import, check, context, grading, + package exports, SQL migration from empty DB. +- `pnpm check:public-data` — no real health data in repo. +- `performance/` — nine scenarios on 100k (CI) and 3M (large job); compare + before/after Rust with same seed and hardware notes. + +**After CR5 (planned)** + +- `spec/conformance/` — language-neutral fixtures; `scripts/check-conformance.ts` + runs in CI. Rust napi module runs the same vectors as TypeScript. + +**Parity rule** + +- For any function moved to Rust: every vector that passed in TS must pass in + Rust on all release platforms. No release if native prebuild missing on a + tier-1 platform without TS fallback. + +**Regression for migrate** + +- Do not change CR4 files in Rust PRs until CR4 lands; then add integration + tests only via existing migrate test suite, not a second migrate implementation. + +## 10. npm packaging sketch (if B or C approved) + +- Root package `athleticstandard` remains the install target. +- `napi-rs` (or `@napi-rs/cli`) builds platform triples in release CI; artifacts + attached or published via optional dependency package pattern used by other + native npm modules. +- `engines.node >=20` unchanged. +- `package.json#exports` unchanged for public paths; optional subpath + `athleticstandard/native` only if needed for advanced embedders — owner + decision. +- WASM: reserve for a future embedder need; not the default CLI path. + +## 11. Draft decision for owner approval (not recorded yet) + +When the owner accepts Rust work, append something like the following to +`build-history/v1.0.0/decisions.md` as **D130** (number may shift if other +decisions land first). Wording is draft only. + +--- + +### D130. Rust core modules only after demonstrated need (draft) + +Athletic Standard adopts Rust **only** for bounded, measured needs inside the +existing `athleticstandard` npm package. D121’s “no Rust core now” is +superseded **to the extent** the owner documents a §4 trigger and approves a +phase-1 module list. D121’s thin-OSS principle remains: no MCP, no HTTP +service, no maintained Swift port, and no full language port without vectors. + +D7 remains in force. D8 remains in force for npm install and CLI entry; TypeScript +keeps Zod normative schemas and the `ath` command surface. + +Rust code must pass the same conformance vectors as TypeScript, keep SQLite +triggers as the enforcement layer for the two-tier wall, and not fork `ath +migrate` behavior. + +Rejected alternatives: + +- **Full Rust rewrite before vectors exist.** Rejected because parity cannot be + proven and D121’s intent would be bypassed. +- **Rust as a separate product without npm integration.** Rejected because + distribution and the `ath` CLI must stay `npm i athleticstandard`. +- **Adopt Rust without a named maintainer.** Rejected because native prebuilds + require ongoing CI ownership. + +--- + +Until D130 (or equivalent) is appended and approved, **do not merge Rust code**. + +## 12. Open decisions (owner — answer in order) + +1. **Is there a documented §4 trigger today?** If no, stop at Option A and + close this plan until evidence exists. If yes, name which trigger (1–4) and + attach data (benchmark file, issue link, or security note). + +2. **Which option?** A (stay TS), B (full Rust core behind npm), or C (one + module first). Recommendation: A unless (1) is yes; then C. + +3. **First Rust module (only if C or B):** measurement-series math, import + merge, baselines/stats, export assembly, or other — pick one for phase 1. + +4. **Binding technology:** napi-rs native prebuilds (recommended for CLI) vs + WASM vs both. Recommendation: napi-rs for Node; defer WASM. + +5. **Platform tier-1 list for native prebuilds:** e.g. `linux-x64-gnu`, + `linux-arm64-gnu`, `darwin-arm64`, `darwin-x64`, `win32-x64-msvc` — confirm + or shrink. + +6. **TS fallback policy:** require fallback implementation until all tier-1 + prebuilds ship (recommended) vs hard-require native and fail install + elsewhere. + +7. **When to append D130:** approve this plan as-is, approve with edits, or + reject and keep D121 with no Rust timeline. + +## 13. Relationship to in-flight work + +| Work | Relationship | +|---|---| +| CR4 `ath migrate` | Do not edit migrate sources in Rust planning PRs; Rust must use the same UX and SQL outcomes when it touches DBs. | +| CR5 conformance vectors | Prerequisite before enabling Rust by default; Rust spike may add vectors for its module in the same PR series. | +| CR8 workspace split | Compatible: `@ath/core` pure logic is the first TS boundary; Rust module replaces or accelerates the same pure functions, not `store` migrations first. | +| v1.0.0 npm publish | Rust is not a release gate for v1.0.0 unless the owner explicitly promotes it. | + +## 14. Approval checklist + +- [ ] Owner answered open decisions 1–7. +- [ ] Draft D130 text accepted or edited. +- [ ] Plan moved or linked from `build-history/v1.0.0/decisions.md` per + repository process. +- [ ] No Rust implementation merged before D130 is recorded. From 8427963e90a190e19a56c92caf0ae2c27882c69b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 18 Oct 2026 02:17:43 +0000 Subject: [PATCH 02/10] Rewrite Rust adoption plan with benchmarks and research Replace process-heavy draft with measured timings, industry context, and a clear defer-Rust recommendation. Revert unapproved README plans/ rule. Signed-off-by: Cursor Agent Co-authored-by: Michael Whitham --- build-history/README.md | 6 - build-history/plans/rust-adoption.md | 408 ++++++++------------------- 2 files changed, 116 insertions(+), 298 deletions(-) diff --git a/build-history/README.md b/build-history/README.md index 62586dfb..344b7894 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -10,16 +10,10 @@ Folders are named for the format version they describe — the same version that 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. -Proposed plans that do not yet have approved D-numbers live in `build-history/plans/` -until the owner accepts them. After acceptance, record the decisions in the -version folder the work produces and link the long-form plan from those -D-numbers (often in that version's `appendix/`). - ## Structure ``` build-history/ - plans/ # proposed plans awaiting owner approval (not yet versioned) v0.1.0/ spec.md # the full build specification for the first version decisions.md # the decision log: what was chosen, what was rejected, and why (D1–D24) diff --git a/build-history/plans/rust-adoption.md b/build-history/plans/rust-adoption.md index 0f719728..e9bc3389 100644 --- a/build-history/plans/rust-adoption.md +++ b/build-history/plans/rust-adoption.md @@ -1,336 +1,160 @@ -# Rust adoption plan (proposed) +# Should Athletic Standard use Rust? -Status: **proposed — awaiting owner approval.** This file is not an approved -decision. No new D-number is recorded in any `decisions.md` until the owner -accepts this plan and the draft decision below. +**Recommendation:** **No — not now.** Keep the core in TypeScript and SQLite. +Ship v1 on the current stack. Revisit Rust only if release performance +limits fail **after** the SQL and batching improvements already listed in the +v1 build spec, or if a builder proves they cannot ship without a supported +native library. -Placement follows the rule that plans stay **outside** a version folder until -their decisions are approved. After approval, link this plan from a new -D-number in the folder for the format version the work produces (likely -`build-history/v1.0.0/` if the npm package stays at 1.x and does not change -record content). +This note lives in `build-history/plans/` as a proposed plan. It is not +approved and does not add a D-number to `decisions.md` yet. -## 1. Core goal - -Keep Athletic Standard easy to install (`npm i athleticstandard`, `ath` on Node -20+) and faithful to the public contracts (`spec/sql`, JSON schemas, two-tier -wall, extension envelope). If Rust is added, it must sit **behind** the same -npm package and CLI surface, not replace them. - -The question is not “should we like Rust?” It is whether a **concrete need** -justifies the maintenance cost of a second implementation language, given D121. - -## 2. What is locked today - -| Decision | What it says for Rust | -|---|---| -| **D7** | Agent interface is CLI + Skill, not MCP. Rust does not change this. Any Rust work must not add a local HTTP or MCP server as the primary interface. | -| **D8** | TypeScript was chosen for distribution (`npx`/`pnpm dlx`), Zod-first schemas, and a workload that did not need a systems language. A Rust **core** does not repeal D8 for the **npm shell**: the published package remains Node-first for install and CLI entry. | -| **D121** | No Rust core, Swift library, MCP, or HTTP service **now**. A future Rust core may ship inside npm behind existing APIs after a **concrete builder need** and the same conformance vectors. | -| **Contribution readiness** | Direct SQLite + language-neutral `spec/` are the cross-language path. Rust is explicitly “later, only on demand.” | -| **v1 spec §13** | Before a second database engine, exhaust indexes, batching, fewer text copies, chunked series, and compressed blocks — then measure again. | - -This plan does **not** assume Rust is approved. It defines when approval would -be honest and how to execute if the owner says yes. - -## 3. What must not break - -Any Rust adoption path must preserve: - -- **Published SQL contract** — `spec/sql/` (generated from `src/db/migrations/`), - triggers enforcing the two-tier wall, extension rules, and migration ordering. -- **SQLite as live record** — same file format, pragmas, and transaction recipe - documented in `spec/sql/README.md`. -- **`ath migrate`** — preview, backup, confirmation, and interactive prompt-on-open - (CR4, in progress elsewhere). This plan does not edit migrate implementation - files; Rust must call the same behavior, not fork it silently. -- **Conformance** — CR5 vectors (when landed) and existing automated tests - remain the parity gate. Rust code is wrong if vectors fail. -- **npm identity** — package name `athleticstandard`, binary `ath`, Node `>=20`, - same `package.json#exports` unless a separate semver-major API decision says - otherwise. -- **OSS thin** — no maintained Swift port, no MCP server, no “build every client - surface” unless a later, separate plan approves it. - -## 4. What would justify Rust (honest need) - -D121 blocks Rust **without demonstrated need**. Any proposal to adopt Rust should -name at least one of these **measured or reported** triggers. Vague “performance” -or “Rust is nicer” is not enough. - -1. **Release performance limits are missed after §13 remedies** — The 100k-record - CI benchmark or 3M large job fails agreed limits after indexes, batching, and - series storage options are tried in TypeScript/SQLite, and profiling shows CPU - in hot loops (import merge, series decode, baseline windows, export), not - I/O or SQLite alone. - -2. **A real builder is blocked without a native library** — Someone shipping a - non-Node app (mobile, desktop, embedded agent runtime) needs a **supported** - shared library with the same semantics as `ath`, and cannot use direct SQLite - + vectors alone within their timeline. The request must be specific (which - commands or calculations, which platform). - -3. **Security or supply-chain pressure on parsing** — A maintained importer or - decode path handles untrusted input at scale, and memory-safe native parsing - with fuzzing is judged lower risk than growing TypeScript parsers. This still - requires vectors and does not skip SQL triggers. - -4. **Contributor capacity** — At least one maintainer can own Rust toolchains, - cross-platform prebuilds, and CI for the next 12 months. Without that, defer. - -If **none** of the above is true today, the correct action is **Option A** (stay -TypeScript) and keep improving SQL and TypeScript hot paths per v1 spec §13. - -## 5. Options - -### Option A — Stay TypeScript; optimize SQLite and TypeScript only - -Keep all logic in the current repo layout. Finish CR4–CR9, land conformance -vectors, and use `performance/` benchmarks as the gate. Revisit Rust only when -§4 triggers fire. - -**Pros** - -- Matches D121 as written; no new decision required. -- One language, one toolchain, aligns with D8 distribution story. -- Zod remains normative for records; no schema drift between Rust and TS. -- Lowest CI and release complexity. - -**Cons** - -- Very large imports or series may stay slower than a tuned native core. -- Non-Node builders rely on direct SQLite + vectors, not a shared `.so`/`.dylib`. -- CPU-heavy calculations stay in Node unless moved to SQLite (views, triggers). - -### Option B — Rust library as the engine; Node CLI stays the façade - -Introduce a `crates/ath-core` (name TBD) Rust crate compiled to native addons -via **napi-rs** (or similar) and loaded from the existing `athleticstandard` -package. TypeScript keeps CLI, Skill packaging, LLM gateway hooks, and thin -wrappers. Heavy work (import merge, series math, export assembly, optional -`check` walks) moves to Rust behind stable internal FFI. - -**Pros** - -- Single npm install with prebuilt binaries per platform (napi-rs pattern). -- Strong speed and memory wins possible on hot paths without changing user - commands. -- Public API stays Node; D8 distribution story largely intact. - -**Cons** - -- Two implementations until parity is proven; ongoing sync on behavior changes. -- Release matrix: linux/macOS/windows × arm64/x64, plus musl where needed. -- Zod/JSON Schema stay in TS; Rust needs generated types or shared fixtures — - drift risk unless conformance vectors are strict. -- Debugging spans Node + native; contributors need Rust toolchain. - -### Option C — Rust only for narrow, high-value modules - -Same packaging as B, but scope Rust to **one** bounded area first, for example: - -- measurement-series decode/encode only, or -- import merge for one vendor, or -- pure calculation helpers used by `ath stats` / baselines. - -Everything else stays TypeScript. Expand only when vectors pass and §4 triggers -justify the next module. - -**Pros** - -- Smallest step that amends D121; proves CI and prebuild pipeline before a big - rewrite. -- Easier rollback: disable native addon and fall back to TS for that module. -- Lessons apply before committing to a full core port. - -**Cons** - -- Boundary design work up front (what is “pure” vs what touches SQLite). -- Two languages in production forever unless later phases expand Rust. -- Some overhead from FFI per call if modules are too granular. - -## 6. Recommendation - -**Default: Option A** until a §4 trigger is documented with evidence (benchmark -JSON, builder issue, or security review). D121 is still the right default for a -thin OSS base finishing v1 publish. - -**If the owner accepts a trigger now: start with Option C**, not a full rewrite. -First candidate module (pending owner decision §8): **measurement-series -sample decode and within-workout calculations**, because they are CPU-bound, -mostly pure, and already have clear inputs/outputs for vectors. Keep all SQLite -writes and migrations in TypeScript (or shared SQL) until CR5 vectors exist. - -**Do not choose Option B (full core)** until Option C has shipped, vectors pass, -and maintainers agree the remaining TS hot paths still fail limits. - -Option B remains the long-term shape **if** multiple modules move and maintaining -split brains in TS and Rust costs more than consolidation. - -## 7. Phased steps (only after owner approves a D-number superseding D121) - -Phase 0 — **No Rust** (current) - -- Land CR4–CR5, SQL contract drift checks, and performance baselines. -- Document current p95/p99 from `performance/results/` for the nine scenarios. - -Phase 1 — **Spike behind a flag** (Option C) - -- Add `crates/` with one crate, napi-rs wiring, and `optionalDependencies` or - prebuild download script; **no** default enable in release until vectors pass. -- Implement one module; TS retains fallback implementation. -- Extend conformance fixtures for that module (input bytes/JSON → expected - outputs). Same tests run against TS fallback and Rust path. +--- -Phase 2 — **Enable by default when parity proven** +## What we measured (2026-10-18, Linux x64, Node 22, 4 vCPUs) -- CI runs vectors on all platforms in the release matrix. -- Turn on Rust path when prebuild exists; TS fallback remains for unsupported - platforms until prebuilds exist or owner drops support. +Commands: `pnpm build`, `pnpm performance:generate`, `pnpm performance:run` +(see `performance/README.md`). Seed: `ath-v1-performance-seed-2`. -Phase 3 — **Expand or consolidate** (optional) +| Operation | 10k records (p95) | 100k records (p95) | Release limit at 100k | +|---|---:|---:|---:| +| Latest value lookup | 0.4 ms | 0.3 ms | 5 ms | +| 28-day evidence | 1.0 ms | 0.9 ms | 10 ms | +| 90-day baseline | 2.2 ms | 36 ms | 100 ms | +| Within-workout series math | 9.0 ms | 8.0 ms | 50 ms | +| Cross-source comparison | 2.0 ms | 68 ms | 150 ms | +| Incremental package import | 5.4 ms | 8.5 ms | 100 ms | +| Full JSON export | 1.4 s | 12.8 s | 20 s | +| Database check | 1.1 s | 10.3 s | 15 s | +| Initial package import | 3.3 s | **31.0 s** | **45 s** | -- Move additional hot paths per §4 evidence. -- If most logic is Rust, collapse duplicate TS implementations and document - internal API. Public npm exports unchanged. +At **100k current records** (~185 MB database, ~100k measurement samples), every +operation sits **inside** the checked limits in `performance/limits.json`. +Nothing in daily agent use (evidence, baselines, series math) is slow. The heavy +work is **whole-file**: import, export, and check walk the full dataset. -Phase 4 — **Standalone Rust library** (only on builder request) +`ath --help` cold start (8 runs): **~170 ms** median — mostly loading the bundled +JavaScript, not SQLite. -- Publish `ath-core` crate to crates.io for non-Node consumers. -- Not required for npm users; separate decision if API surface differs from FFI. +`pnpm test` (327 tests): **~90 s** wall time on this runner. -**Explicit non-goals for early phases** +**Where it hurts at scale:** the repo’s reference **3 million** record run (not +re-run here; numbers are in `performance/limits.json`) shows initial import +~17 minutes, full export ~8.8 minutes, and check ~5.7 minutes. That is I/O and +volume, not a missing Rust parser. -- Rewriting SQL migrations in Rust. -- Replacing Zod with Rust as normative record schema. -- WASM in the browser unless a builder needs it (WASM is slower for file I/O - heavy work; napi-rs is the default for Node CLI). +**SQLite today:** Athletic Standard uses **`@libsql/client`**, which already +downloads a **native libSQL binary** per platform (same class of problem as +`better-sqlite3`). Moving logic to Rust does not remove native code from +`npm install`; it would add **another** native layer on top. -## 8. Risks +--- -| Risk | Mitigation | -|---|---| -| Behavior drift between TS and Rust | CR5 conformance vectors; property tests; TS fallback until green matrix | -| Broken `npm i` on exotic platforms | TS fallback; document supported platforms; fail with clear message | -| Schema changes require two edits | TS remains normative; Rust reads fixtures; codegen later only if justified | -| `ath migrate` divergence | Migrate stays in TS/SQL; Rust never applies migrations without shared code path | -| Violating two-tier wall in native code | DB triggers remain authoritative; Rust uses same SQL write recipes | -| Team overload | Phase 1 time-box; revert if no maintainer owns Rust CI in 90 days | -| Contradicting D121 silently | Owner must approve draft D130 (below) before Phase 1 merges | +## What Rust would and would not fix -## 9. How existing and planned tests prove parity +**Would help (in theory):** tight loops on measurement samples, faster XML/CSV +parsing for huge vendor exports, lower CPU on export serialization. -**Today** +**Would not help much:** SQLite read/write and trigger enforcement (already in +the database engine), CLI startup (Node bundle load), or keeping two +implementations in sync with Zod schemas and conformance tests. -- `pnpm test` — unit and integration tests for import, check, context, grading, - package exports, SQL migration from empty DB. -- `pnpm check:public-data` — no real health data in repo. -- `performance/` — nine scenarios on 100k (CI) and 3M (large job); compare - before/after Rust with same seed and hardware notes. +**Cost:** a Rust core means prebuilt binaries per OS/CPU/libc, release CI matrix, +Rust-capable maintainers, and duplicate behavior tests. The public OSS base is +meant to stay thin (recorded as D121). The agent surface stays CLI + Skill (D7); +Rust is not an excuse to add MCP or a local HTTP server. -**After CR5 (planned)** +**Effort (rough):** one bounded napi-rs module (e.g. series decode only): +several weeks to ship safely with fallbacks. A full “Rust engine” behind `ath`: +many months and ongoing parity work. Not justified while 100k limits still pass. -- `spec/conformance/` — language-neutral fixtures; `scripts/check-conformance.ts` - runs in CI. Rust napi module runs the same vectors as TypeScript. +--- -**Parity rule** +## What other npm tools did with Rust -- For any function moved to Rust: every vector that passed in TS must pass in - Rust on all release platforms. No release if native prebuild missing on a - tier-1 platform without TS fallback. +These tools adopted Rust for **hot, repetitive CPU work** (parse, transform, +minify). They pay for it with **large optional platform packages** and CI +that builds every target. -**Regression for migrate** +| Project | Rust role | Install / ops lesson | +|---|---|---| +| [SWC](https://swc.rs/) | JS/TS compiler | Per-platform `@swc/core-*` packages; Linux x64 install ~27 MB ([comparison table](https://github.com/bluwy/npm-prebuilt-binaries-comparison)). | +| [Biome](https://biomejs.dev/) | Linter + formatter | Single meta-package; ~43–63 MB install per OS ([same comparison](https://github.com/bluwy/npm-prebuilt-binaries-comparison)). | +| [Rolldown](https://rolldown.rs/) / [Oxc](https://oxc.rs/) | Bundler / parser | Optional `@rolldown/binding-*`; WASM fallback exists but native is default for speed. | +| [Lightning CSS](https://lightningcss.dev/) | CSS transform | Smaller binaries (~8–10 MB install) because scope is narrow. | +| [Prisma ORM](https://www.prisma.io/blog/from-rust-to-typescript-a-new-chapter-for-prisma-orm) | **Moved away** from Rust engine (2025–2026) | Cross-language copies hurt; **TypeScript + WASM query compiler** replaced multi‑MB Rust binaries; simpler deploys and more contributors. | -- Do not change CR4 files in Rust PRs until CR4 lands; then add integration - tests only via existing migrate test suite, not a second migrate implementation. +**Lesson for Athletic Standard:** Rust in npm works when the win is huge and the +API surface is stable (SWC, esbuild). Prisma’s reversal is relevant: ATH already +crosses JS↔native for SQLite; adding Rust business logic increases that +boundary unless the speedup is large and measured. ATH is closer to Prisma +(data + queries + validation) than to SWC (compile loop). -## 10. npm packaging sketch (if B or C approved) +--- -- Root package `athleticstandard` remains the install target. -- `napi-rs` (or `@napi-rs/cli`) builds platform triples in release CI; artifacts - attached or published via optional dependency package pattern used by other - native npm modules. -- `engines.node >=20` unchanged. -- `package.json#exports` unchanged for public paths; optional subpath - `athleticstandard/native` only if needed for advanced embedders — owner - decision. -- WASM: reserve for a future embedder need; not the default CLI path. +## napi-rs vs WASM for `athleticstandard` -## 11. Draft decision for owner approval (not recorded yet) +| | **napi-rs** (native addon) | **WASM** | +|---|---|---| +| Fit for `ath` CLI on Node 20+ | Good — same model as libSQL today | Possible but awkward for large file I/O | +| `npm install` | +1 optional package per platform (~8–30 MB typical; see comparison above) | One portable blob; often 3–15 MB | +| Platforms | Must build/test linux/macOS/windows × arm64/x64 (+ musl) ([napi-rs docs](https://napi.rs/docs/introduction/getting-started)) | One build; slower on hot paths | +| CI | Multi-target release workflow | Simpler, but still test all vectors | +| ATH SQLite | Still need libSQL native client | Still need libSQL; WASM does not replace it | -When the owner accepts Rust work, append something like the following to -`build-history/v1.0.0/decisions.md` as **D130** (number may shift if other -decisions land first). Wording is draft only. +**Conclusion:** If ATH ever needs native code for **compute**, **napi-rs** matches +the existing libSQL distribution story. **WASM** is a poor default for +multi‑gigabyte import/export paths. Neither removes the SQLite native dependency. --- -### D130. Rust core modules only after demonstrated need (draft) - -Athletic Standard adopts Rust **only** for bounded, measured needs inside the -existing `athleticstandard` npm package. D121’s “no Rust core now” is -superseded **to the extent** the owner documents a §4 trigger and approves a -phase-1 module list. D121’s thin-OSS principle remains: no MCP, no HTTP -service, no maintained Swift port, and no full language port without vectors. +## What we do now -D7 remains in force. D8 remains in force for npm install and CLI entry; TypeScript -keeps Zod normative schemas and the `ath` command surface. +1. **Stay TypeScript.** Finish v1 publish work, SQL contract, conformance vectors, + and `ath migrate` (in flight elsewhere). +2. **Optimize where the timers point:** batching, indexes, export/check streaming, + and series storage per v1 spec §13 — all before any Rust spike. +3. **Keep `performance/` as the gate.** Limits at 100k and 3M are already encoded. -Rust code must pass the same conformance vectors as TypeScript, keep SQLite -triggers as the enforcement layer for the two-tier wall, and not fork `ath -migrate` behavior. +**Revisit Rust when any of these happen:** -Rejected alternatives: +- **100k initial import** p95 **exceeds 45 s**, or **full JSON export** p95 + **exceeds 20 s**, on the reference runner **after** §13 optimizations land; or +- **3M** initial import p95 **exceeds 30 minutes** after the same optimizations; or +- A **documented builder** needs a supported native library and cannot use direct + SQLite + public vectors within their timeline. -- **Full Rust rewrite before vectors exist.** Rejected because parity cannot be - proven and D121’s intent would be bypassed. -- **Rust as a separate product without npm integration.** Rejected because - distribution and the `ath` CLI must stay `npm i athleticstandard`. -- **Adopt Rust without a named maintainer.** Rejected because native prebuilds - require ongoing CI ownership. +If a trigger fires, start with **one** narrow native module (series math or import +parse), TypeScript fallback, and shared conformance fixtures — not a full rewrite. --- -Until D130 (or equivalent) is appended and approved, **do not merge Rust code**. - -## 12. Open decisions (owner — answer in order) - -1. **Is there a documented §4 trigger today?** If no, stop at Option A and - close this plan until evidence exists. If yes, name which trigger (1–4) and - attach data (benchmark file, issue link, or security note). +## Draft decision for owner (not recorded until approved) -2. **Which option?** A (stay TS), B (full Rust core behind npm), or C (one - module first). Recommendation: A unless (1) is yes; then C. +### D130 (draft). Defer a Rust core until measured limits or a builder force it -3. **First Rust module (only if C or B):** measurement-series math, import - merge, baselines/stats, export assembly, or other — pick one for phase 1. +Athletic Standard does **not** add a Rust core for v1.0.0. D121’s thin public +base stays: file, spec, vectors, CLI, Skills — no maintained Rust port until +the revisit triggers in this plan are met. -4. **Binding technology:** napi-rs native prebuilds (recommended for CLI) vs - WASM vs both. Recommendation: napi-rs for Node; defer WASM. +If a trigger is met, Rust may ship **inside** `athleticstandard` behind existing +commands, with conformance parity and without changing D7’s CLI + Skill surface. -5. **Platform tier-1 list for native prebuilds:** e.g. `linux-x64-gnu`, - `linux-arm64-gnu`, `darwin-arm64`, `darwin-x64`, `win32-x64-msvc` — confirm - or shrink. +Rejected for now: -6. **TS fallback policy:** require fallback implementation until all tier-1 - prebuilds ship (recommended) vs hard-require native and fail install - elsewhere. +- **Rust core without failed limits or a named builder.** Extra native binaries + and maintainers without a measured win. +- **WASM as the default CLI engine.** Poor fit for large SQLite-backed I/O. +- **Replacing libSQL with better-sqlite3 just to “add Rust.”** ATH already uses + a native SQLite stack; the question is application logic, not the driver brand. -7. **When to append D130:** approve this plan as-is, approve with edits, or - reject and keep D121 with no Rust timeline. - -## 13. Relationship to in-flight work - -| Work | Relationship | -|---|---| -| CR4 `ath migrate` | Do not edit migrate sources in Rust planning PRs; Rust must use the same UX and SQL outcomes when it touches DBs. | -| CR5 conformance vectors | Prerequisite before enabling Rust by default; Rust spike may add vectors for its module in the same PR series. | -| CR8 workspace split | Compatible: `@ath/core` pure logic is the first TS boundary; Rust module replaces or accelerates the same pure functions, not `store` migrations first. | -| v1.0.0 npm publish | Rust is not a release gate for v1.0.0 unless the owner explicitly promotes it. | +--- -## 14. Approval checklist +**Placement note:** `build-history/README.md` does not name a folder for +unapproved plans. This file stays at `build-history/plans/rust-adoption.md` +until approval; then it should be linked from a recorded D-number in the +appropriate version folder (likely `v1.0.0/appendix/` if the work does not +change the format version). -- [ ] Owner answered open decisions 1–7. -- [ ] Draft D130 text accepted or edited. -- [ ] Plan moved or linked from `build-history/v1.0.0/decisions.md` per - repository process. -- [ ] No Rust implementation merged before D130 is recorded. +**Evidence artifacts (local only, not committed):** +`performance/generated/{10k,100k}/`, `performance/results/local/*-rust-plan.json`. From 5fff98dc13f1cad6cadd895e0975d7c879377d4a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 18 Oct 2026 02:22:51 +0000 Subject: [PATCH 03/10] Remove benchmarking from Rust plan; pause rewrite Per owner direction: drop ATH timing and performance framing. Mark plan paused until focus is set. README plans/ rule remains reverted. Signed-off-by: Cursor Agent Co-authored-by: Michael Whitham --- build-history/plans/rust-adoption.md | 114 ++++++--------------------- 1 file changed, 22 insertions(+), 92 deletions(-) diff --git a/build-history/plans/rust-adoption.md b/build-history/plans/rust-adoption.md index e9bc3389..e48ff6b3 100644 --- a/build-history/plans/rust-adoption.md +++ b/build-history/plans/rust-adoption.md @@ -1,72 +1,24 @@ # Should Athletic Standard use Rust? -**Recommendation:** **No — not now.** Keep the core in TypeScript and SQLite. -Ship v1 on the current stack. Revisit Rust only if release performance -limits fail **after** the SQL and batching improvements already listed in the -v1 build spec, or if a builder proves they cannot ship without a supported -native library. +**Recommendation (interim):** **No — not now.** Keep the core in TypeScript and +SQLite and ship v1 on the current stack. D121 keeps the public OSS base thin; D7 +keeps the agent surface as CLI + Skill, not MCP or a local HTTP service. This note lives in `build-history/plans/` as a proposed plan. It is not approved and does not add a D-number to `decisions.md` yet. ---- - -## What we measured (2026-10-18, Linux x64, Node 22, 4 vCPUs) - -Commands: `pnpm build`, `pnpm performance:generate`, `pnpm performance:run` -(see `performance/README.md`). Seed: `ath-v1-performance-seed-2`. - -| Operation | 10k records (p95) | 100k records (p95) | Release limit at 100k | -|---|---:|---:|---:| -| Latest value lookup | 0.4 ms | 0.3 ms | 5 ms | -| 28-day evidence | 1.0 ms | 0.9 ms | 10 ms | -| 90-day baseline | 2.2 ms | 36 ms | 100 ms | -| Within-workout series math | 9.0 ms | 8.0 ms | 50 ms | -| Cross-source comparison | 2.0 ms | 68 ms | 150 ms | -| Incremental package import | 5.4 ms | 8.5 ms | 100 ms | -| Full JSON export | 1.4 s | 12.8 s | 20 s | -| Database check | 1.1 s | 10.3 s | 15 s | -| Initial package import | 3.3 s | **31.0 s** | **45 s** | - -At **100k current records** (~185 MB database, ~100k measurement samples), every -operation sits **inside** the checked limits in `performance/limits.json`. -Nothing in daily agent use (evidence, baselines, series math) is slow. The heavy -work is **whole-file**: import, export, and check walk the full dataset. - -`ath --help` cold start (8 runs): **~170 ms** median — mostly loading the bundled -JavaScript, not SQLite. - -`pnpm test` (327 tests): **~90 s** wall time on this runner. - -**Where it hurts at scale:** the repo’s reference **3 million** record run (not -re-run here; numbers are in `performance/limits.json`) shows initial import -~17 minutes, full export ~8.8 minutes, and check ~5.7 minutes. That is I/O and -volume, not a missing Rust parser. - -**SQLite today:** Athletic Standard uses **`@libsql/client`**, which already -downloads a **native libSQL binary** per platform (same class of problem as -`better-sqlite3`). Moving logic to Rust does not remove native code from -`npm install`; it would add **another** native layer on top. +**Status:** Mike asked to drop performance benchmarking from this plan and to +**pause** further rewriting until he sets what the plan should focus on. The +sections below are background only, not a finished proposal. --- -## What Rust would and would not fix - -**Would help (in theory):** tight loops on measurement samples, faster XML/CSV -parsing for huge vendor exports, lower CPU on export serialization. +## SQLite and native code today -**Would not help much:** SQLite read/write and trigger enforcement (already in -the database engine), CLI startup (Node bundle load), or keeping two -implementations in sync with Zod schemas and conformance tests. - -**Cost:** a Rust core means prebuilt binaries per OS/CPU/libc, release CI matrix, -Rust-capable maintainers, and duplicate behavior tests. The public OSS base is -meant to stay thin (recorded as D121). The agent surface stays CLI + Skill (D7); -Rust is not an excuse to add MCP or a local HTTP server. - -**Effort (rough):** one bounded napi-rs module (e.g. series decode only): -several weeks to ship safely with fallbacks. A full “Rust engine” behind `ath`: -many months and ongoing parity work. Not justified while 100k limits still pass. +Athletic Standard uses **`@libsql/client`**, which already downloads a **native +libSQL binary** per platform (similar in distribution terms to `better-sqlite3`). +Adding a Rust application core would not remove native code from `npm install`; +it would add another native layer on top of the existing SQLite client. --- @@ -87,8 +39,8 @@ that builds every target. **Lesson for Athletic Standard:** Rust in npm works when the win is huge and the API surface is stable (SWC, esbuild). Prisma’s reversal is relevant: ATH already crosses JS↔native for SQLite; adding Rust business logic increases that -boundary unless the speedup is large and measured. ATH is closer to Prisma -(data + queries + validation) than to SWC (compile loop). +boundary. ATH is closer to Prisma (data + queries + validation) than to SWC +(compile loop). --- @@ -104,46 +56,27 @@ boundary unless the speedup is large and measured. ATH is closer to Prisma **Conclusion:** If ATH ever needs native code for **compute**, **napi-rs** matches the existing libSQL distribution story. **WASM** is a poor default for -multi‑gigabyte import/export paths. Neither removes the SQLite native dependency. - ---- - -## What we do now - -1. **Stay TypeScript.** Finish v1 publish work, SQL contract, conformance vectors, - and `ath migrate` (in flight elsewhere). -2. **Optimize where the timers point:** batching, indexes, export/check streaming, - and series storage per v1 spec §13 — all before any Rust spike. -3. **Keep `performance/` as the gate.** Limits at 100k and 3M are already encoded. - -**Revisit Rust when any of these happen:** - -- **100k initial import** p95 **exceeds 45 s**, or **full JSON export** p95 - **exceeds 20 s**, on the reference runner **after** §13 optimizations land; or -- **3M** initial import p95 **exceeds 30 minutes** after the same optimizations; or -- A **documented builder** needs a supported native library and cannot use direct - SQLite + public vectors within their timeline. - -If a trigger fires, start with **one** narrow native module (series math or import -parse), TypeScript fallback, and shared conformance fixtures — not a full rewrite. +large SQLite-backed import/export paths. Neither removes the SQLite native +dependency. --- ## Draft decision for owner (not recorded until approved) -### D130 (draft). Defer a Rust core until measured limits or a builder force it +### D130 (draft). Defer a Rust core unless a later plan approves it Athletic Standard does **not** add a Rust core for v1.0.0. D121’s thin public base stays: file, spec, vectors, CLI, Skills — no maintained Rust port until -the revisit triggers in this plan are met. +a future owner-approved plan supersedes that deferral. -If a trigger is met, Rust may ship **inside** `athleticstandard` behind existing -commands, with conformance parity and without changing D7’s CLI + Skill surface. +If Rust is approved later, it may ship **inside** `athleticstandard` behind +existing commands, with conformance parity and without changing D7’s CLI + Skill +surface. Rejected for now: -- **Rust core without failed limits or a named builder.** Extra native binaries - and maintainers without a measured win. +- **Rust core without an approved plan and named need.** Extra native binaries + and maintainers under D121. - **WASM as the default CLI engine.** Poor fit for large SQLite-backed I/O. - **Replacing libSQL with better-sqlite3 just to “add Rust.”** ATH already uses a native SQLite stack; the question is application logic, not the driver brand. @@ -155,6 +88,3 @@ unapproved plans. This file stays at `build-history/plans/rust-adoption.md` until approval; then it should be linked from a recorded D-number in the appropriate version folder (likely `v1.0.0/appendix/` if the work does not change the format version). - -**Evidence artifacts (local only, not committed):** -`performance/generated/{10k,100k}/`, `performance/results/local/*-rust-plan.json`. From 5610f02b2375778b1f2c643bcf415889bbf26564 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 18 Oct 2026 02:25:22 +0000 Subject: [PATCH 04/10] Rewrite Rust plan around one embeddable engine Goal: single Rust core with per-platform bindings; athleticstandard wraps via napi-rs. Research, tooling, phased PRs, draft D130/D131. Signed-off-by: Cursor Agent Co-authored-by: Michael Whitham --- build-history/plans/rust-adoption.md | 202 +++++++++++++++++++-------- 1 file changed, 140 insertions(+), 62 deletions(-) diff --git a/build-history/plans/rust-adoption.md b/build-history/plans/rust-adoption.md index e48ff6b3..f8db0579 100644 --- a/build-history/plans/rust-adoption.md +++ b/build-history/plans/rust-adoption.md @@ -1,90 +1,168 @@ -# Should Athletic Standard use Rust? +# One Rust engine for Athletic Standard -**Recommendation (interim):** **No — not now.** Keep the core in TypeScript and -SQLite and ship v1 on the current stack. D121 keeps the public OSS base thin; D7 -keeps the agent surface as CLI + Skill, not MCP or a local HTTP service. +**What we are doing:** Build **one** Athletic Standard engine in Rust. Every +platform links that same library directly. There is no local HTTP service, no +MCP server, and no second implementation in TypeScript, Swift, or Kotlin. The +existing npm package **`athleticstandard`** and the **`ath`** CLI stay the public +install path (`npm i athleticstandard`); they become a thin Node wrapper around +the Rust engine, same as an iOS or Python app would use. -This note lives in `build-history/plans/` as a proposed plan. It is not -approved and does not add a D-number to `decisions.md` yet. +**Why:** Builders want to read and write the athlete file from watches, phones, +desktop apps, Python notebooks, and the web without re‑implementing rules that +already live in SQL triggers, Zod schemas, and migration logic. One engine +means one place to fix bugs and one set of conformance tests for every language. -**Status:** Mike asked to drop performance benchmarking from this plan and to -**pause** further rewriting until he sets what the plan should focus on. The -sections below are background only, not a finished proposal. +This plan is **proposed** (not approved). It lives at +`build-history/plans/rust-adoption.md` until the owner records draft decisions +below in `decisions.md`. --- -## SQLite and native code today +## What others learned shipping Rust to many languages -Athletic Standard uses **`@libsql/client`**, which already downloads a **native -libSQL binary** per platform (similar in distribution terms to `better-sqlite3`). -Adding a Rust application core would not remove native code from `npm install`; -it would add another native layer on top of the existing SQLite client. +| Project | Pattern | What worked | What hurt | +|---|---|---|---| +| [Mozilla application-services](https://github.com/mozilla/application-services/) + [UniFFI](https://github.com/mozilla/uniffi-rs) | Rust components; Kotlin/Swift/Python from UniFFI; iOS “megazord” XCFramework | Same API shape on mobile; Glean moved bindings to UniFFI and cut glue code ([talk slides](https://fnordig.de/talks/2022/dataclub/glean-uniffi-migration.pdf)) | Large CI matrix; Rust + mobile toolchains; cross-team ownership | +| [Signal libsignal](https://github.com/signalapp/libsignal) | Custom `#[bridge_fn]` macros; C FFI + JNI + Node; Maven/CocoaPods with prebuilt natives | Tight control over crypto APIs; published artifacts per platform ([bridge README](https://github.com/signalapp/libsignal/blob/main/rust/bridge/README.md)) | Heavy custom tooling (`cbindgen`, `gen_java_decl.py`); few casual contributors | +| [Matrix Rust SDK](https://github.com/matrix-org/matrix-rust-sdk/blob/main/ARCHITECTURE.md) | Core crates + `matrix-sdk-ffi` (UniFFI) for Swift/Kotlin; separate `wasm-bindgen` for web crypto | Clear split: Rust core, thin FFI, platform packages ([bindings](https://github.com/matrix-org/matrix-rust-sdk/tree/main/bindings)) | Android/iOS release profiles tuned for binary size; many targets to build | +| [Automerge](https://github.com/automerge/automerge) | Rust core; JS via WASM; C for other languages | One CRDT implementation everywhere ([2.0 blog](https://automerge.org/blog/automerge-2/)) | WASM loading differs per bundler ([init docs](https://automerge.org/docs/reference/library-initialization/)); React Native needed C, not WASM | +| [Polars](https://github.com/pola-rs/polars) | Rust query engine; Python via PyO3/maturin; Node via [napi-rs](https://github.com/pola-rs/nodejs-polars) | Each host gets idiomatic API; Rust stays internal | Multiple binding stacks (PyO3 vs napi-rs); compile farms for releases | ---- +**Lessons for ATH:** Use **one FFI strategy per host family** (UniFFI for +Apple/Android/Python, napi-rs for Node, wasm-bindgen for browser). Keep the +**public contract** in `spec/` (SQL files, JSON schemas, conformance vectors) so +bindings do not become a second spec. Expect **release engineering** to be a real +job: prebuilt libraries per OS/CPU, not just Rust source. Plan for **fewer +casual contributors** in the core; most app developers only touch thin wrappers. -## What other npm tools did with Rust +--- -These tools adopted Rust for **hot, repetitive CPU work** (parse, transform, -minify). They pay for it with **large optional platform packages** and CI -that builds every target. +## Recommended tooling -| Project | Rust role | Install / ops lesson | +| Layer | Choice | Reason | |---|---|---| -| [SWC](https://swc.rs/) | JS/TS compiler | Per-platform `@swc/core-*` packages; Linux x64 install ~27 MB ([comparison table](https://github.com/bluwy/npm-prebuilt-binaries-comparison)). | -| [Biome](https://biomejs.dev/) | Linter + formatter | Single meta-package; ~43–63 MB install per OS ([same comparison](https://github.com/bluwy/npm-prebuilt-binaries-comparison)). | -| [Rolldown](https://rolldown.rs/) / [Oxc](https://oxc.rs/) | Bundler / parser | Optional `@rolldown/binding-*`; WASM fallback exists but native is default for speed. | -| [Lightning CSS](https://lightningcss.dev/) | CSS transform | Smaller binaries (~8–10 MB install) because scope is narrow. | -| [Prisma ORM](https://www.prisma.io/blog/from-rust-to-typescript-a-new-chapter-for-prisma-orm) | **Moved away** from Rust engine (2025–2026) | Cross-language copies hurt; **TypeScript + WASM query compiler** replaced multi‑MB Rust binaries; simpler deploys and more contributors. | - -**Lesson for Athletic Standard:** Rust in npm works when the win is huge and the -API surface is stable (SWC, esbuild). Prisma’s reversal is relevant: ATH already -crosses JS↔native for SQLite; adding Rust business logic increases that -boundary. ATH is closer to Prisma (data + queries + validation) than to SWC -(compile loop). +| SQLite in Rust | [`rusqlite`](https://github.com/rusqlite/rusqlite) (bundled SQLite, same pragmas as `spec/sql/README.md`) | One engine owns migrations and writes; matches published SQL contract | +| Node / `athleticstandard` | [napi-rs](https://napi.rs/docs/introduction/getting-started) | Same distribution model as today’s native deps; optional per-platform npm packages | +| Swift, Kotlin, Python | [UniFFI](https://mozilla.github.io/uniffi-rs/) | Proven for mobile + Python; generates bindings from Rust API surface | +| Web | [wasm-bindgen](https://rustwasm.github.io/wasm-bindgen/) (+ `wasm-pack` or npm WASM asset) | Direct file access in browser is limited; WASM fits sandboxed embedders | +| C API (optional later) | UniFFI’s C scaffolding or a thin `extern "C"` layer | Escape hatch for watch OS or embedders UniFFI does not cover yet | + +**Not recommended:** A separate local service (violates product shape and D7). +**Not in scope for step 1:** Replacing the Skill or CLI UX—only the engine +underneath. --- -## napi-rs vs WASM for `athleticstandard` +## Rust core vs thin platform shells + +**Inside the Rust engine (`ath-core` or similar workspace crate):** + +- Open, migrate, and check `athlete.ath.sqlite` using the ordered SQL in + `spec/sql/migrations/` and metadata rules in `spec/sql/README.md`. +- Enforce athlete-record rules in code **and** rely on existing SQL triggers for + the two-tier wall, extension envelope limits, and other database-enforced + rules. +- Validation of record payloads against the v1 format (aligned with + `src/v1/schema.ts` / generated JSON Schema until a single schema source is + chosen). +- Measurement-series encode/decode and shared calculations (baselines, stats, + within-workout math). +- JSON package import/export parity with today’s portable format. +- Migration preview/apply logic used by `ath migrate` (behavior must match CR4; + implementation moves to Rust without changing the UX contract). + +**Stays thin per platform:** + +- **Node:** Commander CLI, Skill packaging, help text generation, LLM gateway + hooks for `predict` / `backtest` (D7: still CLI + Skill, not MCP). +- **Swift / Kotlin:** App UI, permissions, background tasks, file pickers. +- **Python:** Notebooks and scripts call UniFFI bindings. +- **Web:** WASM module + JS loader; host app handles storage APIs. + +**Same results everywhere:** `spec/conformance/` vectors (CR5) and existing +`pnpm test` scenarios become the cross-language gate. Each binding runs the +same fixtures; Rust is the reference implementation. Record content version +(`athleticstandard_version`) and SQL schema version (`sql_schema_version`) stay +independent, as today. -| | **napi-rs** (native addon) | **WASM** | -|---|---|---| -| Fit for `ath` CLI on Node 20+ | Good — same model as libSQL today | Possible but awkward for large file I/O | -| `npm install` | +1 optional package per platform (~8–30 MB typical; see comparison above) | One portable blob; often 3–15 MB | -| Platforms | Must build/test linux/macOS/windows × arm64/x64 (+ musl) ([napi-rs docs](https://napi.rs/docs/introduction/getting-started)) | One build; slower on hot paths | -| CI | Multi-target release workflow | Simpler, but still test all vectors | -| ATH SQLite | Still need libSQL native client | Still need libSQL; WASM does not replace it | +--- + +## Step-by-step path (each step = its own PR) + +1. **Rust core + Node wrapper, tests green.** Add `crates/ath-core`, wire + napi-rs into `athleticstandard`, call Rust for database open/migrate/check + and one read path. Keep TypeScript implementations behind a flag as fallback + until vectors pass on all CI platforms. Do not change `package.json` name, + `bin`, or `engines`. + +2. **Move write paths and import/export.** Port package import, export, and + validation into the engine; delete duplicate TS logic once parity tests pass. + Regenerate nothing by hand—`pnpm generate:*` stays the source for published + `spec/` artifacts. + +3. **Swift package (UniFFI).** XCFramework or SwiftPM wrapper; document how an + iOS or watch app opens the same SQLite file. No separate “ATH service.” + +4. **Kotlin / Android (UniFFI).** Same FFI crate as Swift; publish AAR or Maven + coordinates as a follow-on decision. -**Conclusion:** If ATH ever needs native code for **compute**, **napi-rs** matches -the existing libSQL distribution story. **WASM** is a poor default for -large SQLite-backed import/export paths. Neither removes the SQLite native -dependency. +5. **Python (UniFFI).** Wheel with extension module for agents and science + stacks. + +6. **Web (wasm-bindgen).** Crate subset for validation and read-only paths where + full SQLite in WASM is acceptable; document limits for large files. + +7. **Retire the TypeScript engine.** Remove fallback once Node, Swift, and + conformance CI all use Rust only. + +Steps 3–6 can reorder if a builder need appears first; steps 1–2 block +everything else. --- -## Draft decision for owner (not recorded until approved) +## Risks and costs + +- **Maintainers:** Need Rust plus release tooling for mobile and npm prebuilds. +- **CI:** Multi-target builds (see Matrix “small-release” profiles for size). +- **Schema drift:** Until one generator owns types, Rust and Zod must both run + conformance checks on every PR. +- **D121 “thin OSS”:** This plan **widens** the core deliberately; it does not + add MCP, HTTP, or extra maintained *ports*—it replaces ports with bindings. + +--- + +## Draft decisions for owner (not recorded until approved) + +### D130 (draft). Single Rust engine with generated language bindings + +Athletic Standard implements file logic **once** in Rust. The npm package +`athleticstandard` and the `ath` CLI remain the Node distribution and wrap that +engine via napi-rs. Swift, Kotlin, Python, and web embedders use UniFFI or +wasm-bindgen rather than maintained hand-written ports. -### D130 (draft). Defer a Rust core unless a later plan approves it +This **supersedes D121** only for “no Rust core”: Rust is approved as the core, +not as an optional speed-up. D121’s rejection of a local HTTP service, MCP +server, and unrelated language ports **remains**. D7 **remains**: agents use CLI ++ Skill; Rust does not add a conversational server. -Athletic Standard does **not** add a Rust core for v1.0.0. D121’s thin public -base stays: file, spec, vectors, CLI, Skills — no maintained Rust port until -a future owner-approved plan supersedes that deferral. +Rejected alternatives: -If Rust is approved later, it may ship **inside** `athleticstandard` behind -existing commands, with conformance parity and without changing D7’s CLI + Skill -surface. +- **Separate TypeScript engine long term.** Two implementations will diverge on + triggers, migrations, and vectors. +- **Local API service for mobile.** Extra process and deployment; bindings only. +- **Per-app copy-paste of SQL rules.** Already rejected by the public SQL + contract; engine must execute that contract. -Rejected for now: +### D131 (draft). Public spec and vectors outrank binding APIs -- **Rust core without an approved plan and named need.** Extra native binaries - and maintainers under D121. -- **WASM as the default CLI engine.** Poor fit for large SQLite-backed I/O. -- **Replacing libSQL with better-sqlite3 just to “add Rust.”** ATH already uses - a native SQLite stack; the question is application logic, not the driver brand. +The normative contracts are `spec/sql/`, generated JSON Schema, and +`spec/conformance/`. Generated binding APIs may change between releases if the +spec version does not. Breaking record or SQL schema versions follow the +existing format versioning rules. --- -**Placement note:** `build-history/README.md` does not name a folder for -unapproved plans. This file stays at `build-history/plans/rust-adoption.md` -until approval; then it should be linked from a recorded D-number in the -appropriate version folder (likely `v1.0.0/appendix/` if the work does not -change the format version). +**Placement:** `build-history/README.md` does not name a folder for unapproved +plans. This file remains here until approval, then moves or links from +`build-history/v1.0.0/appendix/` and a recorded D-number (format version +unchanged if only implementation moves). From aaf6d5235795315cbc358e5e7668fb2f100be72c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 02:39:38 +0000 Subject: [PATCH 05/10] docs: revise Rust adoption plan per owner brief Rewrite rust-adoption.md (no TS fallback or engine flag), add capability inventory and calculation coverage tables, append proposed D130-D132 reconciled with D116/D121/D125, and update AGENTS.md and progress. Co-authored-by: Michael Whitham --- AGENTS.md | 5 +- build-history/plans/rust-adoption.md | 408 +++++++++++++----- .../plans/rust-calculation-coverage.md | 79 ++++ .../plans/rust-capability-inventory.md | 76 ++++ build-history/v1.0.0/decisions.md | 65 +++ build-history/v1.0.0/progress.md | 15 + 6 files changed, 527 insertions(+), 121 deletions(-) create mode 100644 build-history/plans/rust-calculation-coverage.md create mode 100644 build-history/plans/rust-capability-inventory.md diff --git a/AGENTS.md b/AGENTS.md index d87d0351..f194b5d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,8 @@ 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` feeds generated JSON Schema; `src/schema.ts` is legacy 0.x. The proposed Rust plan (D130–D132, `build-history/plans/rust-adoption.md`) moves the normative record model into `ath-core` with generated JSON Schema and TypeScript types — do not extend hand-maintained Zod as the long-term source of truth once that cutover lands. +9. **`build-history/plans/rust-adoption.md`** — proposed single Rust core, prerequisites, migration stages, and deletion gates. Inventory and calculation coverage tables live beside it in `build-history/plans/`. 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 @@ -27,7 +28,7 @@ describe released 0.x behavior. - **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). +- **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, run `pnpm generate:sql-contract` if the TypeScript migration strings remain the authoring path, and keep `spec/sql/` in sync. 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). When Rust owns the model (D131), regenerate JSON Schema and TypeScript from Rust instead of editing Zod as normative. - **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/plans/rust-adoption.md b/build-history/plans/rust-adoption.md index f8db0579..3cebb8bc 100644 --- a/build-history/plans/rust-adoption.md +++ b/build-history/plans/rust-adoption.md @@ -1,168 +1,338 @@ -# One Rust engine for Athletic Standard +# Rust adoption plan (proposed) -**What we are doing:** Build **one** Athletic Standard engine in Rust. Every -platform links that same library directly. There is no local HTTP service, no -MCP server, and no second implementation in TypeScript, Swift, or Kotlin. The -existing npm package **`athleticstandard`** and the **`ath`** CLI stay the public -install path (`npm i athleticstandard`); they become a thin Node wrapper around -the Rust engine, same as an iOS or Python app would use. +**Status:** proposed. Recorded draft decisions: D130–D132 in +`build-history/v1.0.0/decisions.md`. Supporting tables: +[`rust-capability-inventory.md`](rust-capability-inventory.md), +[`rust-calculation-coverage.md`](rust-calculation-coverage.md). -**Why:** Builders want to read and write the athlete file from watches, phones, -desktop apps, Python notebooks, and the web without re‑implementing rules that -already live in SQL triggers, Zod schemas, and migration logic. One engine -means one place to fix bugs and one set of conformance tests for every language. +**Goal:** One Rust core (`ath-core`) holds every rule about athlete records. Node, +iOS, and later hosts use thin bindings. Keep the npm package name +`athleticstandard` and the `ath` command. Do not add a local HTTP service or MCP +server (D7 stands). -This plan is **proposed** (not approved). It lives at -`build-history/plans/rust-adoption.md` until the owner records draft decisions -below in `decisions.md`. +This plan supersedes earlier draft text in this file that described a TypeScript +fallback flag or a long-term dual engine. There is one cutover, not a permanent +switch. --- -## What others learned shipping Rust to many languages +## 1. Starting point (repository today) -| Project | Pattern | What worked | What hurt | -|---|---|---|---| -| [Mozilla application-services](https://github.com/mozilla/application-services/) + [UniFFI](https://github.com/mozilla/uniffi-rs) | Rust components; Kotlin/Swift/Python from UniFFI; iOS “megazord” XCFramework | Same API shape on mobile; Glean moved bindings to UniFFI and cut glue code ([talk slides](https://fnordig.de/talks/2022/dataclub/glean-uniffi-migration.pdf)) | Large CI matrix; Rust + mobile toolchains; cross-team ownership | -| [Signal libsignal](https://github.com/signalapp/libsignal) | Custom `#[bridge_fn]` macros; C FFI + JNI + Node; Maven/CocoaPods with prebuilt natives | Tight control over crypto APIs; published artifacts per platform ([bridge README](https://github.com/signalapp/libsignal/blob/main/rust/bridge/README.md)) | Heavy custom tooling (`cbindgen`, `gen_java_decl.py`); few casual contributors | -| [Matrix Rust SDK](https://github.com/matrix-org/matrix-rust-sdk/blob/main/ARCHITECTURE.md) | Core crates + `matrix-sdk-ffi` (UniFFI) for Swift/Kotlin; separate `wasm-bindgen` for web crypto | Clear split: Rust core, thin FFI, platform packages ([bindings](https://github.com/matrix-org/matrix-rust-sdk/tree/main/bindings)) | Android/iOS release profiles tuned for binary size; many targets to build | -| [Automerge](https://github.com/automerge/automerge) | Rust core; JS via WASM; C for other languages | One CRDT implementation everywhere ([2.0 blog](https://automerge.org/blog/automerge-2/)) | WASM loading differs per bundler ([init docs](https://automerge.org/docs/reference/library-initialization/)); React Native needed C, not WASM | -| [Polars](https://github.com/pola-rs/polars) | Rust query engine; Python via PyO3/maturin; Node via [napi-rs](https://github.com/pola-rs/nodejs-polars) | Each host gets idiomatic API; Rust stays internal | Multiple binding stacks (PyO3 vs napi-rs); compile farms for releases | +Reviewed on branch `cursor/rust-adoption-plan-0ce5` after merging `main`. -**Lessons for ATH:** Use **one FFI strategy per host family** (UniFFI for -Apple/Android/Python, napi-rs for Node, wasm-bindgen for browser). Keep the -**public contract** in `spec/` (SQL files, JSON schemas, conformance vectors) so -bindings do not become a second spec. Expect **release engineering** to be a real -job: prebuilt libraries per OS/CPU, not just Rust source. Plan for **fewer -casual contributors** in the core; most app developers only touch thin wrappers. +| Check | Baseline result | +|---|---| +| `pnpm check:public-data` | pass | +| `pnpm typecheck` | pass | +| `pnpm test` | pass (31 files, 327 tests) | +| `pnpm build` | pass | + +**What exists:** v1 SQLite via libSQL in TypeScript (`src/db/`), Zod normative +records in `src/v1/schema.ts`, published SQL under `spec/sql/` (still generated +from TypeScript migration strings), provider importers through a legacy 0.x hop, +calculation operations in `src/db/calculate.ts`, contribution foundation CR1–CR3 +done (D115–D129), CR5 conformance vectors still pending. + +**Open pull requests to coordinate with (do not duplicate):** + +- [#20](https://github.com/mwhitham/ath/pull/20) — this plan and decisions. +- [#15](https://github.com/mwhitham/ath/pull/15) — contribution-readiness plan text; + prerequisite work lands on `main` with decisions already partially recorded (D129). +- [#25](https://github.com/mwhitham/ath/pull/25) — migrate flow, import check, + structured logging, docs; port behavior to Rust after it stabilizes in TypeScript. + +**Grokbot verification:** No Grokbot-named code, scenarios, or browser verifier +live in this repository today. Reuse existing Vitest coverage (`tests/v1-cli-writes.test.ts`, +`tests/v1-export-import.test.ts`, `tests/v1-direct-sql.test.ts`, provider import tests) +as the behavioral catalog until Grokbot publishes shared scenario IDs. During transition, +any browser-based verifier Grokbot maintains can run against the same synthetic fixtures +under `spec/conformance/`. **Owner:** Grokbot owns verification evidence; Rust work +owns core, bindings, and packaging. + +**SwiftUI verification app (single location):** `apps/verification-ios/` — small +SwiftUI app depending on the UniFFI Swift package from `crates/ath-uniffi`. It opens +a snapshot `.ath.sqlite` produced by the installed CLI, applies one correction, and +writes history. Do not add a second demo app elsewhere in the repo. --- -## Recommended tooling +## 2. Architecture: one core, thin consumers -| Layer | Choice | Reason | -|---|---|---| -| SQLite in Rust | [`rusqlite`](https://github.com/rusqlite/rusqlite) (bundled SQLite, same pragmas as `spec/sql/README.md`) | One engine owns migrations and writes; matches published SQL contract | -| Node / `athleticstandard` | [napi-rs](https://napi.rs/docs/introduction/getting-started) | Same distribution model as today’s native deps; optional per-platform npm packages | -| Swift, Kotlin, Python | [UniFFI](https://mozilla.github.io/uniffi-rs/) | Proven for mobile + Python; generates bindings from Rust API surface | -| Web | [wasm-bindgen](https://rustwasm.github.io/wasm-bindgen/) (+ `wasm-pack` or npm WASM asset) | Direct file access in browser is limited; WASM fits sandboxed embedders | -| C API (optional later) | UniFFI’s C scaffolding or a thin `extern "C"` layer | Escape hatch for watch OS or embedders UniFFI does not cover yet | +| Component | Responsibility | +|---|---| +| **ath-core** | Records, validation, storage, history, conflicts, provider parsing, +normalization, calculations, package import/export, attachments, deletion, erasure | +| **ath-node** | napi-rs bindings; blocking work off the Node event loop | +| **ath-uniffi** | UniFFI bindings; exercised through Swift first | +| **TypeScript CLI** | Arguments, help, presentation, Skill, credentials, external model calls | +| **Swift app** | `apps/verification-ios/` — screens, file access, permissions, lifecycle | -**Not recommended:** A separate local service (violates product shape and D7). -**Not in scope for step 1:** Replacing the Skill or CLI UX—only the engine -underneath. +Internal Rust modules stay inside `ath-core` unless a dependency forces a separate +crate. Storage starts with **rusqlite** and bundled SQLite, matching `spec/sql/` +pragmas and triggers. + +Platform code may read HealthKit or file exports. ATH interpretation, normalization, +and write decisions live in Rust. --- -## Rust core vs thin platform shells +## 3. Remove duplicate rules and scaffolding + +End state: -**Inside the Rust engine (`ath-core` or similar workspace crate):** +- One executable record model. +- One implementation of domain behavior. +- One supported write interface: **domain operations on the core**. -- Open, migrate, and check `athlete.ath.sqlite` using the ordered SQL in - `spec/sql/migrations/` and metadata rules in `spec/sql/README.md`. -- Enforce athlete-record rules in code **and** rely on existing SQL triggers for - the two-tier wall, extension envelope limits, and other database-enforced - rules. -- Validation of record payloads against the v1 format (aligned with - `src/v1/schema.ts` / generated JSON Schema until a single schema source is - chosen). -- Measurement-series encode/decode and shared calculations (baselines, stats, - within-workout math). -- JSON package import/export parity with today’s portable format. -- Migration preview/apply logic used by `ath migrate` (behavior must match CR4; - implementation moves to Rust without changing the UX contract). +Remove, after parity proof at each gate: -**Stays thin per platform:** +- Legacy 0.x record model (`src/schema.ts`) from import paths. +- Hand-maintained TypeScript validation and calculations that duplicate Rust. +- Duplicate SQL definitions (TypeScript string migrations once SQL files are canonical). +- Legacy writers and superseded engine code. -- **Node:** Commander CLI, Skill packaging, help text generation, LLM gateway - hooks for `predict` / `backtest` (D7: still CLI + Skill, not MCP). -- **Swift / Kotlin:** App UI, permissions, background tasks, file pickers. -- **Python:** Notebooks and scripts call UniFFI bindings. -- **Web:** WASM module + JS loader; host app handles storage APIs. +**Not allowed at cutover:** engine-selection flags, automatic TypeScript fallback, or +compatibility facades around removed APIs. -**Same results everywhere:** `spec/conformance/` vectors (CR5) and existing -`pnpm test` scenarios become the cross-language gate. Each binding runs the -same fixtures; Rust is the reference implementation. Record content version -(`athleticstandard_version`) and SQL schema version (`sql_schema_version`) stay -independent, as today. +Temporary TypeScript may remain **only** until a named stage passes tests. Every +temporary path has a removal milestone in +[`rust-capability-inventory.md`](rust-capability-inventory.md). Do not reorganize the +TypeScript engine into a new architecture that Rust will immediately replace. --- -## Step-by-step path (each step = its own PR) +## 4. Rust as the executable definition of records -1. **Rust core + Node wrapper, tests green.** Add `crates/ath-core`, wire - napi-rs into `athleticstandard`, call Rust for database open/migrate/check - and one read path. Keep TypeScript implementations behind a flag as fallback - until vectors pass on all CI platforms. Do not change `package.json` name, - `bin`, or `engines`. +Rust types and explicit semantic validators define valid ATH records. **Generate** +JSON Schema and TypeScript data types from that model. Binding types map mechanically +to the same definitions. -2. **Move write paths and import/export.** Port package import, export, and - validation into the engine; delete duplicate TS logic once parity tests pass. - Regenerate nothing by hand—`pnpm generate:*` stays the source for published - `spec/` artifacts. +Inventory of Zod refinements and relationships: +[`rust-capability-inventory.md`](rust-capability-inventory.md) (preserve, correct, or +remove, with reason). -3. **Swift package (UniFFI).** XCFramework or SwiftPM wrapper; document how an - iOS or watch app opens the same SQLite file. No separate “ATH service.” +Generated JSON Schema must express every rule it can represent. Remaining semantic +rules stay documented and enforced only through `ath-core` validation. No second +handwritten validator in a host language. -4. **Kotlin / Android (UniFFI).** Same FFI crate as Swift; publish AAR or Maven - coordinates as a follow-on decision. +Specify and test across Rust, Node, Swift, and portable packages: -5. **Python (UniFFI).** Wheel with extension module for agents and science - stacks. +- timestamps and time zones +- units and numeric limits +- optional vs null vs missing +- unknown fields and extension envelopes +- deterministic serialization (stable ordering where the format requires it) + +--- -6. **Web (wasm-bindgen).** Crate subset for validation and read-only paths where - full SQLite in WASM is acceptable; document limits for large files. +## 5. One SQL source and a small public API -7. **Retire the TypeScript engine.** Remove fallback once Node, Swift, and - conformance CI all use Rust only. +**Canonical storage definition:** plain SQL in `spec/sql/migrations/`. Rust embeds +those files. Published SQL in releases comes from the same files. TypeScript loads +the same files at runtime (prerequisite PR); the generator becomes verify-only, then +retires. -Steps 3–6 can reorder if a builder need appears first; steps 1–2 block -everything else. +Keep foreign keys, constraints, and integrity triggers. Do not redesign storage without +a concrete correctness or simplicity gain. + +**Writes:** official supported writes go through domain operations in `ath-core`. SQLite +stays open and documented for inspection. D116 still allows direct SQLite access with +required pragmas and trigger enforcement, but **D132** retires the promise that a +third party can recreate the full revision protocol using only documented direct SQL. +Stable views remain for reads (D125); narrow direct-write tables may stay for simple +cases, not full lifecycle parity. + +Expose typed operations and errors. No arbitrary SQL callback surface and no opaque +`execute(JSON)` API. + +**Concurrency:** connection ownership, serialized writes, stale-state checks, and handle +closure are defined in the core. Blocking work runs off the Node event loop and off the +main iOS UI thread (async boundary in bindings). --- -## Risks and costs +## 6. Capabilities the core must keep + +All current v1 behaviors in the capability inventory, including: -- **Maintainers:** Need Rust plus release tooling for mobile and npm prebuilds. -- **CI:** Multi-target builds (see Matrix “small-release” profiles for size). -- **Schema drift:** Until one generator owns types, Rust and Zod must both run - conformance checks on every PR. -- **D121 “thin OSS”:** This plan **widens** the core deliberately; it does not - add MCP, HTTP, or extra maintained *ports*—it replaces ports with bindings. +- two-tier wall between measured records and athlete reports +- source identity; imported vs reported vs calculated values +- stable IDs, corrections, history, stale-edit rejection +- provider timestamps, reporting periods, units +- repeatable imports without duplicates; deliberate provider corrections +- complete export and restore (history, extensions, dense samples, attachments, + import identity, erasure markers) +- safe conflict and transaction failure behavior +- distinct deletion vs privacy erasure +- reproducible calculations with explained inputs + +Attachment staging must commit or roll back with the database transaction. Failed +operations must not leave records pointing at missing files. + +Reuse proven parsers, SQL, algorithms, and fixtures. Fix bugs; do not encode bugs as +compatibility. --- -## Draft decisions for owner (not recorded until approved) +## 7. Calculation coverage -### D130 (draft). Single Rust engine with generated language bindings +See [`rust-calculation-coverage.md`](rust-calculation-coverage.md). Broad library work +is explicit batches after the foundation proof — not a prerequisite to prove architecture. -Athletic Standard implements file logic **once** in Rust. The npm package -`athleticstandard` and the `ath` CLI remain the Node distribution and wrap that -engine via napi-rs. Swift, Kotlin, Python, and web embedders use UniFFI or -wasm-bindgen rather than maintained hand-written ports. +Use large existing workloads (`performance/`) only to detect **material** regressions or +memory problems. Do not benchmark for speed targets or justify Rust by performance. + +--- -This **supersedes D121** only for “no Rust core”: Rust is approved as the core, -not as an optional speed-up. D121’s rejection of a local HTTP service, MCP -server, and unrelated language ports **remains**. D7 **remains**: agents use CLI -+ Skill; Rust does not add a conversational server. +## 8–9. Methods and explainability -Rejected alternatives: +Calculation families (HRV, heart rate, sleep, training, activity, recovery) are listed +in the coverage table with stages **Existing calculations** vs **Expanded calculations**. -- **Separate TypeScript engine long term.** Two implementations will diverge on - triggers, migrations, and vectors. -- **Local API service for mobile.** Extra process and deployment; bindings only. -- **Per-app copy-paste of SQL rules.** Already rejected by the public SQL - contract; engine must execute that contract. +Rules: -### D131 (draft). Public spec and vectors outrank binding APIs +- RMSSD and SDNN stay separate; never merge baselines or substitute silently. +- Imported branded scores stay `provider_result`; generic ATH methods use their own names. +- Ordinary modules plus a small method registry — no plugin framework. +- Each result carries method, version, parameters, inputs, exclusions, and references. +- Insufficient inputs → clear `unavailable` reason. +- Tests use independent reference answers. -The normative contracts are `spec/sql/`, generated JSON Schema, and -`spec/conformance/`. Generated binding APIs may change between releases if the -spec version does not. Breaking record or SQL schema versions follow the -existing format versioning rules. +Establish the **calculation contract** during prerequisites (documented in coverage file). --- -**Placement:** `build-history/README.md` does not name a folder for unapproved -plans. This file remains here until approval, then moves or links from -`build-history/v1.0.0/appendix/` and a recorded D-number (format version -unchanged if only implementation moves). +## 10. Import completeness + +Parsers normalize into the canonical Rust model. No route through `src/schema.ts`. + +Field-level mapping checks, not row counts alone. Import **receipt** required (see +coverage doc). Video findings (Oura readiness, sleep scores, contributors, SpO₂, +invalid records after upgrade/reimport) stay open investigation targets until reproduced +with synthetic regressions fixed in Rust. + +--- + +## 11. Prerequisites (concrete, no scope creep) + +| Prerequisite | Delivered by | +|---|---| +| Capability and dependency inventory | `rust-capability-inventory.md` + this plan | +| Reconcile plan, decisions, contribution-readiness | D130–D132; `AGENTS.md` update; progress note | +| Canonical SQL files | `spec/sql/` runtime load PR on `main` | +| Language-neutral behavior fixtures | `spec/conformance/` PR on `main` | +| Rust workspace, ath-node, ath-uniffi, focused CI | `crates/*` PR on `main` | +| Calculation contract and coverage table | `rust-calculation-coverage.md` | +| Dead code and temporary milestones | deletion checklist below + importExport removal PR | + +Defer: community catalog infrastructure, speculative DB backends, TypeScript workspace +split (D115), generic extension frameworks beyond the v1 envelope. + +--- + +## 12. Foundation proof (CLI + iPhone) + +**Required proof:** + +1. Installed CLI creates a database and measurement. +2. iPhone app opens the file and corrects the measurement. +3. Installed CLI reads the correction and retained history. + +Also prove: reopen, valid source attribution, invalid input rejection, stale-edit +rejection, unsupported version rejection, unchanged data after refused operations. + +Snapshots transfer closed and consistent between environments; compare logical data and +history. + +**Simulator gate:** must run the iOS target in the **iPhone Simulator**. Browser-only or +macOS compile-only does **not** satisfy the gate. + +**Environment status (Linux CI agent):** **BLOCKED** — missing Xcode, iOS SDK, and +iPhone Simulator. Cannot be reported as PASS from this environment. + +Reuse Grokbot/browser verification during transition if available externally. Permanent +setup: `apps/verification-ios/`, CLI, and automated tests. + +**Do not start the broad feature port until foundation proof passes.** + +--- + +## 13. Migration stages + +| Stage | Completion requirement | +|---|---| +| **Foundation** | Core, Node and Swift packaging, shared model, basic storage, verified round trip | +| **Records and lifecycle** | Full validation, queries, history, corrections, deletion, erasure, safe failures | +| **Provider imports** | Canonical parsing, field reconciliation, repeat imports, corrections, time handling | +| **Portable packages** | Preview/apply, conflicts, export, restore, extensions, dense samples, attachments | +| **Existing calculations** | Rust implementations, independent reference tests, explanations | +| **Expanded calculations** | Named batches from coverage table | +| **Cutover and distribution** | Consumers on Rust; obsolete TS engine deleted; release artifacts verified | + +Each stage lists modules, dependencies, test IDs, acceptance criteria, code to delete, +and blockers in the implementing PR. + +Migration completion is separate from expanded calculation batches; both stay scheduled. + +--- + +## 14. Data and formats + +No general legacy compatibility system for external users. Preserve owner files through +explicit, tested conversion on copies when needed. + +Do not silently convert on open. Unsupported storage versions fail clearly. Keep record +format version and SQL schema version independent. + +--- + +## 15. Packaging and verification + +- Node: prebuilt natives per declared platform matrix; consumers do not compile Rust. +- Swift: builds on declared iOS targets; test packed artifacts in clean projects. +- Shared `spec/conformance/` fixtures run in Rust, Node, and Swift tests. +- Report PASS / FAIL / BLOCKED / NOT IMPLEMENTED. Data loss or corruption blocks completion. + +Android, Python, browser storage, Watch, and hosted sync are follow-on — they do not +block the first Node + iOS release. + +--- + +## 16. Deletion checklist + +Delete when the stage gate passes (not before): + +| Code / artifact | Gate | +|---|---| +| `src/schema.ts` and 0.x import routing | Provider imports | +| `src/import/index.ts#importExport` | Prerequisite (unused) | +| TypeScript `INITIAL_SCHEMA_SQL` strings as source | SQL canonical verify-only | +| Hand-maintained `src/v1/schema.ts` as normative | Foundation + codegen live | +| Duplicate validation in `src/validate.ts` for v1 | Records and lifecycle | +| `src/db/calculate.ts` engine | Existing calculations parity | +| Provider merge via `ImportPayload` 0.x | Provider imports | +| TypeScript-only migration runner logic replaced by Rust | Cutover | +| Engine fallback or feature flags (if any added during dev) | Cutover | + +--- + +## Next implementation task + +On `main`, merge the prerequisite PR chain (canonical SQL runtime load → conformance +fixtures → Rust workspace skeleton with CI → remove `importExport`). Then implement +`ath-core` open/create database using embedded SQL and wire `ath-node` for a single +read path used by one CLI command behind an internal dev hook — still without public +cutover until the iPhone simulator round trip passes on macOS hardware. + +--- + +## Industry reference (tooling) + +| Host | Binding | +|---|---| +| Node / npm | napi-rs | +| Swift / Kotlin | UniFFI | +| Web (later) | wasm-bindgen | + +See prior research table in git history at commit `5610f02` if needed; this plan does +not treat web or Android as first-release blockers. diff --git a/build-history/plans/rust-calculation-coverage.md b/build-history/plans/rust-calculation-coverage.md new file mode 100644 index 00000000..27e2e3a5 --- /dev/null +++ b/build-history/plans/rust-calculation-coverage.md @@ -0,0 +1,79 @@ +# Provider capability and calculation coverage + +One table for import fields and calculations. **Stage** names match +`build-history/plans/rust-adoption.md`. + +Classification: + +- **observation** — imported measured value with source +- **provider_result** — branded score or summary attributed to the vendor +- **reproducible** — ATH can recompute from documented inputs and a named method +- **ath_estimate** — transparent ATH method when vendor does not ship the value +- **unavailable** — required inputs or method missing; reason stated + +| Provider capability | Input / export path | ATH representation | Method and reference | Required data | Current support | Stage | +|---|---|---|---|---|---|---| +| WHOOP recovery score | CSV `physiological_cycles` | `provider_score` | provider_result — store as reported | 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 tagged notes | observation / report | text fields | partial | Provider imports | +| WHOOP HRV (RMSSD) | CSV cycles | `point_measurement` `hrv_rmssd` | observation | nightly value | yes | Existing calculations | +| WHOOP resting HR | CSV cycles | `point_measurement` `resting_heart_rate` | observation | nightly value | yes | Existing calculations | +| WHOOP workout HR samples | CSV | `measurement_sample` series | observation | time series | partial | Provider imports | +| Oura readiness score | export / API fields | `provider_score` | provider_result | readiness object | **gap** — investigation target | Provider imports | +| Oura sleep score | export | `provider_score` | provider_result | sleep summary | **gap** | Provider imports | +| Oura readiness contributors | export | extensions or structured fields | provider_result | contributor list | **gap** | Provider imports | +| Oura SpO2 / blood oxygen | export | `point_measurement` | observation | SpO2 readings | **gap** | Provider imports | +| Oura sleep stages | export | `sleep_session` stages | observation | stage durations | partial | Provider imports | +| Oura HRV (RMSSD) | export | `point_measurement` `hrv_rmssd` | observation | sleep summary | yes | Existing calculations | +| Oura temperature deviation | export | `point_measurement` | observation | temp signal | partial | Provider imports | +| Apple Health HRV (SDNN) | export.zip | `point_measurement` `hrv_sdnn` | observation | SDNN samples | yes | Existing calculations | +| 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 Health beat-to-beat for RMSSD | export.zip ECG / beat lists | series → RMSSD | reproducible — `hrv_rmssd` from intervals | beat timestamps | yes (`src/hrv.ts`) | Existing calculations | +| Summary stats (mean, min, max, count) | CLI `ath calculate summary` | calculation result | reproducible — `ath-runtime-v1` | point or series | yes | Existing calculations | +| Baseline (rolling window) | CLI baseline | calculation result | reproducible | history window | yes | Existing calculations | +| Trend (slope / direction) | 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 | core library | `hrv_rmssd` | reproducible — standard RMSSD formula | beat intervals ms | yes | Existing calculations | +| HRV SDNN daily | measurements | `hrv_sdnn` | reproducible — SDNN definition | beat series | partial | 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 — e.g. lowest 5-min mean | HR samples | unavailable — method not chosen | Expanded calculations | +| Heart-rate zones / time in zone | workouts + max HR | calculation result | reproducible — zone model documented | HR series, zone bounds | unavailable | Expanded calculations | +| Heart-rate recovery | post-workout HR | calculation result | reproducible — delta at 1/2 min | HR series | unavailable | Expanded calculations | +| Sleep duration / efficiency | sleep sessions | calculation result | reproducible | session times | partial from sessions | Expanded calculations | +| Sleep interruptions / timing / regularity | sleep sessions | calculation result | reproducible | session history | unavailable | Expanded calculations | +| Sleep stage summaries | staged sleep | calculation result | reproducible — sum supplied stages only | stage minutes | partial | Expanded calculations | +| Infer sleep stages from raw sensors | accelerometer / HR | — | unavailable — not inferring vendor stages | raw sensors | unavailable — by policy | — | +| Training load (HR-based) | workouts + HR | calculation result | ath_estimate — named ATH method TBD | HR zones, duration | unavailable | Expanded calculations | +| Training load (RPE-based) | athlete report + duration | calculation result | ath_estimate | RPE, duration | unavailable | Expanded calculations | +| Strength volume | workouts | calculation result | reproducible — sets × reps × load | structured workout | partial | Expanded calculations | +| Recovery / readiness (ATH generic) | HRV + sleep + RHR | calculation result | ath_estimate — explicit formula in registry | baselines per method | unavailable | Expanded calculations | +| WHOOP/Oura branded readiness as ATH score | — | — | unavailable — use provider_result or separate ATH method name | — | n/a | — | + +## Calculation contract (prerequisite) + +Every calculation result returned from `ath-core` must include: + +- `method_id` and `method_version` +- parameters used (window, grouping, timezone, source filters) +- units and quantity +- time range and record revisions consumed +- exclusions and missing-data handling +- `unavailable` with reason when inputs are insufficient + +Numerical tests use reference answers computed outside the implementation under test. +RMSSD and SDNN never share a baseline. Provider scores stay labeled as vendor results. + +## Import completeness (measurable) + +Imports must emit a **receipt**: imported, unchanged, corrected, skipped (with reason), +invalid, and unexpectedly missing fields. Silent loss of a supported mapped field is a +failure. Video findings (Oura readiness, sleep scores, contributors, SpO₂, invalid +records after reimport) are regression targets documented in the Rust plan until reproduced +with synthetic fixtures. diff --git a/build-history/plans/rust-capability-inventory.md b/build-history/plans/rust-capability-inventory.md new file mode 100644 index 00000000..03108cfb --- /dev/null +++ b/build-history/plans/rust-capability-inventory.md @@ -0,0 +1,76 @@ +# Capability and dependency inventory (Rust adoption) + +Maps today’s TypeScript implementation to the planned Rust core (`ath-core`) and thin +host shells. Status is **current** unless noted **planned** or **remove**. + +## Host shells (stay thin) + +| Area | Today | Owner after cutover | +|---|---|---| +| CLI argument parsing, help, presentation | `src/program.ts`, `src/help.ts`, `src/cli.ts` | TypeScript CLI | +| Skill install and references | `src/skill.ts`, `skill/` | TypeScript CLI | +| Credentials and model gateway | `src/keyring.ts`, `src/gateway.ts`, `src/predict.ts` | TypeScript CLI | +| Progress and share UX | `src/progress.ts`, `src/share.ts` | TypeScript CLI | +| SwiftUI verification app | not in repo yet | Swift app under `apps/verification-ios/` (see rust-adoption plan) | + +## ath-core (single executable domain) + +| Capability | Current location | Rust module (planned) | Notes | +|---|---|---|---| +| v1 record shapes and JSON rules | `src/v1/schema.ts`, generated `schema/1.0.0/` | `model`, `validate` | Zod refinements move to Rust validators; JSON Schema and TS types generated from Rust | +| Legacy 0.x shapes | `src/schema.ts` | none | Remove after cutover; importers stop routing through 0.x | +| SQLite open, pragmas, migrate | `src/db/migrate.ts`, `src/db/client.ts` | `storage` | Reads embedded `spec/sql/migrations/*.sql` | +| Record write, revision, history | `src/db/records.ts`, `revision-encoding.ts` | `records` | Official write path; replaces ad hoc direct-SQL revision recipes | +| Queries and views | `src/db/query.ts`, `records-view.ts`, `series-view.ts` | `query` | | +| Conflicts and transactions | `src/db/conflicts.ts`, `transaction.ts` | `storage` | | +| Deletion and erasure | `src/db/erase.ts` | `lifecycle` | | +| Package import and export | `src/db/import-package.ts`, `export.ts` | `package` | | +| Attachments | `src/db/attachments.ts`, `attachment-ingest.ts` | `attachments` | Staging must roll back with failed transactions | +| Provider import | `src/import/*`, `src/db/provider-import.ts` | `import` | Normalize straight into canonical model; drop `ImportPayload` via 0.x | +| Dense series encode/decode | `src/series.ts`, `src/db/series-view.ts` | `series` | | +| Calculations | `src/db/calculate.ts`, `src/hrv.ts`, `src/stats.ts` | `calc` + method registry | Expand per coverage table | +| Check and drift | `src/db/check.ts`, `scripts/check-schema-drift.ts` | `check` | | +| Evidence and grading hooks | `src/db/evidence.ts`, `prediction-grade.ts` | `grading` (host calls models; core stores results) | | +| UUID and IDs | `src/db/uuid.ts` | `ids` | | +| SQL contract metadata | `src/db/sql-contract.ts`, `spec/sql/` | embed + `contract` | Plain SQL files are canonical | + +## Generated public contracts + +| Artifact | Today | After Rust foundation | +|---|---|---| +| JSON Schema | from `src/v1/schema.ts` | from Rust model | +| TypeScript types | Zod inference | generated from JSON Schema or Rust export | +| `spec/sql/` | generated from TS migration strings | canonical source; TS and Rust embed the same files | +| Conformance vectors | missing (`CR5` pending) | `spec/conformance/`; shared across Rust, Node, Swift | + +## Zod and extension inventory (validation migration) + +| Rule area | In Zod today | Rust plan | +|---|---|---| +| Two-tier wall (source required on measured records) | `src/v1/schema.ts` + SQL triggers | Both; triggers stay in SQL | +| Athlete reports cannot claim `source` | schema + triggers | same | +| Record type unions and required fields | Zod objects | Rust enums + validators | +| `extensions` envelope size and namespacing | `src/v1/extensions.ts` | Rust validator | +| Portable package unknown fields | strict package schemas | Rust import validator | +| Cross-record links and protected references | partial in Zod; more in SQL | full semantic checks in core | +| Provider period and timezone fields | `src/v1/schema.ts` | preserve | +| RMSSD vs SDNN quantities | separate fields | never merge baselines | +| Legacy 0.x-only rules | `src/schema.ts` | remove with 0.x paths | + +## Dependencies between open work + +| Pull request | Overlap with Rust prerequisites | +|---|---| +| [#15](https://github.com/mwhitham/ath/pull/15) (contribution foundation plan) | CR5 conformance, CR6 guidance, CR3 SQL — implement prerequisites on `main`; do not duplicate #15 doc-only deltas | +| [#25](https://github.com/mwhitham/ath/pull/25) (migrate, import check, logging) | `ath migrate` and import receipts belong in core eventually; land #25 behaviors in TS first, port to Rust in Provider imports stage | +| [#20](https://github.com/mwhitham/ath/pull/20) (this plan) | Docs and decisions only | + +## Temporary dual paths (must have removal milestones) + +| Temporary path | Milestone to remove | +|---|---| +| TypeScript engine in `src/db/*` | Cutover stage: delete after foundation proof and stage gates | +| `src/schema.ts` 0.x model in import pipeline | Provider imports stage | +| `generate:sql-contract` from TS strings | Records stage: SQL files edited directly; generator becomes verify-only or removed | +| Hand-maintained Zod as normative | Foundation stage: Rust owns validation; Zod becomes generated | +| `src/import/index.ts#importExport` | Prerequisite PR: delete unused 0.x export writer | diff --git a/build-history/v1.0.0/decisions.md b/build-history/v1.0.0/decisions.md index 58b02da1..7897ce00 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -1286,3 +1286,68 @@ 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 and other mobile hosts use UniFFI (`ath-uniffi`) without a separate local +service. + +This supersedes D121 only where D121 deferred a Rust core. D121 still rejects +building every client surface before need; this decision names Rust as the core +because one builder needs a single cross-language engine now. D7 remains: CLI plus +Skill, not MCP or a conversational server. + +Rejected alternatives: + +- **Maintain a long-term TypeScript engine beside Rust.** Rejected because two + implementations diverge on triggers, migrations, and conformance vectors. +- **Engine-selection flag or automatic TypeScript fallback at cutover.** Rejected + because it preserves duplicate rules indefinitely. +- **Local HTTP service for mobile.** Rejected for the same reasons as D7 and D121. + +This follows the [Rust adoption plan](../../plans/rust-adoption.md). + +## D131. Generated contracts and conformance vectors outrank binding APIs (proposed) + +The public contracts are `spec/sql/`, generated JSON Schema, and +`spec/conformance/` behavior fixtures. Rust types and validators in `ath-core` +are the source for generated JSON Schema and TypeScript data types. Binding APIs +may change between releases when the format version does not. Breaking record or +SQL schema versions follow existing format versioning rules. + +`CORE_API_VERSION` (D128) still governs community extension manifests. It is +independent of binding refactors that do not change importer or calculation +interfaces. + +Rejected alternatives: + +- **Keep Zod in `src/v1/schema.ts` as the long-term normative validator.** Rejected + because host-language validators duplicate Rust and drift from embeddings. +- **Treat napi or UniFFI shapes as the spec.** Rejected because bindings are not + portable across languages. + +This follows the [Rust adoption plan](../../plans/rust-adoption.md). + +## D132. Supported writes go through the core; direct SQL is not a full protocol (proposed) + +Builders may still open the SQLite file with ordinary tools and respect required +pragmas (D116). Triggers and constraints continue to enforce the two-tier wall and +other critical rules. Official Athletic Standard products and documented integration +paths perform record lifecycle work through typed domain operations in `ath-core`, +not by recreating the complete revision protocol through ad hoc direct SQL alone. + +Stable read views and any narrow documented writable tables (D125) remain for simple +direct access. They do not replace core operations for corrections, history, +conflicts, package import, attachments, or erasure. + +Rejected alternatives: + +- **Require every writer to use Node.** Rejected; D116 stands for direct SQLite access. +- **Promise full lifecycle parity through direct SQL recipes.** Rejected because it + duplicates the core and breaks when internal encodings change. + +This follows the [Rust adoption plan](../../plans/rust-adoption.md). diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index 158c552d..72d71ae1 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -67,3 +67,18 @@ The long-form sequence is in 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. + +## Rust adoption prerequisites (proposed) + +Tracked in [`plans/rust-adoption.md`](../plans/rust-adoption.md). Draft decisions +D130–D132. Does not block v1 npm publish by itself; foundation proof blocks broad +Rust port. + +| Step | Deliverable | Status | +|---|---|---| +| R0 | Revised plan, inventory, coverage table, decisions, `AGENTS.md` | in review — PR #20 | +| R1 | Runtime loads canonical `spec/sql/migrations/*.sql` | pending — follow-up PR on `main` | +| R2 | `spec/conformance/` language-neutral fixtures | pending — follow-up PR on `main` | +| R3 | Rust workspace (`ath-core`, `ath-node`, `ath-uniffi`) and CI `cargo check` | pending — follow-up PR on `main` | +| R4 | Remove unused `importExport`; document temporary dual paths | pending — follow-up PR on `main` | +| R5 | iPhone simulator CLI ↔ app round trip | **BLOCKED** — requires Xcode and iOS Simulator on macOS | From a1668f61f823f0e1d1063323ef1a18b8e5985d46 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 03:40:53 +0000 Subject: [PATCH 06/10] docs: fact-check Rust plan per PR #20 review Move plan tables to v1.0.0 appendix. Rewrite D130-D132 with explicit supersedes list, npm 2.0.0 cutover, and D121/D7 citations. Fix coverage and inventory, AGENTS.md, and progress. Plain-English plan edits. Co-authored-by: Michael Whitham --- AGENTS.md | 5 +- build-history/plans/rust-adoption.md | 338 ------------------ .../plans/rust-calculation-coverage.md | 79 ---- .../plans/rust-capability-inventory.md | 76 ---- .../v1.0.0/appendix/rust-adoption.md | 282 +++++++++++++++ .../appendix/rust-calculation-coverage.md | 74 ++++ .../appendix/rust-capability-inventory.md | 71 ++++ build-history/v1.0.0/decisions.md | 114 ++++-- build-history/v1.0.0/progress.md | 19 +- 9 files changed, 513 insertions(+), 545 deletions(-) delete mode 100644 build-history/plans/rust-adoption.md delete mode 100644 build-history/plans/rust-calculation-coverage.md delete mode 100644 build-history/plans/rust-capability-inventory.md create mode 100644 build-history/v1.0.0/appendix/rust-adoption.md create mode 100644 build-history/v1.0.0/appendix/rust-calculation-coverage.md create mode 100644 build-history/v1.0.0/appendix/rust-capability-inventory.md diff --git a/AGENTS.md b/AGENTS.md index f194b5d2..0a894f23 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,8 +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. Today, v1 Zod in `src/v1/schema.ts` feeds generated JSON Schema; `src/schema.ts` is legacy 0.x. The proposed Rust plan (D130–D132, `build-history/plans/rust-adoption.md`) moves the normative record model into `ath-core` with generated JSON Schema and TypeScript types — do not extend hand-maintained Zod as the long-term source of truth once that cutover lands. -9. **`build-history/plans/rust-adoption.md`** — proposed single Rust core, prerequisites, migration stages, and deletion gates. Inventory and calculation coverage tables live beside it in `build-history/plans/`. +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 @@ -28,7 +27,7 @@ describe released 0.x behavior. - **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 (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, run `pnpm generate:sql-contract` if the TypeScript migration strings remain the authoring path, and keep `spec/sql/` in sync. 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). When Rust owns the model (D131), regenerate JSON Schema and TypeScript from Rust instead of editing Zod as normative. +- **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). After Rust owns the model (approved D131), 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/plans/rust-adoption.md b/build-history/plans/rust-adoption.md deleted file mode 100644 index 3cebb8bc..00000000 --- a/build-history/plans/rust-adoption.md +++ /dev/null @@ -1,338 +0,0 @@ -# Rust adoption plan (proposed) - -**Status:** proposed. Recorded draft decisions: D130–D132 in -`build-history/v1.0.0/decisions.md`. Supporting tables: -[`rust-capability-inventory.md`](rust-capability-inventory.md), -[`rust-calculation-coverage.md`](rust-calculation-coverage.md). - -**Goal:** One Rust core (`ath-core`) holds every rule about athlete records. Node, -iOS, and later hosts use thin bindings. Keep the npm package name -`athleticstandard` and the `ath` command. Do not add a local HTTP service or MCP -server (D7 stands). - -This plan supersedes earlier draft text in this file that described a TypeScript -fallback flag or a long-term dual engine. There is one cutover, not a permanent -switch. - ---- - -## 1. Starting point (repository today) - -Reviewed on branch `cursor/rust-adoption-plan-0ce5` after merging `main`. - -| Check | Baseline result | -|---|---| -| `pnpm check:public-data` | pass | -| `pnpm typecheck` | pass | -| `pnpm test` | pass (31 files, 327 tests) | -| `pnpm build` | pass | - -**What exists:** v1 SQLite via libSQL in TypeScript (`src/db/`), Zod normative -records in `src/v1/schema.ts`, published SQL under `spec/sql/` (still generated -from TypeScript migration strings), provider importers through a legacy 0.x hop, -calculation operations in `src/db/calculate.ts`, contribution foundation CR1–CR3 -done (D115–D129), CR5 conformance vectors still pending. - -**Open pull requests to coordinate with (do not duplicate):** - -- [#20](https://github.com/mwhitham/ath/pull/20) — this plan and decisions. -- [#15](https://github.com/mwhitham/ath/pull/15) — contribution-readiness plan text; - prerequisite work lands on `main` with decisions already partially recorded (D129). -- [#25](https://github.com/mwhitham/ath/pull/25) — migrate flow, import check, - structured logging, docs; port behavior to Rust after it stabilizes in TypeScript. - -**Grokbot verification:** No Grokbot-named code, scenarios, or browser verifier -live in this repository today. Reuse existing Vitest coverage (`tests/v1-cli-writes.test.ts`, -`tests/v1-export-import.test.ts`, `tests/v1-direct-sql.test.ts`, provider import tests) -as the behavioral catalog until Grokbot publishes shared scenario IDs. During transition, -any browser-based verifier Grokbot maintains can run against the same synthetic fixtures -under `spec/conformance/`. **Owner:** Grokbot owns verification evidence; Rust work -owns core, bindings, and packaging. - -**SwiftUI verification app (single location):** `apps/verification-ios/` — small -SwiftUI app depending on the UniFFI Swift package from `crates/ath-uniffi`. It opens -a snapshot `.ath.sqlite` produced by the installed CLI, applies one correction, and -writes history. Do not add a second demo app elsewhere in the repo. - ---- - -## 2. Architecture: one core, thin consumers - -| Component | Responsibility | -|---|---| -| **ath-core** | Records, validation, storage, history, conflicts, provider parsing, -normalization, calculations, package import/export, attachments, deletion, erasure | -| **ath-node** | napi-rs bindings; blocking work off the Node event loop | -| **ath-uniffi** | UniFFI bindings; exercised through Swift first | -| **TypeScript CLI** | Arguments, help, presentation, Skill, credentials, external model calls | -| **Swift app** | `apps/verification-ios/` — screens, file access, permissions, lifecycle | - -Internal Rust modules stay inside `ath-core` unless a dependency forces a separate -crate. Storage starts with **rusqlite** and bundled SQLite, matching `spec/sql/` -pragmas and triggers. - -Platform code may read HealthKit or file exports. ATH interpretation, normalization, -and write decisions live in Rust. - ---- - -## 3. Remove duplicate rules and scaffolding - -End state: - -- One executable record model. -- One implementation of domain behavior. -- One supported write interface: **domain operations on the core**. - -Remove, after parity proof at each gate: - -- Legacy 0.x record model (`src/schema.ts`) from import paths. -- Hand-maintained TypeScript validation and calculations that duplicate Rust. -- Duplicate SQL definitions (TypeScript string migrations once SQL files are canonical). -- Legacy writers and superseded engine code. - -**Not allowed at cutover:** engine-selection flags, automatic TypeScript fallback, or -compatibility facades around removed APIs. - -Temporary TypeScript may remain **only** until a named stage passes tests. Every -temporary path has a removal milestone in -[`rust-capability-inventory.md`](rust-capability-inventory.md). Do not reorganize the -TypeScript engine into a new architecture that Rust will immediately replace. - ---- - -## 4. Rust as the executable definition of records - -Rust types and explicit semantic validators define valid ATH records. **Generate** -JSON Schema and TypeScript data types from that model. Binding types map mechanically -to the same definitions. - -Inventory of Zod refinements and relationships: -[`rust-capability-inventory.md`](rust-capability-inventory.md) (preserve, correct, or -remove, with reason). - -Generated JSON Schema must express every rule it can represent. Remaining semantic -rules stay documented and enforced only through `ath-core` validation. No second -handwritten validator in a host language. - -Specify and test across Rust, Node, Swift, and portable packages: - -- timestamps and time zones -- units and numeric limits -- optional vs null vs missing -- unknown fields and extension envelopes -- deterministic serialization (stable ordering where the format requires it) - ---- - -## 5. One SQL source and a small public API - -**Canonical storage definition:** plain SQL in `spec/sql/migrations/`. Rust embeds -those files. Published SQL in releases comes from the same files. TypeScript loads -the same files at runtime (prerequisite PR); the generator becomes verify-only, then -retires. - -Keep foreign keys, constraints, and integrity triggers. Do not redesign storage without -a concrete correctness or simplicity gain. - -**Writes:** official supported writes go through domain operations in `ath-core`. SQLite -stays open and documented for inspection. D116 still allows direct SQLite access with -required pragmas and trigger enforcement, but **D132** retires the promise that a -third party can recreate the full revision protocol using only documented direct SQL. -Stable views remain for reads (D125); narrow direct-write tables may stay for simple -cases, not full lifecycle parity. - -Expose typed operations and errors. No arbitrary SQL callback surface and no opaque -`execute(JSON)` API. - -**Concurrency:** connection ownership, serialized writes, stale-state checks, and handle -closure are defined in the core. Blocking work runs off the Node event loop and off the -main iOS UI thread (async boundary in bindings). - ---- - -## 6. Capabilities the core must keep - -All current v1 behaviors in the capability inventory, including: - -- two-tier wall between measured records and athlete reports -- source identity; imported vs reported vs calculated values -- stable IDs, corrections, history, stale-edit rejection -- provider timestamps, reporting periods, units -- repeatable imports without duplicates; deliberate provider corrections -- complete export and restore (history, extensions, dense samples, attachments, - import identity, erasure markers) -- safe conflict and transaction failure behavior -- distinct deletion vs privacy erasure -- reproducible calculations with explained inputs - -Attachment staging must commit or roll back with the database transaction. Failed -operations must not leave records pointing at missing files. - -Reuse proven parsers, SQL, algorithms, and fixtures. Fix bugs; do not encode bugs as -compatibility. - ---- - -## 7. Calculation coverage - -See [`rust-calculation-coverage.md`](rust-calculation-coverage.md). Broad library work -is explicit batches after the foundation proof — not a prerequisite to prove architecture. - -Use large existing workloads (`performance/`) only to detect **material** regressions or -memory problems. Do not benchmark for speed targets or justify Rust by performance. - ---- - -## 8–9. Methods and explainability - -Calculation families (HRV, heart rate, sleep, training, activity, recovery) are listed -in the coverage table with stages **Existing calculations** vs **Expanded calculations**. - -Rules: - -- RMSSD and SDNN stay separate; never merge baselines or substitute silently. -- Imported branded scores stay `provider_result`; generic ATH methods use their own names. -- Ordinary modules plus a small method registry — no plugin framework. -- Each result carries method, version, parameters, inputs, exclusions, and references. -- Insufficient inputs → clear `unavailable` reason. -- Tests use independent reference answers. - -Establish the **calculation contract** during prerequisites (documented in coverage file). - ---- - -## 10. Import completeness - -Parsers normalize into the canonical Rust model. No route through `src/schema.ts`. - -Field-level mapping checks, not row counts alone. Import **receipt** required (see -coverage doc). Video findings (Oura readiness, sleep scores, contributors, SpO₂, -invalid records after upgrade/reimport) stay open investigation targets until reproduced -with synthetic regressions fixed in Rust. - ---- - -## 11. Prerequisites (concrete, no scope creep) - -| Prerequisite | Delivered by | -|---|---| -| Capability and dependency inventory | `rust-capability-inventory.md` + this plan | -| Reconcile plan, decisions, contribution-readiness | D130–D132; `AGENTS.md` update; progress note | -| Canonical SQL files | `spec/sql/` runtime load PR on `main` | -| Language-neutral behavior fixtures | `spec/conformance/` PR on `main` | -| Rust workspace, ath-node, ath-uniffi, focused CI | `crates/*` PR on `main` | -| Calculation contract and coverage table | `rust-calculation-coverage.md` | -| Dead code and temporary milestones | deletion checklist below + importExport removal PR | - -Defer: community catalog infrastructure, speculative DB backends, TypeScript workspace -split (D115), generic extension frameworks beyond the v1 envelope. - ---- - -## 12. Foundation proof (CLI + iPhone) - -**Required proof:** - -1. Installed CLI creates a database and measurement. -2. iPhone app opens the file and corrects the measurement. -3. Installed CLI reads the correction and retained history. - -Also prove: reopen, valid source attribution, invalid input rejection, stale-edit -rejection, unsupported version rejection, unchanged data after refused operations. - -Snapshots transfer closed and consistent between environments; compare logical data and -history. - -**Simulator gate:** must run the iOS target in the **iPhone Simulator**. Browser-only or -macOS compile-only does **not** satisfy the gate. - -**Environment status (Linux CI agent):** **BLOCKED** — missing Xcode, iOS SDK, and -iPhone Simulator. Cannot be reported as PASS from this environment. - -Reuse Grokbot/browser verification during transition if available externally. Permanent -setup: `apps/verification-ios/`, CLI, and automated tests. - -**Do not start the broad feature port until foundation proof passes.** - ---- - -## 13. Migration stages - -| Stage | Completion requirement | -|---|---| -| **Foundation** | Core, Node and Swift packaging, shared model, basic storage, verified round trip | -| **Records and lifecycle** | Full validation, queries, history, corrections, deletion, erasure, safe failures | -| **Provider imports** | Canonical parsing, field reconciliation, repeat imports, corrections, time handling | -| **Portable packages** | Preview/apply, conflicts, export, restore, extensions, dense samples, attachments | -| **Existing calculations** | Rust implementations, independent reference tests, explanations | -| **Expanded calculations** | Named batches from coverage table | -| **Cutover and distribution** | Consumers on Rust; obsolete TS engine deleted; release artifacts verified | - -Each stage lists modules, dependencies, test IDs, acceptance criteria, code to delete, -and blockers in the implementing PR. - -Migration completion is separate from expanded calculation batches; both stay scheduled. - ---- - -## 14. Data and formats - -No general legacy compatibility system for external users. Preserve owner files through -explicit, tested conversion on copies when needed. - -Do not silently convert on open. Unsupported storage versions fail clearly. Keep record -format version and SQL schema version independent. - ---- - -## 15. Packaging and verification - -- Node: prebuilt natives per declared platform matrix; consumers do not compile Rust. -- Swift: builds on declared iOS targets; test packed artifacts in clean projects. -- Shared `spec/conformance/` fixtures run in Rust, Node, and Swift tests. -- Report PASS / FAIL / BLOCKED / NOT IMPLEMENTED. Data loss or corruption blocks completion. - -Android, Python, browser storage, Watch, and hosted sync are follow-on — they do not -block the first Node + iOS release. - ---- - -## 16. Deletion checklist - -Delete when the stage gate passes (not before): - -| Code / artifact | Gate | -|---|---| -| `src/schema.ts` and 0.x import routing | Provider imports | -| `src/import/index.ts#importExport` | Prerequisite (unused) | -| TypeScript `INITIAL_SCHEMA_SQL` strings as source | SQL canonical verify-only | -| Hand-maintained `src/v1/schema.ts` as normative | Foundation + codegen live | -| Duplicate validation in `src/validate.ts` for v1 | Records and lifecycle | -| `src/db/calculate.ts` engine | Existing calculations parity | -| Provider merge via `ImportPayload` 0.x | Provider imports | -| TypeScript-only migration runner logic replaced by Rust | Cutover | -| Engine fallback or feature flags (if any added during dev) | Cutover | - ---- - -## Next implementation task - -On `main`, merge the prerequisite PR chain (canonical SQL runtime load → conformance -fixtures → Rust workspace skeleton with CI → remove `importExport`). Then implement -`ath-core` open/create database using embedded SQL and wire `ath-node` for a single -read path used by one CLI command behind an internal dev hook — still without public -cutover until the iPhone simulator round trip passes on macOS hardware. - ---- - -## Industry reference (tooling) - -| Host | Binding | -|---|---| -| Node / npm | napi-rs | -| Swift / Kotlin | UniFFI | -| Web (later) | wasm-bindgen | - -See prior research table in git history at commit `5610f02` if needed; this plan does -not treat web or Android as first-release blockers. diff --git a/build-history/plans/rust-calculation-coverage.md b/build-history/plans/rust-calculation-coverage.md deleted file mode 100644 index 27e2e3a5..00000000 --- a/build-history/plans/rust-calculation-coverage.md +++ /dev/null @@ -1,79 +0,0 @@ -# Provider capability and calculation coverage - -One table for import fields and calculations. **Stage** names match -`build-history/plans/rust-adoption.md`. - -Classification: - -- **observation** — imported measured value with source -- **provider_result** — branded score or summary attributed to the vendor -- **reproducible** — ATH can recompute from documented inputs and a named method -- **ath_estimate** — transparent ATH method when vendor does not ship the value -- **unavailable** — required inputs or method missing; reason stated - -| Provider capability | Input / export path | ATH representation | Method and reference | Required data | Current support | Stage | -|---|---|---|---|---|---|---| -| WHOOP recovery score | CSV `physiological_cycles` | `provider_score` | provider_result — store as reported | 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 tagged notes | observation / report | text fields | partial | Provider imports | -| WHOOP HRV (RMSSD) | CSV cycles | `point_measurement` `hrv_rmssd` | observation | nightly value | yes | Existing calculations | -| WHOOP resting HR | CSV cycles | `point_measurement` `resting_heart_rate` | observation | nightly value | yes | Existing calculations | -| WHOOP workout HR samples | CSV | `measurement_sample` series | observation | time series | partial | Provider imports | -| Oura readiness score | export / API fields | `provider_score` | provider_result | readiness object | **gap** — investigation target | Provider imports | -| Oura sleep score | export | `provider_score` | provider_result | sleep summary | **gap** | Provider imports | -| Oura readiness contributors | export | extensions or structured fields | provider_result | contributor list | **gap** | Provider imports | -| Oura SpO2 / blood oxygen | export | `point_measurement` | observation | SpO2 readings | **gap** | Provider imports | -| Oura sleep stages | export | `sleep_session` stages | observation | stage durations | partial | Provider imports | -| Oura HRV (RMSSD) | export | `point_measurement` `hrv_rmssd` | observation | sleep summary | yes | Existing calculations | -| Oura temperature deviation | export | `point_measurement` | observation | temp signal | partial | Provider imports | -| Apple Health HRV (SDNN) | export.zip | `point_measurement` `hrv_sdnn` | observation | SDNN samples | yes | Existing calculations | -| 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 Health beat-to-beat for RMSSD | export.zip ECG / beat lists | series → RMSSD | reproducible — `hrv_rmssd` from intervals | beat timestamps | yes (`src/hrv.ts`) | Existing calculations | -| Summary stats (mean, min, max, count) | CLI `ath calculate summary` | calculation result | reproducible — `ath-runtime-v1` | point or series | yes | Existing calculations | -| Baseline (rolling window) | CLI baseline | calculation result | reproducible | history window | yes | Existing calculations | -| Trend (slope / direction) | 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 | core library | `hrv_rmssd` | reproducible — standard RMSSD formula | beat intervals ms | yes | Existing calculations | -| HRV SDNN daily | measurements | `hrv_sdnn` | reproducible — SDNN definition | beat series | partial | 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 — e.g. lowest 5-min mean | HR samples | unavailable — method not chosen | Expanded calculations | -| Heart-rate zones / time in zone | workouts + max HR | calculation result | reproducible — zone model documented | HR series, zone bounds | unavailable | Expanded calculations | -| Heart-rate recovery | post-workout HR | calculation result | reproducible — delta at 1/2 min | HR series | unavailable | Expanded calculations | -| Sleep duration / efficiency | sleep sessions | calculation result | reproducible | session times | partial from sessions | Expanded calculations | -| Sleep interruptions / timing / regularity | sleep sessions | calculation result | reproducible | session history | unavailable | Expanded calculations | -| Sleep stage summaries | staged sleep | calculation result | reproducible — sum supplied stages only | stage minutes | partial | Expanded calculations | -| Infer sleep stages from raw sensors | accelerometer / HR | — | unavailable — not inferring vendor stages | raw sensors | unavailable — by policy | — | -| Training load (HR-based) | workouts + HR | calculation result | ath_estimate — named ATH method TBD | HR zones, duration | unavailable | Expanded calculations | -| Training load (RPE-based) | athlete report + duration | calculation result | ath_estimate | RPE, duration | unavailable | Expanded calculations | -| Strength volume | workouts | calculation result | reproducible — sets × reps × load | structured workout | partial | Expanded calculations | -| Recovery / readiness (ATH generic) | HRV + sleep + RHR | calculation result | ath_estimate — explicit formula in registry | baselines per method | unavailable | Expanded calculations | -| WHOOP/Oura branded readiness as ATH score | — | — | unavailable — use provider_result or separate ATH method name | — | n/a | — | - -## Calculation contract (prerequisite) - -Every calculation result returned from `ath-core` must include: - -- `method_id` and `method_version` -- parameters used (window, grouping, timezone, source filters) -- units and quantity -- time range and record revisions consumed -- exclusions and missing-data handling -- `unavailable` with reason when inputs are insufficient - -Numerical tests use reference answers computed outside the implementation under test. -RMSSD and SDNN never share a baseline. Provider scores stay labeled as vendor results. - -## Import completeness (measurable) - -Imports must emit a **receipt**: imported, unchanged, corrected, skipped (with reason), -invalid, and unexpectedly missing fields. Silent loss of a supported mapped field is a -failure. Video findings (Oura readiness, sleep scores, contributors, SpO₂, invalid -records after reimport) are regression targets documented in the Rust plan until reproduced -with synthetic fixtures. diff --git a/build-history/plans/rust-capability-inventory.md b/build-history/plans/rust-capability-inventory.md deleted file mode 100644 index 03108cfb..00000000 --- a/build-history/plans/rust-capability-inventory.md +++ /dev/null @@ -1,76 +0,0 @@ -# Capability and dependency inventory (Rust adoption) - -Maps today’s TypeScript implementation to the planned Rust core (`ath-core`) and thin -host shells. Status is **current** unless noted **planned** or **remove**. - -## Host shells (stay thin) - -| Area | Today | Owner after cutover | -|---|---|---| -| CLI argument parsing, help, presentation | `src/program.ts`, `src/help.ts`, `src/cli.ts` | TypeScript CLI | -| Skill install and references | `src/skill.ts`, `skill/` | TypeScript CLI | -| Credentials and model gateway | `src/keyring.ts`, `src/gateway.ts`, `src/predict.ts` | TypeScript CLI | -| Progress and share UX | `src/progress.ts`, `src/share.ts` | TypeScript CLI | -| SwiftUI verification app | not in repo yet | Swift app under `apps/verification-ios/` (see rust-adoption plan) | - -## ath-core (single executable domain) - -| Capability | Current location | Rust module (planned) | Notes | -|---|---|---|---| -| v1 record shapes and JSON rules | `src/v1/schema.ts`, generated `schema/1.0.0/` | `model`, `validate` | Zod refinements move to Rust validators; JSON Schema and TS types generated from Rust | -| Legacy 0.x shapes | `src/schema.ts` | none | Remove after cutover; importers stop routing through 0.x | -| SQLite open, pragmas, migrate | `src/db/migrate.ts`, `src/db/client.ts` | `storage` | Reads embedded `spec/sql/migrations/*.sql` | -| Record write, revision, history | `src/db/records.ts`, `revision-encoding.ts` | `records` | Official write path; replaces ad hoc direct-SQL revision recipes | -| Queries and views | `src/db/query.ts`, `records-view.ts`, `series-view.ts` | `query` | | -| Conflicts and transactions | `src/db/conflicts.ts`, `transaction.ts` | `storage` | | -| Deletion and erasure | `src/db/erase.ts` | `lifecycle` | | -| Package import and export | `src/db/import-package.ts`, `export.ts` | `package` | | -| Attachments | `src/db/attachments.ts`, `attachment-ingest.ts` | `attachments` | Staging must roll back with failed transactions | -| Provider import | `src/import/*`, `src/db/provider-import.ts` | `import` | Normalize straight into canonical model; drop `ImportPayload` via 0.x | -| Dense series encode/decode | `src/series.ts`, `src/db/series-view.ts` | `series` | | -| Calculations | `src/db/calculate.ts`, `src/hrv.ts`, `src/stats.ts` | `calc` + method registry | Expand per coverage table | -| Check and drift | `src/db/check.ts`, `scripts/check-schema-drift.ts` | `check` | | -| Evidence and grading hooks | `src/db/evidence.ts`, `prediction-grade.ts` | `grading` (host calls models; core stores results) | | -| UUID and IDs | `src/db/uuid.ts` | `ids` | | -| SQL contract metadata | `src/db/sql-contract.ts`, `spec/sql/` | embed + `contract` | Plain SQL files are canonical | - -## Generated public contracts - -| Artifact | Today | After Rust foundation | -|---|---|---| -| JSON Schema | from `src/v1/schema.ts` | from Rust model | -| TypeScript types | Zod inference | generated from JSON Schema or Rust export | -| `spec/sql/` | generated from TS migration strings | canonical source; TS and Rust embed the same files | -| Conformance vectors | missing (`CR5` pending) | `spec/conformance/`; shared across Rust, Node, Swift | - -## Zod and extension inventory (validation migration) - -| Rule area | In Zod today | Rust plan | -|---|---|---| -| Two-tier wall (source required on measured records) | `src/v1/schema.ts` + SQL triggers | Both; triggers stay in SQL | -| Athlete reports cannot claim `source` | schema + triggers | same | -| Record type unions and required fields | Zod objects | Rust enums + validators | -| `extensions` envelope size and namespacing | `src/v1/extensions.ts` | Rust validator | -| Portable package unknown fields | strict package schemas | Rust import validator | -| Cross-record links and protected references | partial in Zod; more in SQL | full semantic checks in core | -| Provider period and timezone fields | `src/v1/schema.ts` | preserve | -| RMSSD vs SDNN quantities | separate fields | never merge baselines | -| Legacy 0.x-only rules | `src/schema.ts` | remove with 0.x paths | - -## Dependencies between open work - -| Pull request | Overlap with Rust prerequisites | -|---|---| -| [#15](https://github.com/mwhitham/ath/pull/15) (contribution foundation plan) | CR5 conformance, CR6 guidance, CR3 SQL — implement prerequisites on `main`; do not duplicate #15 doc-only deltas | -| [#25](https://github.com/mwhitham/ath/pull/25) (migrate, import check, logging) | `ath migrate` and import receipts belong in core eventually; land #25 behaviors in TS first, port to Rust in Provider imports stage | -| [#20](https://github.com/mwhitham/ath/pull/20) (this plan) | Docs and decisions only | - -## Temporary dual paths (must have removal milestones) - -| Temporary path | Milestone to remove | -|---|---| -| TypeScript engine in `src/db/*` | Cutover stage: delete after foundation proof and stage gates | -| `src/schema.ts` 0.x model in import pipeline | Provider imports stage | -| `generate:sql-contract` from TS strings | Records stage: SQL files edited directly; generator becomes verify-only or removed | -| Hand-maintained Zod as normative | Foundation stage: Rust owns validation; Zod becomes generated | -| `src/import/index.ts#importExport` | Prerequisite PR: delete unused 0.x export writer | 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..6efb17be --- /dev/null +++ b/build-history/v1.0.0/appendix/rust-adoption.md @@ -0,0 +1,282 @@ +# 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 2.0.0** is when the package drops Zod-based normative exports (D131). **npm 1.1.0** +(#25) still uses Zod. **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` (D125 narrows). + +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–9. 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. + +--- + +## 10. 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. + +--- + +## 11. 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 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. + +--- + +## 12. 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. + +--- + +## 13. 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). + +--- + +## 14. Data + +No broad legacy system for external users. Use explicit, tested conversion on copies when +needed. Do not silently upgrade a database on open. + +--- + +## 15. 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. + +--- + +## 16. 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 §11. 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 7897ce00..eecb7869 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -1293,61 +1293,97 @@ 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 and other mobile hosts use UniFFI (`ath-uniffi`) without a separate local -service. +Swift hosts use UniFFI (`ath-uniffi`) for a maintained library and verification +app; D121 no longer defers that Swift surface. -This supersedes D121 only where D121 deferred a Rust core. D121 still rejects -building every client surface before need; this decision names Rust as the core -because one builder needs a single cross-language engine now. D7 remains: CLI plus -Skill, not MCP or a conversational server. +**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. +- **D115** — splitting into published `@ath/*` workspace packages before need. The + Rust plan defers that split; one build focuses on `ath-core` and bindings first. + +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: -- **Maintain a long-term TypeScript engine beside Rust.** Rejected because two - implementations diverge on triggers, migrations, and conformance vectors. -- **Engine-selection flag or automatic TypeScript fallback at cutover.** Rejected - because it preserves duplicate rules indefinitely. -- **Local HTTP service for mobile.** Rejected for the same reasons as D7 and D121. +- **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) -This follows the [Rust adoption plan](../../plans/rust-adoption.md). +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). -## D131. Generated contracts and conformance vectors outrank binding APIs (proposed) +**Supersedes:** -The public contracts are `spec/sql/`, generated JSON Schema, and -`spec/conformance/` behavior fixtures. Rust types and validators in `ath-core` -are the source for generated JSON Schema and TypeScript data types. Binding APIs -may change between releases when the format version does not. Breaking record or -SQL schema versions follow existing format versioning rules. +- **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). +- **D126** — for normative Zod exports and hand-maintained `./schema` types: those + stable TypeScript surfaces may be removed only in npm major version **2.0.0**, not + in a minor release. Until 2.0.0, D126 still applies to what the package exports. + [Pull request #25](https://github.com/mwhitham/ath/pull/25) ships **1.1.0** on the + Zod-based model. +- **D116** — the sentence that Zod remains the logical record definition. -`CORE_API_VERSION` (D128) still governs community extension manifests. It is -independent of binding refactors that do not change importer or calculation -interfaces. +**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 require npm **2.0.0** to drop the old Zod-based +exports. Compatibility facades that keep two validators are rejected. Rejected alternatives: -- **Keep Zod in `src/v1/schema.ts` as the long-term normative validator.** Rejected - because host-language validators duplicate Rust and drift from embeddings. -- **Treat napi or UniFFI shapes as the spec.** Rejected because bindings are not - portable across languages. +- **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) -This follows the [Rust adoption plan](../../plans/rust-adoption.md). +Builders may still open the SQLite file with ordinary tools, enable required pragmas, +and rely on triggers and constraints (portions of **D116** remain). 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`. -## D132. Supported writes go through the core; direct SQL is not a full protocol (proposed) +**Supersedes:** -Builders may still open the SQLite file with ordinary tools and respect required -pragmas (D116). Triggers and constraints continue to enforce the two-tier wall and -other critical rules. Official Athletic Standard products and documented integration -paths perform record lifecycle work through typed domain operations in `ath-core`, -not by recreating the complete revision protocol through ad hoc direct SQL alone. +- **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. +- **D116** — Zod as the logical record definition (see D131) and any reading that + official products must implement lifecycle only through ad hoc direct SQL. +- **D93** — implementing domain storage by issuing raw parameterized SQL from the + Node package as the long-term official writer. Node becomes a thin binding; SQL + execution for official writes moves into `ath-core` (rusqlite). Third-party direct + SQLite access for simple cases is unchanged where triggers enforce rules. -Stable read views and any narrow documented writable tables (D125) remain for simple -direct access. They do not replace core operations for corrections, history, -conflicts, package import, attachments, or erasure. +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; D116 stands for direct SQLite access. -- **Promise full lifecycle parity through direct SQL recipes.** Rejected because it - duplicates the core and breaks when internal encodings change. +- **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](../../plans/rust-adoption.md). +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 72d71ae1..a10ccd0d 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -68,17 +68,16 @@ 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. -## Rust adoption prerequisites (proposed) +## Rust adoption (proposed) -Tracked in [`plans/rust-adoption.md`](../plans/rust-adoption.md). Draft decisions -D130–D132. Does not block v1 npm publish by itself; foundation proof blocks broad -Rust port. +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 | Revised plan, inventory, coverage table, decisions, `AGENTS.md` | in review — PR #20 | -| R1 | Runtime loads canonical `spec/sql/migrations/*.sql` | pending — follow-up PR on `main` | -| R2 | `spec/conformance/` language-neutral fixtures | pending — follow-up PR on `main` | -| R3 | Rust workspace (`ath-core`, `ath-node`, `ath-uniffi`) and CI `cargo check` | pending — follow-up PR on `main` | -| R4 | Remove unused `importExport`; document temporary dual paths | pending — follow-up PR on `main` | -| R5 | iPhone simulator CLI ↔ app round trip | **BLOCKED** — requires Xcode and iOS Simulator on macOS | +| 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 | From 759fc31d47392c5ead60ba1be4de77b9ac18cdfc Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 03:45:02 +0000 Subject: [PATCH 07/10] docs: second fact-check pass on Rust plan (PR #20) Fix D115 defer wording, D126 follow vs supersede, deprecation path, D116/D93 accuracy, plan headings, build-history README versions, progress. Co-authored-by: Michael Whitham --- AGENTS.md | 2 +- build-history/README.md | 5 +- .../v1.0.0/appendix/rust-adoption.md | 35 ++++++------ build-history/v1.0.0/decisions.md | 53 +++++++++++-------- build-history/v1.0.0/progress.md | 5 +- 5 files changed, 58 insertions(+), 42 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0a894f23..f006f263 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,7 @@ describe released 0.x behavior. - **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 (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). After Rust owns the model (approved D131), regenerate JSON Schema and TypeScript from Rust instead of extending normative Zod. +- **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..1a04e985 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -6,7 +6,10 @@ This folder is the permanent record of what we decided to build and why. 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. -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 index 6efb17be..5a80827a 100644 --- a/build-history/v1.0.0/appendix/rust-adoption.md +++ b/build-history/v1.0.0/appendix/rust-adoption.md @@ -102,10 +102,12 @@ 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 2.0.0** is when the package drops Zod-based normative exports (D131). **npm 1.1.0** -(#25) still uses Zod. **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. +**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. --- @@ -130,7 +132,7 @@ 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` (D125 narrows). +using only the old direct-write recipes in `spec/sql/README.md` (**D132** narrows **D125**). No opaque `execute(JSON)` API. @@ -150,7 +152,7 @@ Fix bugs when found. Do not treat old bugs as compatibility. --- -## 7–9. Calculations +## 7. Calculations See [`rust-calculation-coverage.md`](rust-calculation-coverage.md). The wide calculation library comes **after** the foundation proof. @@ -160,9 +162,12 @@ 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). + --- -## 10. Import completeness +## 8. Import completeness Parsers should land in the canonical Rust model without routing through `src/schema.ts`. @@ -175,7 +180,7 @@ for synthetic regressions in the build. --- -## 11. Work in the approved build PR +## 9. Work in the approved build PR | Item | Notes | |---|---| @@ -187,7 +192,7 @@ for synthetic regressions in the build. | Calculation contract | Coverage appendix | | Dead code | e.g. unused `importExport`; milestones in inventory | -Defer: catalog infrastructure, extra database backends, D115 workspace split, generic +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 @@ -195,7 +200,7 @@ does not change what D128 covers. --- -## 12. Foundation proof (CLI + iPhone) +## 10. Foundation proof (CLI + iPhone) 1. Installed CLI creates a database and a measurement. 2. iPhone app opens it and corrects the measurement. @@ -212,7 +217,7 @@ Do not start the wide port until this proof passes. --- -## 13. Migration steps +## 11. Migration steps | Step | Done when | |---|---| @@ -228,14 +233,14 @@ Record-format version and SQL schema version stay separate from npm versioning ( --- -## 14. Data +## 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. --- -## 15. Packaging and checks +## 13. Packaging and checks Prebuilt natives for declared Node platforms. Swift builds on declared iOS targets. @@ -245,7 +250,7 @@ Report PASS, FAIL, BLOCKED, or NOT IMPLEMENTED. --- -## 16. Deletion checklist +## 14. Deletion checklist Remove only after the step above passes: @@ -267,7 +272,7 @@ Remove only after the step above passes: 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 §11. Public cutover waits on the iPhone simulator proof on macOS. +items in §9. Public cutover waits on the iPhone simulator proof on macOS. --- diff --git a/build-history/v1.0.0/decisions.md b/build-history/v1.0.0/decisions.md index eecb7869..1d1b3dc9 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -1294,7 +1294,8 @@ 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 no longer defers that Swift surface. +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):** @@ -1302,8 +1303,13 @@ app; D121 no longer defers that Swift surface. 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. -- **D115** — splitting into published `@ath/*` workspace packages before need. The - Rust plan defers that split; one build focuses on `ath-core` and bindings first. + +**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” @@ -1328,13 +1334,16 @@ Schema, and language-neutral behavior fixtures under `spec/conformance/` (CR5). - **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). -- **D126** — for normative Zod exports and hand-maintained `./schema` types: those - stable TypeScript surfaces may be removed only in npm major version **2.0.0**, not - in a minor release. Until 2.0.0, D126 still applies to what the package exports. - [Pull request #25](https://github.com/mwhitham/ath/pull/25) ships **1.1.0** on the - Zod-based model. - **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 @@ -1346,36 +1355,36 @@ Schema, and language-neutral behavior fixtures under `spec/conformance/` (CR5). 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 require npm **2.0.0** to drop the old Zod-based -exports. Compatibility facades that keep two validators are rejected. +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. +- **Remove stable TypeScript exports in a minor npm release without prior deprecation.** + Rejected by D126. This follows the [Rust adoption plan](appendix/rust-adoption.md). ## D132. Supported writes go through the core; narrow direct SQL (proposed) -Builders may still open the SQLite file with ordinary tools, enable required pragmas, -and rely on triggers and constraints (portions of **D116** remain). 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`. +**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. -- **D116** — Zod as the logical record definition (see D131) and any reading that - official products must implement lifecycle only through ad hoc direct SQL. -- **D93** — implementing domain storage by issuing raw parameterized SQL from the - Node package as the long-term official writer. Node becomes a thin binding; SQL - execution for official writes moves into `ath-core` (rusqlite). Third-party direct - SQLite access for simple cases is unchanged where triggers enforce rules. +- **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. diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index a10ccd0d..000793b1 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -64,9 +64,8 @@ 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 and CR2 landed before athleticstandard@1.0.0 shipped. Remaining CR3–CR9 work and +the cross-platform part of step 10 still block updated release steps 11 and 12. ## Rust adoption (proposed) From 30847e9bb3c38a8789e711a8c1f91b2df2076d7b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 03:47:33 +0000 Subject: [PATCH 08/10] docs: mark v1.0.0 npm release done in progress.md Co-authored-by: Michael Whitham --- build-history/v1.0.0/progress.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index 000793b1..2a6697fa 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 | ✅ done — `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 @@ -47,7 +47,7 @@ are recorded in `performance/limits.json`. ## Pre-publish contribution foundation -D115–D128 and section 19 of `spec.md` add work before release steps 11 and 12. +D115–D128 and section 19 of `spec.md` add follow-on work after the 1.0.0 npm release. The long-form sequence is in [`appendix/contribution-readiness.md`](appendix/contribution-readiness.md). @@ -64,8 +64,8 @@ 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 landed before athleticstandard@1.0.0 shipped. Remaining CR3–CR9 work and -the cross-platform part of step 10 still block updated release steps 11 and 12. +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) From c7ed2da785b2bdc0df199671e4e4c945a27a406e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 03:50:52 +0000 Subject: [PATCH 09/10] docs: final PR #20 wording fixes (D126, progress, build-history) Co-authored-by: Michael Whitham --- AGENTS.md | 2 +- build-history/README.md | 2 +- build-history/v1.0.0/decisions.md | 3 +-- build-history/v1.0.0/progress.md | 10 +++++----- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f006f263..65baea1b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,7 +26,7 @@ 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. +- **`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. diff --git a/build-history/README.md b/build-history/README.md index 1a04e985..339566fd 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -4,7 +4,7 @@ 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 **record format version** they describe — the same version that appears in `athleticstandard_version`. The npm package version and diff --git a/build-history/v1.0.0/decisions.md b/build-history/v1.0.0/decisions.md index 1d1b3dc9..48bd0c0d 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -1361,8 +1361,7 @@ 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 without prior deprecation.** - Rejected by D126. +- **Remove stable TypeScript exports in a minor npm release.** Rejected by D126. 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 2a6697fa..303700ff 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -16,7 +16,7 @@ Tracks the build order from `spec.md`. Update when a step lands. | 9 | Update checks, help, the Skill, SPEC, README, and package exports | ✅ done | | 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 | ✅ done — `athleticstandard@1.0.0` on npm (2026-10-18, `main` 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 follow-on work after the 1.0.0 npm release. -The long-form sequence is in -[`appendix/contribution-readiness.md`](appendix/contribution-readiness.md). +D115–D128 and `spec.md` §19 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 | |---|---|---| From 77c1bf17fd407ccae197cc54388fcfa6805dfd63 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 19 Oct 2026 03:53:30 +0000 Subject: [PATCH 10/10] =?UTF-8?q?docs:=20clarify=20=C2=A719=20implements?= =?UTF-8?q?=20D115-D128=20in=20progress?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Michael Whitham --- build-history/v1.0.0/progress.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index 303700ff..74d82c26 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -47,7 +47,7 @@ are recorded in `performance/limits.json`. ## Contribution foundation (CR4–CR9 after 1.0.0) -D115–D128 and `spec.md` §19 listed CR4–CR9 as pre-publish work. **CR4–CR9 slipped past +`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).