From 86f1728fa3e0c6158ad2d5a01c16b79cee0cb501 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 14 Oct 2026 16:46:26 +0000 Subject: [PATCH 1/2] docs: record contribution foundation and D129 early-build exception Co-authored-by: Michael Whitham --- .../v1.0.0/appendix/contribution-readiness.md | 1126 +++++++++++++++++ build-history/v1.0.0/decisions.md | 289 +++++ build-history/v1.0.0/progress.md | 23 + build-history/v1.0.0/spec.md | 122 ++ 4 files changed, 1560 insertions(+) create mode 100644 build-history/v1.0.0/appendix/contribution-readiness.md diff --git a/build-history/v1.0.0/appendix/contribution-readiness.md b/build-history/v1.0.0/appendix/contribution-readiness.md new file mode 100644 index 00000000..cd824ef7 --- /dev/null +++ b/build-history/v1.0.0/appendix/contribution-readiness.md @@ -0,0 +1,1126 @@ +# Contribution readiness plan + +Status: approved. D115–D128 in `../decisions.md` record the choices. The v1 +format changes are appended to `../spec.md`, and their work is tracked in +`../progress.md`. + +## Plain-English summary + +Athletic Standard stays small. +The product is one local SQLite file, a public specification, and the existing CLI and Skill. +The file enforces its important rules even when another program writes it. +Builders may read and write it directly with ordinary SQLite tools. +They do not need a Node service or an Athletic Standard language library. +Agents get machine-readable rules, examples, test vectors, and a build-on-ATH Skill. +The first change adds a safe place for namespaced extension data. +The same change moves critical record rules into SQLite constraints and triggers. +That schema work must land before v1.0.0 is published to npm. +Next come plain SQL migrations, stable read views, and documented writable tables. +Conformance tests then show any app or agent whether its implementation is correct. +The existing npm package gains clear internal boundaries without breaking its public name. +Reviewed skills, importers, and calculations may ship in the main package. +Catalog inclusion means tests passed; it is not an endorsement or hosted approval. +HTTP, MCP, Rust, Swift libraries, and other ports wait until a real builder needs them. + +## 1. Goal + +Make the public Athletic Standard repository safe and practical to build on. +A builder should be able to read and write the SQLite record without running +Node or waiting for a maintained language library. A TypeScript app should +have stable package entry points. Contributors should have clear ways to add +skills, provider importers, and calculations. + +Accepted public work may later ship in `athleticstandard`. A private hosted +product can then adopt it by updating its exact package pin. The public +repository must not depend on private code or private checks. + +This plan preserves the current product boundary: + +- SQLite is the live local record. +- JSON is the complete portable package. +- The two-tier wall remains structural. Measured records require a source. + Athlete reports cannot claim one. +- The public package is not an app, a coach, or medical advice. +- Community entries are not fetched or run merely because they appear in a + catalog. +- Forks may add other runtimes or loading models. Official Athletic Standard + and the hosted product run only reviewed code compiled into releases. +- The open-source base stays thin: the file, specification, conformance + vectors, CLI, and Skills. + +## 2. Why this plan is in the v1 appendix + +`build-history/README.md` names version folders after the format version they +produce. This plan covers repository work as well as the remaining v1 format +work. The approved extension envelope and database-enforced rules belong to +v1.0.0 because npm still publishes 0.4.3. The full plan is supporting material +for D115–D128, so the repository process places it in the v1 appendix. + +The approved work follows the repository process: + +1. D115–D128 are appended after D114 in `../decisions.md`. +2. The v1 format amendment is appended to `../spec.md`. +3. Pending pre-publish work is appended to `../progress.md`. +4. Put later format changes in the folder named for the version they produce. +5. Keep this appendix as the long-form plan linked from each decision. + +## 3. Verified starting point + +This review uses `main` after pull request +[#14](https://github.com/mwhitham/ath/pull/14) merged. + +| Area | What exists now | Readiness gap | +|---|---|---| +| SQLite versions | `database_metadata.sql_schema_version` and `PRAGMA user_version` are both checked in `src/db/migrate.ts` and `src/db/check.ts`. | `src/db/migrations/001-initial.ts` contains the only schema as a TypeScript string. `migrateDatabase` throws for every version other than 1. There is no standalone SQL contract or forward migration runner. | +| Record schemas | `src/v1/schema.ts` is the public record definition. Generated JSON Schemas live in `schema/1.0.0/`. | The SQL schema and JSON Schema can drift without one check that compares all generated public artifacts. | +| Cross-language use | A standard SQLite file and complete JSON package exist. | There are no language-neutral query examples, conformance vectors, stable writable-table contract, or tested direct-write transaction recipe. | +| Pure logic | `src/v1/schema.ts` and some calculation helpers are independent of file access. | Database calculations live in `src/db/calculate.ts`. Import, series, model, key, file, and package paths use Node file APIs. The published package requires Node 20. | +| Local API | The CLI and Skill expose named operations. | No local HTTP or MCP service is planned. Direct SQLite, the CLI, and Skills are the approved thin public interfaces. | +| Package API | `package.json` already has `.`, `./database`, `./schema`, JSON Schema, and Skill entry points. `tests/v1-package-exports.test.ts` checks them. | `src/index.ts` uses `export *`. There is no public API policy, API reference, deprecation rule, or importer entry point. | +| Importers | Apple Health, WHOOP, and Oura parsing feeds the common `ImportPayload` in `src/import/merge.ts`. | `src/import/index.ts` uses `VENDOR_LABELS` and nested format branches. `ImportPayload` and `mergePayload` are not public. There is no importer interface or registry. | +| Skills | `skill/` contains one versioned Skill. `src/skill.ts` installs and updates that one directory. | There is no selected multi-skill loader or build-on-ATH Skill. D41 is superseded by the approved explicit local-install rule. | +| CLI and services | Tests can replace model completion and model catalog functions. | `src/program.ts` writes to the console and process state throughout. `src/update.ts`, `src/keyring.ts`, and `src/gateway.ts` hold separate package, keyring, URL, and site constants. | +| Extensions | Strict Zod objects and refusal of unknown package fields prevent silent data loss. | Records have no namespaced extension field. Adding one without tier and preservation rules could weaken the two-tier wall. | +| Contribution checks | Release-only cross-platform and performance workflows exist. | There is no pull-request check on `main`. Pull request #5 adds it, public-data checks, and a first `CONTRIBUTING.md`. It should land before this plan is executed. | +| Repository guidance | `AGENTS.md`, `README.md`, `SPEC.md`, and the build history explain the current release. | There is no contributor-facing architecture guide, extension guide, public API guide, build-on-ATH Skill, issue template, pull request template, or `CODEOWNERS`. | +| Site metadata | Repository and issue links are present in `package.json`. | The homepage is `https://athleticstandard.ai`; the intended public site is `https://ath.fit`. | + +The earlier review was wrong in two places: + +- A schema-version table is not wholly missing. `database_metadata` already + carries `sql_schema_version`, with `PRAGMA user_version` as a local mirror. + The missing part is a public SQL migration chain. +- Subpath exports are not wholly missing. The missing part is a stated and + documented stability boundary. + +Additional gaps found during review: + +- Provider import still passes through the old model in `src/schema.ts` before + `src/db/provider-import.ts` maps it into v1 records. This leaves two domain + models in active maintenance. +- `src/import/index.ts#importExport` is an unused 0.x JSON write path. It makes + the supported importer contract unclear. +- `src/models.ts#defaultModelPath` only replaces `.json`, even though the live + file now ends in `.ath.sqlite`. +- The public JavaScript database handle is opaque under D104, but direct + SQLite writes are now approved. Critical correctness rules therefore need + to move from Node-only checks into SQL constraints and triggers. +- The release workflows and the proposed pull-request workflow in #5 use + different Node and action versions. They should share one supported version + policy after #5 lands. + +## 4. Recommended end state + +Use a workspace with small packages, but reach it through compatibility +entry points. Do not make the repository move and public package split one +large pull request. + +```text +spec/ + README.md + json-schema/ + sql/ + migrations/ + conformance/ +packages/ + core/ # @ath/core: schemas, values, pure transforms, API version + store/ # @ath/store: SQLite operations and file adapters + importers/ # @ath/importers: interface, registry, built-in importers +src/ # athleticstandard compatibility facade and ath CLI +skills/ + build-on-ath/ # agent-facing guide for direct SQLite and extension work +community/ + schema/ + skill// + importer// + calculation// + community-catalog.json +``` + +The existing `athleticstandard` npm name and `ath` command remain supported. +The root package re-exports the supported APIs from the workspace packages. +The split packages should start as workspace packages. Publishing them under +the `@ath` scope happens only after package ownership and release policy are +confirmed. While they are private workspaces, the root build must bundle their +code into `athleticstandard`; a published package cannot refer to an +unpublished workspace dependency. + +The `spec/` directory is language-neutral. Generated files may also remain at +their current package paths for compatibility. One generator writes both +locations and one drift check verifies them. + +### 4.1 Contract boundaries + +There are four different contracts. Their versions must not be conflated. + +1. `athleticstandard_version` versions athlete-owned record content. +2. `sql_schema_version` versions the SQLite encoding and migrations. +3. `CORE_API_VERSION` versions the public extension interfaces. +4. The npm package version versions shipped TypeScript and CLI behavior. + +An npm release may change without changing the record format. An additive SQL +index may change the SQL version without changing record content. A breaking +importer interface changes `CORE_API_VERSION`. Each conformance vector names +the contract and version it tests. Record, SQL, and core API vectors do not +share one version. + +### 4.2 Direct SQLite builders + +Direct SQLite reads and writes are public interfaces: + +- Publish ordered `.sql` migration files. +- Publish the required SQLite version and compile options. +- Publish stable read views. Views give clients one versioned read contract + inside SQLite. Example queries alone do not. +- Publish a small set of stable writable tables. Every other table is + internal. +- Require every client connection to run `PRAGMA foreign_keys = ON`. +- Back critical cross-table rules with triggers because foreign-key + enforcement is set per connection. +- Enforce field shape with `STRICT`, `CHECK`, `NOT NULL`, `UNIQUE`, foreign + keys, and SQLite JSON functions. +- Enforce the two-tier wall, revision order, current-revision pointers, + deletion state, and protected links in the database. +- Publish JSON decoding fixtures for `record_revisions.record_json`. +- Publish transaction recipes and conformance tests for direct writers. + +No hand-maintained Swift, Rust, or other language library is required for +v1. Agents and builders can generate one from the machine-readable contract +when needed. + +### 4.3 Community code and hosted promotion + +The catalog describes reviewed source in this repository. It is not a remote +plugin store. Catalog generation never downloads or runs an entry. + +Skills remain passive instructions. Official Athletic Standard and the hosted +product run only reviewed importers and calculations compiled into the main +`athleticstandard` package. The default runtime never loads arbitrary code +from a community directory. Forks are free to choose another model. Promotion +into the hosted product follows this order: + +1. Merge the public contribution with synthetic tests. +2. Release an exact public package version. +3. Update the hosted product's exact package pin. +4. Run the hosted product's own checks. + +Catalog inclusion records passed public tests only. It is not endorsement and +does not approve hosted promotion. This keeps the public package as the source +reviewed by both products without copying an untracked private variant. + +## 5. Pull request sequence + +Every pull request below is independently mergeable. Each one must preserve +the current `athleticstandard` imports and `ath` commands unless its breaking +change is expressly approved. + +### PR 0 — Land the health-data safeguard first + +Dependency, not product implementation. It lands first because every later +pull request needs its health-data and CI checks. PR 1 remains the first +product and schema change. + +Scope: + +- Merge [#5](https://github.com/mwhitham/ath/pull/5) after it is rebased. +- Treat its `.github/workflows/ci.yml`, `CONTRIBUTING.md`, + `scripts/check-public-data.ts`, `.gitignore`, `AGENTS.md`, and package script + as the starting point. +- Rebase each later pull request after #5. +- Treat [#13](https://github.com/mwhitham/ath/pull/13) as superseded by merged + #14. It has no remaining change to carry into this plan. + +Files touched: only the files already owned by #5. + +Acceptance: + +- Pull requests run public-data, type, test, and build checks. +- Branch rules require the check after it exists on `main`. +- Synthetic fixtures remain allowlisted. + +Risk: a stale rebase could drop the v1 fixture exceptions added by #14. +Review the combined `.gitignore` and public-data allowlist. + +### PR 1 — Finish the v1 schema before npm publish + +This pull request is the first implementation step. It must merge before +v1.0.0 is published to npm. + +Scope: + +- Add an optional, namespaced, size-limited `extensions` envelope to records. +- Make extension values inherit the parent record's measured or + athlete-reported tier. +- Preserve unknown extension values through SQLite and complete JSON package + round trips. +- Add `STRICT`, `CHECK`, `NOT NULL`, `UNIQUE`, and foreign-key constraints + wherever SQLite can enforce the current v1 rules. +- Add triggers for critical cross-table rules, including: + - measured records require a valid source; + - athlete-reported records cannot claim a source; + - record and revision types agree; + - revision numbers and previous-revision links are valid; + - current-revision pointers identify the current retained revision; + - deletion and erasure state cannot contradict current records; + - protected evidence and result links keep valid record types. +- Validate stored JSON shape with SQLite JSON functions. +- Add direct-SQL tests that bypass Node operations and prove invalid writes + fail in SQLite. +- Append the approved v1 decisions after D114 and update the v1 spec and + progress before implementation. + +Files touched: + +- `build-history/v1.0.0/decisions.md` +- `build-history/v1.0.0/spec.md` +- `build-history/v1.0.0/progress.md` +- `src/v1/schema.ts` +- `schema/1.0.0/**` +- `src/db/migrations/**` +- `src/db/records.ts` +- `src/db/import-package.ts` +- `src/db/export.ts` +- `SPEC.md` +- schema, direct-SQL, package round-trip, and safety tests + +Acceptance: + +- npm still reports 0.4.3 when this work starts. +- The v1 schema includes the extension envelope before v1.0.0 is published. +- Unknown extension values survive database and package round trips. +- Extension limits reject oversized or deeply nested values. +- Direct SQL cannot bypass the two-tier wall or critical revision, deletion, + erasure, and link rules. +- Every measured write still identifies its source. +- Every athlete-reported write is structurally unable to claim a source. +- Generated JSON Schemas and fixtures are current. + +Risk: triggers can reject valid bulk, restore, or migration work when their +transaction ordering differs from normal writes. Test creation, correction, +package restore, provider import, deletion, erasure, and migration through +both Node and direct SQL. + +### PR 1A — Add contribution governance + +Scope: + +- Expand #5's `CONTRIBUTING.md` rather than replacing it. +- Add `.github/PULL_REQUEST_TEMPLATE.md`, + `.github/ISSUE_TEMPLATE/bug.yml`, + `.github/ISSUE_TEMPLATE/importer.yml`, + `.github/ISSUE_TEMPLATE/calculation.yml`, and + `.github/ISSUE_TEMPLATE/skill.yml`. +- Add `.github/CODEOWNERS` with `@mwhitham` for `spec/`, migrations, schemas, + release workflows, and community policy. Other areas may be reviewed by any + maintainer. +- Use these exact owner patterns: + - `/spec/ @mwhitham` + - `/src/db/migrations/ @mwhitham` + - `/src/v1/schema.ts @mwhitham` + - `/schema/ @mwhitham` + - `/.github/workflows/release-*.yml @mwhitham` + - `/community/policy.json @mwhitham` +- Do not add a catch-all owner. Normal repository permissions let any + maintainer review every other path. +- D123 records a narrow exception to the impersonal-repository rule. GitHub + owner handles are allowed only in `CODEOWNERS` and in text that explains + that file. A real account is required because this repository has no team + handle. +- Add DCO sign-off instructions and a required sign-off check. +- Keep MIT and do not add a contributor license agreement. + +Files touched: + +- `CONTRIBUTING.md` +- `.github/**` +- documentation tests + +Acceptance: + +- Each issue form asks for synthetic data only. +- The pull request template requires fixture safety and generated-file checks. +- DCO sign-off is required, MIT remains the license, and there is no + contributor license agreement. +- `@mwhitham` owns the approved protected areas. Other paths do not require + that owner specifically. +- No private repository name or private process is required by a public + contributor. + +Risk: governance files can block all contributions when owner names or DCO +rules are wrong. Land required checks only after a test pull request passes. + +### PR 1B — Add architecture and build-on guides + +Scope: + +- Add `ARCHITECTURE.md`, `docs/build-on-ath.md`, and + `docs/extensions.md`. +- Document the current package, record, store, importer, and CLI + boundaries before moving files. +- Change `package.json#homepage` and the gateway referrer in + `src/gateway.ts` to `https://ath.fit`. +- Document extension promotion. An extension becomes an official field only + after repeated real use, stable meaning across builders, clear tier rules, + and a separately approved format change. + +Files touched: + +- `ARCHITECTURE.md` +- `docs/build-on-ath.md` +- `docs/extensions.md` +- `README.md` +- `package.json` +- `src/gateway.ts` +- documentation tests + +Acceptance: + +- A new contributor can identify each current boundary and its planned + package. +- The build-on guide states that direct SQLite reads and writes are supported. +- It tells clients to enable `PRAGMA foreign_keys` and names the constraints + and triggers that remain authoritative. +- Public links use `ath.fit`. +- `docs/extensions.md` explains that linked extension records may be added + later and that popular extensions require a new format decision before + promotion to official fields. +- No private repository is required to follow the guide. + +Risk: an architecture guide can promise the target before it exists. Mark +current behavior and planned behavior separately. + +### PR 2 — Publish the SQLite contract as plain SQL + +Scope: + +- Create `spec/sql/migrations/001-initial.sql` from the completed v1 schema in + `src/db/migrations/001-initial.ts`. +- Keep `database_metadata.sql_schema_version` as the version table. Do not add + a second source of truth. +- Define ordered migration names, transaction rules, rollback behavior, + minimum SQLite version, and the relation to `PRAGMA user_version`. +- Change the Node migration runner to read or import generated SQL rather than + owning a separate string. +- Add a migration ledger test that creates every supported schema from zero + and upgrades every retained prior version. +- Add a drift check between migration files, a newly created database, and the + expected table, index, trigger, and view list. +- Add stable SQL read views and document their columns and version policy. +- Name the small set of stable writable tables and their required transaction + order. Mark every other table internal. +- Publish the constraint and trigger contract in machine-readable form. +- Add `ath migrate` with preview, backup, and explicit confirmation for + agents and scripts. +- On interactive database open, preview the migration and ask the person to + confirm. Never migrate in a noninteractive open. +- Create and verify a backup before applying any migration. + +Files touched: + +- `spec/sql/README.md` +- `spec/sql/migrations/001-initial.sql` +- `src/db/migrations/**` +- `src/db/migrate.ts` +- `src/db/check.ts` +- `src/program.ts` +- `src/help.ts` +- `scripts/check-schema-drift.ts` +- `tests/v1-db.test.ts` +- direct-write and migration tests +- `skill/references/cli.md` +- `package.json` + +Acceptance: + +- `sqlite3` can create the schema from published SQL without TypeScript. +- A database made by plain SQL has the same schema as one made by + `createDatabase`. +- The Node runner can migrate from each retained schema version. +- A changed table without a migration or drift update fails CI. +- Metadata and `PRAGMA user_version` agree after each migration. +- Plain `sqlite3` can use every stable read view and writable table. +- Direct clients are told to enable `PRAGMA foreign_keys`. +- Critical rules still fail through triggers when a test connection omits that + pragma. +- `ath migrate` previews, backs up, and confirms before writing. +- Interactive open prompts after a backup is ready. Noninteractive open + refuses and points to `ath migrate`. +- A failed migration leaves the original database usable and the backup + verified. + +Risk: the initial migration currently relies on parameterized metadata inserts +after table creation. The SQL contract must state which values a runner +supplies. It must not embed a fixed database ID or creation time. Backup and +prompt code must also work for WAL files and interrupted migrations. + +### PR 3 — Add language-neutral conformance fixtures + +Scope: + +- Add `spec/conformance/` with small JSON, SQL, and expected-result fixtures. +- Cover timestamps, UUIDv7 IDs, record revisions, deletions, source links, + dense samples, package order, calculations, direct writes, constraints, + triggers, stable views, writable tables, and migration results. +- Generate fixtures from fixed inputs. Do not hand-edit the generated outputs. +- Add one runner that checks fixture hashes and expected results. +- Add CI on Linux, macOS, and Windows for the language-neutral contract. Reuse + the release platform matrix rather than creating a conflicting matrix. +- Add machine-readable contract metadata for required pragmas, stable views, + writable tables, internal tables, constraints, triggers, and transaction + recipes. +- Update `AGENTS.md` with the direct-write and generated-artifact rules. +- Add `skills/build-on-ath/SKILL.md`. It teaches agents to inspect the + machine-readable contract, generate only the client code a project needs, + and run conformance before writing athlete data. +- Package the build-on-ATH Skill without changing the existing Skill path. + +Files touched: + +- `spec/conformance/**` +- `scripts/generate-conformance.ts` +- `scripts/check-conformance.ts` +- `tests/conformance.test.ts` +- `AGENTS.md` +- `skills/build-on-ath/**` +- `docs/build-on-ath.md` +- `.github/workflows/ci.yml` +- `.github/workflows/release-cross-platform.yml` +- `package.json` + +Acceptance: + +- Another language can implement the tests without importing npm code. +- The fixture generator is deterministic. +- SDNN and RMSSD have separate vectors and expected values. +- Measured and athlete-reported fixtures prove the two-tier wall. +- Direct-write vectors pass without importing npm code. +- The build-on-ATH Skill contains no hand-maintained language client. +- An agent can find required pragmas, stable reads, stable writes, and tests + from the machine-readable contract. +- CI fails on changed generated output. + +Risk: fixtures can accidentally describe current implementation bugs as the +contract. Each vector needs a short rule citation from `SPEC.md` or an approved +decision. + +### PR 4 — Lock the v1.0.0 npm publish gate + +Scope: + +- Add packed-tarball tests for every published JavaScript and specification + entry point. +- Verify the v1 extension schema, SQL enforcement, migrations, stable views, + writable tables, conformance files, and both official Skills ship in the + tarball. +- Add a release check that refuses v1.0.0 when any v1 schema or conformance + artifact is stale. +- Align pull-request and release workflow runtime versions. +- Add release notes for direct writes, required pragmas, extensions, and + explicit migrations. + +Files touched: + +- package tarball tests +- `package.json` +- `.github/workflows/ci.yml` +- release workflows +- release-note template + +Acceptance: + +- `npm view athleticstandard version` is still 0.4.3 before this gate lands. +- Tests install the packed artifact in an empty project with no workspace + links. +- The packed v1 package contains the extension envelope and database + enforcement from PR 1. +- It contains the SQL contract, migration commands, conformance vectors, and + build-on-ATH Skill from PRs 2 and 3. +- A stale or missing v1 artifact blocks publish. +- All cross-platform and measured v1 release checks pass before npm publish. + +Risk: the repository already declares package version 1.0.0. A release command +could publish it before the schema gate is complete. Keep publishing manual +and blocked by this required check until PRs 1 through 4 land. + +### PR 5 — Define and document the public core API + +Scope: + +- Add `CORE_API_VERSION = "1.0.0"`. +- Replace root `export *` statements with an explicit reviewed export list + while preserving all currently supported names. +- Add stability markers: stable, experimental, and internal. +- Define stable tool IDs, data-group IDs, and the `community.` grammar for + later manifests. +- Generate an API reference from the actual exported types. +- Add an API report test that requires review for additions and removals. +- Keep deprecated stable APIs working with warnings until the next major npm + release. That major release may remove them. + +Files touched: + +- `src/index.ts` +- `src/v1/schema.ts` +- `src/db/index.ts` +- `src/core-api.ts` +- `package.json` +- `tests/v1-package-exports.test.ts` +- `docs/api/**` +- API report configuration and checked output + +Acceptance: + +- Existing documented imports compile unchanged. +- Each public export has a stability label and reference entry. +- Deep imports outside `package.json#exports` remain unsupported. +- A public removal or type break fails the API report check. +- `CORE_API_VERSION` is available to manifests and runtime checks. +- Stable tool IDs and data-group IDs have one generated public list. + +Risk: an explicit list can accidentally remove a schema export that a user +already imports. Compare the built package before and after and keep aliases +for supported names. + +### PR 6 — Establish the workspace and extract `@ath/core` + +Scope: + +- Add `pnpm-workspace.yaml` and shared TypeScript/build settings. +- Move schemas, plain values, deterministic JSON helpers, and other no-I/O + logic into `packages/core/`. +- Enforce a no-Node-built-ins rule in `@ath/core`. +- Keep root `athleticstandard` and `athleticstandard/schema` exports as + compatibility wrappers. +- Move algorithm vectors from implementation tests into + `spec/conformance/algorithms/`. + +Files touched: + +- `pnpm-workspace.yaml` +- `packages/core/**` +- `src/index.ts` +- `src/v1/schema.ts` +- `tsup.config.ts` +- `tsconfig*.json` +- `package.json` +- `pnpm-lock.yaml` +- affected tests + +Acceptance: + +- `@ath/core` builds for a browser-like environment with no Node built-ins. +- The current root and schema imports return the same names and behavior. +- The CLI and all tests pass without path aliases that consumers cannot use. +- Algorithm fixtures can be consumed without npm. + +Risk: package splitting can introduce duplicate Zod copies or declaration +paths that only work in the workspace. Test packed tarballs, not only source +imports. + +### PR 6A — Extract SQLite storage without behavior changes + +Scope: + +- Move database operations to `packages/store/`. +- Keep the public database handle opaque for JavaScript callers. +- Keep `athleticstandard/database` as a compatibility wrapper. + +Files touched: + +- `packages/store/**` +- `src/db/**` +- `src/index.ts` +- `tsup.config.ts` +- package export tests + +Acceptance: + +- Node file, zip, and keyring code is absent from `@ath/core`. +- Existing database imports and CLI behavior remain unchanged. +- Packed `athleticstandard` contains the store code even while `@ath/store` + remains an unpublished workspace. + +Risk: moving modules can change declaration paths or package initialization. +Compare packed exports and database behavior before and after the move. + +### PR 6B — Add value and platform adapters + +Scope: + +- Define clock, random-ID, database-client, file, archive, and secret-store + adapters. +- Move Node file, zip, and keyring work behind Node adapters. +- Keep local file security checks mandatory in the Node file adapter. +- Inject clock and ID sources into store domain operations. + +Files touched: + +- `packages/store/src/adapters/**` +- `packages/store/src/**` +- `src/file.ts` +- `src/series.ts` +- `src/import/zip.ts` +- `src/keyring.ts` +- adapter and platform tests + +Acceptance: + +- Store operations can be tested with fixed clock and ID sources. +- Pure packages contain no Node built-ins. +- File permission and symbolic-link protections pass on supported platforms. +- A missing security capability produces a refusal or explicit warning. + +Risk: an adapter can make a required security check look optional. Keep the +safe Node adapter as the CLI default and test every refusal. + +### PR 7 — Define the importer interface and registry + +Scope: + +- Define `Importer`, `ImporterDetection`, `ImportContext`, and + `ImportPayload` in `packages/importers/`. +- Export payload validation and merge operations through a supported subpath. +- Replace `VENDOR_LABELS` and nested format branches in + `src/import/index.ts` with a deterministic registry. +- Register Apple Health, WHOOP, and Oura as built-ins. +- Make detection report ambiguity instead of picking the first match. +- Version each importer's matching recipe, preserving D108. + +Files touched: + +- `packages/importers/**` +- `src/import/**` +- `src/db/provider-import.ts` +- `src/schema.ts` +- `package.json` +- `tsup.config.ts` +- `tests/import*.test.ts` +- `tests/v1-provider-import.test.ts` +- provider fixtures under `tests/fixtures/exports/` + +Acceptance: + +- A synthetic importer can be registered in a test without editing a switch. +- Duplicate IDs, ambiguous detection, unsupported versions, and invalid + payloads fail with clear errors. +- Existing Apple, WHOOP, and Oura fixture results do not change. +- No importer writes directly to SQLite. + +Risk: changing detection order can change which importer receives an +ambiguous file. Add ambiguity fixtures before replacing the branches. + +### PR 7A — Remove the 0.x importer model + +Scope: + +- Replace `HardSignalT` and `SoftSignalT` in `ImportPayload` with v1 draft + records. +- Move matching-key creation into the versioned importer result. +- Retire or isolate the unused `src/import/index.ts#importExport` path. +- Remove old model dependencies from `src/db/provider-import.ts`. + +Files touched: + +- `packages/importers/**` +- `src/import/**` +- `src/db/provider-import.ts` +- `src/schema.ts` +- importer conformance fixtures and tests + +Acceptance: + +- `ImportPayload` has one v1 model. +- Existing provider record IDs, matching keys, source facts, and receipts do + not change. +- The supported v1 CLI does not call the old JSON merge path. + +Risk: moving off the 0.x intermediate model can change IDs or matching keys. +Lock current results with conformance fixtures before changing the model. + +### PR 8 — Define calculation extensions and portable vectors + +Scope: + +- Separate pure calculation functions from queries in + `src/db/calculate.ts`. +- Define a calculation descriptor with ID, version, accepted input groups, + output record type, and deterministic run function. +- Add a registry for built-in calculations. +- Publish source-separated vectors for summaries, baselines, trends, + correlations, and workout drift. +- Preserve exact input evidence references on every stored result. + +Files touched: + +- `packages/core/src/calculations/**` +- `packages/store/src/calculate.ts` +- `src/db/calculate.ts` +- `spec/conformance/calculations/**` +- `tests/v1-calculate.test.ts` +- `tests/v1-schema.test.ts` +- package exports and API docs + +Acceptance: + +- Pure calculations accept values and return values without a database or + filesystem. +- Query selection remains in the store package. +- Every result can identify exact input record revisions. +- Provider sources never combine in a baseline. +- SDNN and RMSSD remain separate operations and fixtures. + +Risk: a generic calculation interface may hide operation-specific safety +limits. Keep per-operation limits and evidence rules in the descriptor and +tests. + +### PR 9 — Centralize runtime configuration and fix model paths + +Scope: + +- Centralize package name, command name, Skill name, keyring service, public + site, and model gateway settings. +- Fix `src/models.ts#defaultModelPath` for `.ath.sqlite`. +- Keep gateway and update code out of core and store packages. + +Files touched: + +- `src/program.ts` +- `src/config.ts` +- `src/update.ts` +- `src/keyring.ts` +- `src/gateway.ts` +- `src/models.ts` +- command tests and generated `skill/references/cli.md` + +Acceptance: + +- Branding and service constants have one reviewed source. +- Model settings are placed correctly beside `.ath.sqlite`. +- Existing command output and gateway behavior do not change. + +Risk: changing keyring service names would orphan saved keys. Keep the current +service value as the default and treat any rename as a separate migration. + +### PR 9A — Separate the CLI application from output and process state + +Scope: + +- Introduce an application service that returns typed results and errors. +- Inject output, error output, exit status, clock, configuration, and prompts + into the CLI layer. +- Remove direct `console.*` and `process.exit*` use from reusable operations. + +Files touched: + +- `src/program.ts` +- `src/cli.ts` +- `src/application/**` +- command tests +- generated `skill/references/cli.md` + +Acceptance: + +- Commands can run in tests without changing global process state. +- JSON command output contains no warnings or progress text on standard output. +- Existing command names, options, exit codes, and text remain covered. + +Risk: changing output plumbing can break scripts that parse JSON or rely on +exit codes. Snapshot both standard output streams and status for each command. + +### PR 10 — Add the community layout and manifest schema + +Scope: + +- Add `community///` for `skill`, `importer`, and `calculation`. +- Add a strict `community/schema/ath.manifest.schema.json`. +- Require these fields: + - `id`, in the form `community.` + - `kind` + - `version`, as one exact semantic version + - `coreRange`, as a supported `CORE_API_VERSION` range + - `formatRange`, as the supported `athleticstandard_version` range + - `cliRange` for Skills that call `ath` + - `tools`, limited to stable tool IDs + - `writeMode`, limited to `read` or `propose` + - `dataGroups`, limited to documented groups + - `requiresRawSeries` + - `license`, as a valid SPDX expression + - `deprecated` + - `replacedBy`, required only when there is a replacement +- Also require `name`, `description`, and a kind-specific `entrypoint`. + Without an entry point, a catalog cannot locate the reviewed source. +- Add one minimal synthetic example for each kind. +- Document that a manifest grants no runtime authority. +- Document that reviewed items approved for official use are compiled into the + main `athleticstandard` package. There is no third-party runtime loader. + +Files touched: + +- `community/schema/ath.manifest.schema.json` +- `community/README.md` +- `community/skill/example/**` +- `community/importer/example/**` +- `community/calculation/example/**` +- `docs/extensions.md` +- manifest validation tests + +Acceptance: + +- Directory kind and ID match the manifest. +- IDs and versions are unique. +- `replacedBy` names an existing compatible item and cannot form a cycle. +- Tool and data-group values come from generated allowlists. +- Every entry has an SPDX-compatible license. +- Examples use only synthetic data and cannot write without confirmation. +- Skills that call the CLI declare both `coreRange` and `cliRange`. +- A manifest cannot make an entry loadable at runtime. + +Risk: `coreRange` can claim compatibility that tests do not prove. Catalog +generation must include only versions that pass the contract runner. + +### PR 11 — Add isolated community contract checks + +Scope: + +- Add one contract runner with kind-specific suites. +- Skill checks cover passive language, allowed tool names, `read|propose` + behavior, and fixture prompts. +- Importer checks cover detection, malformed input, resource limits, + deterministic payloads, and no direct writes. +- Calculation checks cover deterministic vectors, source separation, + evidence, and resource limits. +- Add a machine-readable public policy file for blocked capabilities. +- Extend #5's public-data check instead of creating a second health-data + scanner. +- Run executable importer and calculation checks in a process with no secrets, + filtered environment variables, network denial, a read-only checkout, one + temporary writable directory, memory limits, and time limits. + +Files touched: + +- `community/policy.json` +- `scripts/check-community.ts` +- `tests/community/**` +- `package.json` +- `.github/workflows/ci.yml` + +Acceptance: + +- A manifest alone cannot cause code execution. +- Entries with blocked tools, undeclared writes, real data, network use, or + failed fixtures are excluded and fail CI. +- Executable checks cannot read repository secrets, write outside their + temporary directory, or reach the network. + +Risk: text scanning cannot prove a Skill is safe. Treat it as one check, not a +security boundary. Human review and a narrow runtime permission model remain +required. + +### PR 11A — Generate the release community catalog + +Scope: + +- Generate `community/community-catalog.json` from validated manifests and + passing contract results. +- Check catalog drift on pull requests. +- Regenerate and verify the catalog during release. +- Record item version, core, format, and CLI ranges, license, deprecation, and + fixture result. +- Mark the catalog as test results only. Catalog presence is not endorsement + or approval for hosted promotion. + +Files touched: + +- `community/community-catalog.json` +- `scripts/generate-community-catalog.ts` +- catalog tests +- `package.json` +- `.github/workflows/ci.yml` +- release workflows + +Acceptance: + +- Catalog order and bytes are deterministic. +- A release fails when the checked catalog is stale. +- Failed or blocked entries never appear in the catalog. +- Catalog generation reads results but never runs entry code. +- Hosted promotion remains a separate review outside catalog generation. + +Risk: a generated catalog can be mistaken for approval. Include the +compatibility-only meaning in the file metadata and public docs. + +### PR 12 — Support selected multiple skills + +D41 is superseded for this narrow case. A community Skill may be installed +only when it is explicitly named. + +Scope: + +- Generalize `src/skill.ts` from one shipped directory to a list of selected + skill descriptors. +- Keep `ath skill install` installing only the official bundled Skill by + default. +- Add explicit commands to list and install a named local community Skill. +- Show source, version, permissions, and destination before installation. +- Never fetch a Skill from the network or install every catalog entry. +- Preserve stale-version reporting per installed Skill. + +Files touched: + +- `src/skill.ts` +- `src/program.ts` +- `src/help.ts` +- `skill/**` +- `tests/skill.test.ts` +- `tests/cli.test.ts` +- generated `skill/references/cli.md` + +Acceptance: + +- Current single-Skill behavior is unchanged without new options. +- Installing one Skill does not delete another. +- No read command installs or refreshes a Skill. +- A Skill with an incompatible `coreRange` is refused. +- The user must name each community Skill to install. + +Risk: listing community work can look like endorsement. The command and docs +must distinguish compatibility checks from review or recommendation. + +## Later, only on demand + +Do not build these now: + +- A local HTTP or OpenAPI service. +- A local stdio MCP server. +- A maintained Swift library or example app. +- A Rust core or maintained Rust library. +- Any other hand-maintained language port. + +A real builder request must name the missing capability before one of these +becomes an active plan. The machine-readable specification and test vectors +let an agent generate a narrow client without waiting for this repository. + +A future Rust core remains compatible with this direction. It may ship inside +the npm package and sit behind existing public APIs. The same conformance +vectors must keep its results aligned with other implementations. + +## 6. Compatibility and migration + +| Change | Breaks existing users? | Migration | +|---|---|---| +| CI, templates, guides, `ath.fit` metadata | No runtime break. New contribution checks can block a pull request. | Rebase and satisfy the documented checks. | +| Plain SQL migration files and database enforcement | No published v1 user exists yet. Invalid direct writes that previously reached internal tables will now fail. | Regenerate repository fixtures. Future v1 databases use `ath migrate` or confirmed interactive open after backup. Published 0.4.3 files remain outside the v1 migration promise under D101. | +| Explicit export list | It can break users only if a current public name is missed. | Preserve the built export list. A deprecated stable API warns and remains available until the next major release. | +| `CORE_API_VERSION` | No. It adds a separate compatibility version for extensions. | Start at `1.0.0`. Increase it by semantic-version rules when the public extension interface changes. | +| Workspace package split | No for supported `athleticstandard` imports and `ath` commands. | Root compatibility entry points re-export the new packages. New apps may adopt `@ath/*` after publishing is approved. | +| Importer v1 payload | It can break undocumented deep imports. No importer API is currently public. | Publish the new subpath and a mapping guide. Keep one temporary adapter if an actual user is found. | +| CLI output separation | It can break scripts if text, JSON, or exit codes change. | Lock current behavior with stream and status tests. Announce any intentional correction. | +| Optional extension envelope | No published v1 user exists yet because npm latest is 0.4.3. It changes the current unreleased v1 schema. | Land it in v1.0.0 before npm publish. Regenerate schemas and fixtures. Every v1 reader preserves unknown extension values. | +| Community manifests and catalog | No. They are additive and passive. | Existing bundled Skill remains the default. | +| Multi-skill install | No when current defaults are preserved. | Community installs are explicit. Existing installed copies continue to report their own versions. | +| Reviewed community code in `athleticstandard` | No for existing exports. New built-ins are additive. | Update the exact package version. Catalog presence alone does not add runtime code. | +| Direct third-party SQLite writes | This is a new supported interface before the first v1 npm publish. | Enable `PRAGMA foreign_keys`, use only stable writable tables, follow documented transactions, and pass conformance tests. SQLite constraints and triggers reject invalid state. | + +No pull request may silently rewrite an athlete database merely because the npm +package was updated. Agents and scripts use explicit `ath migrate` with preview +and confirmation. Interactive open may preview and ask a person to confirm. +Both routes create and verify a backup first. Noninteractive open never +migrates. + +## 7. Approved decisions + +These choices are approved. Record the format and runtime choices as new +D-numbers before their implementation pull requests. + +1. **Keep the open-source base thin.** It contains the SQLite file, public + specification, conformance vectors, existing CLI, and official Skills. + Builders should not need a service or maintained language library. + +2. **Split internal packages first.** Start with private workspace packages + behind `athleticstandard`. Publish `@ath/*` packages only after a real need + and stable packed-package checks. + +3. **Use semantic core API versions.** `CORE_API_VERSION` starts at `1.0.0`. + Community `coreRange` values use normal semantic version ranges. + +4. **Support direct SQLite writes.** Correctness belongs in the database. + Use `STRICT`, `CHECK`, `NOT NULL`, `UNIQUE`, foreign keys, JSON checks, and + triggers. Clients must enable `PRAGMA foreign_keys`. Triggers back critical + rules that must survive a connection that fails to enable it. + +5. **Ship the extension envelope in v1.0.0.** Records receive an optional, + namespaced, size-limited `extensions` envelope. It inherits the parent + record's tier and survives every round trip. A minimal pass-through version + is enough for v1. Separate linked extension records may arrive later as an + additive change. Popular extensions should become official fields. + +6. **Compile reviewed official code into releases.** Official Athletic + Standard and the hosted product do not load third-party code at runtime. + Forks remain free to add other loading models. + +7. **Treat catalog inclusion as test status only.** It is not endorsement and + does not approve hosted promotion. Hosted promotion is a separate review. + +8. **Supersede D41 for explicit local Skill installation.** A community Skill + installs only when named. Nothing auto-installs, and the installer never + fetches a remote Skill. + +9. **Use DCO with MIT and no contributor license agreement.** Every + contribution carries DCO sign-off. + +10. **Set protected owners.** `@mwhitham` owns `spec/`, migrations, schemas, + release workflows, and community policy. Any maintainer may review other + areas. D123 records the narrow process exception that permits this GitHub + handle only for `CODEOWNERS` and text that explains it. + +11. **Never migrate silently.** Agents and scripts use `ath migrate` with + preview and confirmation. Interactive open may prompt a person. Every + route creates and verifies a backup before writing. + +12. **Publish stable SQL reads and writes.** Stable views are the read + contract. A small documented set of tables is writable. All other tables + are internal. + +13. **Keep deprecated stable APIs until the next major release.** Emit + warnings and document replacements. That major release may remove them. + +14. **Ship approved community items in `athleticstandard`.** Separate public + packages may come later if a concrete need appears. + +15. **Defer extra runtimes and services.** Do not build local HTTP, local MCP, + Swift libraries or examples, Rust, or other maintained ports now. A future + Rust core may ship through npm behind existing APIs. Shared vectors keep + any future port honest. + +## 8. Release gates + +The contribution-ready milestone is complete only when: + +- #5 is merged and its required check is enabled. +- The extension envelope and database-enforced critical rules land before + v1.0.0 is published to npm. +- Current imports and CLI behavior have compatibility tests. +- Plain SQL migrations, stable read views, stable writable tables, and + language-neutral conformance fixtures are public. +- Direct writes that bypass Node still cannot violate the two-tier wall, + revision, deletion, erasure, or critical link rules. +- `ath migrate` and interactive migration always preview, confirm, and verify + a backup. Noninteractive open never migrates. +- `AGENTS.md` and the build-on-ATH Skill point agents to the machine-readable + contract and conformance runner. +- `CORE_API_VERSION` is `1.0.0`. +- Deprecated stable APIs warn and remain available until the next major + release. +- Public APIs have explicit exports, stability labels, and generated docs. +- Importers and calculations use registries with deterministic synthetic + contract tests. +- Community manifests are strict and the catalog is generated. +- Community entries never run merely because they are cataloged. +- Extension behavior preserves the two-tier wall and unknown data. +- The main `athleticstandard` tarball contains every approved official item + and all promised specification files. +- Release notes state package, core API, SQL, and format versions separately. + +HTTP, MCP, Rust, Swift, and other maintained ports are not release gates. They +remain deferred until a real builder asks for a capability the thin base does +not provide. diff --git a/build-history/v1.0.0/decisions.md b/build-history/v1.0.0/decisions.md index 29728dc9..58b02da1 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -997,3 +997,292 @@ Rejected alternatives: - **Test only 100,000 records.** Rejected because the 3-million-record run is large enough to expose unsafe query bounds and remains practical as a separate release job. + +## D115. Split internal workspace packages before publishing them + +The repository first splits pure logic, storage, and importers into private workspace +packages behind the existing `athleticstandard` package. The root package bundles +their code and keeps the current package name, CLI, and supported entry points. +Scoped `@ath/*` packages are published only after a concrete need and packed-package +tests prove they work outside the workspace. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Publish every workspace package immediately.** Rejected because it creates more + versioned public APIs before their boundaries have been exercised. +- **Keep one source package forever.** Rejected because pure logic, storage, and + importers need enforceable internal boundaries. + +## D116. Direct third-party SQLite writes are supported and SQLite enforces critical rules + +Builders may write Athletic Standard databases directly with SQLite. They do not +need the Node library, CLI, a local service, or a maintained language binding. +Every client must enable `PRAGMA foreign_keys = ON`. + +Critical correctness rules also use database constraints and triggers. The schema +uses `STRICT` tables, `CHECK`, `NOT NULL`, `UNIQUE`, foreign keys, and SQLite JSON +functions. Triggers enforce the two-tier wall, record and revision agreement, +revision and deletion rules, current-revision pointers, and protected links even +when application code is bypassed. Conformance tests execute direct SQL rather than +assuming the Node operations are the only writer. + +D104 still keeps the JavaScript database handle opaque and keeps arbitrary SQL out +of the JavaScript API. This decision supersedes any reading of D104 that direct SQL +writes by another implementation are unsupported. It also strengthens D83: SQLite +is a public encoding with enforced write rules, while Zod remains the logical record +definition. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Require every writer to use the Node package.** Rejected because the SQLite file + is the cross-language foundation. +- **Document rules without enforcing them in SQLite.** Rejected because another + writer could then create a file the official reader cannot safely interpret. +- **Rely on foreign keys alone.** Rejected because foreign-key enforcement is a + per-connection setting and does not express every critical cross-table rule. + +## D117. Official runtimes execute only reviewed code compiled into releases + +Official Athletic Standard and the hosted product do not load third-party importer +or calculation code at runtime. Code approved for official use is reviewed, tested, +and compiled into a release. Forks may choose another loading model. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Load code from the community catalog.** Rejected because catalog metadata and + compatibility tests are not a runtime trust boundary. +- **Forbid plugin loading in forks.** Rejected because forks control their own + runtime and risk policy. + +## D118. v1 records have a namespaced extension envelope + +Every v1 record may carry an optional, namespaced, size-limited `extensions` +envelope. Extension values inherit the parent record's measured, +athlete-reported, or authored class. An extension cannot add a source to an athlete +report or remove the source requirement from measured data. + +All v1 readers, SQLite writes, JSON import, and JSON export preserve extension +values. A minimal pass-through implementation is sufficient for v1.0.0. It must land +before v1.0.0 is published to npm; npm still publishes 0.4.3. This partially +supersedes D91 for the defined envelope: unknown namespaced values inside a valid +envelope are preserved rather than discarded. D91's unknown-field refusal remains +in force outside the envelope. + +Separate linked extension record types may be added later without replacing the +envelope. An extension becomes an official field only after repeated use, stable +meaning across builders, clear tier rules, and a separately approved format change. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Wait until after v1.0.0.** Rejected because strict v1 readers would otherwise + need a format change before builders have any safe extension point. +- **Allow arbitrary unknown top-level fields.** Rejected because strict validation + would no longer distinguish an extension from a typo or unsupported format. +- **Start with separate linked extension records only.** Rejected because a + pass-through envelope is the smaller useful v1 foundation. + +## D119. Community catalog inclusion means tests passed, not endorsement + +An entry appears in `community-catalog.json` only after its manifest and synthetic +contract tests pass. Inclusion does not mean the project recommends its training +advice, accepts medical claims, approves its security for every use, or approves it +for the hosted product. Hosted promotion is a separate review. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Treat catalog inclusion as project approval.** Rejected because compatibility + checks cannot establish coaching quality or suitability for every athlete. +- **Promote every catalog entry into the hosted product.** Rejected because hosted + use has a separate risk and product review. + +## D120. Named local community Skills may be installed explicitly + +A community Skill may be installed only when the person or agent names it. The +official bundled Skill remains the default. Read commands never install or refresh +a Skill. The installer never fetches a remote Skill and never installs the whole +catalog. + +This supersedes D41's decision not to build community distribution. D41's concern +about implied endorsement remains and is answered by D119. D79 remains in force for +the official bundled Skill and its current install locations. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Auto-install compatible Skills.** Rejected because a read or setup command + should not silently add agent instructions. +- **Fetch Skills from catalog URLs.** Rejected because remote fetching adds a code + and content supply chain that the local repository does not need. +- **Keep community installation entirely out of the CLI.** Rejected because an + explicit local install removes repeated manual copying without implying approval. + +## D121. The public foundation stays thin until a builder needs more + +The v1 public foundation is the SQLite file, public specification, conformance +vectors, existing CLI, and official Skills. It does not add a local HTTP service, a +local MCP server, a maintained Swift library or example, a Rust core, or another +maintained language port now. + +D7 remains in force: CLI plus Skill is the agent interface, and MCP is not added. +A future Rust core may ship inside the npm package behind existing APIs. Any future +service or port must start from a concrete builder need and pass the same conformance +vectors. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Build every likely client surface before demand.** Rejected because each surface + adds maintenance without removing a demonstrated blocker. +- **Forbid future ports.** Rejected because shared vectors are intended to let + builders add the smallest implementation they need. + +## D122. Contributions use DCO sign-off, MIT, and no CLA + +Every contribution requires Developer Certificate of Origin sign-off. The repository +keeps the MIT license and does not require a contributor license agreement. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Add a contributor license agreement.** Rejected because no identified legal + need justifies a second contribution agreement. +- **Require no contribution attestation.** Rejected because DCO sign-off provides a + lightweight record that contributors may submit their work. + +## D123. Critical public contracts have explicit owners + +`@mwhitham` owns `spec/`, `src/db/migrations/`, `src/v1/schema.ts`, `schema/`, +`.github/workflows/release-*.yml`, and `community/policy.json`. Other areas may be +reviewed by any maintainer and have no catch-all required owner. + +This is a narrow exception to the repository rule against individual names. A +GitHub owner handle is allowed only in `CODEOWNERS` and in decision or plan text +that explains `CODEOWNERS`. The repository is personal and has no team handle, so +the required owner must be a real account. No other exception is created. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Require one owner for every file.** Rejected because it needlessly blocks normal + maintenance outside the public contracts and release controls. +- **Use no protected owners.** Rejected because format, migration, schema, release, + and community policy changes need explicit review. + +## D124. Database migrations always preview, back up, and ask + +Agents and scripts use explicit `ath migrate`: first preview, then confirm. An +interactive database open may show the same preview and ask the person to confirm. +A noninteractive open never migrates. Every route creates and verifies a SQLite-safe +backup before changing the database. A package update alone never rewrites a file. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Migrate silently on open.** Rejected because opening an athlete record should + not make an unannounced irreversible storage change. +- **Require only manual file copying.** Rejected because copying an open WAL database + is unsafe and does not prove the backup is usable. +- **Support only a separate migration command.** Rejected because an interactive + person may reasonably confirm the same safe flow while opening the file. + +## D125. Stable views are public reads and a small table set is public for writes + +Versioned SQL views are the stable direct-read contract. A small documented set of +tables is the stable direct-write contract. The SQL specification names their +columns, required pragmas, transaction order, constraints, triggers, and version +policy. Every other table is an internal encoding detail and may change through an +ordered migration. + +D104 still governs the named JavaScript domain API. This decision adds a separate +public SQL contract for non-JavaScript and direct SQLite builders. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Make every table stable.** Rejected because internal indexes, ledgers, and + normalized encodings need room to change through migrations. +- **Publish example queries only.** Rejected because copied queries do not provide a + versioned read contract. +- **Allow reads but no direct writes.** Rejected by D116; direct builders are a + supported use. + +## D126. Deprecated stable APIs remain until the next major release + +A stable public TypeScript API may be deprecated with a warning and documented +replacement. It remains available for the rest of the current major version. The +next major npm release may remove it. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Remove stable APIs in a minor release.** Rejected because builders need a + predictable migration boundary. +- **Keep every stable API forever.** Rejected because major releases exist to remove + obsolete contracts after warning. + +## D127. Approved community items ship in the main package first + +A community Skill, importer, or calculation approved for official use ships in the +main `athleticstandard` package. The hosted product can adopt it by updating its +exact package pin after a separate hosted review. Separate public packages are +deferred until size, release, or dependency needs justify them. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Publish each approved item as a separate package now.** Rejected because it adds + release and compatibility work before a concrete need. +- **Copy approved code into the hosted repository.** Rejected because the public + exact-pinned package should remain the shared reviewed implementation. +- **Treat catalog inclusion as package approval.** Rejected because D119 separates + passing public tests from official and hosted approval. + +## D128. The core extension API uses semantic version 1.0.0 + +`CORE_API_VERSION` starts at `1.0.0` and follows semantic versioning. Community +manifests use `coreRange` to state compatibility with importer, calculation, Skill, +and extension interfaces. This version is independent of +`athleticstandard_version`, `sql_schema_version`, and unrelated CLI patch releases. + +This follows the [contribution readiness plan](appendix/contribution-readiness.md). + +Rejected alternatives: + +- **Use the npm package version as the core interface version.** Rejected because CLI + and packaging changes do not necessarily change extension compatibility. +- **Use an unversioned interface.** Rejected because community compatibility would + become guesswork after the first interface change. + +## D129. Build CR1 before the contribution-readiness plan pull request merges + +The repository owner approved implementing contribution-foundation step CR1 and CR2 +from the contribution readiness plan before +[pull request #15](https://github.com/mwhitham/ath/pull/15) merges. The +implementation pull request carries the same decision, specification, progress, and +appendix updates that #15 would land, so build-history stays consistent with the +approved plan. + +Rejected alternatives: + +- **Wait for #15 to merge.** Rejected because the unreleased v1 schema work is + 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. diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index c111bdab..8c7705dc 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -44,3 +44,26 @@ D114 replaced the required 30-million-record release run with focused query-boun tests. The required measured runs now use 100,000 and 3 million records. Both pass all nine operations on the reference runner. Their measurements and review limits 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. +The long-form sequence is in +[`appendix/contribution-readiness.md`](appendix/contribution-readiness.md). + +| Step | Deliverable | Status | +|---|---|---| +| CR0 | Record the approved contribution-foundation decisions | ✅ D115–D128 recorded | +| CR1 | Add the v1 extension envelope and its generated schemas and fixture | ✅ done — D129; implementation started before #15 merged with owner approval | +| CR2 | Enforce the two-tier wall, revisions, deletion, erasure, JSON shape, and protected links with SQLite constraints and triggers | ✅ done — D116; direct-SQL tests in `tests/v1-direct-sql.test.ts` | +| CR3 | Publish plain SQL migrations, stable read views, and the stable writable-table contract | pending | +| CR4 | Add `ath migrate` preview, verified backup, explicit confirmation, and interactive prompt-on-open | pending | +| CR5 | Add direct-SQL and language-neutral conformance vectors | pending | +| CR6 | Publish machine-readable contract metadata, update `AGENTS.md`, and add the build-on-ATH Skill | pending | +| CR7 | Add contribution governance, community manifests, isolated checks, catalog generation, and explicit named Skill installation | pending | +| 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. diff --git a/build-history/v1.0.0/spec.md b/build-history/v1.0.0/spec.md index a7e39d5a..4cd32beb 100644 --- a/build-history/v1.0.0/spec.md +++ b/build-history/v1.0.0/spec.md @@ -1030,3 +1030,125 @@ D114 supersedes the 30-million-record requirement in section 13. Required measur runs use 100,000 records in normal release CI and 3 million records in the separate large release job. Larger generated databases are optional investigation tools and are not a release gate. + +## 19. Pre-publish contribution foundation amendment + +D115–D128 and the +[contribution readiness plan](appendix/contribution-readiness.md) amend the work +required before v1.0.0 is published to npm. They do not change the released 0.4.3 +format. + +### 19.1 Record extensions + +Every record schema has an optional `extensions` object. Its keys are namespaced +extension IDs. Its values are bounded JSON values. The generated schema defines the +key grammar, value grammar, maximum depth, maximum collection sizes, and maximum +encoded size before release. + +An extension inherits the class of its parent record: + +- An extension on a measured record still requires the parent record's source. +- An extension on an athlete-reported record cannot add or claim a source. +- An extension on an authored record remains governed by the parent record's author, + evidence, content version, and status. + +SQLite revisions, current records, complete JSON export, package import, merge, +correction, and every public reader preserve unknown valid extension values. The +deterministic JSON writer may normalize their JSON encoding but cannot change their +values. Unknown fields outside the extension envelope still follow section 9.2 and +are refused. + +The extension envelope is part of v1.0.0. It and its limits must land before the +first v1 npm publish. The current unreleased v1 fixture and generated schemas are +regenerated. Separate linked extension record types are later additive work and are +not required for v1.0.0. + +### 19.2 Database-enforced writes + +Direct third-party SQLite writes are supported. The JavaScript handle remains opaque +as specified by D104, but it is not the only supported writer. + +Every direct client must enable and verify: + +```sql +PRAGMA foreign_keys = ON; +PRAGMA busy_timeout = 5000; +``` + +The database enforces critical validity without relying on the Node operations. +Use `STRICT` tables, `NOT NULL`, `CHECK`, `UNIQUE`, foreign keys, SQLite JSON +functions, and triggers. Constraints and triggers cover at least: + +- The measured and athlete-reported sides of the two-tier wall. +- Record type agreement between current rows, retained revisions, and typed rows. +- Complete `record_json` shape needed to identify its record and class. +- Sequential revisions and valid previous-revision links. +- Current-revision pointers. +- Deletion and erasure state. +- Source, evidence, result, grade, attachment, and other protected link types. + +Foreign keys remain required. Critical cross-table rules also have trigger coverage +where a connection with foreign keys disabled could otherwise create a database that +official readers accept. Direct-SQL tests bypass the Node library and prove each +invalid state is refused. + +Before the first v1 publish, the ordinary SQL migration is finalized from these +rules and the deterministic repository fixture is regenerated. There is no +published earlier v1 database that needs a compatibility migration. + +### 19.3 Stable SQL contract + +Versioned SQL views are the stable direct-read contract. A small documented set of +tables is the stable direct-write contract. The machine-readable SQL specification +lists: + +- Stable views and their columns. +- Stable writable tables and their columns. +- Internal tables. +- Required pragmas. +- Transaction order. +- Constraints and triggers. +- SQL schema compatibility. + +Tables not listed as stable writable tables are internal. They may change through an +ordered migration. Example queries do not make an internal table public. + +### 19.4 Migration behavior + +`ath migrate` first previews the source and target SQL schema versions, planned +steps, backup location, and compatibility effect. Agents and scripts then provide +explicit confirmation. An interactive database open may show the same preview and +ask the person to confirm. A noninteractive open refuses migration and points to +`ath migrate`. + +Every migration route creates and verifies a SQLite-safe backup before the first +database write. It accounts for WAL state and does not copy an open WAL database as +if that were a complete backup. A package update alone never migrates a database. + +### 19.5 Machine-readable contract and agent guidance + +The repository publishes language-neutral conformance vectors for direct reads, +direct writes, extension preservation, invalid constraints, migrations, and +deterministic calculations. `AGENTS.md` and the build-on-ATH Skill point builders to +the machine-readable SQL and record contracts. No maintained Swift, Rust, or other +language library is required for v1. + +`CORE_API_VERSION` is `1.0.0`. It versions the community importer, calculation, +Skill, and extension interfaces independently of `athleticstandard_version`, +`sql_schema_version`, and the npm package version. + +### 19.6 Additional pre-publish build order + +Complete these steps after the existing implemented v1 work and before steps 11 and +12 release a prerelease or v1.0.0: + +1. Add the extension envelope and SQLite-enforced critical rules. +2. Finalize plain SQL migrations, stable read views, and stable writable tables. +3. Add direct-SQL and language-neutral conformance vectors. +4. Add machine-readable contract metadata and the build-on-ATH Skill. +5. Pack the npm artifact and prove it contains every v1 schema, SQL, conformance, + and Skill file. +6. Run the functional, cross-platform, and D114 measured release checks. + +Local HTTP, local MCP, maintained language ports, and runtime loading of third-party +code are not v1 release work. From 7e7e5330622558df79fd0b2736a81054188b3094 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 14 Oct 2026 16:48:21 +0000 Subject: [PATCH 2/2] feat: add v1 record extensions and SQLite enforcement triggers Optional namespaced extensions on current records and revisions persist through SQLite, export, and import. record_revisions.extensions_json stores the envelope. SQLite triggers enforce the two-tier wall, revision type agreement, deletion flags, erasure blocks, and protected link revisions. Co-authored-by: Michael Whitham --- SPEC.md | 7 + examples/demo-athlete/athlete.ath.sqlite | Bin 458752 -> 466944 bytes schema/1.0.0/athleticstandard.schema.json | 451 +++++++++++++++++++- schema/1.0.0/measurement-series.schema.json | 55 ++- schema/athleticstandard.schema.json | 451 +++++++++++++++++++- scripts/check-public-data.ts | 2 +- src/db/backtest.ts | 15 +- src/db/check.ts | 31 +- src/db/erase.ts | 15 +- src/db/export.ts | 48 +-- src/db/import-package.ts | 40 +- src/db/migrations/001-initial.ts | 11 + src/db/migrations/enforcement-triggers.ts | 185 ++++++++ src/db/provider-import.ts | 14 +- src/db/query.ts | 22 +- src/db/records.ts | 62 ++- src/db/revision-encoding.ts | 59 +++ src/v1/extensions.ts | 227 ++++++++++ src/v1/schema.ts | 38 +- tests/v1-direct-sql.test.ts | 148 +++++++ tests/v1-extensions.test.ts | 137 ++++++ 21 files changed, 1852 insertions(+), 166 deletions(-) create mode 100644 src/db/migrations/enforcement-triggers.ts create mode 100644 src/db/revision-encoding.ts create mode 100644 src/v1/extensions.ts create mode 100644 tests/v1-direct-sql.test.ts create mode 100644 tests/v1-extensions.test.ts diff --git a/SPEC.md b/SPEC.md index 0c555b4b..c65ab2d6 100644 --- a/SPEC.md +++ b/SPEC.md @@ -89,6 +89,12 @@ Every current record has these fields: | `current_revision` | positive integer | Latest retained revision | | `is_deleted` | boolean | Whether normal deletion hides the record from current views | | `data` | typed object | Complete current logical state | +| `extensions` | optional object | Namespaced extension values that inherit the parent record class | + +`extensions` keys use reverse-DNS names (`owner.example/name`). Values are bounded +JSON. They cannot add a `source_id` to athlete-reported records. Unknown keys +inside a valid envelope are preserved through SQLite and package round trips. +Unknown fields outside `extensions` are still refused. A normally deleted record remains a current envelope with `is_deleted: true`. Its data and revisions remain until a retention rule or privacy erasure removes them. @@ -107,6 +113,7 @@ Every retained revision has: | `became_known_at_basis` | enum | `local_write`, `provider_import`, `package_restore`, or `package_merge` | | `changed_by` | record actor | Actor that made the change | | `data` | typed object | Complete state at this revision | +| `extensions` | optional object | Same envelope as the current record at this revision | A correction cannot use a `became_known_at` earlier than the prior revision. Historical prediction and backtest queries use revision knowledge time, not only the diff --git a/examples/demo-athlete/athlete.ath.sqlite b/examples/demo-athlete/athlete.ath.sqlite index 6f366a16aab947dc2d0afe4bec015fd97a327689..22c92215ca91d56912f931b510e745843f14da5e 100644 GIT binary patch delta 11099 zcmds7dvF`oz1}^mJ=$GKmX$b`Z8^y%U}WRC#K|=wbsXb3a_k#y<3~tB9*Qh&Y{j-D zOEMu)y1`Bwhh*BQf}GrRXbGi(_TEy0r|j+Rox%Xaw6vj=w3!Y=3N*CLBs3Tpm|I$C z&%X4QAKW{kxB6pebRNHR&Ue1wb9ev#^8L@0A6sk*6UpC(*s?V|Ydt5o3|s$V{mA;B z^&RWm*56w%Sbu9h2euLyiHot=w)n28mdW?XGK!nnZZz6!YRF@Q@dfmhDBKwp0ug^O z5OME`1Ot4pYfCTR-0EuH$X9Ya{$&nm>)|^#-Es@x*{u!Wd3mDy4$qL^SD7)oif`&z zuZYn`MfZh-)IsazxmA1v?+o_s5xh}n%7h^y&>tO09jy*t)4<WAyN-~i zc7wcyvB8AMEkWz#2Y1^@b{mCzO7C5$&Ok4JnPlSi_nbDdKxrRI%qaZwYwUayH&)+! zwke6Db$1Rp&#A3uTx_z{@=n@ERv6FEv0R9Js#>18fjD$E}lnwf{e+u$@g zN>(Ph!^FP69aG2^UqW?Eu6_S3_-CZi!yj=sSlFF}jW|b`KQ(PN6>;~n7uem#!|Y=C zXTx{ki`2)K3Cl)uulYyBISX&$$ylrgb(WKR<;Nq^JqyWkAXO|NeKcc!gkUhrgmk!! z+)k47&>tOS*W|9LW26JOE^x0V34g#R+!+}e@<#=?r`ZARn`_apPSU05$Qn?H`WKSL z818mZUy6>Mq{|UpKrWU-^T<2Fah^1M+wer8WZ=n9-mNfiAk4(C32uZdf*06-r>?-` zREyTj zXBLu+&`WE98J%4NjMB~q-~wo94Hz(9yKND)2ip=GEJwd<1WToph2(isKIl&Qu<{DG zfyT;s=!0@JTuxb0-AYg-{kRU4QBOW$;3dP&;FBLzn0`uFNP;lG#qsPfVTe6S|AKmv z-e=is_L*KHUASwDc|$C=9KcoRKj%@8Ne`7%F9NBum^uxRt(2-IYtf!!YN52NlsXI0 zOC{7gas|Eus!KY%96Uxs^S23TZ$x_*Q^#S$3TW@DmiJwTo++moWGklZ2E5rOv~LAy zP(j%>pE?XqPXYckPd%~BVm?e15L1Mujyu5J!1f!XY$bflZ~>kI?;DO56j?41QAaQpuN8-u~Vbk_5NjQA=+O^twh_NhlSEdh19d8y#4<` z|2>cTCfC*q?K@V{iQq^l zLHAhCFz1;g%+2(}3`shzeWtINekJc8|K5tleuCaK(aqBJ2D-*TuZMO|Jr=nbZM{rg zk6vTw3i4J|L(+Dsl%55_oo0K^NN zOp3Fi7cNqzusv;!>!fSV^lKEljiEcyv5QpaQ*RhZ{!y}!-nGQ|KllJWgz4){4@1x$ z#_xj5w9WjSd5r8a*O^zFSI1&gh>p`u5`LT@rGXQ)7of6l&<*5PdC!X;*iS?0OW&aX zOg_*>cUW&X{YKqt*R9YlG|GplLT}WQ5Pk1KdeILr(~XpZg^c<4QKgyQZrHd5+R>@| z={C@Kn?m&;-%ndn?+Lm{x^zF?Ks^bYCCbD30ImH9AIWn6E5}hW-8hLO3jVgJGXLEZpH&{j=5}yHNMA zC+Zy#BJPkUECix%e;^`+qnR@_-t~63ZP?)I<}lx08ogMm>E) zLVwUR6j2_#rEdIr$o-G zOt*K);~#cMf}>%t;7&y~X%jNw%_CC8!F_(2x{m8Ow`7I<3Fwmx=eUCu{Z+K04O;@I zvLi8ZN+(vOz$gYFiZc#3CQW#s+~kQyJ>G#~{9pa20uu@ccl(C~rySzT>Mt*lf|8Q1 zWE%_~J{Tt!ZZd=64vMNWvao@bI`4xAWY)Nge7YnX$zxjBLDt!Ekq4~rR*#Pn8U25CAE zlIB9Q`-(p1G!+h_OiK&h5-2*1O+nb>jVfxKvIT5TuKhxaR^d1T#};}ZF|BFO zqrSY1$V_@WZr!ck(fsT?5@q|I7uK9AJA=l~AWXj_O;^R7w{rC^MGOXV+{)Fs6et)S zJr0pMs5@OPEJ=x3)acqR$8gvO`y*Nuop}MXn5d(k)C?^g5EFiL4pEG{FYI$t;^u^$ z2yV{`q0?g;#bv6=1I8bFGFj)6p_(RM4YP4Q4{v_P@Hdh*pI1WPu&^7)djT(wfCAX8 zVGR9&ejEd-YdEV!B>*1x`_u#{BbwC5Meykojv_O`nN|3s&Ce1j%JE2UiP?9SvWetv zr2zjK@*UBaBjHKEt&9lt|2E$db0s{px$xw%Qxh8X(r3zd2!dRuB@bd+LOXr%pK1+r z>!5o!0`z-TEa2*t%=I55dzeeIFJ@6U6{F-8Wq9>`%8*MJrj78#lo~{iuwQ;l@V`yT zr%m?7xfK#J^eT6@KNs@f7>LZB{hfWNtDGuF&-&oXatltyIpPXoxnO#o8)uyi0Y9Ms z&Cp9V5?5leS8NA5!Z>!QXD0NRADyz&#U-*q)Vz~oR3loMN9na@Cj8z9O#px&h!K-m-V$#+W$VkNec-yi1l zh<(^I4Geq2gLtjT=nyWJ`S23>SCngS=o2GdDsy^Po)Nulpi9I^rW?%iff20;G&XO< z=-5%qjO#_dP|%MnC&PkLP>~a0`O-&5{kXcK$FNFiFMC{4-9@Fkmpvl4q%1D**)wwx zLyjKw9r={nTq0-?lNKPoXr>)2SuD|xmX-95tqb9#x0)FbYQeK?q_Eiu?!{-wjtSD! z*NCX;MMiTHAO)W}iPR)!W0kRn0+g6u{>;p6aIH}-gCtX%>CI2Z8rjCD4+mN)#Un8s z)#b z`E;0~rbXm@F^3t)NG9drlBQCEQVTI-T)^lM9L)IQSz)Q_hHj#@e`%(*JSRPt~YBn^+5;K;|A zG@(PnEaC7(#q_FT5|~`LWGs>spNuiO4(2PGi&v*=p0{XTot5xshi?CHRr9f}gP-9Q zgi0ONVr0ZgT4{b3NknTnnyrJH%p9cqe*otA-Fp<1c8Jt;SUZi|C&(2_pL_R^r(dmv zDA}Fbu0(0Uz0;u?nNb2Rfdu#Ja3%{R{>02=uAMJKll^MS_y)dKiQi=0GcypK#_FEs z&542>kItNir^bC%dK{Xy^71*XtS&tBD=2+sy;3>Ds|M{lQW42|4Vk#Vh*Q+wE__}u zq2yTq^Lz=Vl;CkNDZgs_JYGVH_+|L#`4Xxt?3=?22RUJ7h!UdUlI3?6!t@0Dy0P(} z{v$cG>}mLF!60Ee%ho_YbqaqwIT(v==EesL@b`382WzzN=^Vp_(wS%A<0R{{;Ep9@ zezimT>a(zfG`Y<3=!vcRCwXZ54ysW4!*g%~n3_zuuV$iM>$@)g%&<**`~^4$*oB8tQHz;3hRp6WyDGS2wUjW+463vekg^Mqv|XE2^Hya0H-r2@bmyru+? zT`*Cri4V2X(zf5@Q?Z?P+_7px{rs^qZXPU_Y=3}90P8Qt9nM45>Wt$But0kCZCC@? z@B(?+BdfIy9sUJfC~dd||Ak@=MamS9*7NlD=>q9Te}e4*wh-pGxfZ;aFLK<$MP=qq br2Mg_)b%ku0odYFJgx1pmyqxmm{#iV0X9WJ delta 2408 zcmdT`dr(x@8NcT{=bn3Z@4frrwL(@|7d9ZcMNAAbia-zpDi8!8Ail`Wco7)@iF8cmGG1Vb7Y9hnkC?b%Dx{L$%5|LvXG z-`xBA9_Ks1`vIv#fWQc!41gq`Z1h3&iIG|dwXqUUCZ%19)v_I+eakH^nS!(Ci2&K>>2ldR%=7rrPndj=rM~fb^h*OC$f_E7xL99V&J9M}Z5yXcEdcx== z_Kh-?_Y~)=#$}`4_IukVcA0LclhohfQp})Pnl{>>vFiUf@GrbjBHr(Ze#8r15Tg0% z)KeAYl_na(|K1Ny{(%?b#D^|e1>#FDBw{`(7G9&pe(I@tWYFz&0%VAuSU3j!cp@xA zDg0Uj%tU_v+azh2=Ygp}XAh&EhEgu8AHyq>z~5N_=;WISKS)kBji6#GVa2Ghx!DDl zLDRLr;`!=r=TpWl;}E>1gpJK1x37-xxPl)M5>y~t1CMF^xvThBeC~HZ#hL-w4UjjQ z54RyNAJz+YzV|!ui1T;hDDb`g@HoomjeU@fMse3|;t_B6!JmOh75sevhd7B;jinwg zRjBOjh4a8K+=q^%K76ucKS*`2;{j);?p0hU3+wOLtJwm3ymm=FukFL1s_Pta`gX&q zKZ^IG^(adpp^uQoUgZT{Bu%t+kp;j{^^gj2=L39}q6xh7Z+M+I+5<}qzwd!Dlc}dP z#d;{4D9ea^MMm@8w@4ztb`9t7tSflBh+M<~xU{HR#C?LlMx7CiBF9jK_>%Q!6{d76 z`Z#u#9U&QPhLNg&CW+VdOG>3u+1{Q_%BBrwP2w#*MCaXWRD*xAMoqNU=$G)GXe;ol zwQ7-&kdH;$XCz4Y!X8r2Q5Sg(J;`6WMFOZooV!JGA-bCu=ex)gG4ifzasH3p zTv*Qc^@Eq6+@J=;v)$w>?sTbW{xQ^|`U2#D!mz5C&3cmkk8GKJANh))$sCW zH4n`adz;mv(6LsnlHULrE7QwElE@*Q2GJtXoKCw@=OGof97CgM!BAGI=&(m|hRt(k zn?Awb%XY9Da!%Ng{2#7~@|l>!Ip0Pw>j={zR49sMbm5@-qk zr=KRG#bQVbtpa{CjZQ_2`2VJgkgC{a5Bh0YXCp-g=~il=;^;Q7n^-?>`&=vj|DPFr z0GLM3y1cQ120U|3P0sEY2nQ;d^X@0iy zy$Y<>DGiystR>PybEmk)=L6IaMnEyw+o|?TavlP*npm*y^be7)@vYf|xf@GVF%vYo zmvWEfb6Tx&pB^$+BnXG9wE([ ], [ "examples/demo-athlete/athlete.ath.sqlite", - "317ee514b34c60a6b57a8f0915612a55d4f4e45200b3c2e2c7f374e1714ab05c", + "b41026440643f556e034ed4061d69fa6f442eb87505b7f5961c3da253f591f8c", ], [ "examples/demo-athlete/attachments/01890f3e-e7d3-7cc0-88c8-00000000000e.png", diff --git a/src/db/backtest.ts b/src/db/backtest.ts index 57a5e7c4..ecc94d39 100644 --- a/src/db/backtest.ts +++ b/src/db/backtest.ts @@ -3,6 +3,7 @@ import { dirname, join } from "node:path"; import type { CompleteRequest, CompleteResponse } from "../gateway.js"; import { CurrentRecord, type CurrentRecordT } from "../v1/schema.js"; import { databaseClient, type AthleticDatabase } from "./client.js"; +import { currentRecordPayloadFromRow } from "./revision-encoding.js"; import { buildEvidence } from "./evidence.js"; import { readRecordRevisions } from "./records.js"; @@ -92,7 +93,8 @@ async function backtestRecords( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM records JOIN record_revisions ON record_revisions.record_id = records.record_id @@ -100,16 +102,7 @@ async function backtestRecords( WHERE records.record_type IN ('benchmark_definition', 'benchmark_result') ORDER BY records.created_at, records.record_id `); - return result.rows.map((row) => - CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }), - ); + return result.rows.map((row) => CurrentRecord.parse(currentRecordPayloadFromRow(row))); } export async function runV1Backtest( diff --git a/src/db/check.ts b/src/db/check.ts index 7cdc91a2..108931db 100644 --- a/src/db/check.ts +++ b/src/db/check.ts @@ -23,6 +23,10 @@ import { storedAttachmentName, } from "./attachments.js"; import { validateTypedRelationships } from "./records.js"; +import { + currentRecordPayloadFromRow, + recordRevisionPayloadFromRow, +} from "./revision-encoding.js"; export interface DatabaseCheckIssue { severity: "error" | "warning"; @@ -246,7 +250,8 @@ export async function checkDatabase( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM records LEFT JOIN record_revisions ON record_revisions.record_id = records.record_id @@ -271,14 +276,7 @@ export async function checkDatabase( }); continue; } - const parsed = CurrentRecord.safeParse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }); + const parsed = CurrentRecord.safeParse(currentRecordPayloadFromRow(row)); if (!parsed.success) { issues.push({ severity: "error", @@ -343,7 +341,8 @@ export async function checkDatabase( became_known_at, became_known_at_basis, changed_by_json, - record_json + record_json, + extensions_json FROM record_revisions WHERE record_id > ? OR (record_id = ? AND revision > ?) ORDER BY record_id, revision @@ -362,17 +361,7 @@ export async function checkDatabase( for (const row of revisionRows.rows) { revisionAfterId = String(row.record_id); revisionAfterNumber = Number(row.revision); - const parsed = RecordRevision.safeParse({ - record_id: row.record_id, - record_type: row.record_type, - revision: revisionAfterNumber, - previous_revision: - row.previous_revision === null ? null : Number(row.previous_revision), - became_known_at: row.became_known_at, - became_known_at_basis: row.became_known_at_basis, - changed_by: JSON.parse(String(row.changed_by_json)) as unknown, - data: JSON.parse(String(row.record_json)) as unknown, - }); + const parsed = RecordRevision.safeParse(recordRevisionPayloadFromRow(row)); if (!parsed.success) { issues.push({ severity: "error", diff --git a/src/db/erase.ts b/src/db/erase.ts index eaea164a..70d0e332 100644 --- a/src/db/erase.ts +++ b/src/db/erase.ts @@ -15,6 +15,7 @@ import { type AthleticDatabase, } from "./client.js"; import { incrementDatabaseRevision } from "./records.js"; +import { currentRecordPayloadFromRow } from "./revision-encoding.js"; import { withWriteTransaction } from "./transaction.js"; export interface ErasureRecord { @@ -95,7 +96,8 @@ function dependencySql(): string { records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM dependencies JOIN records ON records.record_id = dependencies.record_id JOIN record_revisions @@ -124,16 +126,7 @@ async function dependentRecords( sql: dependencySql(), args: [RecordId.parse(rootRecordId)], }); - return result.rows.map((row) => - CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }), - ); + return result.rows.map((row) => CurrentRecord.parse(currentRecordPayloadFromRow(row))); } export async function previewRecordErasure( diff --git a/src/db/export.ts b/src/db/export.ts index e666bbe8..cbdf5406 100644 --- a/src/db/export.ts +++ b/src/db/export.ts @@ -37,6 +37,10 @@ import { refuseSymbolicLinkComponents, type AthleticDatabase, } from "./client.js"; +import { + currentRecordPayloadFromRow, + recordRevisionPayloadFromRow, +} from "./revision-encoding.js"; export interface ExportDatabaseOptions { exported_at?: string; @@ -81,28 +85,11 @@ async function writeOwnerOnly(path: string, bytes: Uint8Array): Promise { } function parseCurrentRow(row: Record): CurrentRecordT { - return CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }); + return CurrentRecord.parse(currentRecordPayloadFromRow(row)); } function parseRevisionRow(row: Record): RecordRevisionT { - return RecordRevision.parse({ - record_id: row.record_id, - record_type: row.record_type, - revision: Number(row.revision), - previous_revision: - row.previous_revision === null ? null : Number(row.previous_revision), - became_known_at: row.became_known_at, - became_known_at_basis: row.became_known_at_basis, - changed_by: JSON.parse(String(row.changed_by_json)) as unknown, - data: JSON.parse(String(row.record_json)) as unknown, - }); + return RecordRevision.parse(recordRevisionPayloadFromRow(row)); } function parseDeletionRow(row: Record): RecordDeletionT { @@ -135,7 +122,8 @@ async function readCurrentRecords( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM records JOIN record_revisions ON record_revisions.record_id = records.record_id @@ -162,7 +150,8 @@ async function readRevisions( became_known_at, became_known_at_basis, changed_by_json, - record_json + record_json, + extensions_json FROM record_revisions WHERE (? = 1 OR record_type <> 'measurement_sample') ORDER BY record_id, revision @@ -293,7 +282,8 @@ async function readSampleChunk( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM measurement_samples JOIN records ON records.record_id = measurement_samples.record_id JOIN record_revisions @@ -320,16 +310,7 @@ async function readSampleChunk( SERIES_CHUNK_RECORDS, ], }); - return result.rows.map((row) => - CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }), - ) as Array< + return result.rows.map((row) => parseCurrentRow(row)) as Array< Extract >; } @@ -395,7 +376,8 @@ async function readSampleChunkHistory( record_revisions.became_known_at, record_revisions.became_known_at_basis, record_revisions.changed_by_json, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM measurement_samples JOIN record_revisions ON record_revisions.record_id = measurement_samples.record_id diff --git a/src/db/import-package.ts b/src/db/import-package.ts index 6796216c..5c1d90d7 100644 --- a/src/db/import-package.ts +++ b/src/db/import-package.ts @@ -34,6 +34,11 @@ import { type AthleticDatabase, } from "./client.js"; import { readDatabaseMetadata } from "./migrate.js"; +import { + currentRecordPayloadFromRow, + recordRevisionPayloadFromRow, + serializeExtensionsJson, +} from "./revision-encoding.js"; import { incrementDatabaseRevision, upsertTypedRecord, @@ -608,7 +613,8 @@ async function localRecordsById( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM records JOIN record_revisions ON record_revisions.record_id = records.record_id @@ -618,14 +624,7 @@ async function localRecordsById( args: chunk, }); for (const row of result.rows) { - const record = CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }); + const record = CurrentRecord.parse(currentRecordPayloadFromRow(row)); records.set(record.record_id, record); } } @@ -650,7 +649,8 @@ async function localRevisionsById( became_known_at, became_known_at_basis, changed_by_json, - record_json + record_json, + extensions_json FROM record_revisions WHERE record_id IN (${chunk.map(() => "?").join(", ")}) ORDER BY record_id, revision @@ -658,17 +658,7 @@ async function localRevisionsById( args: chunk, }); for (const row of result.rows) { - const revision = RecordRevision.parse({ - record_id: row.record_id, - record_type: row.record_type, - revision: Number(row.revision), - previous_revision: - row.previous_revision === null ? null : Number(row.previous_revision), - became_known_at: row.became_known_at, - became_known_at_basis: row.became_known_at_basis, - changed_by: JSON.parse(String(row.changed_by_json)) as unknown, - data: JSON.parse(String(row.record_json)) as unknown, - }); + const revision = RecordRevision.parse(recordRevisionPayloadFromRow(row)); const group = revisions.get(revision.record_id) ?? []; group.push(revision); revisions.set(revision.record_id, group); @@ -879,17 +869,19 @@ function revisionStatement(revision: RecordRevisionT): InStatement { revision, record_type, record_json, + extensions_json, became_known_at, became_known_at_basis, changed_by_json, previous_revision - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `, args: [ revision.record_id, revision.revision, revision.record_type, JSON.stringify(revision.data), + revision.extensions === undefined ? null : JSON.stringify(revision.extensions), revision.became_known_at, revision.became_known_at_basis, JSON.stringify(revision.changed_by), @@ -1066,17 +1058,19 @@ async function insertRevision( revision, record_type, record_json, + extensions_json, became_known_at, became_known_at_basis, changed_by_json, previous_revision - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `, args: [ revision.record_id, revision.revision, revision.record_type, JSON.stringify(revision.data), + serializeExtensionsJson(revision.extensions), revision.became_known_at, revision.became_known_at_basis, JSON.stringify(revision.changed_by), diff --git a/src/db/migrations/001-initial.ts b/src/db/migrations/001-initial.ts index 31758573..3a744859 100644 --- a/src/db/migrations/001-initial.ts +++ b/src/db/migrations/001-initial.ts @@ -1,3 +1,5 @@ +import { ENFORCEMENT_TRIGGERS_SQL } from "./enforcement-triggers.js"; + /** * Initial Athletic Standard v1 SQLite schema. * @@ -61,6 +63,13 @@ CREATE TABLE record_revisions ( revision INTEGER NOT NULL CHECK (revision >= 1), record_type TEXT NOT NULL, record_json TEXT NOT NULL CHECK (json_valid(record_json)), + extensions_json TEXT CHECK ( + extensions_json IS NULL OR ( + json_valid(extensions_json) AND + json_type(extensions_json) = 'object' AND + length(extensions_json) <= 65536 + ) + ), became_known_at TEXT NOT NULL, became_known_at_basis TEXT NOT NULL CHECK (became_known_at_basis IN ( 'local_write', @@ -695,4 +704,6 @@ CREATE TABLE authored_record_evidence ( FOREIGN KEY (evidence_record_id, evidence_revision) REFERENCES record_revisions (record_id, revision) ) STRICT; + +${ENFORCEMENT_TRIGGERS_SQL} `; diff --git a/src/db/migrations/enforcement-triggers.ts b/src/db/migrations/enforcement-triggers.ts new file mode 100644 index 00000000..c56bc716 --- /dev/null +++ b/src/db/migrations/enforcement-triggers.ts @@ -0,0 +1,185 @@ +/** + * SQLite triggers that enforce critical cross-table rules for direct writers (D116). + * + * Foreign keys remain required, but these triggers also refuse invalid states when + * application code bypasses the Node library. + */ +export const ENFORCEMENT_TRIGGERS_SQL = ` +CREATE TRIGGER record_revisions_record_type_matches_parent_insert +BEFORE INSERT ON record_revisions +FOR EACH ROW +WHEN ( + SELECT record_type FROM records WHERE record_id = NEW.record_id +) IS NOT NULL + AND ( + SELECT record_type FROM records WHERE record_id = NEW.record_id + ) <> NEW.record_type +BEGIN + SELECT RAISE(ABORT, 'record_revisions.record_type must match records.record_type'); +END; + +CREATE TRIGGER record_revisions_record_type_matches_parent_update +BEFORE UPDATE OF record_type ON record_revisions +FOR EACH ROW +WHEN ( + SELECT record_type FROM records WHERE record_id = NEW.record_id +) IS NOT NULL + AND ( + SELECT record_type FROM records WHERE record_id = NEW.record_id + ) <> NEW.record_type +BEGIN + SELECT RAISE(ABORT, 'record_revisions.record_type must match records.record_type'); +END; + +CREATE TRIGGER records_current_revision_must_exist +BEFORE UPDATE OF current_revision ON records +FOR EACH ROW +WHEN ( + SELECT revision + FROM record_revisions + WHERE record_id = NEW.record_id AND revision = NEW.current_revision +) IS NULL +BEGIN + SELECT RAISE(ABORT, 'records.current_revision must reference an existing revision'); +END; + +CREATE TRIGGER athlete_report_data_cannot_claim_source_insert +BEFORE INSERT ON record_revisions +FOR EACH ROW +WHEN NEW.record_type IN ('athlete_report', 'nutrition_entry') + AND json_extract(NEW.record_json, '$.source_id') IS NOT NULL +BEGIN + SELECT RAISE(ABORT, 'athlete-reported record data cannot contain source_id'); +END; + +CREATE TRIGGER athlete_report_data_cannot_claim_source_update +BEFORE UPDATE OF record_json ON record_revisions +FOR EACH ROW +WHEN NEW.record_type IN ('athlete_report', 'nutrition_entry') + AND json_extract(NEW.record_json, '$.source_id') IS NOT NULL +BEGIN + SELECT RAISE(ABORT, 'athlete-reported record data cannot contain source_id'); +END; + +CREATE TRIGGER athlete_report_extensions_cannot_claim_source_insert +BEFORE INSERT ON record_revisions +FOR EACH ROW +WHEN NEW.record_type IN ('athlete_report', 'nutrition_entry', 'attachment', 'athlete_profile') + AND NEW.extensions_json IS NOT NULL + AND EXISTS ( + SELECT 1 + FROM json_tree(NEW.extensions_json) + WHERE key = 'source_id' + ) +BEGIN + SELECT RAISE(ABORT, 'athlete-reported record extensions cannot contain source_id'); +END; + +CREATE TRIGGER athlete_report_extensions_cannot_claim_source_update +BEFORE UPDATE OF extensions_json ON record_revisions +FOR EACH ROW +WHEN NEW.record_type IN ('athlete_report', 'nutrition_entry', 'attachment', 'athlete_profile') + AND NEW.extensions_json IS NOT NULL + AND EXISTS ( + SELECT 1 + FROM json_tree(NEW.extensions_json) + WHERE key = 'source_id' + ) +BEGIN + SELECT RAISE(ABORT, 'athlete-reported record extensions cannot contain source_id'); +END; + +CREATE TRIGGER records_deleted_flag_must_match_deletion_row +BEFORE UPDATE OF is_deleted ON records +FOR EACH ROW +WHEN ( + NEW.is_deleted = 1 AND ( + SELECT record_id FROM record_deletions WHERE record_id = NEW.record_id + ) IS NULL +) OR ( + NEW.is_deleted = 0 AND ( + SELECT record_id FROM record_deletions WHERE record_id = NEW.record_id + ) IS NOT NULL +) +BEGIN + SELECT RAISE(ABORT, 'records.is_deleted must match record_deletions'); +END; + +CREATE TRIGGER record_erasure_blocks_current_record_insert +BEFORE INSERT ON records +FOR EACH ROW +WHEN ( + SELECT record_id FROM record_erasure_markers WHERE record_id = NEW.record_id +) IS NOT NULL +BEGIN + SELECT RAISE(ABORT, 'erased records cannot have a current records row'); +END; + +CREATE TRIGGER record_erasure_blocks_current_record_update +BEFORE UPDATE ON records +FOR EACH ROW +WHEN ( + SELECT record_id FROM record_erasure_markers WHERE record_id = NEW.record_id +) IS NOT NULL +BEGIN + SELECT RAISE(ABORT, 'erased records cannot have a current records row'); +END; + +CREATE TRIGGER typed_row_record_type_matches_insert +BEFORE INSERT ON athlete_profile +FOR EACH ROW +WHEN NEW.record_type <> 'athlete_profile' +BEGIN + SELECT RAISE(ABORT, 'athlete_profile.record_type must be athlete_profile'); +END; + +CREATE TRIGGER typed_row_record_type_matches_sources_insert +BEFORE INSERT ON sources +FOR EACH ROW +WHEN NEW.record_type <> 'source' +BEGIN + SELECT RAISE(ABORT, 'sources.record_type must be source'); +END; + +CREATE TRIGGER typed_row_record_type_matches_point_measurements_insert +BEFORE INSERT ON point_measurements +FOR EACH ROW +WHEN NEW.record_type <> 'point_measurement' +BEGIN + SELECT RAISE(ABORT, 'point_measurements.record_type must be point_measurement'); +END; + +CREATE TRIGGER typed_row_record_type_matches_athlete_reports_insert +BEFORE INSERT ON athlete_reports +FOR EACH ROW +WHEN NEW.record_type <> 'athlete_report' +BEGIN + SELECT RAISE(ABORT, 'athlete_reports.record_type must be athlete_report'); +END; + +CREATE TRIGGER point_measurements_require_source_insert +BEFORE INSERT ON point_measurements +FOR EACH ROW +WHEN NEW.source_id IS NULL +BEGIN + SELECT RAISE(ABORT, 'measured records require source_id'); +END; + +CREATE TRIGGER prediction_result_links_revision_exists_insert +BEFORE INSERT ON prediction_result_links +FOR EACH ROW +WHEN ( + SELECT revision + FROM record_revisions + WHERE record_id = NEW.prediction_id AND revision = NEW.prediction_revision +) IS NULL + OR ( + SELECT revision + FROM record_revisions + WHERE record_id = NEW.benchmark_result_id + AND revision = NEW.benchmark_result_revision + ) IS NULL +BEGIN + SELECT RAISE(ABORT, 'prediction_result_links must reference existing revisions'); +END; +`; diff --git a/src/db/provider-import.ts b/src/db/provider-import.ts index 815569fc..9fbc959f 100644 --- a/src/db/provider-import.ts +++ b/src/db/provider-import.ts @@ -1,5 +1,6 @@ import type { Transaction } from "@libsql/client"; import { + CurrentRecord, PointMeasurementTypeSchema, RecordActor, RecordType, @@ -19,6 +20,7 @@ import { atOffsetOf } from "../series.js"; import { parseProviderExport, type ParsedProviderExport } from "../import/index.js"; import type { ProviderSummaryImport } from "../import/merge.js"; import { databaseClient, type AthleticDatabase } from "./client.js"; +import { currentRecordPayloadFromRow } from "./revision-encoding.js"; import { incrementDatabaseRevision, insertRevision, @@ -909,7 +911,8 @@ async function recordsByImportKey( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM record_import_keys JOIN records ON records.record_id = record_import_keys.record_id JOIN record_revisions @@ -922,14 +925,7 @@ async function recordsByImportKey( for (const row of result.rows) { records.set( `${String(row.match_key_method)}\u0000${String(row.match_key)}`, - { - record_id: String(row.record_id), - record_type: RecordType.parse(row.record_type), - current_revision: Number(row.current_revision), - created_at: UtcTimestamp.parse(row.created_at), - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as never, - } as CurrentRecordT, + CurrentRecord.parse(currentRecordPayloadFromRow(row)), ); } } diff --git a/src/db/query.ts b/src/db/query.ts index b18ca863..21df1be7 100644 --- a/src/db/query.ts +++ b/src/db/query.ts @@ -10,6 +10,7 @@ import { type SeriesQuantity, } from "../v1/schema.js"; import { databaseClient, type AthleticDatabase } from "./client.js"; +import { currentRecordPayloadFromRow } from "./revision-encoding.js"; type SqlValue = string | number | bigint | boolean | Uint8Array | ArrayBuffer | null; @@ -72,14 +73,7 @@ function timeRangeConditions( } function parseCurrentRow(row: Record): CurrentRecordT { - return CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }); + return CurrentRecord.parse(currentRecordPayloadFromRow(row)); } export async function queryMeasurements( @@ -110,7 +104,8 @@ export async function queryMeasurements( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM point_measurements JOIN records ON records.record_id = point_measurements.record_id JOIN record_revisions @@ -150,7 +145,8 @@ export async function querySeries( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM measurement_samples JOIN records ON records.record_id = measurement_samples.record_id JOIN record_revisions @@ -201,7 +197,8 @@ export async function querySessions( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM ${table} JOIN records ON records.record_id = ${table}.record_id JOIN record_revisions @@ -285,7 +282,8 @@ export async function queryRecordsAsOf( record_revisions.revision AS current_revision, records.created_at, 0 AS is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM visible_revisions JOIN record_revisions ON record_revisions.record_id = visible_revisions.record_id diff --git a/src/db/records.ts b/src/db/records.ts index d2bee87e..9aaaf0f9 100644 --- a/src/db/records.ts +++ b/src/db/records.ts @@ -16,8 +16,15 @@ import { type RecordTypeT, } from "../v1/schema.js"; import { databaseClient, type AthleticDatabase } from "./client.js"; +import { + currentRecordPayloadFromRow, + parseExtensionsJson, + recordRevisionPayloadFromRow, + serializeExtensionsJson, +} from "./revision-encoding.js"; import { withWriteTransaction } from "./transaction.js"; import { createUuidV7 } from "./uuid.js"; +import type { RecordExtensionsT } from "../v1/extensions.js"; type SqlValue = string | number | bigint | boolean | Uint8Array | ArrayBuffer | null; @@ -25,6 +32,7 @@ export interface WriteRecordInput { record_type: RecordTypeT; data: unknown; changed_by: RecordActorT; + extensions?: RecordExtensionsT; record_id?: string; created_at?: string; became_known_at?: string; @@ -35,6 +43,7 @@ export interface CorrectRecordInput { record_id: string; expected_revision: number; data: unknown; + extensions?: RecordExtensionsT; changed_by: RecordActorT; became_known_at?: string; became_known_at_basis?: "local_write" | "provider_import" | "package_merge"; @@ -728,6 +737,7 @@ export async function insertRevision( became_known_at_basis: becameKnownAtBasis, changed_by: changedBy, data: record.data, + extensions: record.extensions, }); await transaction.execute({ sql: ` @@ -736,17 +746,19 @@ export async function insertRevision( revision, record_type, record_json, + extensions_json, became_known_at, became_known_at_basis, changed_by_json, previous_revision - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `, args: [ revision.record_id, revision.revision, revision.record_type, requiredJson(revision.data), + serializeExtensionsJson(revision.extensions), revision.became_known_at, revision.became_known_at_basis, requiredJson(revision.changed_by), @@ -812,6 +824,7 @@ export async function writeRecords( current_revision: 1, is_deleted: false, data: input.data, + extensions: input.extensions, }); await transaction.execute({ @@ -1029,7 +1042,8 @@ export async function correctRecord( records.current_revision, records.created_at, records.is_deleted, - record_revisions.became_known_at + record_revisions.became_known_at, + record_revisions.extensions_json FROM records JOIN record_revisions ON record_revisions.record_id = records.record_id @@ -1064,6 +1078,7 @@ export async function correctRecord( current_revision: currentRevision + 1, is_deleted: false, data: input.data, + extensions: input.extensions ?? parseExtensionsJson(row.extensions_json ?? null), }); await insertRevision( @@ -1161,7 +1176,8 @@ export async function readRecord( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM records JOIN record_revisions ON record_revisions.record_id = records.record_id @@ -1174,14 +1190,7 @@ export async function readRecord( if (row === undefined) { return null; } - return CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }); + return CurrentRecord.parse(currentRecordPayloadFromRow(row)); } export async function listRecords( @@ -1211,7 +1220,8 @@ export async function listRecords( records.current_revision, records.created_at, records.is_deleted, - record_revisions.record_json + record_revisions.record_json, + record_revisions.extensions_json FROM records JOIN record_revisions ON record_revisions.record_id = records.record_id @@ -1223,16 +1233,7 @@ export async function listRecords( args, }); - return result.rows.map((row) => - CurrentRecord.parse({ - record_id: row.record_id, - record_type: row.record_type, - current_revision: Number(row.current_revision), - created_at: row.created_at, - is_deleted: Number(row.is_deleted) === 1, - data: JSON.parse(String(row.record_json)) as unknown, - }), - ); + return result.rows.map((row) => CurrentRecord.parse(currentRecordPayloadFromRow(row))); } export async function readRecordRevisions( @@ -1250,24 +1251,13 @@ export async function readRecordRevisions( became_known_at, became_known_at_basis, changed_by_json, - record_json + record_json, + extensions_json FROM record_revisions WHERE record_id = ? ORDER BY revision `, args: [parsedRecordId], }); - return result.rows.map((row) => - RecordRevision.parse({ - record_id: row.record_id, - record_type: row.record_type, - revision: Number(row.revision), - previous_revision: - row.previous_revision === null ? null : Number(row.previous_revision), - became_known_at: row.became_known_at, - became_known_at_basis: row.became_known_at_basis, - changed_by: JSON.parse(String(row.changed_by_json)) as unknown, - data: JSON.parse(String(row.record_json)) as unknown, - }), - ); + return result.rows.map((row) => RecordRevision.parse(recordRevisionPayloadFromRow(row))); } diff --git a/src/db/revision-encoding.ts b/src/db/revision-encoding.ts new file mode 100644 index 00000000..8523fd0c --- /dev/null +++ b/src/db/revision-encoding.ts @@ -0,0 +1,59 @@ +import { RecordExtensions, type RecordExtensionsT } from "../v1/extensions.js"; + +export function parseExtensionsJson( + value: unknown, +): RecordExtensionsT | undefined { + if (value === null || value === undefined) { + return undefined; + } + if (typeof value !== "string") { + throw new Error("extensions_json must be text"); + } + const parsed = JSON.parse(value) as unknown; + if (parsed === null) { + return undefined; + } + return RecordExtensions.parse(parsed); +} + +export function serializeExtensionsJson( + extensions: RecordExtensionsT | undefined, +): string | null { + if (extensions === undefined) { + return null; + } + return JSON.stringify(extensions); +} + +export function currentRecordPayloadFromRow( + row: Record, +): Record { + const extensions = parseExtensionsJson(row.extensions_json ?? null); + return { + record_id: row.record_id, + record_type: row.record_type, + current_revision: Number(row.current_revision), + created_at: row.created_at, + is_deleted: Number(row.is_deleted) === 1, + data: JSON.parse(String(row.record_json)) as unknown, + ...(extensions === undefined ? {} : { extensions }), + }; +} + +export function recordRevisionPayloadFromRow( + row: Record, +): Record { + const extensions = parseExtensionsJson(row.extensions_json ?? null); + return { + record_id: row.record_id, + record_type: row.record_type, + revision: Number(row.revision), + previous_revision: + row.previous_revision === null ? null : Number(row.previous_revision), + became_known_at: row.became_known_at, + became_known_at_basis: row.became_known_at_basis, + changed_by: JSON.parse(String(row.changed_by_json)) as unknown, + data: JSON.parse(String(row.record_json)) as unknown, + ...(extensions === undefined ? {} : { extensions }), + }; +} diff --git a/src/v1/extensions.ts b/src/v1/extensions.ts new file mode 100644 index 00000000..2b3f7be3 --- /dev/null +++ b/src/v1/extensions.ts @@ -0,0 +1,227 @@ +/** + * Optional namespaced extension envelope on v1 records (D118). + * + * Extension values inherit the parent record class. They cannot claim a source on + * athlete-reported records or remove source requirements from measured data. + */ +import { z } from "zod"; + +/** Maximum UTF-8 bytes for the whole extensions object when JSON-encoded. */ +export const EXTENSIONS_MAX_ENCODED_BYTES = 65_536; + +/** Maximum UTF-8 bytes for one extension value when JSON-encoded. */ +export const EXTENSION_VALUE_MAX_ENCODED_BYTES = 16_384; + +/** Maximum extension keys on one record. */ +export const EXTENSIONS_MAX_KEYS = 32; + +/** Maximum nesting depth for extension JSON values (objects and arrays). */ +export const EXTENSION_VALUE_MAX_DEPTH = 8; + +/** Maximum length of one extension string value. */ +export const EXTENSION_STRING_MAX_LENGTH = 4_096; + +/** Maximum array length at one extension array node. */ +export const EXTENSION_ARRAY_MAX_LENGTH = 256; + +/** Maximum object keys at one extension object node. */ +export const EXTENSION_OBJECT_MAX_KEYS = 64; + +/** + * Namespaced extension ID: reverse-DNS owner segment, slash, extension name. + * Example: `ath.fit/demo/widget`. + */ +export const ExtensionId = z + .string() + .regex( + /^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+\/[a-z][a-z0-9][a-z0-9._-]*$/, + "namespaced extension id", + ) + .max(200); + +export type ExtensionIdT = z.infer; + +const ATHLETE_REPORTED_RECORD_TYPES = new Set([ + "athlete_report", + "nutrition_entry", + "attachment", + "athlete_profile", +]); + +const FORBIDDEN_EXTENSION_KEYS = new Set(["source_id"]); + +function encodedUtf8Length(value: string): number { + return new TextEncoder().encode(value).length; +} + +function extensionValueDepth(value: unknown, depth = 1): number { + if (value === null || typeof value !== "object") { + return depth; + } + if (Array.isArray(value)) { + if (value.length === 0) { + return depth; + } + return Math.max(...value.map((child) => extensionValueDepth(child, depth + 1))); + } + const entries = Object.entries(value as Record); + if (entries.length === 0) { + return depth; + } + return Math.max(...entries.map(([, child]) => extensionValueDepth(child, depth + 1))); +} + +function collectForbiddenExtensionKeys( + value: unknown, + path: string, + issues: Array<{ path: string; message: string }>, +): void { + if (value === null || typeof value !== "object") { + return; + } + if (Array.isArray(value)) { + value.forEach((child, index) => { + collectForbiddenExtensionKeys(child, `${path}[${index}]`, issues); + }); + return; + } + for (const [key, child] of Object.entries(value as Record)) { + if (FORBIDDEN_EXTENSION_KEYS.has(key)) { + issues.push({ + path: path === "" ? key : `${path}.${key}`, + message: "extensions cannot contain source_id", + }); + } + collectForbiddenExtensionKeys(child, path === "" ? key : `${path}.${key}`, issues); + } +} + +function validateExtensionValueShape( + value: unknown, + path: string, + depth: number, + issues: Array<{ path: string; message: string }>, +): void { + if (depth > EXTENSION_VALUE_MAX_DEPTH) { + issues.push({ path, message: `extension value exceeds depth ${EXTENSION_VALUE_MAX_DEPTH}` }); + return; + } + if (value === null) { + return; + } + if (typeof value === "string") { + if (value.length > EXTENSION_STRING_MAX_LENGTH) { + issues.push({ + path, + message: `extension string exceeds ${EXTENSION_STRING_MAX_LENGTH} characters`, + }); + } + return; + } + if (typeof value === "number" || typeof value === "boolean") { + return; + } + if (Array.isArray(value)) { + if (value.length > EXTENSION_ARRAY_MAX_LENGTH) { + issues.push({ + path, + message: `extension array exceeds ${EXTENSION_ARRAY_MAX_LENGTH} elements`, + }); + } + value.forEach((child, index) => { + validateExtensionValueShape(child, `${path}[${index}]`, depth + 1, issues); + }); + return; + } + if (typeof value === "object") { + const entries = Object.entries(value as Record); + if (entries.length > EXTENSION_OBJECT_MAX_KEYS) { + issues.push({ + path, + message: `extension object exceeds ${EXTENSION_OBJECT_MAX_KEYS} keys`, + }); + } + for (const [key, child] of entries) { + validateExtensionValueShape(child, path === "" ? key : `${path}.${key}`, depth + 1, issues); + } + } +} + +const ExtensionJsonValue: z.ZodType = z.lazy(() => + z.union([ + z.string().max(EXTENSION_STRING_MAX_LENGTH), + z.number().finite(), + z.boolean(), + z.null(), + z.array(ExtensionJsonValue).max(EXTENSION_ARRAY_MAX_LENGTH), + z.record(z.string(), ExtensionJsonValue), + ]), +); + +export const RecordExtensions = z + .record(z.string(), ExtensionJsonValue) + .superRefine((extensions, context) => { + const keys = Object.keys(extensions); + for (const key of keys) { + const parsedId = ExtensionId.safeParse(key); + if (!parsedId.success) { + context.addIssue({ + code: "custom", + path: [key], + message: "extension key must be a namespaced extension id", + }); + } + } + if (keys.length > EXTENSIONS_MAX_KEYS) { + context.addIssue({ + code: "custom", + message: `extensions cannot contain more than ${EXTENSIONS_MAX_KEYS} keys`, + }); + return; + } + const encoded = JSON.stringify(extensions); + if (encodedUtf8Length(encoded) > EXTENSIONS_MAX_ENCODED_BYTES) { + context.addIssue({ + code: "custom", + message: `extensions exceed ${EXTENSIONS_MAX_ENCODED_BYTES} encoded bytes`, + }); + } + for (const [extensionId, value] of Object.entries(extensions)) { + const valueEncoded = JSON.stringify(value); + if (encodedUtf8Length(valueEncoded) > EXTENSION_VALUE_MAX_ENCODED_BYTES) { + context.addIssue({ + code: "custom", + path: [extensionId], + message: `extension value exceeds ${EXTENSION_VALUE_MAX_ENCODED_BYTES} encoded bytes`, + }); + } + const depthIssues: Array<{ path: string; message: string }> = []; + validateExtensionValueShape(value, extensionId, 1, depthIssues); + for (const issue of depthIssues) { + context.addIssue({ + code: "custom", + path: issue.path.split(/\.|\[|\]/).filter(Boolean), + message: issue.message, + }); + } + } + }); + +export type RecordExtensionsT = z.infer; + +export function validateExtensionsForRecordType( + recordType: string, + extensions: RecordExtensionsT | undefined, +): void { + if (extensions === undefined) { + return; + } + if (!ATHLETE_REPORTED_RECORD_TYPES.has(recordType)) { + return; + } + const issues: Array<{ path: string; message: string }> = []; + collectForbiddenExtensionKeys(extensions, "", issues); + if (issues.length > 0) { + throw new Error(issues[0]?.message ?? "invalid extensions for athlete-reported record"); + } +} diff --git a/src/v1/schema.ts b/src/v1/schema.ts index efd04fb9..f37660d4 100644 --- a/src/v1/schema.ts +++ b/src/v1/schema.ts @@ -6,6 +6,7 @@ * belong here. */ import { z } from "zod"; +import { RecordExtensions, validateExtensionsForRecordType } from "./extensions.js"; export const ATHLETIC_STANDARD_VERSION = "1.0.0"; @@ -832,17 +833,30 @@ const currentRecordFields = { created_at: UtcTimestamp, current_revision: RecordRevisionNumber, is_deleted: z.boolean(), + extensions: RecordExtensions.optional(), } as const; function currentRecordVariant( recordType: T, data: S, ) { - return z.strictObject({ - ...currentRecordFields, - record_type: z.literal(recordType), - data, - }); + return z + .strictObject({ + ...currentRecordFields, + record_type: z.literal(recordType), + data, + }) + .superRefine((value, context) => { + try { + validateExtensionsForRecordType(recordType, value.extensions); + } catch (error) { + context.addIssue({ + code: "custom", + path: ["extensions"], + message: (error as Error).message, + }); + } + }); } export const AthleteProfileRecord = currentRecordVariant("athlete_profile", AthleteProfileData); @@ -958,6 +972,7 @@ function recordRevisionVariant ...recordRevisionFields, record_type: z.literal(recordType), data, + extensions: RecordExtensions.optional(), }) .refine( (value) => @@ -968,7 +983,18 @@ function recordRevisionVariant path: ["previous_revision"], message: "previous_revision must be null for revision 1 or the prior revision number", }, - ); + ) + .superRefine((value, context) => { + try { + validateExtensionsForRecordType(recordType, value.extensions); + } catch (error) { + context.addIssue({ + code: "custom", + path: ["extensions"], + message: (error as Error).message, + }); + } + }); } export const AthleteProfileRevision = recordRevisionVariant( diff --git a/tests/v1-direct-sql.test.ts b/tests/v1-direct-sql.test.ts new file mode 100644 index 00000000..c2c5020c --- /dev/null +++ b/tests/v1-direct-sql.test.ts @@ -0,0 +1,148 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { createClient } from "@libsql/client"; +import { afterEach, describe, expect, it } from "vitest"; +import { createDatabase, writeRecord } from "../src/db/index.js"; + +const databaseId = "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1f01"; +const createdAt = "2026-08-09T12:00:00.000Z"; +const sourceId = "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1e02"; +const reportId = "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1e04"; + +const timestampReceipt = { + timestamp_text: "2026-08-09T06:12:00-05:00", + utc_offset_text: "-05:00", + utc_offset_meaning: "provider_cycle_offset" as const, + timestamp_basis: "source_offset_timestamp" as const, +}; + +const toolActor = { + author_type: "tool" as const, + tool: "ath", + tool_version: "1.0.0", +}; + +const toolActorJson = JSON.stringify(toolActor); + +const directories: string[] = []; + +async function tempPath(): Promise { + const directory = await mkdtemp(join(tmpdir(), "ath-v1-direct-sql-")); + directories.push(directory); + return join(directory, "athlete.ath.sqlite"); +} + +async function sqlClient(path: string) { + const client = createClient({ url: pathToFileURL(path).href }); + await client.execute("PRAGMA foreign_keys = ON"); + return client; +} + +function athleteReportData(extra: Record = {}) { + return { + report_type: "soreness", + reported_at: createdAt, + input_reported_at: timestampReceipt, + reported_via: "text" as const, + ...extra, + }; +} + +async function seededDatabase(): Promise { + const path = await tempPath(); + const database = await createDatabase(path, { databaseId, createdAt }); + await writeRecord(database, { + record_type: "source", + record_id: sourceId, + created_at: createdAt, + changed_by: toolActor, + data: { + source_type: "wearable", + data_writer: "WHOOP", + data_route: "whoop_csv", + vendor: "whoop", + }, + }); + await database.close(); + return path; +} + +describe("v1 direct SQLite enforcement", () => { + afterEach(async () => { + for (const directory of directories.splice(0)) { + await rm(directory, { recursive: true, force: true }); + } + }); + + async function expectBadRevisionInsert( + path: string, + recordJson: string, + extensionsJson: string | null, + ): Promise { + const client = await sqlClient(path); + const transaction = await client.transaction("write"); + try { + await transaction.execute({ + sql: ` + INSERT INTO records (record_id, record_type, current_revision, created_at, is_deleted) + VALUES (?, 'athlete_report', 1, ?, 0) + `, + args: [reportId, createdAt], + }); + await transaction.execute({ + sql: ` + INSERT INTO record_revisions ( + record_id, revision, record_type, record_json, extensions_json, + became_known_at, became_known_at_basis, changed_by_json, previous_revision + ) VALUES (?, 1, 'athlete_report', ?, ?, ?, 'local_write', ?, NULL) + `, + args: [reportId, recordJson, extensionsJson, createdAt, toolActorJson], + }); + await transaction.commit(); + throw new Error("expected revision insert to fail"); + } catch (error) { + await transaction.rollback(); + expect((error as Error).message).toMatch(/source_id/); + } finally { + transaction.close(); + await client.close(); + } + } + + it("refuses athlete-reported record data that claims a source", async () => { + const path = await seededDatabase(); + await expectBadRevisionInsert( + path, + JSON.stringify(athleteReportData({ source_id: sourceId })), + null, + ); + }); + + it("refuses extensions that smuggle source_id onto athlete-reported records", async () => { + const path = await seededDatabase(); + await expectBadRevisionInsert( + path, + JSON.stringify(athleteReportData()), + JSON.stringify({ "ath.fit/demo-widget": { source_id: sourceId } }), + ); + }); + + it("refuses a revision whose record_type disagrees with the parent record", async () => { + const path = await seededDatabase(); + const client = await sqlClient(path); + await expect( + client.execute({ + sql: ` + INSERT INTO record_revisions ( + record_id, revision, record_type, record_json, extensions_json, + became_known_at, became_known_at_basis, changed_by_json, previous_revision + ) VALUES (?, 2, 'athlete_report', ?, NULL, ?, 'local_write', ?, 1) + `, + args: [sourceId, JSON.stringify(athleteReportData()), createdAt, toolActorJson], + }), + ).rejects.toThrow(/record_type/); + await client.close(); + }); +}); diff --git a/tests/v1-extensions.test.ts b/tests/v1-extensions.test.ts new file mode 100644 index 00000000..2c52aacc --- /dev/null +++ b/tests/v1-extensions.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it, afterAll } from "vitest"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + createDatabase, + exportRecords, + importRecords, + loadAthleticStandardPackage, + previewPackageImport, + readRecord, + writeRecord, + type AthleticDatabase, +} from "../src/db/index.js"; +import { AthleteReportRecord } from "../src/v1/schema.js"; + +const databaseId = "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1f01"; +const sourceId = "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1e02"; +const pointId = "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1e03"; +const reportId = "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1e04"; +const createdAt = "2026-08-09T12:00:00.000Z"; + +const timestampReceipt = { + timestamp_text: "2026-08-09T06:12:00-05:00", + utc_offset_text: "-05:00", + utc_offset_meaning: "provider_cycle_offset" as const, + timestamp_basis: "source_offset_timestamp" as const, +}; + +const toolActor = { + author_type: "tool" as const, + tool: "ath", + tool_version: "1.0.0", +}; + +const openDatabases: AthleticDatabase[] = []; + +async function tempDatabasePath(): Promise { + const directory = await mkdtemp(join(tmpdir(), "ath-v1-ext-")); + return join(directory, "athlete.ath.sqlite"); +} + +async function newDatabase(): Promise { + const path = await tempDatabasePath(); + const database = await createDatabase(path, { databaseId, createdAt }); + openDatabases.push(database); + return database; +} + +describe("v1 record extensions", () => { + afterAll(async () => { + for (const database of openDatabases) { + await database.close(); + } + }); + + it("rejects athlete-reported extensions that contain source_id", () => { + const parsed = AthleteReportRecord.safeParse({ + record_id: reportId, + record_type: "athlete_report", + created_at: createdAt, + current_revision: 1, + is_deleted: false, + data: { + report_type: "soreness", + reported_at: createdAt, + input_reported_at: timestampReceipt, + reported_via: "text", + }, + extensions: { + "ath.fit/demo-widget": { source_id: sourceId }, + }, + }); + expect(parsed.success).toBe(false); + }); + + it("preserves extensions through SQLite write, read, export, and import", async () => { + const database = await newDatabase(); + await writeRecord(database, { + record_type: "source", + record_id: sourceId, + created_at: createdAt, + changed_by: toolActor, + data: { + source_type: "wearable", + data_writer: "WHOOP", + data_route: "whoop_csv", + vendor: "whoop", + }, + }); + const extensions = { + "ath.fit/demo-widget": { note: "synthetic", count: 2 }, + }; + await writeRecord(database, { + record_type: "point_measurement", + record_id: pointId, + created_at: createdAt, + became_known_at: createdAt, + became_known_at_basis: "provider_import", + changed_by: toolActor, + extensions, + data: { + source_id: sourceId, + received_at: createdAt, + received_at_basis: "import_time", + quantity: "hrv_rmssd", + recorded_at: "2026-08-09T11:12:00.000Z", + input_timestamp: timestampReceipt, + value: { + standard_value: 62, + standard_unit: "ms", + input_value: 62, + input_unit: "ms", + }, + }, + }); + + const readBack = await readRecord(database, pointId); + expect(readBack?.extensions).toEqual(extensions); + + const exportRoot = await mkdtemp(join(tmpdir(), "ath-v1-ext-export-")); + const exportDir = join(exportRoot, "package"); + await exportRecords(database, exportDir); + const importedPath = await tempDatabasePath(); + const imported = await createDatabase(importedPath, { + databaseId: "01890f3e-e7d3-7cc0-88c8-5d9c6b3a1f99", + createdAt, + }); + openDatabases.push(imported); + const loaded = await loadAthleticStandardPackage(exportDir); + const preview = await previewPackageImport(imported, loaded); + await importRecords(imported, preview); + const importedRecord = await readRecord(imported, pointId); + expect(importedRecord?.extensions).toEqual(extensions); + await rm(exportRoot, { recursive: true, force: true }); + }); +});