diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64a0c1d4..82b9162a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,10 @@ permissions: jobs: verify: + strategy: + fail-fast: false + matrix: + node-version: [22, 24] runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 @@ -19,7 +23,7 @@ jobs: version: 10.33.3 - uses: actions/setup-node@v4 with: - node-version: 20 + node-version: ${{ matrix.node-version }} cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm check:public-data diff --git a/.github/workflows/release-cross-platform.yml b/.github/workflows/release-cross-platform.yml index cae9c4d6..e74a2447 100644 --- a/.github/workflows/release-cross-platform.yml +++ b/.github/workflows/release-cross-platform.yml @@ -4,7 +4,7 @@ on: workflow_dispatch: push: tags: - - "v1.0.0-*" + - "v*" permissions: contents: read diff --git a/.gitignore b/.gitignore index 0f719541..f1a28c87 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,14 @@ validation-data/ !tests/fixtures/exports/apple/workout-routes/route_2026-08-09_7.00pm.gpx !tests/fixtures/exports/oura/oura_daily_readiness.csv !tests/fixtures/exports/oura/oura_sleep.csv +!tests/fixtures/exports/oura-member-portal/member-portal-dailyreadiness.csv +!tests/fixtures/exports/oura-member-portal/member-portal-dailysleep.csv +!tests/fixtures/exports/oura-portal/dailyreadiness.csv +!tests/fixtures/exports/oura-portal/dailysleep.csv +!tests/fixtures/exports/oura-portal/dailyactivity.csv +!tests/fixtures/npm-100-encoding/athlete.ath.sqlite +!tests/fixtures/exports/oura-spo2/oura_sleep_spo2_flat.csv +!tests/fixtures/exports/oura-spo2/oura_sleep_spo2_json.csv !tests/fixtures/exports/whoop/journal_entries.csv !tests/fixtures/exports/whoop/physiological_cycles.csv !tests/fixtures/exports/whoop/sleeps.csv diff --git a/README.md b/README.md index fa9f0ae5..167da407 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,17 @@ Anyone who can read the database file can read the athlete record. ## Install -Athletic Standard needs Node.js 20 or newer. +Athletic Standard needs Node.js 22 or newer. + +SQL schema migration (`ath migrate`) and confirmed `ath repair` use the `sqlite3` +command-line tool for verified backups. Install it and ensure it is on `PATH` before +running either command. + +When typed-table columns disagree with the current revision in meaning (for example +after direct SQL edits), run `ath repair -y --from-revision +--confirm-revision-align ` after reviewing the preview. Each attempt +writes a new `.repair-backup.*.sqlite` file beside the database; failed attempts +leave that file in place for restore. ```sh npm install -g athleticstandard diff --git a/build-history/README.md b/build-history/README.md index 344b7894..f4651310 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -6,7 +6,11 @@ This folder is the permanent record of what we decided to build and why. Every plan we execute gets its spec written into a versioned subfolder here **before or as** the build happens. Within a version, all decisions go in that version's `decisions.md` — append new D-numbers, don't rewrite earlier ones. Supporting research goes in `appendix/` in the same version folder and is linked from the D-number. If a later build is a new plan, it gets a new version folder; the old one stays as-is. -Folders are named for the format version they describe — the same version that appears in `athleticstandard_version` and in the npm package. A plan that revises the format gets a folder matching the version it produces. +Folders are named for the **record format version** they describe — the same version +that appears in `athleticstandard_version` on records and packages. The npm package +version can move faster (for example `1.1.0` on npm while the format stays `1.0.0`); +those releases still append decisions under the format folder they change (see D144). +A plan that revises the format gets a folder matching the new format version. D-numbers run continuously across version folders. D25 follows D24 even though it lives in a different folder, so a decision can be cited by number alone. diff --git a/build-history/v1.0.0/decisions.md b/build-history/v1.0.0/decisions.md index 58b02da1..7a583342 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -1286,3 +1286,315 @@ Rejected alternatives: required before the first v1 npm publish and does not depend on #15 landing first. - **Implement without recording the plan text.** Rejected because build-history must contain the approved decisions and specification before or as the build happens. + +## D130. npm package 1.1.0 ships while `athleticstandard_version` stays 1.0.0 + +The npm package version tracks CLI and packaging behavior. `athleticstandard_version` +in the database and JSON package tracks athlete-owned record content. Release 1.1.0 +changes migrate, repair, import, and export behavior without changing the public v1 +record schema, so the format version remains `1.0.0`. + +Rejected alternatives: + +- **Bump the format version to 1.1.0.** Rejected because no normative field or record + type changed in `src/v1/schema.ts`. +- **Keep npm at 1.0.0 while changing migrate behavior.** Rejected because published + 1.0.0 already contains the default-model path bug and cannot be overwritten in place. + +## D131. SQL schema version 2 repairs npm 1.0.0 provider-import typed-table bytes + +npm 1.0.0 could write `data_json` with a different key order than +`record_revisions.record_json` for the same logical record. `ath check` compares those +columns byte for byte. SQL schema version 2 runs a one-time repair in the migration +runner that copies `record_json` into `data_json` only when +`semanticJsonEqual` says the values match (including nested key order). A true +semantic mismatch aborts migration and points to `ath repair` after fixing the +revision payload. The published `002` SQL file bumps `database_metadata`; row +alignment runs in TypeScript inside the same write transaction as +`PRAGMA user_version = 2`. + +Rejected alternatives: + +- **Require export, empty init, and import.** Rejected as the only path because it is + slow, easy to skip, and was untested in CI. +- **Stop byte comparison in `ath check`.** Rejected because direct-SQL writers rely on + the typed tables matching the current revision bytes. + +## D132. `ath repair` for encoding repair without a schema bump + +`ath repair` previews and applies the same typed-table byte repair as migration step 2 +on any supported `sql_schema_version`, including schema 1, without bumping +`sql_schema_version`. Databases that still need schema 2 must run `ath migrate` for +the one-way upgrade; migrate runs the same encoding repair inside that step. When +typed-table bytes disagree with the current revision in meaning, `ath repair +--from-revision` copies `record_json` into `data_json` after backup and explicit +database-ID confirmation. Confirmed repair uses the same verified `sqlite3` backup +path as migrate and reuses an existing repair backup when the revision did not change. + +Rejected alternatives: + +- **Repair without backup.** Rejected because a failed repair must be recoverable from + a verified copy, matching migrate. +- **Let repair bump `sql_schema_version`.** Rejected because schema version and repair + are separate operator steps; migrate owns the one-way schema upgrade. + +## D133. Migration backup uses inode checks and honest WAL failure text + +After a verified `sqlite3` backup, `executeConfirmedDatabaseMigration` re-checks the +database file inode and `database_state.current_revision` before enabling WAL and +before applying migrations. If migration fails after WAL was enabled, the error +message includes the underlying cause and says whether the revision changed; it points +to restore from the backup only when the revision changed. + +Rejected alternatives: + +- **Inode check only.** Rejected because another writer can commit between backup and + migration without replacing the file. +- **Claim the file is unchanged on any failure.** Rejected because WAL mode may already + be enabled even when the revision did not change. + +## D134. Interactive open uses the same confirmed migration path as `ath migrate` + +Interactive open now asks for the database ID, then calls +`executeConfirmedDatabaseMigration` instead of duplicating backup and migration steps +in the CLI layer. + +Rejected alternatives: + +- **Keep a separate interactive migration implementation in the CLI.** Rejected because + backup, WAL, and failure text would drift from `ath migrate`. +- **Auto-migrate without database ID confirmation.** Rejected because migration is + one-way and must stay explicit. + +## D135. Package export uses stable key order and durable writes + +Export JSON sorts object keys by UTF-16 code unit order (JavaScript string order), not +`localeCompare`. Each package file is written through a temporary file, `fsync`, and +`rename`. The whole package directory is built in a hidden sibling folder, synced, then +renamed into place so a crash cannot leave a half-written export tree. + +Rejected alternatives: + +- **Write directly into the destination directory.** Rejected because partial exports + look complete until `export-manifest.json` appears. +- **Locale-aware key sorting.** Rejected because exports must match across machines. + +## D136. Oura member-portal CSV columns (`score`, JSON `contributors`, JSON SpO2) + +The Oura importer maps member-portal `score` from the contributor keys inside the JSON +`contributors` cell (readiness vs sleep vs activity sub-scores use different key sets), +parses contributor JSON cells, and reads JSON `spo2_percentage` only when the cell +starts with `{` so flat SpO2 columns are not duplicated. + +Rejected alternatives: + +- **Infer readiness or sleep score from the filename.** Rejected because Trends bundles + mix categories in one table. +- **Treat a bare `score` header as an Oura marker in detect.** Rejected because it is + not specific enough outside member-portal exports. + +## D137. Document the `sqlite3` CLI dependency for migration backup + +README and `skill/references/cli.md` state that `ath migrate` and confirmed `ath +repair` need the `sqlite3` command on `PATH`. The backup error no longer claims a +minimum SQLite version that the tool does not enforce. + +Rejected alternatives: + +- **Shell out to a bundled sqlite3 binary.** Rejected because it would enlarge the npm + package and duplicate the system tool CI already uses. +- **Use only libSQL backup APIs.** Rejected because verified backup parity with + `sqlite3 .backup` is already tested and documented. + +## D138. Remove unreachable prerelease JSON runtime modules + +Modules only referenced by excluded 0.x JSON tests and unused import paths were +removed from `src/`. The live CLI path still uses `src/import/*` for provider parsing +and `src/v1/schema.ts` for records. Legacy `loadFile` / `saveFile` helpers were removed +from `src/file.ts`; `src/schema.ts` remains for provider import types. + +Rejected alternatives: + +- **Delete `src/schema.ts` with the JSON runtime.** Rejected because provider import + still maps through legacy signal types until a typed v1 import layer exists. +- **Keep JSON load helpers for undocumented callers.** Rejected because v1 commands use + SQLite only. + +## D139. Split CLI runtime and preview rendering out of `src/program.ts` + +Shared terminal prompts, database open helpers, and import preview rendering moved to +`src/cli/runtime.ts` and `src/cli/preview-render.ts`. `buildProgram()` remains the +command registry. + +Rejected alternatives: + +- **Leave all helpers inline in `program.ts`.** Rejected because the file was too large + to review safely. +- **Move commands into separate binaries.** Rejected because the Skill and docs assume + one `ath` entry point. + +## D140. CI runs on Node.js 22 and 24 + +Pull-request CI uses Node 22 and 24. The package `engines` field requires Node 22 or +newer. + +Rejected alternatives: + +- **Stay on Node 20.** Rejected because Node 22 is the current maintenance baseline + for new LTS work in this repo. +- **CI on a single Node version only.** Rejected because publish targets both 22 and 24. + +## D141. Cross-platform release workflow accepts any `v*` tag + +`release-cross-platform.yml` triggers on `workflow_dispatch` and on tags matching `v*` +so releases are not blocked on a single historical tag pattern. + +Rejected alternatives: + +- **Keep a single hard-coded release tag.** Rejected because it blocked `v1.1.0`. +- **Manual-only releases with no tag trigger.** Rejected because cross-platform checks + would not run automatically. + +## D142. Prior pull request #3 broke the build-history folder rule + +Pull request #3 landed build-history content without matching the version-folder rule +later written in `build-history/README.md`. This entry records the violation; earlier +folders are not moved or rewritten. + +Rejected alternatives: + +- **Rewrite `v0.1.0/` to match today's README.** Rejected because build-history is + append-only. +- **Ignore the violation.** Rejected because agents rely on the README rule. + +## D143. Prior pull requests #4, #6, and #14 broke the build-history folder rule + +Those pull requests committed plan or decision text outside the version-folder pattern +now required by `build-history/README.md`. Pull request #14's migration study lives in +`build-history/v1.0.0/appendix/v0.4.3-migration.md` and is cited here rather than +relitigated. They are recorded here without retroactive folder moves. + +Rejected alternatives: + +- **Merge their decisions into a single synthetic folder.** Rejected because it would + rewrite merged history. +- **Delete the offending files.** Rejected because decisions must stay citeable. + +## D144. npm package version and format version use different folder names + +Build-history folders are named for `athleticstandard_version`, not the npm package +version. npm `1.1.0` work therefore continues under `build-history/v1.0.0/` while the +record format stays `1.0.0`. `build-history/README.md` now states that rule explicitly. + +Rejected alternatives: + +- **Create `build-history/v1.1.0/` for npm-only releases.** Rejected because no format + version `1.1.0` exists in `src/v1/schema.ts`. +- **Require npm and format versions to share one folder name.** Rejected because patch + npm releases often change CLI behavior without schema changes. + +## D145. Prior pull request #25 merged 1.1.0 prep without a new format folder + +Pull request #25 carried npm `1.1.0` preparation while the format remained `1.0.0`. +That matches D144 and does not require a new build-history version folder. npm registry +`latest` was still `1.0.0` when that pull request merged. + +Rejected alternatives: + +- **Treat #25 as publishing npm 1.1.0.** Rejected because the registry still showed + `1.0.0` after merge. +- **Rewrite #25's build-history paths.** Rejected because merged folders stay as-is. + +## D146. v1.0.0 progress table vs cross-platform workflow that never ran + +v1.0.0 `progress.md` still lists release step 10 with checkboxes that predate later +workflow edits. A cross-platform workflow file existed before the 1.0.0 npm publish +with trigger `v1.0.0-*`, but GitHub Actions recorded zero runs on that workflow and +the repository had no release tags, so npm `1.0.0` shipped without cross-platform CI. +D141 later widened tag matching to `v*`; it did not retroactively run cross-platform +checks for 1.0.0. + +Rejected alternatives: + +- **Rewrite the step-10 table to match today's workflow.** Rejected because + build-history is append-only. +- **Claim cross-platform CI ran for 1.0.0.** Rejected because the workflow history shows + zero runs and no tags existed at publish time. + +## D147. Draft pull requests #20 and #31 may renumber D-numbers later + +This release continues D-numbers from D129 on `main`. Open drafts already claim +overlapping ranges and should renumber when they merge; merged history is not rewritten. + +Rejected alternatives: + +- **Renumber merged D-numbers when drafts land.** Rejected because merged decisions + must stay stable for citations. +- **Block this release until drafts renumber.** Rejected because draft ranges do not + change shipped behavior. + +## D148. License moves in pull requests #10 and #12 + +Pull request #10 switched the repository license to Apache-2.0. Pull request #12 +switched it back to MIT. Neither change altered the Athletic Standard file format, so +neither received a build-history version folder; this D-number records the sequence. + +Rejected alternatives: + +- **Fold license history into D143 folder-rule entries.** Rejected because #10 and #12 + were not folder-rule violations. +- **Omit license history.** Rejected because agents grep decisions for licensing. + +## D149. Read-only CLI opens do not enable WAL + +Read-only commands (`check`, `stats`, `records`, `calculate`, `series`, `export`, +and `migrate --dry-run`) open the database with `deferWal: true` so they do not +switch an existing delete-mode file to WAL. `releaseLocalDatabase` runs +`PRAGMA wal_checkpoint(TRUNCATE)` when a connection had enabled WAL, so confirmed +writes do not leave `-wal` and `-shm` files behind after close. + +Opening or writing against a read-only main database file (mode `444`) on a database +that is already in WAL mode may still create or extend `-wal` and `-shm` files +because SQLite opens the WAL journal for the connection. The tool does not delete +those sidecars after a failed write (D151). + +Rejected alternatives: + +- **Enable WAL on every open for performance.** Rejected because read-only commands + must not change the database file hash. +- **Leave WAL sidecars after read-only use.** Rejected because operators treat extra + files as unexpected writes. + +## D150. No automatic SQLite `user_version` header recovery + +If `PRAGMA user_version` disagrees with `database_metadata.sql_schema_version`, every +command refuses. This build sets `user_version` inside the migration write +transaction, so a metadata-only advance without row repair should not occur in normal +use. Recovery is restore from backup, or `ath init --empty` plus `ath import` from a +complete JSON package. + +Rejected alternatives: + +- **Reconcile `user_version` on read.** Rejected because it hides broken metadata and + breaks read-only guarantees. +- **Silent header repair without checking row data.** Rejected because applying + `002-provider-encoding-repair.sql` alone already showed false "no migration required" + states while `ath check` failed. + +## D151. Failed writes must not delete WAL sidecar files + +When a write transaction rolls back, the tool may switch a connection from WAL back to +DELETE only if the database file was already in DELETE mode before that attempt. If +`PRAGMA journal_mode = DELETE` returns busy because another connection holds a read +snapshot, the tool leaves `-wal` and `-shm` in place. If the file was already in WAL +mode, a failed write does not change journal mode or remove sidecars. Unlinking sidecars +after a failed write can destroy committed data that has not been checkpointed into the +main file. + +Rejected alternatives: + +- **Unlink `-wal` and `-shm` after any failed write.** Rejected because a later failed + command can erase committed rows another connection still needs from the WAL file. +- **Leave every failed write in WAL mode.** Rejected because DELETE-mode npm 1.0.0 files + should return to DELETE when the revert succeeds, matching operator expectations for + single-file databases. diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index 25ccc18f..46c994c1 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -64,13 +64,17 @@ The long-form sequence is in | CR8 | Add internal workspace boundaries, `CORE_API_VERSION` 1.0.0, explicit public exports, and API deprecation checks | pending | | CR9 | Verify the packed v1 tarball contains every promised schema, SQL, conformance, community, and Skill file | pending | -CR1 and CR2 change the unreleased v1 schema. They must finish before v1.0.0 is -published to npm. Release steps 11 and 12 remain blocked until CR1–CR9 and the -cross-platform part of step 10 pass. +npm `athleticstandard@1.0.0` is published on the registry. `main` carries npm +`1.1.0` code (D130) for the next publish while `athleticstandard_version` stays +`1.0.0`. That work includes SQL schema 2 migrate and repair, provider-encoding +repair, durable export, Oura member-portal CSV, `ath repair`, default model path +beside the database, structured log envelope, and docs. -npm `athleticstandard@1.0.0` is published. 1.1.0 is a package release of this -format version: `ath migrate`, provider-import check, structured log envelope, -default model path (`athlete.ath.model` beside `athlete.ath.sqlite`, not -overwriting the database), and docs. The record format stays `1.0.0`. -Remaining contribution-readiness steps continue on later package versions of -the same format. +Release step 10 cross-platform CI is wired to `v*` tags and `workflow_dispatch` +(D141). D146 records that the pre-1.0.0 workflow trigger never ran before npm +`1.0.0` shipped. Step 12 (npm publish of `1.1.0`) stays open until review +finishes. PR #33 adds read-only CLI opens without WAL, `ath repair --from-revision`, +safe export staging cleanup, and migrate-only `user_version` recovery. + +Remaining contribution-readiness steps continue on later package versions of the same +format. diff --git a/examples/demo-athlete/athlete.ath.sqlite b/examples/demo-athlete/athlete.ath.sqlite index 659f09f6..3c863cb0 100644 Binary files a/examples/demo-athlete/athlete.ath.sqlite and b/examples/demo-athlete/athlete.ath.sqlite differ diff --git a/package.json b/package.json index 998a44e3..ab701a11 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ ], "type": "module", "engines": { - "node": ">=20" + "node": ">=22" }, "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/scripts/check-public-data.ts b/scripts/check-public-data.ts index ec8e83d9..2f4af1fd 100644 --- a/scripts/check-public-data.ts +++ b/scripts/check-public-data.ts @@ -14,7 +14,7 @@ const approvedSyntheticFixtures = new Map([ ], [ "examples/demo-athlete/athlete.ath.sqlite", - "5245f0e073e981a4fdd655a8dbc159e3ab674986774a6900c7b7592481196cdc", + "4cd79efecd8e4dd901fc7a6af43cc287e008cbe175002490a34e2addf07067ed", ], [ "examples/demo-athlete/attachments/01890f3e-e7d3-7cc0-88c8-00000000000e.png", @@ -44,6 +44,38 @@ const approvedSyntheticFixtures = new Map([ "tests/fixtures/exports/oura/oura_sleep.csv", "ed59f11d1bb995278882238e26eea72830a114be67d74b2d223f96c8bfe6fb1b", ], + [ + "tests/fixtures/exports/oura-member-portal/member-portal-dailyreadiness.csv", + "1bf215c48dd4b8fc433d6e63dd067c1d905e373a4ce5f1a02c5ed990daaed0e8", + ], + [ + "tests/fixtures/exports/oura-member-portal/member-portal-dailysleep.csv", + "b9ba34447d2aeb8fb9bd66a3dd90fdf9346aab4c516182578e4ebbad8ae105d0", + ], + [ + "tests/fixtures/exports/oura-spo2/oura_sleep_spo2_flat.csv", + "3e7aaefc6b60bca8f9120bb60020aa61f15c3b989c80848935d6bac0e4429ce7", + ], + [ + "tests/fixtures/exports/oura-spo2/oura_sleep_spo2_json.csv", + "949053c0c1503dbabd6773acd2813888c9d9ff360588fca2e253443476632902", + ], + [ + "tests/fixtures/exports/oura-portal/dailyreadiness.csv", + "1bf215c48dd4b8fc433d6e63dd067c1d905e373a4ce5f1a02c5ed990daaed0e8", + ], + [ + "tests/fixtures/exports/oura-portal/dailysleep.csv", + "b9ba34447d2aeb8fb9bd66a3dd90fdf9346aab4c516182578e4ebbad8ae105d0", + ], + [ + "tests/fixtures/exports/oura-portal/dailyactivity.csv", + "d6ba261d94ccc36bce98d959ea17339b39f2642e241f584d0fdb8be18a6abc62", + ], + [ + "tests/fixtures/npm-100-encoding/athlete.ath.sqlite", + "8469f3dfe29768f78b86c4d23e641b5070fd78683b77a7d342925ddc1b81a075", + ], [ "tests/fixtures/exports/whoop/journal_entries.csv", "db60258f8c69f115afe427fdc442e6c97c85b9cc96b3d086e5aabc52157701d9", diff --git a/scripts/check-schema-drift.ts b/scripts/check-schema-drift.ts index 6e6b1f5a..5c95c2ee 100644 --- a/scripts/check-schema-drift.ts +++ b/scripts/check-schema-drift.ts @@ -11,9 +11,11 @@ import { createClient } from "@libsql/client"; import { fileURLToPath, pathToFileURL } from "node:url"; import { buildSqlContractDocument, + MIGRATION_002_FILE_HEADER, publishedMigrationSql, readDatabaseFileHeader, } from "../src/db/sql-contract.js"; +import { PROVIDER_ENCODING_REPAIR_SQL } from "../src/db/migrations/002-provider-encoding-repair.js"; import { SQLITE_APPLICATION_ID } from "../src/db/client.js"; import { createDatabase, @@ -155,6 +157,10 @@ function expectedMigrationFileContents(): string { return `${header}${publishedMigrationSql()}\n`; } +function expectedMigration002FileContents(): string { + return `${MIGRATION_002_FILE_HEADER}${PROVIDER_ENCODING_REPAIR_SQL}\n`; +} + function checkGeneratedFilesFresh(): void { const migrationPath = join(root, "spec", "sql", "migrations", "001-initial.sql"); const onDisk = readFileSync(migrationPath, "utf8"); @@ -171,6 +177,15 @@ function checkGeneratedFilesFresh(): void { if (contractOnDisk !== contractExpected) { throw new Error("spec/sql/contract.json is stale; run pnpm generate:sql-contract"); } + + const migration002Path = join(root, "spec", "sql", "migrations", "002-provider-encoding-repair.sql"); + const migration002OnDisk = readFileSync(migration002Path, "utf8"); + const migration002Expected = expectedMigration002FileContents(); + if (migration002OnDisk !== migration002Expected) { + throw new Error( + "spec/sql/migrations/002-provider-encoding-repair.sql is stale; run pnpm generate:sql-contract", + ); + } } export async function checkSchemaDrift(): Promise { diff --git a/scripts/generate-npm100-fixture.ts b/scripts/generate-npm100-fixture.ts new file mode 100644 index 00000000..0d126c21 --- /dev/null +++ b/scripts/generate-npm100-fixture.ts @@ -0,0 +1,26 @@ +/** + * Regenerates tests/fixtures/npm-100-encoding/athlete.ath.sqlite from npm 1.0.0. + * Requires network once; commit the output and update scripts/check-public-data.ts. + */ +import { execFileSync } from "node:child_process"; +import { mkdirSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const outDir = join(root, "tests/fixtures/npm-100-encoding"); +const exportsDir = join(root, "tests/fixtures/exports"); + +mkdirSync(outDir, { recursive: true }); +const run = (args: string[]) => { + execFileSync("npx", ["--yes", "athleticstandard@1.0.0", ...args], { + cwd: outDir, + encoding: "utf8", + stdio: "inherit", + }); +}; +run(["init", "-y", "--no-skill"]); +for (const provider of ["whoop", "oura", "apple"]) { + run(["import", "-y", resolve(exportsDir, provider)]); +} +console.log(`wrote ${join(outDir, "athlete.ath.sqlite")}`); diff --git a/scripts/generate-sql-contract.ts b/scripts/generate-sql-contract.ts index e99f9306..a5da7e61 100644 --- a/scripts/generate-sql-contract.ts +++ b/scripts/generate-sql-contract.ts @@ -7,12 +7,15 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { buildSqlContractDocument, + MIGRATION_002_FILE_HEADER, publishedMigrationSql, } from "../src/db/sql-contract.js"; +import { PROVIDER_ENCODING_REPAIR_SQL } from "../src/db/migrations/002-provider-encoding-repair.js"; const root = join(dirname(fileURLToPath(import.meta.url)), ".."); const sqlDir = join(root, "spec", "sql"); const migrationPath = join(sqlDir, "migrations", "001-initial.sql"); +const migration002Path = join(sqlDir, "migrations", "002-provider-encoding-repair.sql"); const contractPath = join(sqlDir, "contract.json"); const header = `-- Athletic Standard SQL schema migration 001 (sql_schema_version 1). @@ -27,5 +30,8 @@ mkdirSync(dirname(migrationPath), { recursive: true }); writeFileSync(migrationPath, `${header}${publishedMigrationSql()}\n`); console.log(`wrote spec/sql/migrations/001-initial.sql`); +writeFileSync(migration002Path, `${MIGRATION_002_FILE_HEADER}${PROVIDER_ENCODING_REPAIR_SQL}\n`); +console.log(`wrote spec/sql/migrations/002-provider-encoding-repair.sql`); + writeFileSync(contractPath, JSON.stringify(buildSqlContractDocument(), null, 2) + "\n"); console.log(`wrote spec/sql/contract.json`); diff --git a/scripts/performance/generate-database.ts b/scripts/performance/generate-database.ts index 982ea2e5..6180512d 100644 --- a/scripts/performance/generate-database.ts +++ b/scripts/performance/generate-database.ts @@ -312,7 +312,7 @@ async function addBulkSamples( json_extract(sample.data_json, '$.recorded_at'), json_extract(sample.data_json, '$.value.standard_value'), json_extract(sample.data_json, '$.value.standard_unit'), - 30000, + NULL, NULL, '${CREATED_AT}', sample.data_json diff --git a/skill/SKILL.md b/skill/SKILL.md index 1e474061..2e7bef3a 100644 --- a/skill/SKILL.md +++ b/skill/SKILL.md @@ -90,7 +90,8 @@ Set up: | `ath --update` | Update `ath` and refresh a skill already present | | `ath key` | Manage an optional terminal model-gateway key outside athlete data | | `ath models` | List gateway models or save a terminal default | -| `ath migrate` | Preview and apply a SQL schema migration after a verified backup | +| `ath migrate` | Preview and apply a SQL schema migration after a verified backup (needs `sqlite3` on PATH) | +| `ath repair` | Repair typed-table bytes after npm 1.0.0 imports; use `--from-revision` when typed columns disagree with the revision (needs `sqlite3` on PATH when candidates exist) | Import, export, and create: diff --git a/skill/references/cli.md b/skill/references/cli.md index 6dd0024b..8c262135 100644 --- a/skill/references/cli.md +++ b/skill/references/cli.md @@ -15,6 +15,7 @@ is offered, it shows the write and writes nothing. - [ath skill](#ath-skill) — where the agent skill is installed, and whether each copy is current - [ath skill install](#ath-skill-install) — copy the skill into .agents/skills and every harness folder here - [ath migrate](#ath-migrate) — preview and apply a SQL schema migration after a verified backup +- [ath repair](#ath-repair) — repair typed-table JSON bytes left by npm 1.0.0 provider imports - [ath import](#ath-import) — preview and import a v1 package or Apple Health, WHOOP, or Oura export - [ath conflicts](#ath-conflicts) — review and resolve the temporary conflicts from a package import - [ath conflicts show](#ath-conflicts-show) — show complete local and imported values from the current conflict preview @@ -58,6 +59,7 @@ Set up: init [options] create a new athlete.ath.sqlite here, with the well-known benchmarks defined skill [options] where the agent skill is installed, and whether each copy is current migrate [options] [file] preview and apply a SQL schema migration after a verified backup + repair [options] [file] repair typed-table JSON bytes left by npm 1.0.0 provider imports key [options] save or show a gateway key — never stored in the athlete file models [options] list live text models that can reason, or save your usual one @@ -108,6 +110,28 @@ Options: is here --json structured output, for an agent rather than a person -h, --help display help for command + + +Examples: + + Answer three questions, then write the file: + $ ath init + + Skip the questions: + $ ath init -y --name "Sam Reyes" --birth-year 1991 --sex female + +The file is created here, called athlete.ath.sqlite, with the well-known +benchmarks already defined. Nothing leaves your machine. + +For a complete v1 package restore, create an empty destination: + $ ath init -y --empty + $ ath import ./saved-package + $ ath import ./saved-package --yes + +The agent skill is written to .agents/skills, which Claude Code, Cursor, +Codex, and Gemini CLI read, and into any of .claude, .cursor, .codex, +.gemini, or .github already here. An agent in this folder then knows how +to read and write the file. Pass --no-skill to skip that. ``` ## ath skill @@ -124,6 +148,25 @@ Options: Commands: install [options] copy the skill into .agents/skills and every harness folder here + + +Examples: + + Where the skill is installed, and whether each copy is current: + $ ath skill + + Upgrade ath, and replace the skill here if one is already installed: + $ ath --update + + Replace the skill without upgrading ath: + $ ath skill install + +The skill is a folder an agent reads to learn the file and the commands. +ath init writes it to .agents/skills and into any harness folder already +here. Each copy carries its version. When a copy is older than the one +this ath ships, other commands say so once on stderr. `ath --update` +replaces an installed copy after upgrading ath. This command replaces +it without upgrading. ``` ## ath skill install @@ -159,6 +202,60 @@ Options: --json structured preview; never confirms the migration -h, --help display help for command + + +Examples: + + Preview the SQL schema migration plan: + $ ath migrate + + Apply after reviewing the preview: + $ ath migrate -y --confirm-migration + + Return the preview as JSON for an agent: + $ ath migrate --json + +Migration never runs silently. A verified SQLite backup is created before the +first schema write. Non-interactive commands refuse an outdated database and +point here. + +Requires the `sqlite3` command-line tool on PATH for verified backups (same as +`ath repair` when repair candidates exist). +``` + +## ath repair + +``` +Usage: ath repair [options] [file] + +repair typed-table JSON bytes left by npm 1.0.0 provider imports + +Arguments: + file the database to repair (default: the one in this folder) + +Options: + --file repair a database other than the one in this folder + -y, --yes apply the repair after reviewing the preview + --from-revision copy typed-table JSON from the current revision when bytes disagree in meaning + --confirm-revision-align repeat the database ID exactly when using --from-revision + --dry-run show how many records would change and write nothing + --json structured preview only + -h, --help display help for command + + +Examples: + + Preview provider-encoding repair candidates: + $ ath repair + + Apply key-order-only repair after npm 1.0.0 provider imports: + $ ath repair -y + + Rebuild typed tables from the current revision when direct SQL changed values: + $ ath repair -y --from-revision --confirm-revision-align + +Each confirmed repair creates a new verified SQLite backup. Failed attempts leave +that backup on disk for restore; retry creates another backup. ``` ## ath import @@ -176,6 +273,34 @@ Options: -y, --yes apply a conflict-free preview --json structured preview; never confirms the write -h, --help display help for command + + +Examples: + + Preview a complete v1 package: + $ ath import ~/Backups/athletic-standard-export + + Apply it only after the preview has no conflicts: + $ ath import ~/Backups/athletic-standard-export --yes + + Preview a provider export: + $ ath import ~/Downloads/apple_health_export.zip + $ ath import ~/Downloads/whoop-export + $ ath import ~/Downloads/oura-export + +The default is always a preview. `--json` is also only a preview and +never confirms a write. Provider rows keep separate Apple Health, WHOOP, +and Oura source routes. Repeating an unchanged export reports matching +records. A corrected provider row creates a retained revision. + +For a v1 package, an empty database adopts the package database ID and +exact revision history. A database with the same ID can accept new +records and later revisions. Import never deletes a local record merely +because a package omits it. A different database ID is refused because +it may belong to another athlete. Unknown fields and records that v1 cannot +represent are listed in the preview and block the write. No flag discards them. +Athletic Standard 0.x JSON files are +prerelease formats and are not imported by v1. ``` ## ath conflicts @@ -194,6 +319,26 @@ Commands: resolve [options] choose the local, imported, or a corrected value for one conflict help [command] display help for command + + +Examples: + + Show complete local and imported values for every current conflict: + $ ath conflicts show + + Keep the local record: + $ ath conflicts resolve --choice local + + Accept the imported record as a new local revision: + $ ath conflicts resolve --choice imported + + Supply a complete corrected data object as a new local revision: + $ ath conflicts resolve --choice corrected \ + --data '{"...":"..."}' + +These commands change only a temporary conflict file. They do not change athlete +data. After every conflict has a choice, rerun the exact package import with +--yes. A changed package or database makes every saved choice stale. ``` ## ath conflicts show @@ -246,6 +391,24 @@ Options: --file export a database other than the one in this folder --json structured command result -h, --help display help for command + + +Examples: + + Write a complete portable package: + $ ath export ./athlete-backup + + Return the command result as JSON: + $ ath export ./athlete-backup --json + +SQLite remains the live record. The exported JSON package is a snapshot +and does not stay synchronized. The package includes complete current +records, retained revisions, deletions, dense samples, and permitted +attachments. The manifest is written last. + +The export has no time by default, so two exports of the same database +revision are byte-identical. Supply a fixed --exported-at only when a +manifest time is needed. ``` ## ath log @@ -272,6 +435,39 @@ Options: --dry-run show what would be written, and write nothing --json structured preview for an agent; never confirms the write -h, --help display help for command + + +Examples: + + A note, taken exactly as typed. No quotes needed: + $ ath log slept badly, about 5 hours + + A manual measurement. Name RMSSD or SDNN rather than saying only HRV: + $ ath log RMSSD 61 ms + + How something felt, with a rating: + $ ath log sore quads 4/5 + + A benchmark result: + $ ath log Fran in 4:41 rx + + A photo attached to one athlete report: + $ ath log Meal photo --attachment ./receipt.png + + A structured record from an agent. Run `ath log`, paste one record + object or an array, and press Ctrl-D: + $ ath log + {"record_type":"goal","data":{"authorship":{...},"title":"Fran under 4:30"}} + ^D + +Plain text creates one record. A structured JSON array creates one +validated batch. The preview shows every stable ID and complete record +before one transaction writes anything. `--json` returns that preview +and never confirms a write. Pass `--yes` only after approval. + +--attachment accepts PNG, JPEG, WebP, or PDF files up to 25 MiB. Pass it +more than once for several files. Exactly one athlete report or nutrition +entry in the batch owns them. No file is copied during a JSON preview. ``` ## ath link @@ -292,6 +488,23 @@ Options: --dry-run show what would change and write nothing --json structured preview; never confirms the write -h, --help display help for command + + +Examples: + + Find the stable IDs and current result revision: + $ ath records list --type benchmark_result + $ ath records list --type workout_session + + Preview the link: + $ ath link --revision 1 --json + + Write it after review: + $ ath link --revision 1 --yes + +The benchmark result owns this link. Linking creates a new revision of +that result. A stale --revision is refused rather than overwriting a +correction made after the preview. ``` ## ath correct @@ -315,6 +528,23 @@ Options: --dry-run show what would change and write nothing --json structured preview; never confirms the write -h, --help display help for command + + +Examples: + + Read the current revision and complete data: + $ ath records show --history --json + + Preview a complete replacement: + $ ath correct --revision 2 --data '{"...":"..."}' --json + + Write after review: + $ ath correct --revision 2 --data '{"...":"..."}' --yes + +Correction keeps the stable ID and complete earlier revisions. The +expected revision prevents a stale preview from overwriting newer data. +Use --attachment while correcting an athlete report or nutrition entry to +create and link a supported file in the same database revision. ``` ## ath delete @@ -334,6 +564,19 @@ Options: --dry-run show what would change and write nothing --json structured preview; never confirms the write -h, --help display help for command + + +Examples: + + Preview a normal deletion: + $ ath delete --revision 2 --json + + Hide it from current views after review: + $ ath delete --revision 2 --yes + +Normal deletion retains the complete record and revision history. Privacy +erasure is a different command because it removes values and cannot be +undone from the database. ``` ## ath erase @@ -361,6 +604,24 @@ Options: nothing --json structured preview; never confirms the erasure -h, --help display help for command + + +Examples: + + Preview the record, every dependent record, and each attachment: + $ ath erase --revision 2 --json + + Permanently erase after reviewing that preview: + $ ath erase --revision 2 --yes \ + --confirm-erasure + +Erasure removes the current record, its revision history, records that +depend on it, and their attachment files. It leaves only value-free +markers saying which stable IDs were erased. + +This cannot be undone from the database. Scripts need both --yes and an +exact --confirm-erasure value. Interactive use asks the same two +questions. `--json` and `--dry-run` never erase anything. ``` ## ath check @@ -378,6 +639,23 @@ Options: --validate-export also build and validate a temporary complete JSON package --json structured output, for an agent rather than a person -h, --help display help for command + + +Examples: + + Check the file in this folder: + $ ath check + + Check one somewhere else: + $ ath check ~/training/athlete.ath.sqlite + +An error means the database breaks a rule of the format and says which rule. +A warning means something is worth knowing but the database is still valid. +The check covers SQLite integrity, schema versions, foreign keys, domain rules, +record relationships, revision chains, session ordering, and attachments. + +Also build and validate a temporary complete JSON package: + $ ath check --validate-export ``` ## ath key @@ -394,6 +672,27 @@ Options: Commands: set save a Vercel or OpenRouter key in the OS password store clear [gateway] delete the saved gateway key from the password store + + +Examples: + + Save a Vercel or OpenRouter key in the computer's password store: + $ ath key set vercel + $ ath key set openrouter + + See which gateway is saved, not the key itself: + $ ath key + + Delete it: + $ ath key clear + +There is no Athletic Standard subscription. A key is only for calling a +model from a bare terminal. Inside a harness you do not need one. + +The key never goes in the athlete file. Agents read that file. If the +password store is missing, the command refuses. It will not write a +plaintext file. A key already in AI_GATEWAY_API_KEY or OPENROUTER_API_KEY +still works, for scripts. ``` ## ath key set @@ -438,6 +737,19 @@ Options: --file the athlete file whose default to save --json structured output, for an agent rather than a person -h, --help display help for command + + +Examples: + + Every live text model that can reason, including open weights: + $ ath models + + Save your usual model in athlete.ath.model next to athlete.ath.sqlite: + $ ath models --default openai/gpt-oss-120b + +Needs a gateway key. The list is fetched each time, so a new open-weight +model appears without a new ath. Image, audio, and embedding models are +out. We do not pick a favourite lab for you. ``` ## ath predict @@ -461,6 +773,28 @@ Options: --dry-run show the prediction, and write nothing --json evidence for a harness, not a prediction -h, --help display help for command + + +Examples: + + Predict Fran. Needs a gateway key in a bare terminal: + $ ath models + $ ath predict fran --model qwen/qwen3-235b-a22b + + Save a usual model, then predict without naming it: + $ ath models --default openai/gpt-oss-120b + $ ath predict fran + + Evidence for a harness, not a prediction. No key needed: + $ ath predict fran --json + +A prediction needs a model. In Claude Code, Cursor, or Codex the model +is already there: pull evidence with --json, reason, write with +`ath log`. In a bare terminal this command calls the model you chose, +prints the number, and asks once before writing. + +--as-of hides everything after that day and does not write. Replaying +the past is `ath backtest`. ``` ## ath backtest @@ -480,6 +814,23 @@ Options: -y, --yes do not ask before a long --all run --json structured output, for an agent rather than a person -h, --help display help for command + + +Examples: + + Replay history with the models you name: + $ ath backtest --model qwen/qwen3-235b-a22b --model openai/gpt-oss-120b + + Every live text model that can reason, after showing the count: + $ ath backtest --all + +A prediction needs a model, so a key is required. No key → refuse. In a +harness, daily predictions use the harness model; this command is for +comparing models on a history you already have. + +A result is replayed only when an earlier result on the same benchmark +exists. Evidence is as of the day before. The athlete file is not +written. The report's summary is the later share payload. ``` ## ath share @@ -493,6 +844,15 @@ Options: --file look next to a file other than the one in this folder --json structured output, for an agent rather than a person -h, --help display help for command + + +Examples: + + Name the latest backtest report: + $ ath share + +Not built yet. The shareable part of a backtest is the summary in the +report file this names. ``` ## ath grade @@ -516,6 +876,27 @@ Options: --dry-run show what would be written, and write nothing --json structured preview; never confirms the write -h, --help display help for command + + +Examples: + + Find the prediction and result IDs: + $ ath records list --type prediction + $ ath records list --type benchmark_result + + Preview the exact link and grade: + $ ath grade --result --json + + Write after review: + $ ath grade --result --yes + +`ath grade` never logs a result. It grades two records that already +exist. It creates a stable prediction-result link when needed and saves +the deterministic arithmetic against exact revisions. + +A result inside the prediction's stated range is a hit. Anything else is +a miss. A prediction error analysis is a separate authored record written +through structured `ath log`, not through a grade flag. ``` ## ath calculate @@ -549,6 +930,45 @@ Options: --file read a database other than the one in this folder --json structured calculation receipt -h, --help display help for command + + +Examples: + + A 90-day baseline, kept separate for each source: + $ ath calculate baseline hrv_rmssd --from 2026-07-01 --to 2026-09-28 + + Daily totals in an explicit calendar timezone: + $ ath calculate summary steps --group day --from 2026-09-01 \ + --to 2026-09-30 --timezone America/Chicago + + Compare two sources without pooling them: + $ ath calculate compare-sources resting_heart_rate \ + --source --compare-source + + Correlate same-day means: + $ ath calculate correlation hrv_rmssd --other-quantity resting_heart_rate \ + --source --timezone America/Chicago + + Baseline WHOOP recovery scores that have an absolute source time: + $ ath calculate baseline recovery --record-kind provider-score + + Summarize Oura readiness by Oura's own assigned day: + $ ath calculate provider-period-summary readiness \ + --record-kind provider-score --period-type oura_day_unspecified + +Named operations are summary, baseline, trend, coverage, compare-sources, +correlation, workout-drift, and provider-period-summary. The provider-period +operation requires --period-type and never turns that period into a calendar day. + +Record kinds are measurement, provider-score, provider-summary, and +session-summary. Measurement is the default. Naming the kind keeps measurements, +scores, and source-reported totals separate even when their names are similar. + +The result names its method, exact record revisions, exclusions, sources, date +range, and timezone or provider period when one was used. + +Manual sources never enter these device calculations. Different sources, +RMSSD and SDNN, temperature types, and distance types are never pooled. ``` ## ath series @@ -581,6 +1001,26 @@ Options: --json structured output, for an agent rather than a person --file read a file other than the one in this folder -h, --help display help for command + + +Examples: + + One row per day: + $ ath series heart_rate + + A window, and one device: + $ ath series hrv_beats --from 2026-08-01 --to 2026-08-31 --source whoop-1 + + Every sample, not a daily summary: + $ ath series heart_rate --raw --from 2026-08-14 --to 2026-08-14 + +Calendar days use the timezone saved in the athlete profile. Pass a different +one explicitly when needed: + $ ath series heart_rate --from 2026-08-14 --to 2026-08-14 --timezone America/Denver + +Dense samples live in SQLite. This command reads them without replacing the +provider summaries that may describe the same workout or night. `ath stats` +lists which series exist. ``` ## ath stats @@ -597,6 +1037,25 @@ Options: --file summarize a database other than the one in this folder --json structured output, for an agent rather than a person -h, --help display help for command + + +Examples: + + What is in the file, and where it came from: + $ ath stats + + As data, for an agent: + $ ath stats --json + +Baselines are listed per source and never averaged across them, because +two devices measuring one thing give two answers. Each carries how many +observations it rests on, over what days, and the rule used. + +Each source also lists the devices seen writing under it, with the days +each one covered — which is where a replaced watch becomes visible. + +Predictions are counted by who made them, so you can see which agent and +model has actually been right about you. ``` ## ath records @@ -614,6 +1073,25 @@ Commands: show [options] show one record, one revision, its history, or its links help [command] display help for command + + +Examples: + + Find stable IDs for all current records: + $ ath records list + + List only predictions: + $ ath records list --type prediction + + Show one record and its complete revision timeline: + $ ath records show 01890f3e-e7d3-7cc0-88c8-000000000010 --history + + Show the records it links to and the records that link to it: + $ ath records show 01890f3e-e7d3-7cc0-88c8-000000000010 --links + +`ath records list` is for finding stable IDs. `ath records show` reads one +logical record, a named revision, its history, and its links. Use `ath stats` +for the fixed overview and `ath series` for dense samples. ``` ## ath records list diff --git a/spec/sql/README.md b/spec/sql/README.md index af08cebc..f5f28349 100644 --- a/spec/sql/README.md +++ b/spec/sql/README.md @@ -34,13 +34,20 @@ set: ```sql PRAGMA application_id = 0x41544831; -PRAGMA user_version = 1; +PRAGMA user_version = ; ``` `application_id` marks the file as Athletic Standard (`ATH1`). `user_version` must match `database_metadata.sql_schema_version`. See `contract.json` for the current version number. +Read-only commands (`check`, `stats`, `migrate --dry-run`, and similar) must not +write `PRAGMA user_version` or otherwise change the database file. If +`PRAGMA user_version` does not match `database_metadata.sql_schema_version`, every +command refuses until the file is fixed. Restore from a verified migration or repair +backup, or build a new database with `ath init --empty` and `ath import` from a +complete JSON package exported earlier. + ## Write transactions SQLite resets `defer_foreign_keys` after each `COMMIT` or `ROLLBACK`. Do not set it @@ -61,6 +68,7 @@ Then run the record steps below and `COMMIT`. On failure, `ROLLBACK`. | Order | File | `sql_schema_version` after apply | |---|---|---| | 1 | `migrations/001-initial.sql` | 1 | +| 2 | `migrations/002-provider-encoding-repair.sql` | 2 | Rules: @@ -69,11 +77,16 @@ Rules: - After `001-initial.sql`, the runner inserts one `database_metadata` row and one `database_state` row, then sets the file header pragmas above. The runner supplies `database_id` and `created_at`. They are not embedded in the SQL file. +- Migration `002-provider-encoding-repair.sql` bumps `database_metadata` to schema 2. + The runner aligns typed-table `data_json` to `record_revisions.record_json` inside + the same write transaction using semantic equality (key-order-only mismatches from + npm 1.0.0 provider imports). It sets `PRAGMA user_version = 2` before `COMMIT`. The + runner bumps `database_state.current_revision` when at least one row changes. - Roll back the transaction on failure. A failed migration must leave the prior file usable. -Forward upgrades from earlier published SQL versions will be added here when they -exist. v1.0.0 ships only schema version 1. +npm `athleticstandard@1.0.0` ships SQL schema version 1. npm `1.1.0` adds migration +002 for existing databases created by `1.0.0`. ## Stable read views diff --git a/spec/sql/contract.json b/spec/sql/contract.json index b286d802..84ac9c7a 100644 --- a/spec/sql/contract.json +++ b/spec/sql/contract.json @@ -1,6 +1,6 @@ { "contract": "athleticstandard-sql", - "sql_schema_version": 1, + "sql_schema_version": 2, "minimum_sqlite_version": "3.45.0", "user_version_mirror": { "description": "On local SQLite files, PRAGMA user_version equals database_metadata.sql_schema_version after creation.", @@ -21,6 +21,11 @@ "version": 1, "file": "migrations/001-initial.sql", "description": "Initial Athletic Standard v1 schema, enforcement triggers, and stable read views." + }, + { + "version": 2, + "file": "migrations/002-provider-encoding-repair.sql", + "description": "Repair typed-table JSON bytes after npm 1.0.0 provider imports without changing record content." } ], "metadata_insert": { @@ -31,7 +36,7 @@ ], "header_pragmas": [ "PRAGMA application_id = 1096042545;", - "PRAGMA user_version = 1;" + "PRAGMA user_version = 2;" ] }, "file_header_pragmas": { diff --git a/spec/sql/migrations/002-provider-encoding-repair.sql b/spec/sql/migrations/002-provider-encoding-repair.sql new file mode 100644 index 00000000..f4165fd8 --- /dev/null +++ b/spec/sql/migrations/002-provider-encoding-repair.sql @@ -0,0 +1,7 @@ +-- Athletic Standard SQL schema migration 002 (sql_schema_version 2). +-- Generated by pnpm generate:sql-contract. Do not edit by hand. +-- +-- Bumps database_metadata. Typed-table alignment runs in the migration runner (see +-- src/db/repair.ts). See spec/sql/README.md and spec/sql/contract.json. + +UPDATE database_metadata SET sql_schema_version = 2 WHERE singleton_id = 1; diff --git a/src/backtest.ts b/src/backtest.ts deleted file mode 100644 index d483e848..00000000 --- a/src/backtest.ts +++ /dev/null @@ -1,353 +0,0 @@ -/** - * `ath backtest` — replay history with a model, write a report, not the athlete - * file (D77). - * - * A result is replayed only when an earlier result on the same benchmark exists - * (D10). Evidence is as of the day before (D69). Grade math is the same as - * `ath grade`. - */ -import { writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { - ATHLETIC_STANDARD_VERSION, - type AthleticStandardFileT, - type BenchmarkT, - type GradeT, - type HardSignalT, - type ScoreT, -} from "./schema.js"; -import { evidenceFor } from "./context.js"; -import { scorePrediction } from "./grade.js"; -import { type GatewayName } from "./keyring.js"; -import { loadCatalog, requireOnList, resolveModel } from "./models.js"; -import { predictFromEvidence } from "./predict.js"; -import { PredictRefusal } from "./predict-errors.js"; -import { describeScore } from "./score.js"; -import { dayBefore, dayOf } from "./signals.js"; -import { localTimestamp } from "./log.js"; - -export type ResultSignal = Extract; - -export interface ReplayRow { - model: string; - benchmark: string; - as_of: string; - recorded_at: string; - actual: ScoreT; - predicted?: ScoreT; - range?: { low: ScoreT; high: ScoreT }; - grade?: GradeT; - history_depth: number; - error?: string; -} - -export interface DepthBucket { - n: number; - median_abs_error_pct: number | null; -} - -export interface ModelSummary { - model: string; - n: number; - n_failed: number; - median_abs_error_pct: number | null; - mean_abs_error_pct: number | null; - in_range_rate: number | null; - in_range: number; - by_history_depth: { - "1": DepthBucket; - "2-3": DepthBucket; - "4+": DepthBucket; - }; -} - -export interface BacktestSummary { - n_replayed: number; - n_skipped: number; - models: ModelSummary[]; - winner: string | null; -} - -export interface BacktestReport { - athleticstandard_version: string; - created_at: string; - gateway: GatewayName; - models: string[]; - replays: ReplayRow[]; - summary: BacktestSummary; -} - -export interface BacktestOptions { - models?: string[]; - all?: boolean; - gateway?: GatewayName; - now?: Date; -} - -export interface PlannedBacktest { - targets: ResultSignal[]; - skipped: number; - models: string[]; - gateway: GatewayName; -} - -/** - * Results that can be replayed: each has at least one earlier result on the - * same benchmark (D10). - */ -export function replayableResults(file: AthleticStandardFileT): { - targets: ResultSignal[]; - skipped: number; -} { - const results = file.hard_signals - .filter((s): s is ResultSignal => s.type === "benchmark_result") - .slice() - .sort((a, b) => Date.parse(a.recorded_at) - Date.parse(b.recorded_at)); - - const seen = new Map(); - const targets: ResultSignal[] = []; - let skipped = 0; - for (const result of results) { - const prior = seen.get(result.benchmark) ?? 0; - if (prior === 0) skipped++; - else targets.push(result); - seen.set(result.benchmark, prior + 1); - } - return { targets, skipped }; -} - -export function historyDepth(file: AthleticStandardFileT, result: ResultSignal): number { - const day = dayOf(result.recorded_at); - return file.hard_signals.filter( - (s): s is ResultSignal => - s.type === "benchmark_result" && - s.benchmark === result.benchmark && - dayOf(s.recorded_at) < day, - ).length; -} - -export async function planBacktest( - file: AthleticStandardFileT, - athletePath: string, - options: BacktestOptions, -): Promise { - const { targets, skipped } = replayableResults(file); - if (targets.length === 0) { - throw new PredictRefusal( - `nothing to replay. A result is replayed only when an earlier result on the ` + - `same benchmark exists. Log a second attempt, or import a history that has one.`, - ); - } - - let models: string[]; - let gateway: GatewayName; - if (options.all) { - const catalog = await loadCatalog(options.gateway); - gateway = catalog.gateway; - models = catalog.models.map((m) => m.id); - if (models.length === 0) { - throw new PredictRefusal( - `the ${gateway} catalog marked no text models that can reason, so there is nothing to run.`, - ); - } - } else if (options.models && options.models.length > 0) { - const catalog = await loadCatalog(options.gateway); - gateway = catalog.gateway; - models = options.models.map((id) => requireOnList(id, catalog.models)); - } else { - const resolved = await resolveModel(athletePath, undefined, options.gateway); - gateway = resolved.gateway; - models = [resolved.model]; - } - - return { targets, skipped, models, gateway }; -} - -export async function runBacktest( - file: AthleticStandardFileT, - athletePath: string, - plan: PlannedBacktest, - now: Date = new Date(), -): Promise { - const replays: ReplayRow[] = []; - const byId = new Map(file.benchmarks.map((b) => [b.id, b])); - - for (const model of plan.models) { - for (const result of plan.targets) { - const benchmark = byId.get(result.benchmark); - if (!benchmark) continue; - const asOf = dayBefore(dayOf(result.recorded_at), 1); - const depth = historyDepth(file, result); - try { - const evidence = evidenceFor(file, athletePath, benchmark, asOf); - const prediction = await predictFromEvidence(file, evidence, { - gateway: plan.gateway, - model, - now, - }); - const grade = scorePrediction( - prediction.predicted, - result.result, - benchmark.score_type, - prediction.range, - ); - const row: ReplayRow = { - model, - benchmark: result.benchmark, - as_of: asOf, - recorded_at: result.recorded_at, - actual: result.result, - predicted: prediction.predicted, - grade, - history_depth: depth, - }; - if (prediction.range) row.range = prediction.range; - replays.push(row); - } catch (e) { - replays.push({ - model, - benchmark: result.benchmark, - as_of: asOf, - recorded_at: result.recorded_at, - actual: result.result, - history_depth: depth, - error: (e as Error).message, - }); - } - } - } - - const summary = summarise(replays, plan.models, plan.targets.length, plan.skipped); - return { - athleticstandard_version: ATHLETIC_STANDARD_VERSION, - created_at: localTimestamp(now), - gateway: plan.gateway, - models: plan.models, - replays, - summary, - }; -} - -export function summarise( - replays: ReplayRow[], - models: string[], - nReplayed: number, - nSkipped: number, -): BacktestSummary { - const rows = models.map((model) => summariseModel(model, replays.filter((r) => r.model === model))); - return { - n_replayed: nReplayed, - n_skipped: nSkipped, - models: rows, - winner: pickWinner(rows), - }; -} - -function summariseModel(model: string, rows: ReplayRow[]): ModelSummary { - const graded = rows.filter((r) => r.grade); - const errors = graded.map((r) => r.grade!.abs_error_pct); - const inRange = graded.filter((r) => r.grade!.in_range).length; - return { - model, - n: graded.length, - n_failed: rows.length - graded.length, - median_abs_error_pct: median(errors), - mean_abs_error_pct: mean(errors), - in_range_rate: graded.length === 0 ? null : Math.round((inRange / graded.length) * 1000) / 1000, - in_range: inRange, - by_history_depth: { - "1": bucket(graded, (d) => d === 1), - "2-3": bucket(graded, (d) => d >= 2 && d <= 3), - "4+": bucket(graded, (d) => d >= 4), - }, - }; -} - -function bucket(rows: ReplayRow[], take: (depth: number) => boolean): DepthBucket { - const errors = rows.filter((r) => take(r.history_depth) && r.grade).map((r) => r.grade!.abs_error_pct); - return { n: errors.length, median_abs_error_pct: median(errors) }; -} - -function pickWinner(rows: ModelSummary[]): string | null { - const ranked = rows - .filter((r) => r.n > 0 && r.median_abs_error_pct !== null) - .slice() - .sort((a, b) => { - const med = (a.median_abs_error_pct ?? Infinity) - (b.median_abs_error_pct ?? Infinity); - if (med !== 0) return med; - const avg = (a.mean_abs_error_pct ?? Infinity) - (b.mean_abs_error_pct ?? Infinity); - if (avg !== 0) return avg; - return b.n - a.n; - }); - return ranked[0]?.model ?? null; -} - -function median(values: number[]): number | null { - if (values.length === 0) return null; - const sorted = values.slice().sort((a, b) => a - b); - const mid = Math.floor(sorted.length / 2); - const raw = sorted.length % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!; - return Math.round(raw * 10) / 10; -} - -function mean(values: number[]): number | null { - if (values.length === 0) return null; - return Math.round((values.reduce((a, b) => a + b, 0) / values.length) * 10) / 10; -} - -export function reportFilename(now: Date): string { - const stamp = localTimestamp(now).replace(/[:.]/g, "").replace(/([+-]\d{4})$/, ""); - const day = stamp.slice(0, 10); - const time = stamp.slice(11, 17); - return `backtest-${day}T${time}.json`; -} - -export function writeReport(athletePath: string, report: BacktestReport, now: Date): string { - const path = join(dirname(athletePath), reportFilename(now)); - writeFileSync(path, `${JSON.stringify(report, null, 2)}\n`, "utf8"); - return path; -} - -export function renderReport(report: BacktestReport, path: string): string { - const lines = [ - `replayed ${report.summary.n_replayed} results` + - (report.summary.n_skipped > 0 - ? ` (${report.summary.n_skipped} skipped: first-ever result, nothing to anchor to)` - : ""), - ``, - ]; - - const cols = [ - { head: "model", get: (m: ModelSummary) => m.model }, - { head: "n", get: (m: ModelSummary) => String(m.n) }, - { head: "median", get: (m: ModelSummary) => pct(m.median_abs_error_pct) }, - { head: "mean", get: (m: ModelSummary) => pct(m.mean_abs_error_pct) }, - { head: "in-range", get: (m: ModelSummary) => (m.n === 0 ? "—" : `${m.in_range}/${m.n}`) }, - { head: "1 prior", get: (m: ModelSummary) => pct(m.by_history_depth["1"].median_abs_error_pct) }, - { head: "2-3", get: (m: ModelSummary) => pct(m.by_history_depth["2-3"].median_abs_error_pct) }, - { head: "4+", get: (m: ModelSummary) => pct(m.by_history_depth["4+"].median_abs_error_pct) }, - ]; - const widths = cols.map((c) => Math.max(c.head.length, ...report.summary.models.map((m) => c.get(m).length))); - const line = (cells: string[]) => cells.map((c, i) => c.padEnd(widths[i]!)).join(" "); - lines.push(line(cols.map((c) => c.head))); - lines.push(line(widths.map((w) => "-".repeat(w)))); - for (const row of report.summary.models) lines.push(line(cols.map((c) => c.get(row)))); - - lines.push(""); - lines.push( - report.summary.winner - ? `winner on this file: ${report.summary.winner}` - : `no winner — no model returned a graded prediction`, - ); - lines.push(`wrote ${path}`); - return lines.join("\n"); -} - -function pct(value: number | null): string { - return value === null ? "—" : `${value}%`; -} - -export function describeReplay(row: ReplayRow, benchmark: BenchmarkT): string { - if (row.error) return `${row.benchmark} ${row.as_of}: failed — ${row.error}`; - return `${row.benchmark} ${row.as_of}: predicted ${row.predicted ? describeScore(row.predicted) : "?"} vs ${describeScore(row.actual)} (${benchmark.score_type})`; -} diff --git a/src/cli.ts b/src/cli.ts index e3933191..1103906b 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,4 +1,22 @@ #!/usr/bin/env node import { buildProgram } from "./program.js"; +import { CliExitError } from "./cli/runtime.js"; +import { releaseAllOpenLocalDatabases } from "./db/client.js"; +import { formatSchemaValidationError } from "./db/validation-message.js"; -buildProgram().parse(); +async function main(): Promise { + try { + await buildProgram().parseAsync(process.argv); + } catch (error) { + if (error instanceof CliExitError) { + process.exitCode = error.exitCode; + } else { + console.error(`ath: ${formatSchemaValidationError(error)}`); + process.exitCode = 1; + } + } finally { + await releaseAllOpenLocalDatabases(); + } +} + +void main(); diff --git a/src/cli/preview-render.ts b/src/cli/preview-render.ts new file mode 100644 index 00000000..c9c7e9c6 --- /dev/null +++ b/src/cli/preview-render.ts @@ -0,0 +1,106 @@ +import type { LogPlan } from "../db/index.js"; + +export function renderImportPreview(preview: { + source_database_id: string; + source_database_revision: number; + destination_database_id: string; + destination_database_revision: number; + restore: boolean; + new_records: readonly string[]; + new_record_count: number; + matching_records: readonly string[]; + matching_record_count: number; + changed_records: readonly string[]; + changed_record_count: number; + record_lists_truncated: boolean; + conflicts: readonly { record_id?: string; message: string }[]; + unrepresentable_records: readonly string[]; + unknown_fields: readonly string[]; +}): string { + const lines = [ + `${preview.restore ? "restore" : "merge"} preview`, + ` source database: ${preview.source_database_id} revision ${preview.source_database_revision}`, + ` destination database: ${preview.destination_database_id} revision ${preview.destination_database_revision}`, + ` new records: ${preview.new_record_count}`, + ` matching records: ${preview.matching_record_count}`, + ` changed records: ${preview.changed_record_count}`, + ` conflicts: ${preview.conflicts.length}`, + ` unrepresentable: ${preview.unrepresentable_records.length}`, + ` unknown fields: ${preview.unknown_fields.length}`, + ]; + if (preview.record_lists_truncated) { + lines.push(" record ID lists: first 1,000 per category"); + } + for (const conflict of preview.conflicts) { + lines.push( + ` ${conflict.record_id === undefined ? "" : `${conflict.record_id}: `}` + + conflict.message, + ); + } + return lines.join("\n"); +} + +export function renderProviderImportPreview(preview: { + imported: string; + destination_database_revision: number; + new_records: readonly { record_id: string; record_type: string }[]; + matching_records: readonly { record_id: string; record_type: string }[]; + changed_records: readonly { + record_id: string; + record_type: string; + current_revision: number; + }[]; + conflicts: readonly { record_id?: string; message: string }[]; + skipped: Readonly>; +}): string { + const skippedCount = Object.values(preview.skipped).reduce( + (total, skipped) => total + skipped.count, + 0, + ); + const lines = [ + `${preview.imported} preview`, + ` destination revision: ${preview.destination_database_revision}`, + ` new records: ${preview.new_records.length}`, + ` matching records: ${preview.matching_records.length}`, + ` changed records: ${preview.changed_records.length}`, + ` conflicts: ${preview.conflicts.length}`, + ` skipped rows: ${skippedCount}`, + ]; + for (const conflict of preview.conflicts) { + lines.push( + ` ${conflict.record_id === undefined ? "" : `${conflict.record_id}: `}` + + conflict.message, + ); + } + for (const [reason, skipped] of Object.entries(preview.skipped)) { + lines.push( + ` skipped ${skipped.count} — ${reason}` + + `${skipped.example === undefined ? "" : ` (example: ${skipped.example})`}`, + ); + } + return lines.join("\n"); +} + +export function renderLogPlan(plan: LogPlan): string { + const lines = [ + `understood: ${plan.interpretation}`, + `records to write: ${plan.inputs.length}`, + ]; + for (const input of plan.inputs) { + lines.push(` ${input.record_id} ${input.record_type}`); + lines.push( + ...JSON.stringify(input.data, null, 2) + .split("\n") + .map((line) => ` ${line}`), + ); + if (input.extensions !== undefined) { + lines.push(" extensions"); + lines.push( + ...JSON.stringify(input.extensions, null, 2) + .split("\n") + .map((line) => ` ${line}`), + ); + } + } + return lines.join("\n"); +} diff --git a/src/cli/runtime.ts b/src/cli/runtime.ts new file mode 100644 index 00000000..f986c114 --- /dev/null +++ b/src/cli/runtime.ts @@ -0,0 +1,184 @@ +import { createInterface } from "node:readline/promises"; +import { findFile } from "../file.js"; +import { + executeConfirmedDatabaseMigration, + MigrationRequiredError, + markSkipWalCheckpointOnRelease, + openDatabase, + releaseLocalDatabase, + type AthleticDatabase, + type MigrationPreview, +} from "../db/index.js"; +import { formatSchemaValidationError } from "../db/validation-message.js"; + +let terminalAnswerForTests: ((question: string) => Promise) | undefined; + +/** Test hook. Production asks on the real terminal. */ +export function useTerminalAnswer( + answer: ((question: string) => Promise) | undefined, +): void { + terminalAnswerForTests = answer; +} + +export class CliExitError extends Error { + readonly exitCode: number; + + constructor(message: string, exitCode = 1) { + super(message); + this.name = "CliExitError"; + this.exitCode = exitCode; + } +} + +export function fail(cause: unknown): never { + const message = formatSchemaValidationError(cause); + console.error(`ath: ${message}`); + throw new CliExitError(message); +} + +export function findOrFail(fileArg?: string): string { + try { + return findFile(fileArg); + } catch (error) { + return fail((error as Error).message); + } +} + +export async function askOnTerminal(question: string): Promise { + if (terminalAnswerForTests) return terminalAnswerForTests(question); + const { createReadStream } = await import("node:fs"); + let input: NodeJS.ReadableStream; + try { + input = + process.stdin.isTTY && process.stdin.readable + ? process.stdin + : createReadStream("/dev/tty"); + } catch { + return null; + } + const rl = createInterface({ input, output: process.stdout }); + try { + return (await rl.question(question)).trim(); + } catch { + return null; + } finally { + rl.close(); + } +} + +export async function confirmWrite( + opts: { yes?: boolean; dryRun?: boolean; json?: boolean }, + question: string, +): Promise { + if (opts.json || opts.dryRun) { + return false; + } + if (opts.yes) { + return true; + } + if (terminalAnswerForTests === undefined && !process.stdout.isTTY) { + fail( + "there is no terminal to ask on, so nothing was written. Pass --yes after reviewing the preview.", + ); + } + const answer = await askOnTerminal(`${question} [y] yes [n] no `); + return /^y(es)?$/i.test(answer ?? ""); +} + +export async function readStdin(): Promise { + if (process.stdin.isTTY) { + process.stderr.write("Paste the entry, then press Ctrl-D:\n"); + } + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk)); + return Buffer.concat(chunks).toString("utf8"); +} + +export async function interactiveMigrationOnOpen( + path: string, + preview: MigrationPreview, +): Promise { + console.log(JSON.stringify({ file: path, ...preview, write_confirmed: false }, null, 2)); + if (!preview.migration_needed) { + return await openDatabase(path, { + onSecurityWarning: (warning) => { + console.warn(`ath: warning: ${warning}`); + }, + }); + } + if (preview.planned_steps.length === 0) { + return fail(preview.compatibility_effect); + } + if (preview.planned_backup_path === null) { + return fail("SQL schema migration requires a local database file"); + } + if (!(await confirmWrite({}, "Create a verified backup and apply this migration?"))) { + return fail("migration was not confirmed; run ath migrate or answer yes when prompted on open"); + } + const secondConfirmation = + (await askOnTerminal(`Type the database ID ${preview.database_id} to confirm migration: `)) ?? + undefined; + if (secondConfirmation !== preview.database_id) { + return fail( + "second confirmation did not exactly match the database ID; nothing was migrated", + ); + } + + const database = await openDatabase(path, { + allowOutdatedSchema: true, + deferWal: true, + onSecurityWarning: (warning) => { + console.warn(`ath: warning: ${warning}`); + }, + }); + try { + const migrationOptions = { backupPath: preview.planned_backup_path }; + const result = await executeConfirmedDatabaseMigration(database, migrationOptions); + console.log( + `migrated SQL schema ${preview.source_sql_schema_version} to ${preview.target_sql_schema_version} ` + + `with verified backup at ${result.backup_path}`, + ); + return database; + } catch (error) { + await releaseLocalDatabase(database); + return fail((error as Error).message); + } +} + +export async function openReadOnlyOrFail(path: string, json = false): Promise { + try { + const database = await openDatabase(path, { + deferWal: true, + allowOutdatedSchema: true, + onSecurityWarning: (warning) => { + if (!json) console.warn(`ath: warning: ${warning}`); + }, + }); + markSkipWalCheckpointOnRelease(database); + return database; + } catch (error) { + if (error instanceof MigrationRequiredError) { + return fail(error.message); + } + return fail((error as Error).message); + } +} + +export async function openOrFail(path: string, json = false): Promise { + try { + return await openDatabase(path, { + deferWal: true, + onSecurityWarning: (warning) => { + if (!json) console.warn(`ath: warning: ${warning}`); + }, + }); + } catch (error) { + if (error instanceof MigrationRequiredError) { + if (json || !process.stdin.isTTY || !process.stdout.isTTY) { + return fail(error.message); + } + return await interactiveMigrationOnOpen(path, error.preview); + } + return fail((error as Error).message); + } +} diff --git a/src/context.ts b/src/context.ts deleted file mode 100644 index 3cd1bbdd..00000000 --- a/src/context.ts +++ /dev/null @@ -1,404 +0,0 @@ -/** - * The evidence a prediction rests on, assembled from the file. - * - * The worry this is built against: hand a model a tidy summary and it repeats the - * summary without reading anything. So the package always carries actual rows, and - * every summary carries the count, the window and the spread it came from — which - * means the reader can check a summary against the rows where the two overlap. - * - * Four sections, unchanged from [v0.1.0 §5](../build-history/v0.1.0/spec.md): - * the benchmark's own history, the recent window row by row, long-range averages - * with their receipts, and the track record of past predictions on this benchmark. - */ -import type { - AthleticStandardFileT, - BenchmarkT, - HardSignalT, - PredictionT, - ScoreT, - SoftSignalT, -} from "./schema.js"; -import { readingsFor } from "./readings.js"; -import { baselineFor } from "./stats.js"; -import { daysBetween, type Coverage } from "./coverage.js"; -import { dayBefore, TRACKED_TYPES } from "./signals.js"; - -/** How far back the row-by-row window reaches. */ -export const RECENT_DAYS = 28; - -export interface ResultRow { - benchmark: string; - recordedAt: string; - score: ScoreT; - scaling?: "rx" | "scaled" | undefined; - note?: string | undefined; - /** The session it was recorded in, when it has one (D48). */ - session?: { source: string; start: string; avgHr?: number | undefined } | undefined; -} - -export interface DayReading { - source: string; - type: string; - unit: string; - /** The reading, or the day's mean when the device wrote a stream. */ - value: number; - /** How many readings that day. One means the value is the reading itself. */ - n: number; - min?: number; - max?: number; -} - -/** - * A number a vendor computed, not one a sensor read (D27). - * - * Carried in the evidence because the skill already tells an agent these may - * corroborate a claim, and the miss dossier already shows them. Leaving them out of - * the one place a prediction is made meant an agent could weigh a WHOOP recovery - * score when explaining a miss and not when avoiding one (D70). - */ -export interface DayVendorScore { - source: string; - metric: string; - value: number; - scale: string; -} - -export interface DayRow { - day: string; - readings: DayReading[]; - sleep: { - source: string; - duration_s?: number | undefined; - time_in_bed_s?: number | undefined; - efficiency_pct?: number | undefined; - }[]; - sessions: { source: string; start: string; end: string; activity?: string; avgHr?: number }[]; - vendor: DayVendorScore[]; -} - -export interface BaselineRow { - source: string; - type: string; - unit: string; - mean: number; - sd: number; - coverage: Coverage; -} - -export interface TrackRow { - id: string; - createdAt: string; - predicted: ScoreT; - actual: ScoreT | null; - grade: PredictionT["grade"]; - lesson: string | null; - /** Who made it: the agent, the model, and the version of ath that wrote it (D66). */ - by: string; -} - -/** - * The most recent results this benchmark has, and how many were left behind. - * - * An athlete with years of Fran attempts would otherwise get every one of them - * printed, and an evidence package too long to read is one that gets skimmed. What - * is dropped is said out loud rather than silently trimmed (D71). - */ -export interface ResultHistory { - rows: ResultRow[]; - /** How many results exist in total, including the ones not shown. */ - total: number; - shown: number; -} - -export interface Evidence { - benchmark: BenchmarkT; - /** Everything after this day is hidden, which is what makes a backtest honest. */ - asOf: string; - from: string; - history: ResultHistory; - related: ResultHistory; - days: DayRow[]; - /** What the day-by-day rows rest on: days present against days in the window. */ - coverage: Coverage; - soft: SoftSignalT[]; - baselines: BaselineRow[]; - track: TrackRow[]; - /** What is missing or disagreeing, named rather than left to be noticed. */ - gaps: string[]; -} - -/** The most recent results this benchmark has. */ -export const MOST_RECENT_RESULTS = 20; -export const MOST_RECENT_RELATED = 10; - -const day = (ts: string) => ts.slice(0, 10); - -/** The workout session a result names, if the file still holds it. */ -function sessionOf( - file: AthleticStandardFileT, - result: Extract, -): ResultRow["session"] { - if (!result.session) return undefined; - const match = file.hard_signals.find( - (s): s is Extract => - s.type === "workout_session" && - s.source === result.session!.source && - s.start === result.session!.start, - ); - return { - source: result.session.source, - start: result.session.start, - avgHr: match?.aggregates.avg_hr_bpm, - }; -} - -function toRow(file: AthleticStandardFileT, r: Extract): ResultRow { - return { - benchmark: r.benchmark, - recordedAt: r.recorded_at, - score: r.result, - scaling: r.scaling, - note: r.note, - session: sessionOf(file, r), - }; -} - -/** - * Assemble the evidence for one benchmark. - * - * `asOf` hides everything after that day, including results, readings and - * predictions. A backtest that can see the answer is not a test. - */ -export function evidenceFor( - file: AthleticStandardFileT, - athleteFilePath: string, - benchmark: BenchmarkT, - asOf: string, -): Evidence { - const from = dayBefore(asOf, RECENT_DAYS - 1); - const upTo = (ts: string) => day(ts) <= asOf; - - const allResults = file.hard_signals.filter( - (s): s is Extract => - s.type === "benchmark_result" && upTo(s.recorded_at), - ); - - const history = mostRecent( - allResults.filter((r) => r.benchmark === benchmark.id), - MOST_RECENT_RESULTS, - file, - ); - - const sameKind = new Set( - file.benchmarks.filter((b) => b.kind === benchmark.kind && b.id !== benchmark.id).map((b) => b.id), - ); - const related = mostRecent( - allResults.filter((r) => sameKind.has(r.benchmark)), - MOST_RECENT_RELATED, - file, - ); - - // --- Section 2: the recent window, row by row --- - const sources = file.sources.map((s) => s.id); - const byDay = new Map(); - const rowFor = (d: string): DayRow => { - const existing = byDay.get(d); - if (existing) return existing; - const fresh: DayRow = { day: d, readings: [], sleep: [], sessions: [], vendor: [] }; - byDay.set(d, fresh); - return fresh; - }; - - for (const source of sources) { - for (const type of TRACKED_TYPES) { - const readings = readingsFor(file, athleteFilePath, type, source, { from, to: asOf }); - if (readings.length === 0) continue; - const grouped = new Map(); - for (const r of readings) grouped.set(day(r.at), [...(grouped.get(day(r.at)) ?? []), r]); - for (const [d, group] of grouped) { - const values = group.map((r) => r.value); - // A device that samples through the night writes hundreds of readings for one - // measurement. The day's mean carries its count and spread so it can still be - // checked, rather than printing a night of samples as though it were evidence. - const mean = Math.round((values.reduce((a, b) => a + b, 0) / values.length) * 10) / 10; - rowFor(d).readings.push({ - source, - type, - unit: group[0]!.unit, - value: mean, - n: values.length, - ...(values.length > 1 ? { min: Math.min(...values), max: Math.max(...values) } : {}), - }); - } - } - } - - for (const sig of file.hard_signals) { - if (sig.type === "sleep_session" && day(sig.end) >= from && day(sig.end) <= asOf) { - rowFor(day(sig.end)).sleep.push({ - source: sig.source, - duration_s: sig.aggregates.duration_s, - time_in_bed_s: sig.aggregates.time_in_bed_s, - efficiency_pct: sig.aggregates.efficiency_pct, - }); - } - if (sig.type === "workout_session" && day(sig.start) >= from && day(sig.start) <= asOf) { - rowFor(day(sig.start)).sessions.push({ - source: sig.source, - start: sig.start, - end: sig.end, - ...(sig.aggregates.activity ? { activity: sig.aggregates.activity } : {}), - ...(sig.aggregates.avg_hr_bpm ? { avgHr: sig.aggregates.avg_hr_bpm } : {}), - }); - } - if (sig.type === "vendor_score" && day(sig.recorded_at) >= from && day(sig.recorded_at) <= asOf) { - rowFor(day(sig.recorded_at)).vendor.push({ - source: sig.source, - metric: sig.metric, - value: sig.value, - scale: sig.scale, - }); - } - } - - const days = [...byDay.values()].sort((a, b) => a.day.localeCompare(b.day)); - const soft = file.soft_signals - .filter((s) => day(s.reported_at) >= from && day(s.reported_at) <= asOf) - .sort((a, b) => a.reported_at.localeCompare(b.reported_at)); - - // --- Section 3: long-range averages, per source and never pooled (D31) --- - // One baseline function, given a day to stop at. `--as-of` hides readings; it does - // not change how the mean is worked out (D69). - const baselines: BaselineRow[] = []; - for (const source of sources) { - for (const type of TRACKED_TYPES) { - const b = baselineFor(file, athleteFilePath, type, source, { asOf }); - if (b) baselines.push({ source, type, unit: unitOf(file, type, source), ...b }); - } - } - - // --- Section 4: the track record on this benchmark --- - const track: TrackRow[] = file.predictions - .filter((p) => p.benchmark === benchmark.id && day(p.created_at) <= asOf) - .sort((a, b) => a.created_at.localeCompare(b.created_at)) - .map((p) => ({ - id: p.id, - createdAt: p.created_at, - predicted: p.predicted, - actual: p.actual?.result ?? null, - grade: p.grade, - lesson: p.miss_analysis?.lesson ?? null, - by: - [p.agent, p.model].filter(Boolean).join(" running ") + - (p.ath_version ? `, on ath ${p.ath_version}` : ""), - })); - - // What the day-by-day section rests on, said as data rather than left to be - // counted off the table (D47). - const withAnything = days.filter( - (d) => d.readings.length > 0 || d.sleep.length > 0 || d.vendor.length > 0, - ); - const coverage: Coverage = { - n: days.reduce((total, d) => total + d.readings.length + d.sleep.length + d.vendor.length, 0), - from, - to: asOf, - days_present: withAnything.length, - days_expected: daysBetween(from, asOf), - source: "every source in the file, kept apart by row", - rule: `every reading, night and vendor score in the ${RECENT_DAYS} days to ${asOf}`, - }; - - return { - benchmark, - asOf, - from, - history, - related, - days, - coverage, - soft, - baselines, - track, - gaps: namedGaps({ from, asOf, days, history, baselines }), - }; -} - -/** The last `limit` results in time order, and how many were left behind (D71). */ -function mostRecent( - results: Extract[], - limit: number, - file: AthleticStandardFileT, -): ResultHistory { - const sorted = [...results].sort((a, b) => a.recorded_at.localeCompare(b.recorded_at)); - const rows = sorted.slice(-limit).map((r) => toRow(file, r)); - return { rows, total: sorted.length, shown: rows.length }; -} - -function unitOf(file: AthleticStandardFileT, type: string, source: string): string { - const point = file.hard_signals.find( - (s): s is Extract => - "unit" in s && s.type === type && s.source === source, - ); - if (point) return point.unit; - const series = file.hard_signals.find( - (s): s is Extract => - s.type === "series_ref" && s.quantity === type && s.source === source, - ); - return series?.unit ?? ""; -} - -/** - * What is missing, said out loud. - * - * An agent that has to notice a gap will sometimes not notice it. Three are worth - * naming every time: days with nothing recorded, a benchmark with too little history - * to extrapolate from, and two devices giving different answers for one measurement. - */ -function namedGaps(input: { - from: string; - asOf: string; - days: DayRow[]; - history: ResultHistory; - baselines: BaselineRow[]; -}): string[] { - const gaps: string[] = []; - - const expected = daysBetween(input.from, input.asOf); - const withData = new Set(input.days.filter((d) => d.readings.length > 0 || d.sleep.length > 0).map((d) => d.day)); - if (withData.size < expected) { - const missing = expected - withData.size; - gaps.push( - `${missing} of the ${expected} days from ${input.from} to ${input.asOf} have no measurements at all.`, - ); - } - - if (input.history.total === 0) { - gaps.push(`No prior result on this benchmark. There is nothing here to extrapolate from.`); - } else if (input.history.total === 1) { - gaps.push( - `Only one prior result on this benchmark (${day(input.history.rows[0]!.recordedAt)}). ` + - `A single point has no trend and no spread.`, - ); - } - - // Two devices measuring one quantity is two answers. Naming the disagreement is - // the honest move; picking one for the reader is not (D31). - const byType = new Map(); - for (const b of input.baselines) byType.set(b.type, [...(byType.get(b.type) ?? []), b]); - for (const [type, rows] of byType) { - if (rows.length < 2) continue; - const low = rows.reduce((a, b) => (a.mean <= b.mean ? a : b)); - const high = rows.reduce((a, b) => (a.mean >= b.mean ? a : b)); - const spread = high.mean - low.mean; - const tolerance = Math.max(low.sd, high.sd, Math.abs(low.mean) * 0.05); - if (spread > tolerance) { - gaps.push( - `${rows.length} sources measure ${type} and they disagree: ` + - rows.map((r) => `${r.source} ${r.mean}${r.unit}`).join(", ") + - `. They are never pooled, so pick the one you mean.`, - ); - } - } - - return gaps; -} diff --git a/src/db/backup.ts b/src/db/backup.ts index b1a132fb..140573c6 100644 --- a/src/db/backup.ts +++ b/src/db/backup.ts @@ -11,19 +11,28 @@ import { } from "./client.js"; import type { DatabaseMetadata } from "./migrate.js"; +let backupNameSequence = 0; + export function formatMigrationBackupTimestamp(date: Date): string { - return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); + const iso = date.toISOString().replace(/[-:]/g, ""); + return `${iso.replace("Z", "")}Z`; } export function defaultMigrationBackupPath(databasePath: string, now = new Date()): string { - return `${databasePath}.migration-backup.${formatMigrationBackupTimestamp(now)}.sqlite`; + backupNameSequence = (backupNameSequence + 1) % 10_000; + return `${databasePath}.migration-backup.${formatMigrationBackupTimestamp(now)}-${backupNameSequence}.sqlite`; +} + +export function defaultRepairBackupPath(databasePath: string, now = new Date()): string { + backupNameSequence = (backupNameSequence + 1) % 10_000; + return `${databasePath}.repair-backup.${formatMigrationBackupTimestamp(now)}-${backupNameSequence}.sqlite`; } function requireSqlite3Cli(): void { const probe = spawnSync("sqlite3", [":memory:", "SELECT 1;"], { encoding: "utf8" }); if (probe.status !== 0) { throw new Error( - "SQLite backup requires the sqlite3 command-line tool. Install SQLite 3.45 or newer.", + "SQLite backup requires the sqlite3 command-line tool on PATH.", ); } } @@ -184,6 +193,8 @@ export async function createVerifiedSqliteBackup( await chmod(backupPath, 0o600); } await verifySqliteBackup(sourceDatabase, backupPath, sourceMetadata); + await removeBackupFileIfPresent(`${backupPath}-wal`); + await removeBackupFileIfPresent(`${backupPath}-shm`); backupCreated = false; } catch (error) { if (backupCreated) { diff --git a/src/db/check-tables.ts b/src/db/check-tables.ts new file mode 100644 index 00000000..01dab42f --- /dev/null +++ b/src/db/check-tables.ts @@ -0,0 +1,26 @@ +export const typedTables: Readonly> = { + athlete_profile: "athlete_profile", + source: "sources", + source_device: "source_devices", + point_measurement: "point_measurements", + measurement_sample: "measurement_samples", + sleep_session: "sleep_sessions", + workout_session: "workout_sessions", + benchmark_result: "benchmark_results", + provider_summary: "provider_summaries", + provider_score: "provider_scores", + athlete_report: "athlete_reports", + nutrition_entry: "nutrition_entries", + attachment: "attachments", + benchmark_definition: "benchmark_definitions", + prediction: "predictions", + prediction_result_link: "prediction_result_links", + prediction_grade: "prediction_grades", + prediction_error_analysis: "prediction_error_analyses", + training_plan: "training_plans", + planned_session: "planned_sessions", + coaching_note: "coaching_notes", + saved_training_review: "saved_training_reviews", + goal: "goals", + nutrition_model_interpretation: "nutrition_model_interpretations", +}; diff --git a/src/db/check.ts b/src/db/check.ts index 108931db..fe6ed253 100644 --- a/src/db/check.ts +++ b/src/db/check.ts @@ -27,6 +27,10 @@ import { currentRecordPayloadFromRow, recordRevisionPayloadFromRow, } from "./revision-encoding.js"; +import type { Client } from "@libsql/client"; +import { typedTables } from "./check-tables.js"; +import { listTypedDenormalizedFindings } from "./typed-denormalized.js"; +import { formatSchemaValidationError } from "./validation-message.js"; export interface DatabaseCheckIssue { severity: "error" | "warning"; @@ -63,42 +67,6 @@ class CheckIssues extends Array { } } -const typedTables: Readonly> = { - athlete_profile: "athlete_profile", - source: "sources", - source_device: "source_devices", - point_measurement: "point_measurements", - measurement_sample: "measurement_samples", - sleep_session: "sleep_sessions", - workout_session: "workout_sessions", - benchmark_result: "benchmark_results", - provider_summary: "provider_summaries", - provider_score: "provider_scores", - athlete_report: "athlete_reports", - nutrition_entry: "nutrition_entries", - attachment: "attachments", - benchmark_definition: "benchmark_definitions", - prediction: "predictions", - prediction_result_link: "prediction_result_links", - prediction_grade: "prediction_grades", - prediction_error_analysis: "prediction_error_analyses", - training_plan: "training_plans", - planned_session: "planned_sessions", - coaching_note: "coaching_notes", - saved_training_review: "saved_training_reviews", - goal: "goals", - nutrition_model_interpretation: "nutrition_model_interpretations", -}; - -function validationMessage(error: { issues: readonly { path: PropertyKey[]; message: string }[] }): string { - const first = error.issues[0]; - if (first === undefined) { - return "record does not match its domain schema"; - } - const path = first.path.length === 0 ? "record" : first.path.join("."); - return `${path}: ${first.message}`; -} - async function checkAttachment( database: AthleticDatabase, record: Extract, @@ -282,7 +250,7 @@ export async function checkDatabase( severity: "error", check: "domain", record_id: currentAfter, - message: validationMessage(parsed.error), + message: formatSchemaValidationError(parsed.error), }); continue; } @@ -367,7 +335,7 @@ export async function checkDatabase( severity: "error", check: "revision", record_id: revisionAfterId, - message: validationMessage(parsed.error), + message: formatSchemaValidationError(parsed.error), }); } } @@ -430,7 +398,7 @@ export async function checkDatabase( severity: "error", check: "deletion", record_id: String(row.record_id), - message: validationMessage(parsed.error), + message: formatSchemaValidationError(parsed.error), }); } } @@ -467,7 +435,7 @@ export async function checkDatabase( severity: "error", check: "erasure_marker", record_id: String(row.record_id), - message: validationMessage(parsed.error), + message: formatSchemaValidationError(parsed.error), }); continue; } @@ -487,6 +455,25 @@ export async function checkDatabase( }); } + const denormalizedFindings = await listTypedDenormalizedFindings(client); + for (const finding of denormalizedFindings) { + if (finding.kind === "mismatch") { + issues.push({ + severity: "error", + check: "typed_denormalized", + record_id: finding.record_id, + message: "typed-table denormalized columns do not match the current revision", + }); + continue; + } + issues.push({ + severity: "error", + check: "typed_denormalized", + record_id: finding.record_id, + message: finding.message, + }); + } + for (const [recordType, table] of Object.entries(typedTables)) { const typedMismatches = await client.execute({ sql: ` diff --git a/src/db/client.ts b/src/db/client.ts index 2550355f..bd8fda0f 100644 --- a/src/db/client.ts +++ b/src/db/client.ts @@ -6,7 +6,7 @@ import { createClient, type Client, type ResultSet } from "@libsql/client"; export const SQLITE_APPLICATION_ID = 0x41544831; export const SQLITE_APPLICATION_MARKER = "ATH1"; export const SQLITE_BUSY_TIMEOUT_MS = 5_000; -export const SQL_SCHEMA_VERSION = 1; +export const SQL_SCHEMA_VERSION = 2; export interface AthleticDatabase { readonly url: string; @@ -16,6 +16,28 @@ export interface AthleticDatabase { } const clients = new WeakMap(); +const openLocalDatabases = new Set(); +const skipWalCheckpointOnRelease = new WeakMap(); + +export function markSkipWalCheckpointOnRelease(database: AthleticDatabase): void { + skipWalCheckpointOnRelease.set(database, true); +} + +export function trackOpenLocalDatabase(database: AthleticDatabase): void { + if (database.isLocal) { + openLocalDatabases.add(database); + } +} + +export function untrackOpenLocalDatabase(database: AthleticDatabase): void { + openLocalDatabases.delete(database); +} + +export async function releaseAllOpenLocalDatabases(): Promise { + for (const database of [...openLocalDatabases]) { + await releaseLocalDatabase(database); + } +} export function databaseClient(database: AthleticDatabase): Client { const client = clients.get(database); @@ -153,6 +175,56 @@ export async function enableLocalWal(database: AthleticDatabase): Promise } } +export function isSqliteBusy(error: unknown): boolean { + if (!(error instanceof Error)) { + return false; + } + const message = error.message.toUpperCase(); + if (message.includes("SQLITE_BUSY") || message.includes("DATABASE IS LOCKED")) { + return true; + } + return "code" in error && String((error as { code: unknown }).code).toUpperCase() === "SQLITE_BUSY"; +} + +/** After a rolled-back write, switch a connection back from WAL only when the file started in DELETE mode. */ +export async function tryRevertDeleteJournalModeAfterFailedWal( + database: AthleticDatabase, + journalBefore: string, +): Promise { + if (journalBefore === "wal") { + return; + } + try { + await databaseClient(database).execute("PRAGMA journal_mode = DELETE"); + } catch (error) { + if (isSqliteBusy(error)) { + return; + } + throw error; + } +} + +/** Close a local database and truncate WAL sidecars when possible. */ +export async function releaseLocalDatabase(database: AthleticDatabase): Promise { + if (!database.isLocal) { + database.close(); + return; + } + try { + const journalMode = String( + (await databaseClient(database).execute("PRAGMA journal_mode")).rows[0]?.journal_mode, + ).toLowerCase(); + if (journalMode === "wal" && skipWalCheckpointOnRelease.get(database) !== true) { + await databaseClient(database).execute("PRAGMA wal_checkpoint(TRUNCATE)"); + } + } catch { + // The file may already be closed or read-only. + } + skipWalCheckpointOnRelease.delete(database); + untrackOpenLocalDatabase(database); + database.close(); +} + async function chmodIfPresent(path: string, mode: number): Promise { try { await chmod(path, mode); diff --git a/src/db/durable-write.ts b/src/db/durable-write.ts new file mode 100644 index 00000000..d12d202f --- /dev/null +++ b/src/db/durable-write.ts @@ -0,0 +1,43 @@ +import { open, rename, unlink } from "node:fs/promises"; +import { dirname } from "node:path"; + +/** Writes bytes to a new path with fsync before the file is visible at the final name. */ +export async function writeOwnerOnlyDurable(path: string, bytes: Uint8Array): Promise { + const directory = dirname(path); + const temporary = `${path}.tmp-${process.pid}-${Date.now()}`; + const file = await open(temporary, "wx", 0o600); + try { + await file.writeFile(bytes); + await file.sync(); + } finally { + await file.close(); + } + await rename(temporary, path); + await syncParentDirectory(directory); +} + +/** + * Directory fsync keeps renames durable on Unix. Node throws EINVAL on Windows, + * where the file fsync above is enough for a single-file write. + */ +export async function syncParentDirectory(directory: string): Promise { + if (process.platform === "win32") { + return; + } + const directoryHandle = await open(directory, "r"); + try { + await directoryHandle.sync(); + } finally { + await directoryHandle.close(); + } +} + +export async function removeFileIfPresent(path: string): Promise { + try { + await unlink(path); + } catch (error) { + if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) { + throw error; + } + } +} diff --git a/src/db/export-staging.ts b/src/db/export-staging.ts new file mode 100644 index 00000000..038d6d79 --- /dev/null +++ b/src/db/export-staging.ts @@ -0,0 +1,76 @@ +import { lstat, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +/** Marker file written into every export staging directory this tool creates. */ +export const EXPORT_STAGING_MARKER = ".athletic-standard-export-staging"; + +export interface ExportStagingMarker { + pid: number; +} + +export function exportStagingDirectoryName(pid: number, timestampMs: number, finalName: string): string { + return `.ath-export-${pid}-${timestampMs}-${finalName}`; +} + +export async function writeExportStagingMarker(directory: string): Promise { + const marker: ExportStagingMarker = { pid: process.pid }; + await writeFile(join(directory, EXPORT_STAGING_MARKER), JSON.stringify(marker), { mode: 0o600 }); +} + +function isProcessAlive(pid: number): boolean { + if (pid <= 0) { + return false; + } + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function readExportStagingMarker( + directory: string, +): Promise { + try { + const raw = await readFile(join(directory, EXPORT_STAGING_MARKER), "utf8"); + const parsed = JSON.parse(raw) as ExportStagingMarker; + if (typeof parsed.pid === "number" && Number.isFinite(parsed.pid)) { + return { pid: parsed.pid }; + } + } catch { + return undefined; + } + return undefined; +} + +export async function cleanupStaleExportStagingDirectories( + parentDirectory: string, + exceptDirectory?: string, +): Promise { + for (const entry of await readdir(parentDirectory)) { + if (!entry.startsWith(".ath-export-")) { + continue; + } + const stalePath = join(parentDirectory, entry); + if (exceptDirectory !== undefined && stalePath === exceptDirectory) { + continue; + } + try { + const stat = await lstat(stalePath); + if (!stat.isDirectory()) { + continue; + } + const marker = await readExportStagingMarker(stalePath); + if (marker === undefined) { + continue; + } + if (isProcessAlive(marker.pid)) { + continue; + } + await rm(stalePath, { recursive: true, force: true }); + } catch { + // Best-effort cleanup of abandoned staging directories. + } + } +} diff --git a/src/db/export.ts b/src/db/export.ts index cbdf5406..ee36fc3a 100644 --- a/src/db/export.ts +++ b/src/db/export.ts @@ -1,12 +1,6 @@ import { createHash } from "node:crypto"; -import { - lstat, - mkdir, - open as openFile, - readFile, - rm, -} from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { lstat, mkdir, readFile, rename, rm, unlink } from "node:fs/promises"; +import { basename, dirname, join } from "node:path"; import type { Transaction } from "@libsql/client"; import { ATHLETIC_STANDARD_VERSION, @@ -41,6 +35,14 @@ import { currentRecordPayloadFromRow, recordRevisionPayloadFromRow, } from "./revision-encoding.js"; +import { syncParentDirectory, writeOwnerOnlyDurable } from "./durable-write.js"; +import { + cleanupStaleExportStagingDirectories, + EXPORT_STAGING_MARKER, + exportStagingDirectoryName, + writeExportStagingMarker, +} from "./export-staging.js"; +import { compareUtf8Keys, deterministicJson } from "./stable-json.js"; export interface ExportDatabaseOptions { exported_at?: string; @@ -53,37 +55,12 @@ export interface ExportDatabaseResult { manifest: ExportManifestT; } -function stableValue(value: unknown): unknown { - if (Array.isArray(value)) { - return value.map(stableValue); - } - if (value !== null && typeof value === "object") { - return Object.fromEntries( - Object.entries(value as Record) - .sort(([left], [right]) => left.localeCompare(right)) - .map(([key, child]) => [key, stableValue(child)]), - ); - } - return value; -} - -export function deterministicJson(value: unknown): Buffer { - return Buffer.from(`${JSON.stringify(stableValue(value), null, 2)}\n`, "utf8"); -} +export { deterministicJson } from "./stable-json.js"; function sha256(bytes: Uint8Array): string { return createHash("sha256").update(bytes).digest("hex"); } -async function writeOwnerOnly(path: string, bytes: Uint8Array): Promise { - const file = await openFile(path, "wx", 0o600); - try { - await file.writeFile(bytes); - } finally { - await file.close(); - } -} - function parseCurrentRow(row: Record): CurrentRecordT { return CurrentRecord.parse(currentRecordPayloadFromRow(row)); } @@ -438,7 +415,10 @@ export async function exportRecords( options.exported_at === undefined ? undefined : UtcTimestamp.parse(options.exported_at); - await refuseSymbolicLinkComponents(dirname(outputDirectory)); + const parentDirectory = dirname(outputDirectory); + const finalName = basename(outputDirectory); + await refuseSymbolicLinkComponents(parentDirectory); + await cleanupStaleExportStagingDirectories(parentDirectory); try { const existing = await lstat(outputDirectory); if (existing.isSymbolicLink()) { @@ -450,7 +430,12 @@ export async function exportRecords( throw error; } } - await mkdir(outputDirectory, { mode: 0o700 }); + const stagingDirectory = join( + parentDirectory, + exportStagingDirectoryName(process.pid, Date.now(), finalName), + ); + await mkdir(stagingDirectory, { mode: 0o700 }); + await writeExportStagingMarker(stagingDirectory); const transaction = await databaseClient(database).transaction("read"); try { @@ -477,8 +462,8 @@ export async function exportRecords( const deletions = await readDeletions(transaction); const erasureMarkers = await readErasureMarkers(transaction); const importKeys = await readImportKeys(transaction); - const seriesDirectory = join(outputDirectory, "series"); - const attachmentDirectory = join(outputDirectory, "attachments"); + const seriesDirectory = join(stagingDirectory, "series"); + const attachmentDirectory = join(stagingDirectory, "attachments"); const files: Array<{ file: string; sha256: string; byte_count: number }> = []; const seriesReferences: Array<{ file: string; @@ -543,7 +528,7 @@ export async function exportRecords( record_import_keys: history.importKeys, }); const bytes = deterministicJson(series); - await writeOwnerOnly(join(outputDirectory, relativePath), bytes); + await writeOwnerOnlyDurable(join(stagingDirectory, relativePath), bytes); const hash = sha256(bytes); files.push({ file: relativePath, @@ -577,7 +562,7 @@ export async function exportRecords( await mkdir(attachmentDirectory, { mode: 0o700 }); } for (const attachment of attachments.sort((left, right) => - left.record_id.localeCompare(right.record_id), + compareUtf8Keys(left.record_id, right.record_id), )) { const storedName = storedAttachmentName(attachment); const sourcePath = join( @@ -594,7 +579,7 @@ export async function exportRecords( throw new Error(`attachment does not match its record: ${attachment.record_id}`); } const relativePath = `attachments/${storedName}`; - await writeOwnerOnly(join(outputDirectory, relativePath), bytes); + await writeOwnerOnlyDurable(join(stagingDirectory, relativePath), bytes); files.push({ file: relativePath, sha256: attachment.data.sha256, @@ -614,8 +599,8 @@ export async function exportRecords( measurement_series_files: seriesReferences, }); const packageBytes = deterministicJson(packageDocument); - const packagePath = join(outputDirectory, "athlete.ath.json"); - await writeOwnerOnly(packagePath, packageBytes); + const packagePath = join(stagingDirectory, "athlete.ath.json"); + await writeOwnerOnlyDurable(packagePath, packageBytes); files.push({ file: "athlete.ath.json", sha256: sha256(packageBytes), @@ -627,16 +612,20 @@ export async function exportRecords( source_database_id: metadata.database_id, database_revision: databaseRevision, ...(exportedAt === undefined ? {} : { exported_at: exportedAt }), - files: files.sort((left, right) => left.file.localeCompare(right.file)), + files: files.sort((left, right) => compareUtf8Keys(left.file, right.file)), record_counts: await recordCounts(transaction), erasure_marker_count: erasureMarkers.length, }); const manifestBytes = deterministicJson(manifest); - await writeOwnerOnly( - join(outputDirectory, "export-manifest.json"), + await writeOwnerOnlyDurable( + join(stagingDirectory, "export-manifest.json"), manifestBytes, ); await transaction.commit(); + await syncParentDirectory(parentDirectory); + await rename(stagingDirectory, outputDirectory); + await unlink(join(outputDirectory, EXPORT_STAGING_MARKER)).catch(() => undefined); + await syncParentDirectory(parentDirectory); return { directory: outputDirectory, database_id: metadata.database_id, @@ -647,7 +636,7 @@ export async function exportRecords( if (!transaction.closed) { await transaction.rollback(); } - await rm(outputDirectory, { recursive: true, force: true }); + await rm(stagingDirectory, { recursive: true, force: true }); throw error; } finally { transaction.close(); diff --git a/src/db/index.ts b/src/db/index.ts index 4ed37b26..705c0e2f 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -2,11 +2,14 @@ export { SQL_SCHEMA_VERSION, SQLITE_APPLICATION_ID, SQLITE_APPLICATION_MARKER, + releaseLocalDatabase, + markSkipWalCheckpointOnRelease, type AthleticDatabase, } from "./client.js"; export { createVerifiedSqliteBackup, defaultMigrationBackupPath, + formatMigrationBackupTimestamp, sqlite3BackupDotCommand, } from "./backup.js"; export { @@ -61,6 +64,15 @@ export { type DatabaseCheckIssue, type DatabaseCheckResult, } from "./check.js"; +export { + countProviderEncodingRepairCandidates, + countRevisionAlignRepairCandidates, + executeConfirmedProviderEncodingRepair, + listRevisionAlignRepairRecordIds, + repairProviderEncoding, + type ConfirmedProviderRepairResult, + type ProviderEncodingRepairResult, +} from "./repair.js"; export { databaseStats, renderDatabaseStats, diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 34bf61c3..420cd7de 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -1,4 +1,8 @@ import { lstat, mkdir, open as openFile, unlink } from "node:fs/promises"; +import { PROVIDER_ENCODING_REPAIR_SQL } from "./migrations/002-provider-encoding-repair.js"; +import { repairProviderEncodingRows } from "./repair.js"; +import { withWriteTransaction } from "./transaction.js"; +import { incrementDatabaseRevision } from "./records.js"; import { dirname } from "node:path"; import type { Transaction } from "@libsql/client"; import { @@ -9,7 +13,10 @@ import { import { connectDatabase, databaseClient, + trackOpenLocalDatabase, + markSkipWalCheckpointOnRelease, enableLocalWal, + tryRevertDeleteJournalModeAfterFailedWal, parseDatabaseTarget, readApplicationId, readUserVersion, @@ -269,6 +276,7 @@ export async function createDatabase( await enableLocalWal(database); await installInitialSchema(database, databaseId, createdAt); await setOwnerOnlyDatabasePermissions(database); + trackOpenLocalDatabase(database); return database; } catch (error) { database.close(); @@ -433,6 +441,7 @@ export async function inspectDatabase( `SQLite user_version ${userVersion} does not match database metadata ${metadata.sql_schema_version}`, ); } + markSkipWalCheckpointOnRelease(database); return database; } catch (error) { database.close(); @@ -495,6 +504,7 @@ export async function openDatabase( if (options.deferWal !== true) { await enableLocalWal(database); } + trackOpenLocalDatabase(database); return database; } catch (error) { database.close(); @@ -515,6 +525,19 @@ async function applyMigrationStep( if (step === undefined) { throw new Error(`No migration is registered for SQL schema version ${targetVersion}`); } + if (targetVersion === 2) { + await withWriteTransaction(database, async (transaction) => { + const repaired = await repairProviderEncodingRows(transaction); + await transaction.executeMultiple(PROVIDER_ENCODING_REPAIR_SQL); + if (database.isLocal) { + await transaction.execute(`PRAGMA user_version = ${targetVersion}`); + } + if (repaired > 0) { + await incrementDatabaseRevision(transaction); + } + }); + return; + } throw new Error( `Migration ${step.file} is not implemented in this ath build (target SQL schema ${targetVersion})`, ); @@ -588,13 +611,81 @@ export async function executeConfirmedDatabaseMigration( throw new Error("Migration backup path is missing"); } + const fileIdentity = + database.localPath === undefined + ? undefined + : await lstat(database.localPath, { bigint: true }).then((stat) => ({ + device: stat.dev, + inode: stat.ino, + })); + const revisionBefore = Number( + ( + await databaseClient(database).execute( + "SELECT current_revision FROM database_state WHERE singleton_id = 1", + ) + ).rows[0]?.current_revision, + ); await createVerifiedSqliteBackup(database, database.localPath, backupPath, metadata); + if (fileIdentity !== undefined && database.localPath !== undefined) { + await assertSameFile(database.localPath, fileIdentity); + } + const revisionAfterBackup = Number( + ( + await databaseClient(database).execute( + "SELECT current_revision FROM database_state WHERE singleton_id = 1", + ) + ).rows[0]?.current_revision, + ); + if (revisionAfterBackup !== revisionBefore) { + throw new Error( + "Database revision changed during migration backup; stop other writers and retry", + ); + } + const journalBefore = String( + (await databaseClient(database).execute("PRAGMA journal_mode")).rows[0]?.journal_mode, + ).toLowerCase(); try { await enableLocalWal(database); + if (fileIdentity !== undefined && database.localPath !== undefined) { + await assertSameFile(database.localPath, fileIdentity); + } + const revisionBeforeMigrate = Number( + ( + await databaseClient(database).execute( + "SELECT current_revision FROM database_state WHERE singleton_id = 1", + ) + ).rows[0]?.current_revision, + ); + if (revisionBeforeMigrate !== revisionBefore) { + throw new Error("Database revision changed before migration could start"); + } await applyPendingDatabaseMigrations(database); } catch (error) { + try { + await tryRevertDeleteJournalModeAfterFailedWal(database, journalBefore); + } catch { + // Best-effort journal revert; the original migration failure is reported below. + } + const revisionAfterFailure = Number( + ( + await databaseClient(database).execute( + "SELECT current_revision FROM database_state WHERE singleton_id = 1", + ) + ).rows[0]?.current_revision, + ); + const cause = + error instanceof Error + ? error.message + : "migration step failed"; + const changed = revisionAfterFailure !== revisionBefore; + let detail = `Cause: ${cause}.`; + if (changed) { + detail += " The database revision changed; restore from the verified backup."; + } else { + detail += " The database revision did not change."; + } throw new Error( - `Migration failed after creating verified backup at ${backupPath}. The original database was not modified.`, + `Migration failed after creating verified backup at ${backupPath}. ${detail}`, { cause: error }, ); } diff --git a/src/db/migrations/002-provider-encoding-repair.ts b/src/db/migrations/002-provider-encoding-repair.ts new file mode 100644 index 00000000..5f64e88e --- /dev/null +++ b/src/db/migrations/002-provider-encoding-repair.ts @@ -0,0 +1,8 @@ +/** + * SQL schema version 2 metadata bump. Typed-table byte repair runs in the migration + * runner through repairProviderEncodingRows(), which copies record_json into data_json + * only when semanticJsonEqual says the values match. + */ +export const PROVIDER_ENCODING_REPAIR_SQL = ` +UPDATE database_metadata SET sql_schema_version = 2 WHERE singleton_id = 1; +`.trim(); diff --git a/src/db/records.ts b/src/db/records.ts index 9aaaf0f9..76f11040 100644 --- a/src/db/records.ts +++ b/src/db/records.ts @@ -15,6 +15,7 @@ import { type RecordRevisionT, type RecordTypeT, } from "../v1/schema.js"; +import { typedTables } from "./check-tables.js"; import { databaseClient, type AthleticDatabase } from "./client.js"; import { currentRecordPayloadFromRow, @@ -205,6 +206,237 @@ async function replaceAuthoredEvidence( } } +/** Denormalized typed-table columns derived the same way as upsertTypedRow. */ +export function typedMainRowFields( + record: CurrentRecordT, +): ReadonlyArray { + switch (record.record_type) { + case "athlete_profile": + return [["default_time_zone", nullable(record.data.default_time_zone)]]; + case "source": + return [ + ["source_type", record.data.source_type], + ["data_writer", record.data.data_writer], + ["data_route", record.data.data_route], + ["vendor", nullable(record.data.vendor)], + ["sensor_type", nullable(record.data.sensor_type)], + ]; + case "source_device": + return [ + ["source_id", record.data.source_id], + ["name", nullable(record.data.name)], + ["manufacturer", nullable(record.data.manufacturer)], + ["model", nullable(record.data.model)], + ["hardware", nullable(record.data.hardware)], + ["serial_number", nullable(record.data.serial_number)], + ["coverage_start_date", nullable(record.data.coverage_start_date)], + ["coverage_end_date", nullable(record.data.coverage_end_date)], + ["accepted_record_count", nullable(record.data.accepted_record_count)], + ]; + case "point_measurement": + return [ + ["source_id", record.data.source_id], + ["quantity", record.data.quantity], + ["recorded_at", nullable(record.data.recorded_at)], + ["standard_value", record.data.value.standard_value], + ["standard_unit", record.data.value.standard_unit], + ["provider_record_id", nullable(record.data.provider_record_id)], + ["received_at", record.data.received_at], + ]; + case "measurement_sample": + return [ + ["source_id", record.data.source_id], + ["quantity", record.data.quantity], + ["recorded_at", record.data.recorded_at], + ["standard_value", record.data.value.standard_value], + ["standard_unit", record.data.value.standard_unit], + ["duration_ms", nullable(record.data.duration_ms)], + ["provider_record_id", nullable(record.data.provider_record_id)], + ["received_at", record.data.received_at], + ]; + case "sleep_session": + return [ + ["source_id", record.data.source_id], + ["start_at", record.data.start_at], + ["end_at", record.data.end_at], + ["provider_record_id", nullable(record.data.provider_record_id)], + ["received_at", record.data.received_at], + ]; + case "workout_session": + return [ + ["source_id", record.data.source_id], + ["start_at", record.data.start_at], + ["end_at", record.data.end_at], + ["activity_type", nullable(record.data.activity_type)], + ["provider_record_id", nullable(record.data.provider_record_id)], + ["received_at", record.data.received_at], + ]; + case "benchmark_result": + return [ + ["source_id", record.data.source_id], + ["benchmark_definition_id", record.data.benchmark_definition_id], + ["recorded_at", record.data.recorded_at], + ["workout_session_id", nullable(record.data.workout_session_id)], + ["provider_record_id", nullable(record.data.provider_record_id)], + ["received_at", record.data.received_at], + ]; + case "provider_score": + return [ + ["source_id", record.data.source_id], + ["metric", record.data.metric], + ["recorded_at", nullable(record.data.recorded_at)], + ["standard_value", record.data.value.standard_value], + ["standard_unit", record.data.value.standard_unit], + ["scale", record.data.scale], + ["provider_record_id", nullable(record.data.provider_record_id)], + ["received_at", record.data.received_at], + ]; + case "provider_summary": + return [ + ["source_id", record.data.source_id], + ["summary_type", record.data.summary_type], + ["recorded_at", nullable(record.data.recorded_at)], + ["standard_value", record.data.value.standard_value], + ["standard_unit", record.data.value.standard_unit], + ["provider_record_id", nullable(record.data.provider_record_id)], + ["received_at", record.data.received_at], + ]; + case "athlete_report": + return [ + ["report_type", record.data.report_type], + ["reported_at", record.data.reported_at], + ]; + case "nutrition_entry": + return [ + ["reported_at", record.data.reported_at], + ["athlete_description", record.data.athlete_description], + ]; + case "attachment": + return [ + ["file_name", record.data.file_name], + ["media_type", record.data.media_type], + ["byte_count", record.data.byte_count], + ["sha256", record.data.sha256], + ]; + case "benchmark_definition": + return [ + ["benchmark_key", record.data.benchmark_key], + ["benchmark_type", record.data.benchmark_type], + ["score_type", record.data.score_type], + ["definition", record.data.definition], + ]; + case "prediction": + return [ + ["benchmark_definition_id", record.data.benchmark_definition_id], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + case "prediction_result_link": + return [ + ["prediction_id", record.data.prediction.record_id], + ["prediction_revision", record.data.prediction.revision], + ["benchmark_result_id", record.data.benchmark_result.record_id], + ["benchmark_result_revision", record.data.benchmark_result.revision], + ["linked_at", record.data.linked_at], + ["created_by_type", record.data.created_by.author_type], + ["content_version", record.data.content_version], + ["status", record.data.status], + ]; + case "prediction_grade": + return [ + ["prediction_result_link_id", record.data.prediction_result_link.record_id], + ["prediction_result_link_revision", record.data.prediction_result_link.revision], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ["signed_error", record.data.signed_error], + ["absolute_error_percentage", record.data.absolute_error_percentage], + ["result_in_predicted_range", record.data.result_in_predicted_range ? 1 : 0], + ]; + case "prediction_error_analysis": + return [ + ["prediction_grade_id", record.data.prediction_grade.record_id], + ["prediction_grade_revision", record.data.prediction_grade.revision], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + case "training_plan": + return [ + ["title", record.data.title], + ["start_date", nullable(record.data.start_date)], + ["end_date", nullable(record.data.end_date)], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + case "planned_session": + return [ + ["training_plan_id", nullable(record.data.training_plan_id)], + ["title", record.data.title], + ["scheduled_date", nullable(record.data.scheduled_date)], + ["scheduled_start_at", nullable(record.data.scheduled_start_at)], + ["completion_status", record.data.completion_status], + ["completed_workout_session_id", nullable(record.data.completed_workout_session_id)], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + case "coaching_note": + return [ + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + case "saved_training_review": + return [ + ["period_start", record.data.period_start], + ["period_end", record.data.period_end], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + case "goal": + return [ + ["title", record.data.title], + ["target_date", nullable(record.data.target_date)], + [ + "target_benchmark_definition_id", + nullable(record.data.target_benchmark_definition_id), + ], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + case "nutrition_model_interpretation": + return [ + ["nutrition_entry_id", record.data.nutrition_entry_id], + ["confidence", record.data.confidence], + ["authored_at", record.data.authorship.authored_at], + ["author_type", record.data.authorship.author.author_type], + ["content_version", record.data.authorship.content_version], + ["status", record.data.authorship.status], + ]; + } +} + +async function upsertTypedRowForRecord( + transaction: Transaction, + table: string, + record: CurrentRecordT, +): Promise { + await upsertTypedRow(transaction, table, record, typedMainRowFields(record)); +} + async function replaceAttachmentLinks( transaction: Transaction, recordId: string, @@ -234,42 +466,16 @@ export async function upsertTypedRecord( ): Promise { switch (record.record_type) { case "athlete_profile": - await upsertTypedRow(transaction, "athlete_profile", record, [ - ["default_time_zone", nullable(record.data.default_time_zone)], - ]); + await upsertTypedRowForRecord(transaction, "athlete_profile", record); break; case "source": - await upsertTypedRow(transaction, "sources", record, [ - ["source_type", record.data.source_type], - ["data_writer", record.data.data_writer], - ["data_route", record.data.data_route], - ["vendor", nullable(record.data.vendor)], - ["sensor_type", nullable(record.data.sensor_type)], - ]); + await upsertTypedRowForRecord(transaction, "sources", record); break; case "source_device": - await upsertTypedRow(transaction, "source_devices", record, [ - ["source_id", record.data.source_id], - ["name", nullable(record.data.name)], - ["manufacturer", nullable(record.data.manufacturer)], - ["model", nullable(record.data.model)], - ["hardware", nullable(record.data.hardware)], - ["serial_number", nullable(record.data.serial_number)], - ["coverage_start_date", nullable(record.data.coverage_start_date)], - ["coverage_end_date", nullable(record.data.coverage_end_date)], - ["accepted_record_count", nullable(record.data.accepted_record_count)], - ]); + await upsertTypedRowForRecord(transaction, "source_devices", record); break; case "point_measurement": - await upsertTypedRow(transaction, "point_measurements", record, [ - ["source_id", record.data.source_id], - ["quantity", record.data.quantity], - ["recorded_at", nullable(record.data.recorded_at)], - ["standard_value", record.data.value.standard_value], - ["standard_unit", record.data.value.standard_unit], - ["provider_record_id", nullable(record.data.provider_record_id)], - ["received_at", record.data.received_at], - ]); + await upsertTypedRowForRecord(transaction, "point_measurements", record); await replaceOrderedJsonChildren( transaction, "point_measurement_calculations", @@ -309,35 +515,13 @@ export async function upsertTypedRecord( } break; case "measurement_sample": - await upsertTypedRow(transaction, "measurement_samples", record, [ - ["source_id", record.data.source_id], - ["quantity", record.data.quantity], - ["recorded_at", record.data.recorded_at], - ["standard_value", record.data.value.standard_value], - ["standard_unit", record.data.value.standard_unit], - ["duration_ms", nullable(record.data.duration_ms)], - ["provider_record_id", nullable(record.data.provider_record_id)], - ["received_at", record.data.received_at], - ]); + await upsertTypedRowForRecord(transaction, "measurement_samples", record); break; case "sleep_session": - await upsertTypedRow(transaction, "sleep_sessions", record, [ - ["source_id", record.data.source_id], - ["start_at", record.data.start_at], - ["end_at", record.data.end_at], - ["provider_record_id", nullable(record.data.provider_record_id)], - ["received_at", record.data.received_at], - ]); + await upsertTypedRowForRecord(transaction, "sleep_sessions", record); break; case "workout_session": - await upsertTypedRow(transaction, "workout_sessions", record, [ - ["source_id", record.data.source_id], - ["start_at", record.data.start_at], - ["end_at", record.data.end_at], - ["activity_type", nullable(record.data.activity_type)], - ["provider_record_id", nullable(record.data.provider_record_id)], - ["received_at", record.data.received_at], - ]); + await upsertTypedRowForRecord(transaction, "workout_sessions", record); await replaceOrderedJsonChildren( transaction, "workout_session_segments", @@ -349,14 +533,7 @@ export async function upsertTypedRecord( ); break; case "benchmark_result": - await upsertTypedRow(transaction, "benchmark_results", record, [ - ["source_id", record.data.source_id], - ["benchmark_definition_id", record.data.benchmark_definition_id], - ["recorded_at", record.data.recorded_at], - ["workout_session_id", nullable(record.data.workout_session_id)], - ["provider_record_id", nullable(record.data.provider_record_id)], - ["received_at", record.data.received_at], - ]); + await upsertTypedRowForRecord(transaction, "benchmark_results", record); await replaceOrderedJsonChildren( transaction, "benchmark_result_segments", @@ -368,33 +545,13 @@ export async function upsertTypedRecord( ); break; case "provider_score": - await upsertTypedRow(transaction, "provider_scores", record, [ - ["source_id", record.data.source_id], - ["metric", record.data.metric], - ["recorded_at", nullable(record.data.recorded_at)], - ["standard_value", record.data.value.standard_value], - ["standard_unit", record.data.value.standard_unit], - ["scale", record.data.scale], - ["provider_record_id", nullable(record.data.provider_record_id)], - ["received_at", record.data.received_at], - ]); + await upsertTypedRowForRecord(transaction, "provider_scores", record); break; case "provider_summary": - await upsertTypedRow(transaction, "provider_summaries", record, [ - ["source_id", record.data.source_id], - ["summary_type", record.data.summary_type], - ["recorded_at", nullable(record.data.recorded_at)], - ["standard_value", record.data.value.standard_value], - ["standard_unit", record.data.value.standard_unit], - ["provider_record_id", nullable(record.data.provider_record_id)], - ["received_at", record.data.received_at], - ]); + await upsertTypedRowForRecord(transaction, "provider_summaries", record); break; case "athlete_report": - await upsertTypedRow(transaction, "athlete_reports", record, [ - ["report_type", record.data.report_type], - ["reported_at", record.data.reported_at], - ]); + await upsertTypedRowForRecord(transaction, "athlete_reports", record); await replaceAttachmentLinks( transaction, record.record_id, @@ -402,10 +559,7 @@ export async function upsertTypedRecord( ); break; case "nutrition_entry": - await upsertTypedRow(transaction, "nutrition_entries", record, [ - ["reported_at", record.data.reported_at], - ["athlete_description", record.data.athlete_description], - ]); + await upsertTypedRowForRecord(transaction, "nutrition_entries", record); await replaceOrderedJsonChildren( transaction, "reported_nutrition_items", @@ -422,64 +576,22 @@ export async function upsertTypedRecord( ); break; case "attachment": - await upsertTypedRow(transaction, "attachments", record, [ - ["file_name", record.data.file_name], - ["media_type", record.data.media_type], - ["byte_count", record.data.byte_count], - ["sha256", record.data.sha256], - ]); + await upsertTypedRowForRecord(transaction, "attachments", record); break; case "benchmark_definition": - await upsertTypedRow(transaction, "benchmark_definitions", record, [ - ["benchmark_key", record.data.benchmark_key], - ["benchmark_type", record.data.benchmark_type], - ["score_type", record.data.score_type], - ["definition", record.data.definition], - ]); + await upsertTypedRowForRecord(transaction, "benchmark_definitions", record); break; case "prediction": - await upsertTypedRow(transaction, "predictions", record, [ - ["benchmark_definition_id", record.data.benchmark_definition_id], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "predictions", record); break; case "prediction_result_link": - await upsertTypedRow(transaction, "prediction_result_links", record, [ - ["prediction_id", record.data.prediction.record_id], - ["prediction_revision", record.data.prediction.revision], - ["benchmark_result_id", record.data.benchmark_result.record_id], - ["benchmark_result_revision", record.data.benchmark_result.revision], - ["linked_at", record.data.linked_at], - ["created_by_type", record.data.created_by.author_type], - ["content_version", record.data.content_version], - ["status", record.data.status], - ]); + await upsertTypedRowForRecord(transaction, "prediction_result_links", record); break; case "prediction_grade": - await upsertTypedRow(transaction, "prediction_grades", record, [ - ["prediction_result_link_id", record.data.prediction_result_link.record_id], - ["prediction_result_link_revision", record.data.prediction_result_link.revision], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ["signed_error", record.data.signed_error], - ["absolute_error_percentage", record.data.absolute_error_percentage], - ["result_in_predicted_range", record.data.result_in_predicted_range ? 1 : 0], - ]); + await upsertTypedRowForRecord(transaction, "prediction_grades", record); break; case "prediction_error_analysis": - await upsertTypedRow(transaction, "prediction_error_analyses", record, [ - ["prediction_grade_id", record.data.prediction_grade.record_id], - ["prediction_grade_revision", record.data.prediction_grade.revision], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "prediction_error_analyses", record); await transaction.execute({ sql: "DELETE FROM prediction_error_causes WHERE prediction_error_analysis_id = ?", args: [record.record_id], @@ -506,29 +618,10 @@ export async function upsertTypedRecord( } break; case "training_plan": - await upsertTypedRow(transaction, "training_plans", record, [ - ["title", record.data.title], - ["start_date", nullable(record.data.start_date)], - ["end_date", nullable(record.data.end_date)], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "training_plans", record); break; case "planned_session": - await upsertTypedRow(transaction, "planned_sessions", record, [ - ["training_plan_id", nullable(record.data.training_plan_id)], - ["title", record.data.title], - ["scheduled_date", nullable(record.data.scheduled_date)], - ["scheduled_start_at", nullable(record.data.scheduled_start_at)], - ["completion_status", record.data.completion_status], - ["completed_workout_session_id", nullable(record.data.completed_workout_session_id)], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "planned_sessions", record); await replaceOrderedJsonChildren( transaction, "planned_session_blocks", @@ -540,46 +633,16 @@ export async function upsertTypedRecord( ); break; case "coaching_note": - await upsertTypedRow(transaction, "coaching_notes", record, [ - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "coaching_notes", record); break; case "saved_training_review": - await upsertTypedRow(transaction, "saved_training_reviews", record, [ - ["period_start", record.data.period_start], - ["period_end", record.data.period_end], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "saved_training_reviews", record); break; case "goal": - await upsertTypedRow(transaction, "goals", record, [ - ["title", record.data.title], - ["target_date", nullable(record.data.target_date)], - [ - "target_benchmark_definition_id", - nullable(record.data.target_benchmark_definition_id), - ], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "goals", record); break; case "nutrition_model_interpretation": - await upsertTypedRow(transaction, "nutrition_model_interpretations", record, [ - ["nutrition_entry_id", record.data.nutrition_entry_id], - ["confidence", record.data.confidence], - ["authored_at", record.data.authorship.authored_at], - ["author_type", record.data.authorship.author.author_type], - ["content_version", record.data.authorship.content_version], - ["status", record.data.authorship.status], - ]); + await upsertTypedRowForRecord(transaction, "nutrition_model_interpretations", record); break; } @@ -587,6 +650,46 @@ export async function upsertTypedRecord( await replaceAuthoredEvidence(transaction, record); } +/** Rebuild the typed table row and children from the current revision bytes. */ +export async function rebuildTypedRowFromCurrentRevision( + transaction: Transaction, + recordId: string, +): Promise { + const result = await transaction.execute({ + sql: ` + SELECT + records.record_id, + records.record_type, + records.current_revision, + records.created_at, + records.is_deleted, + record_revisions.record_json, + record_revisions.extensions_json + FROM records + JOIN record_revisions + ON record_revisions.record_id = records.record_id + AND record_revisions.revision = records.current_revision + WHERE records.record_id = ? + `, + args: [recordId], + }); + const row = result.rows[0]; + if (row === undefined) { + throw new Error(`record ${recordId} is missing its current revision`); + } + const recordJson = String(row.record_json); + const record = CurrentRecord.parse(currentRecordPayloadFromRow(row)); + await upsertTypedRecord(transaction, record); + const table = typedTables[record.record_type]; + if (table === undefined) { + throw new Error(`record type ${record.record_type} has no typed table`); + } + await transaction.execute({ + sql: `UPDATE ${table} SET data_json = ? WHERE record_id = ?`, + args: [recordJson, recordId], + }); +} + async function readTypedRevisionData( transaction: Transaction, recordId: string, diff --git a/src/db/repair.ts b/src/db/repair.ts new file mode 100644 index 00000000..a371603a --- /dev/null +++ b/src/db/repair.ts @@ -0,0 +1,348 @@ +import { lstat } from "node:fs/promises"; +import type { Transaction } from "@libsql/client"; +import { databaseClient, type AthleticDatabase } from "./client.js"; +import { typedTables } from "./check-tables.js"; +import { createVerifiedSqliteBackup, defaultRepairBackupPath } from "./backup.js"; +import { readDatabaseMetadata } from "./migrate.js"; +import { + incrementDatabaseRevision, + rebuildTypedRowFromCurrentRevision, +} from "./records.js"; +import { semanticJsonEqual } from "./stable-json.js"; +import { listTypedDenormalizedMismatchRecordIds } from "./typed-denormalized.js"; +import { withWriteTransaction } from "./transaction.js"; +import { formatSchemaValidationError } from "./validation-message.js"; + +export interface TypedTableMismatch { + record_id: string; + record_type: string; + encoding_only: boolean; +} + +async function listTypedTableMismatches( + database: AthleticDatabase, +): Promise { + const client = databaseClient(database); + const mismatches: TypedTableMismatch[] = []; + for (const [recordType, table] of Object.entries(typedTables)) { + const result = await client.execute({ + sql: ` + SELECT + records.record_id, + record_revisions.record_json, + ${table}.data_json AS typed_json + FROM records + JOIN record_revisions + ON record_revisions.record_id = records.record_id + AND record_revisions.revision = records.current_revision + JOIN ${table} ON ${table}.record_id = records.record_id + WHERE records.record_type = ? + AND ${table}.data_json <> record_revisions.record_json + ORDER BY records.record_id + `, + args: [recordType], + }); + for (const row of result.rows) { + const recordId = String(row.record_id); + const recordJson = String(row.record_json); + const typedJson = String(row.typed_json); + mismatches.push({ + record_id: recordId, + record_type: recordType, + encoding_only: semanticJsonEqual(recordJson, typedJson), + }); + } + } + return mismatches; +} + +async function listDenormalizedMismatchRecordIds( + database: AthleticDatabase, +): Promise { + return listTypedDenormalizedMismatchRecordIds(databaseClient(database)); +} + +export async function countProviderEncodingRepairCandidates( + database: AthleticDatabase, +): Promise { + const mismatches = await listTypedTableMismatches(database); + const encodingJsonIds = new Set( + mismatches.filter((row) => row.encoding_only).map((row) => row.record_id), + ); + const denormalizedIds = await listDenormalizedMismatchRecordIds(database); + const revisionAlignIds = new Set( + mismatches.filter((row) => !row.encoding_only).map((row) => row.record_id), + ); + const denormalizedOnly = denormalizedIds.filter((id) => !revisionAlignIds.has(id)); + return new Set([...encodingJsonIds, ...denormalizedOnly]).size; +} + +export async function countRevisionAlignRepairCandidates( + database: AthleticDatabase, +): Promise { + const mismatches = await listTypedTableMismatches(database); + return mismatches.filter((row) => !row.encoding_only).length; +} + +export async function listRevisionAlignRepairRecordIds( + database: AthleticDatabase, +): Promise { + const mismatches = await listTypedTableMismatches(database); + return mismatches.filter((row) => !row.encoding_only).map((row) => row.record_id); +} + +async function rebuildTypedRows( + transaction: Transaction, + recordIds: readonly string[], + options: { allowSemanticMismatch: boolean }, +): Promise { + if (recordIds.length === 0) { + return 0; + } + let repaired = 0; + for (const recordId of recordIds) { + const meta = await transaction.execute({ + sql: "SELECT record_type FROM records WHERE record_id = ?", + args: [recordId], + }); + const recordType = String(meta.rows[0]?.record_type); + const table = typedTables[recordType]; + if (table === undefined) { + throw new Error(`record ${recordId} has unsupported record type ${recordType}`); + } + const row = await transaction.execute({ + sql: ` + SELECT + record_revisions.record_json, + ${table}.data_json AS typed_json + FROM records + JOIN record_revisions + ON record_revisions.record_id = records.record_id + AND record_revisions.revision = records.current_revision + JOIN ${table} ON ${table}.record_id = records.record_id + WHERE records.record_id = ? + `, + args: [recordId], + }); + const match = row.rows[0]; + if (match === undefined) { + throw new Error(`record ${recordId} is missing typed-table data for repair`); + } + const recordJson = String(match.record_json); + const typedJson = String(match.typed_json); + if ( + recordJson !== typedJson && + !options.allowSemanticMismatch && + !semanticJsonEqual(recordJson, typedJson) + ) { + throw new Error( + `record ${recordId} has a typed-table mismatch that is not key-order only; ` + + `run ath repair --from-revision after reviewing affected records, or restore from backup`, + ); + } + await rebuildTypedRowFromCurrentRevision(transaction, recordId); + repaired++; + } + return repaired; +} + +export async function repairProviderEncodingRows( + transaction: Transaction, +): Promise { + const allIds: string[] = []; + for (const [recordType, table] of Object.entries(typedTables)) { + const rows = await transaction.execute({ + sql: ` + SELECT records.record_id + FROM records + JOIN record_revisions + ON record_revisions.record_id = records.record_id + AND record_revisions.revision = records.current_revision + JOIN ${table} ON ${table}.record_id = records.record_id + WHERE records.record_type = ? + AND ${table}.data_json <> record_revisions.record_json + `, + args: [recordType], + }); + for (const row of rows.rows) { + allIds.push(String(row.record_id)); + } + } + return rebuildTypedRows(transaction, allIds, { allowSemanticMismatch: false }); +} + +export async function repairTypedTablesFromRevisionRows( + transaction: Transaction, + recordIds: readonly string[], +): Promise { + return rebuildTypedRows(transaction, recordIds, { allowSemanticMismatch: true }); +} + +export interface ProviderEncodingRepairResult { + repaired_record_count: number; + database_revision: number; +} + +export interface ConfirmedProviderRepairResult { + backup_path: string; + repaired_record_count: number; + revision_align_record_count: number; + database_revision: number; +} + +export interface ExecuteConfirmedRepairOptions { + backupPath?: string; + now?: Date; + fromRevision?: boolean; +} + +async function readDatabaseRevision(database: AthleticDatabase): Promise { + return Number( + ( + await databaseClient(database).execute( + "SELECT current_revision FROM database_state WHERE singleton_id = 1", + ) + ).rows[0]?.current_revision, + ); +} + +export async function executeConfirmedProviderEncodingRepair( + database: AthleticDatabase, + options: ExecuteConfirmedRepairOptions = {}, +): Promise { + if (database.localPath === undefined) { + throw new Error("Provider-encoding repair requires a local database file"); + } + const metadata = await readDatabaseMetadata(database); + const mismatches = await listTypedTableMismatches(database); + const encodingCandidates = mismatches.filter((row) => row.encoding_only); + const revisionCandidates = mismatches.filter((row) => !row.encoding_only); + const denormalizedIds = await listDenormalizedMismatchRecordIds(database); + const revisionAlignIdSet = new Set(revisionCandidates.map((row) => row.record_id)); + const denormalizedOnlyIds = denormalizedIds.filter((id) => !revisionAlignIdSet.has(id)); + const encodingRecordIds = [ + ...new Set([ + ...encodingCandidates.map((row) => row.record_id), + ...denormalizedOnlyIds, + ]), + ]; + if ( + mismatches.length === 0 && + denormalizedOnlyIds.length === 0 + ) { + const revision = await readDatabaseRevision(database); + return { + backup_path: "", + repaired_record_count: 0, + revision_align_record_count: 0, + database_revision: revision, + }; + } + if (revisionCandidates.length > 0 && options.fromRevision !== true) { + const ids = revisionCandidates.map((row) => row.record_id).join(", "); + throw new Error( + `${revisionCandidates.length} record(s) have typed-table bytes that disagree with the current revision in meaning (${ids}). ` + + "Pass --from-revision and --confirm-revision-align with the database ID after reviewing the preview.", + ); + } + + const revisionBefore = await readDatabaseRevision(database); + const backupPath = + options.backupPath ?? defaultRepairBackupPath(database.localPath, options.now); + + const fileIdentity = await lstat(database.localPath, { bigint: true }).then((stat) => ({ + device: stat.dev, + inode: stat.ino, + })); + + await createVerifiedSqliteBackup(database, database.localPath, backupPath, metadata); + const revisionAfterBackup = await readDatabaseRevision(database); + if (revisionAfterBackup !== revisionBefore) { + throw new Error( + "Database revision changed during repair backup; stop other writers and retry", + ); + } + const statAfterBackup = await lstat(database.localPath, { bigint: true }); + if ( + statAfterBackup.dev !== fileIdentity.device || + statAfterBackup.ino !== fileIdentity.inode + ) { + throw new Error("Database file changed during repair backup"); + } + + try { + const result = await repairProviderEncodingAndRevisionAlign(database, { + encodingRecordIds, + revisionRecordIds: revisionCandidates.map((row) => row.record_id), + }); + return { backup_path: backupPath, ...result }; + } catch (error) { + const revisionAfterFailure = await readDatabaseRevision(database); + const changed = revisionAfterFailure !== revisionBefore; + const causeMessage = formatSchemaValidationError(error); + throw new Error( + `Repair failed after creating verified backup at ${backupPath}. Cause: ${causeMessage}.` + + (changed + ? " The database revision changed; restore from the backup." + : ` Retry with a new backup; previous attempt left ${backupPath} on disk.`), + { cause: error }, + ); + } +} + +async function repairProviderEncodingAndRevisionAlign( + database: AthleticDatabase, + options: { + encodingRecordIds: string[]; + revisionRecordIds: string[]; + }, +): Promise<{ + repaired_record_count: number; + revision_align_record_count: number; + database_revision: number; +}> { + return withWriteTransaction(database, async (transaction) => { + const revisionAligned = await repairTypedTablesFromRevisionRows( + transaction, + options.revisionRecordIds, + ); + const encodingRepaired = await rebuildTypedRows(transaction, options.encodingRecordIds, { + allowSemanticMismatch: false, + }); + const total = encodingRepaired + revisionAligned; + const databaseRevision = + total === 0 + ? Number( + ( + await transaction.execute( + "SELECT current_revision FROM database_state WHERE singleton_id = 1", + ) + ).rows[0]?.current_revision, + ) + : await incrementDatabaseRevision(transaction); + return { + repaired_record_count: encodingRepaired, + revision_align_record_count: revisionAligned, + database_revision: databaseRevision, + }; + }); +} + +export async function repairProviderEncoding( + database: AthleticDatabase, +): Promise { + return withWriteTransaction(database, async (transaction) => { + const repaired = await repairProviderEncodingRows(transaction); + const databaseRevision = + repaired === 0 + ? Number( + ( + await transaction.execute( + "SELECT current_revision FROM database_state WHERE singleton_id = 1", + ) + ).rows[0]?.current_revision, + ) + : await incrementDatabaseRevision(transaction); + return { repaired_record_count: repaired, database_revision: databaseRevision }; + }); +} diff --git a/src/db/sql-contract.ts b/src/db/sql-contract.ts index 75a237e1..0c7c9a6b 100644 --- a/src/db/sql-contract.ts +++ b/src/db/sql-contract.ts @@ -247,8 +247,22 @@ export const MIGRATION_CHAIN = [ file: "migrations/001-initial.sql", description: "Initial Athletic Standard v1 schema, enforcement triggers, and stable read views.", }, + { + version: 2, + file: "migrations/002-provider-encoding-repair.sql", + description: + "Repair typed-table JSON bytes after npm 1.0.0 provider imports without changing record content.", + }, ] as const; +export const MIGRATION_002_FILE_HEADER = `-- Athletic Standard SQL schema migration 002 (sql_schema_version 2). +-- Generated by pnpm generate:sql-contract. Do not edit by hand. +-- +-- Bumps database_metadata. Typed-table alignment runs in the migration runner (see +-- src/db/repair.ts). See spec/sql/README.md and spec/sql/contract.json. + +`; + export function publishedMigrationSql(): string { return INITIAL_SCHEMA_SQL.trim(); } diff --git a/src/db/stable-json.ts b/src/db/stable-json.ts new file mode 100644 index 00000000..14b776b6 --- /dev/null +++ b/src/db/stable-json.ts @@ -0,0 +1,39 @@ +/** Lexicographic order on UTF-16 code units (JavaScript string order), not locale rules. */ +export function compareUtf8Keys(left: string, right: string): number { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} + +export function stableValue(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(stableValue); + } + if (value !== null && typeof value === "object") { + return Object.fromEntries( + Object.entries(value as Record) + .sort(([left], [right]) => compareUtf8Keys(left, right)) + .map(([key, child]) => [key, stableValue(child)]), + ); + } + return value; +} + +export function deterministicJson(value: unknown): Buffer { + return Buffer.from(`${JSON.stringify(stableValue(value), null, 2)}\n`, "utf8"); +} + +/** True when two JSON text columns carry the same logical value (key order ignored). */ +export function semanticJsonEqual(left: string, right: string): boolean { + try { + const normalizedLeft = stableValue(JSON.parse(left) as unknown); + const normalizedRight = stableValue(JSON.parse(right) as unknown); + return JSON.stringify(normalizedLeft) === JSON.stringify(normalizedRight); + } catch { + return false; + } +} diff --git a/src/db/transaction.ts b/src/db/transaction.ts index 9c691c20..3a3ec79d 100644 --- a/src/db/transaction.ts +++ b/src/db/transaction.ts @@ -1,10 +1,19 @@ import type { Transaction } from "@libsql/client"; -import { databaseClient, type AthleticDatabase } from "./client.js"; +import { + databaseClient, + enableLocalWal, + tryRevertDeleteJournalModeAfterFailedWal, + type AthleticDatabase, +} from "./client.js"; export async function withWriteTransaction( database: AthleticDatabase, operation: (transaction: Transaction) => Promise, ): Promise { + const journalBefore = String( + (await databaseClient(database).execute("PRAGMA journal_mode")).rows[0]?.journal_mode, + ).toLowerCase(); + await enableLocalWal(database); const transaction = await databaseClient(database).transaction("write"); try { const foreignKeys = await transaction.execute("PRAGMA foreign_keys"); @@ -19,6 +28,11 @@ export async function withWriteTransaction( if (!transaction.closed) { await transaction.rollback(); } + try { + await tryRevertDeleteJournalModeAfterFailedWal(database, journalBefore); + } catch { + // Best-effort journal revert; the original write failure is thrown below. + } throw error; } finally { transaction.close(); diff --git a/src/db/typed-denormalized.ts b/src/db/typed-denormalized.ts new file mode 100644 index 00000000..7dcfb68a --- /dev/null +++ b/src/db/typed-denormalized.ts @@ -0,0 +1,475 @@ +import type { Client } from "@libsql/client"; +import { ZodError } from "zod"; +import { CurrentRecord, type CurrentRecordT } from "../v1/schema.js"; +import { formatSchemaValidationError } from "./validation-message.js"; +import { typedTables } from "./check-tables.js"; +import { typedMainRowFields } from "./records.js"; + +function normalizeSqlValue(value: unknown): string | number | null { + if (value === null || value === undefined) { + return null; + } + if (typeof value === "bigint") { + return Number(value); + } + if (typeof value === "boolean") { + return value ? 1 : 0; + } + if (typeof value === "number") { + return value; + } + return String(value); +} + +function sqlValuesEqual(left: unknown, right: unknown): boolean { + const a = normalizeSqlValue(left); + const b = normalizeSqlValue(right); + if (a === null && b === null) { + return true; + } + if (a === null || b === null) { + return false; + } + if (typeof a === "number" && typeof b === "number") { + return a === b; + } + return String(a) === String(b); +} + +function parseRecordFromRevisionRow(row: Record): CurrentRecordT { + return CurrentRecord.parse({ + record_id: String(row.record_id), + record_type: String(row.record_type), + created_at: String(row.created_at), + current_revision: Number(row.current_revision), + is_deleted: Number(row.is_deleted) === 1, + data: JSON.parse(String(row.record_json)), + }); +} + +export type TypedDenormalizedFinding = + | { kind: "mismatch"; record_id: string } + | { kind: "parse_error"; record_id: string; message: string }; + +function mainRowMismatch(row: Record, record: CurrentRecordT): boolean { + for (const [column, expected] of typedMainRowFields(record)) { + if (!sqlValuesEqual(row[column], expected)) { + return true; + } + } + return false; +} + +function jsonChildEqual(left: unknown, right: unknown): boolean { + return JSON.stringify(left) === JSON.stringify(right); +} + +async function providerReportingPeriodsMismatch( + client: Client, + record: CurrentRecordT, +): Promise { + if (!("provider_reporting_periods" in record.data)) { + const count = await client.execute({ + sql: "SELECT COUNT(*) AS count FROM provider_reporting_periods WHERE owner_record_id = ?", + args: [record.record_id], + }); + return Number(count.rows[0]?.count) !== 0; + } + const periods = record.data.provider_reporting_periods ?? []; + const rows = await client.execute({ + sql: ` + SELECT period_order, period_type, provider_period_id, provider_date, start_at, end_at, period_json + FROM provider_reporting_periods + WHERE owner_record_id = ? + ORDER BY period_order + `, + args: [record.record_id], + }); + if (rows.rows.length !== periods.length) { + return true; + } + for (const [index, period] of periods.entries()) { + const row = rows.rows[index]; + if (row === undefined) { + return true; + } + if (Number(row.period_order) !== index) { + return true; + } + if (!sqlValuesEqual(row.period_type, period.period_type)) { + return true; + } + if (!sqlValuesEqual(row.provider_period_id, period.provider_period_id ?? null)) { + return true; + } + if (!sqlValuesEqual(row.provider_date, period.provider_date ?? null)) { + return true; + } + if (!sqlValuesEqual(row.start_at, period.start_at ?? null)) { + return true; + } + if (!sqlValuesEqual(row.end_at, period.end_at ?? null)) { + return true; + } + if (!jsonChildEqual(JSON.parse(String(row.period_json)), period)) { + return true; + } + } + return false; +} + +async function orderedJsonChildrenMismatch( + client: Client, + options: { + table: string; + parentColumn: string; + orderColumn: string; + jsonColumn: string; + parentId: string; + children: readonly unknown[]; + }, +): Promise { + const rows = await client.execute({ + sql: ` + SELECT ${options.orderColumn}, ${options.jsonColumn} + FROM ${options.table} + WHERE ${options.parentColumn} = ? + ORDER BY ${options.orderColumn} + `, + args: [options.parentId], + }); + if (rows.rows.length !== options.children.length) { + return true; + } + for (const [index, child] of options.children.entries()) { + const row = rows.rows[index]; + if (row === undefined) { + return true; + } + if (Number(row[options.orderColumn]) !== index) { + return true; + } + if (!jsonChildEqual(JSON.parse(String(row[options.jsonColumn])), child)) { + return true; + } + } + return false; +} + +async function attachmentLinksMismatch( + client: Client, + recordId: string, + attachmentIds: readonly string[], +): Promise { + const rows = await client.execute({ + sql: ` + SELECT attachment_order, attachment_record_id + FROM record_attachment_links + WHERE owner_record_id = ? + ORDER BY attachment_order + `, + args: [recordId], + }); + if (rows.rows.length !== attachmentIds.length) { + return true; + } + for (const [index, attachmentId] of attachmentIds.entries()) { + const row = rows.rows[index]; + if (row === undefined) { + return true; + } + if (Number(row.attachment_order) !== index) { + return true; + } + if (String(row.attachment_record_id) !== attachmentId) { + return true; + } + } + return false; +} + +async function typedChildrenMismatch(client: Client, record: CurrentRecordT): Promise { + switch (record.record_type) { + case "point_measurement": { + const calculations = record.data.calculations ?? []; + if ( + await orderedJsonChildrenMismatch(client, { + table: "point_measurement_calculations", + parentColumn: "point_measurement_id", + orderColumn: "calculation_order", + jsonColumn: "calculation_json", + parentId: record.record_id, + children: calculations, + }) + ) { + return true; + } + const inputRows = await client.execute({ + sql: ` + SELECT calculation_order, input_order, evidence_record_id, evidence_revision + FROM point_measurement_calculation_inputs + WHERE point_measurement_id = ? + ORDER BY calculation_order, input_order + `, + args: [record.record_id], + }); + const expectedInputs: Array<{ + calculation_order: number; + input_order: number; + evidence_record_id: string; + evidence_revision: number; + }> = []; + for (const [calculationIndex, calculation] of calculations.entries()) { + for (const [inputIndex, input] of calculation.input_records.entries()) { + expectedInputs.push({ + calculation_order: calculationIndex, + input_order: inputIndex, + evidence_record_id: input.record_id, + evidence_revision: input.revision, + }); + } + } + if (inputRows.rows.length !== expectedInputs.length) { + return true; + } + for (const [index, expected] of expectedInputs.entries()) { + const row = inputRows.rows[index]; + if (row === undefined) { + return true; + } + if ( + Number(row.calculation_order) !== expected.calculation_order || + Number(row.input_order) !== expected.input_order || + String(row.evidence_record_id) !== expected.evidence_record_id || + Number(row.evidence_revision) !== expected.evidence_revision + ) { + return true; + } + } + break; + } + case "workout_session": + if ( + await orderedJsonChildrenMismatch(client, { + table: "workout_session_segments", + parentColumn: "workout_session_id", + orderColumn: "segment_order", + jsonColumn: "segment_json", + parentId: record.record_id, + children: record.data.segments ?? [], + }) + ) { + return true; + } + break; + case "benchmark_result": + if ( + await orderedJsonChildrenMismatch(client, { + table: "benchmark_result_segments", + parentColumn: "benchmark_result_id", + orderColumn: "segment_order", + jsonColumn: "segment_json", + parentId: record.record_id, + children: record.data.segments ?? [], + }) + ) { + return true; + } + break; + case "nutrition_entry": + if ( + await orderedJsonChildrenMismatch(client, { + table: "reported_nutrition_items", + parentColumn: "nutrition_entry_id", + orderColumn: "item_order", + jsonColumn: "item_json", + parentId: record.record_id, + children: record.data.reported_items, + }) + ) { + return true; + } + if ( + await attachmentLinksMismatch( + client, + record.record_id, + record.data.attachment_ids ?? [], + ) + ) { + return true; + } + break; + case "athlete_report": + if ( + await attachmentLinksMismatch( + client, + record.record_id, + record.data.attachment_ids ?? [], + ) + ) { + return true; + } + break; + case "planned_session": + if ( + await orderedJsonChildrenMismatch(client, { + table: "planned_session_blocks", + parentColumn: "planned_session_id", + orderColumn: "block_order", + jsonColumn: "block_json", + parentId: record.record_id, + children: record.data.blocks, + }) + ) { + return true; + } + break; + case "prediction_error_analysis": { + const causeRows = await client.execute({ + sql: ` + SELECT cause_order, evidence_record_id, evidence_revision, explanation + FROM prediction_error_causes + WHERE prediction_error_analysis_id = ? + ORDER BY cause_order + `, + args: [record.record_id], + }); + const causes = record.data.causes; + if (causeRows.rows.length !== causes.length) { + return true; + } + for (const [index, cause] of causes.entries()) { + const row = causeRows.rows[index]; + if (row === undefined) { + return true; + } + if ( + Number(row.cause_order) !== index || + String(row.evidence_record_id) !== cause.evidence.record_id || + Number(row.evidence_revision) !== cause.evidence.revision || + String(row.explanation) !== cause.explanation + ) { + return true; + } + } + break; + } + default: + break; + } + + if ("authorship" in record.data) { + const evidenceRows = await client.execute({ + sql: ` + SELECT evidence_order, evidence_record_id, evidence_revision + FROM authored_record_evidence + WHERE authored_record_id = ? + ORDER BY evidence_order + `, + args: [record.record_id], + }); + const evidence = record.data.authorship.evidence; + if (evidenceRows.rows.length !== evidence.length) { + return true; + } + for (const [index, item] of evidence.entries()) { + const row = evidenceRows.rows[index]; + if (row === undefined) { + return true; + } + if ( + Number(row.evidence_order) !== index || + String(row.evidence_record_id) !== item.record_id || + Number(row.evidence_revision) !== item.revision + ) { + return true; + } + } + } + + return providerReportingPeriodsMismatch(client, record); +} + +async function recordHasDenormalizedMismatch( + client: Client, + table: string, + joinedRow: Record, + record: CurrentRecordT, +): Promise { + const typed = joinedRow as Record; + if (mainRowMismatch(typed, record)) { + return true; + } + return typedChildrenMismatch(client, record); +} + +/** Typed denormalized mismatches and per-record schema parse failures. */ +export async function listTypedDenormalizedFindings( + client: Client, +): Promise { + const findings: TypedDenormalizedFinding[] = []; + for (const [recordType, table] of Object.entries(typedTables)) { + const rows = await client.execute({ + sql: ` + SELECT + records.record_id, + records.record_type, + records.current_revision, + records.created_at, + records.is_deleted, + record_revisions.record_json, + typed.* + FROM records + JOIN record_revisions + ON record_revisions.record_id = records.record_id + AND record_revisions.revision = records.current_revision + JOIN ${table} AS typed ON typed.record_id = records.record_id + WHERE records.record_type = ? + AND records.is_deleted = 0 + ORDER BY records.record_id + `, + args: [recordType], + }); + for (const row of rows.rows) { + const joinedRow = row as Record; + const recordId = String(joinedRow.record_id); + try { + const record = parseRecordFromRevisionRow(joinedRow); + if (await recordHasDenormalizedMismatch(client, table, joinedRow, record)) { + findings.push({ kind: "mismatch", record_id: recordId }); + } + } catch (error) { + if (error instanceof ZodError) { + findings.push({ + kind: "parse_error", + record_id: recordId, + message: formatSchemaValidationError(error), + }); + continue; + } + if (error instanceof SyntaxError) { + findings.push({ + kind: "parse_error", + record_id: recordId, + message: "record_json is not valid JSON", + }); + continue; + } + throw error; + } + } + } + return findings; +} + +/** Record IDs whose typed-table denormalized columns or child rows disagree with data_json. */ +export async function listTypedDenormalizedMismatchRecordIds( + client: Client, +): Promise { + const findings = await listTypedDenormalizedFindings(client); + return findings + .filter((finding): finding is Extract => + finding.kind === "mismatch", + ) + .map((finding) => finding.record_id); +} diff --git a/src/db/validation-message.ts b/src/db/validation-message.ts new file mode 100644 index 00000000..65f367e5 --- /dev/null +++ b/src/db/validation-message.ts @@ -0,0 +1,45 @@ +import { ZodError } from "zod"; + +function formatZodIssuesJsonString(text: string): string | undefined { + const trimmed = text.trim(); + if (!trimmed.startsWith("[")) { + return undefined; + } + try { + const parsed = JSON.parse(trimmed) as unknown; + if (!Array.isArray(parsed) || parsed.length === 0) { + return undefined; + } + const first = parsed[0] as { path?: unknown[]; message?: string }; + if (typeof first.message !== "string") { + return undefined; + } + const path = + Array.isArray(first.path) && first.path.length > 0 + ? first.path.map(String).join(".") + : "record"; + return `${path}: ${first.message}`; + } catch { + return undefined; + } +} + +export function formatSchemaValidationError(error: unknown): string { + if (error instanceof ZodError) { + const first = error.issues[0]; + if (first === undefined) { + return "record does not match its domain schema"; + } + const path = first.path.length === 0 ? "record" : first.path.join("."); + return `${path}: ${first.message}`; + } + if (error instanceof Error) { + const fromJson = formatZodIssuesJsonString(error.message); + return fromJson ?? error.message; + } + if (typeof error === "string") { + const fromJson = formatZodIssuesJsonString(error); + return fromJson ?? error; + } + return String(error); +} diff --git a/src/file.ts b/src/file.ts index 1e64af88..94a0b571 100644 --- a/src/file.ts +++ b/src/file.ts @@ -1,13 +1,10 @@ /** * Find the live SQLite athlete database. * - * The JSON helpers remain private compatibility code while commands are moved to - * the v1 database. New commands must not treat a JSON export as the live record. + * New commands must not treat a JSON export as the live record. */ -import { readdirSync, readFileSync, writeFileSync, existsSync } from "node:fs"; +import { readdirSync, existsSync } from "node:fs"; import { resolve } from "node:path"; -import { AthleticStandardFile, type AthleticStandardFileT } from "./schema.js"; -import { validateAthleticStandardFile } from "./validate.js"; export const FILE_SUFFIX = ".ath.sqlite"; export const DEFAULT_FILENAME = `athlete${FILE_SUFFIX}`; @@ -57,38 +54,3 @@ export function findFile(explicitPath?: string, cwd = process.cwd()): string { ); } -/** Load without validating (callers that validate should use `check`-style flows). */ -export function loadFileRaw(path: string): unknown { - if (path.endsWith(FILE_SUFFIX)) { - throw new Error( - `this command has not been moved to the v1 SQLite database yet. Nothing was written.`, - ); - } - return JSON.parse(readFileSync(path, "utf8")); -} - -/** - * Load and parse through the schema; throws with a readable message on failure. - * - * The message comes from the same explanation `ath check` gives, because a bare Zod - * union failure says only "Invalid input" — which tells the reader nothing about a - * file they are expected to be able to edit by hand. - */ -export function loadFile(path: string): AthleticStandardFileT { - const raw = loadFileRaw(path); - const parsed = AthleticStandardFile.safeParse(raw); - if (!parsed.success) { - const first = validateAthleticStandardFile(raw).issues.find((i) => i.severity === "error"); - throw new Error( - `${path} is not a valid Athletic Standard file.\n` + - ` ${first?.path ?? "root"}: ${first?.message ?? "unreadable"}\n` + - `Run \`ath check\` for the full list.`, - ); - } - return parsed.data; -} - -/** Stable field order + trailing newline, so files diff cleanly under git. */ -export function saveFile(path: string, file: AthleticStandardFileT): void { - writeFileSync(path, JSON.stringify(file, null, 2) + "\n"); -} diff --git a/src/grade.ts b/src/grade.ts deleted file mode 100644 index 4415f0c4..00000000 --- a/src/grade.ts +++ /dev/null @@ -1,741 +0,0 @@ -/** - * `ath grade` — steps 1 and 2 of the grading procedure in - * [v0.1.0 §6](../build-history/v0.1.0/spec.md), which are the deterministic ones. - * - * The tool matches the attempt to the open prediction, measures the error, and - * classifies it. A hit prints one line and stops, because analysing a hit invites a - * story told after the fact. A miss prints the dossier: the raw material an agent - * needs for step 3, and nothing already chewed into a conclusion. - * - * Step 3 is the agent's, and it comes back through `--analysis`. Every cause it - * names is checked against the file before it is written, because a rule a tool can - * enforce should not live in a skill (D46, D62). - */ -import { - MissAnalysis, - type AthleticStandardFileT, - type BenchmarkT, - type GradeT, - type HardSignalT, - type PredictionT, - type ScoreT, - type SoftSignalT, -} from "./schema.js"; -import { readingsFor } from "./readings.js"; -import { daysBetween, renderCoverage, type Coverage } from "./coverage.js"; -import { - amountIn, - CLOCK_ONLY, - formatDuration, - hoursAndMinutes, - kilosFromLoad, - LOAD_ONLY, - nativeValue, - SCORE_KEY, - secondsFromClock, -} from "./score.js"; -import { manualSource, shiftDay, signalAt, TRACKED_TYPES } from "./signals.js"; -import { - applyDraft, - existingResultOn, - localTimestamp, - noonOn, - sessionBlock, - sessionCandidates, - today, - type Confirm, - type LogDraft, -} from "./log.js"; - -/** Raised when the file cannot be graded, with the remedy in the message. */ -export class GradeRefusal extends Error { - constructor(message: string) { - super(message); - this.name = "GradeRefusal"; - } -} - -/** How far a day's mean must sit from the baseline before it is worth naming. */ -const ANOMALY_SDS = 1.5; - -export type Severity = "hit" | "minor" | "significant" | "severe"; - -export interface Anomaly { - source: string; - type: string; - unit: string; - day: string; - /** That day's mean. */ - value: number; - mean: number; - sd: number; - /** How many standard deviations out, signed. */ - sds: number; - /** What the baseline it is measured against rests on (D47). */ - coverage: Coverage; -} - -export interface Dossier { - /** Everything self-reported in the 72 hours before the attempt. */ - soft: SoftSignalT[]; - /** The day's own measurements, and the night before it. */ - dayOf: HardSignalT[]; - /** Days in the last week whose mean sat far from that source's own baseline. */ - anomalies: Anomaly[]; -} - -export interface GradeOutcome { - benchmark: BenchmarkT; - /** Everything to be written, so the result goes in through `ath log`'s path (D65). */ - draft: LogDraft; - /** The result the grade points at, whether newly written or already in the file. */ - result: Extract; - /** True when the result was already logged and is being graded rather than rewritten. */ - reusedExisting: boolean; - actualText: string; - /** Null when nothing was open, in which case the result is simply logged. */ - prediction: PredictionT | null; - /** Computed, and attached to the prediction only by `applyGrade`. */ - grade: GradeT | null; - severity: Severity | null; - /** How the error reads in the benchmark's own unit, e.g. "3s" or "12 reps". */ - errorText: string; - /** Present on a miss. A hit gets no dossier, on purpose. */ - dossier: Dossier | null; -} - -/** - * Read `--actual` in the benchmark's own unit. - * - * The score type is known, so nothing is guessed — except for a bare number under a - * time or a load, where the reading would change the answer. `4:32` and `272s` are - * both four and a half minutes; `272` alone could be either seconds or minutes, and - * `100` could be kilos or pounds. Those are refused with both readings named, the - * same way an ambiguous date is (D56). - */ -export function parseActual(text: string, scoreType: BenchmarkT["score_type"]): { score: ScoreT; text: string } { - const flat = text.trim(); - - if (scoreType === "time") { - const clock = CLOCK_ONLY.exec(flat); - if (clock) { - const duration_s = secondsFromClock(clock); - if (duration_s > 0) return { score: { duration_s }, text: formatDuration(duration_s) }; - } - const seconds = /^(\d{1,5})\s*s(?:ec|ecs|econds)?$/i.exec(flat); - if (seconds && Number(seconds[1]) > 0) { - const duration_s = Number(seconds[1]); - return { score: { duration_s }, text: formatDuration(duration_s) }; - } - throw new GradeRefusal( - `'${flat}' is not a time. Write it as a clock — \`4:32\`, or \`1:02:30\` past an hour — ` + - `or in seconds with the unit, \`272s\`.`, - ); - } - - if (scoreType === "reps") { - const reps = /^(\d{1,5})(?:\s*reps?)?$/i.exec(flat); - if (reps && Number(reps[1]) > 0) { - return { score: { reps: Number(reps[1]) }, text: `${Number(reps[1])} reps` }; - } - throw new GradeRefusal(`'${flat}' is not a rep count. Write it as \`245\` or \`245 reps\`.`); - } - - const load = LOAD_ONLY.exec(flat); - if (load) { - const weight_kg = kilosFromLoad(load); - if (weight_kg > 0) return { score: { weight_kg }, text: `${weight_kg} kg` }; - } - throw new GradeRefusal( - `'${flat}' has no unit, and a load without one is two different numbers. ` + - `Write it as \`100kg\` or \`225lb\`.`, - ); -} - -/** - * The same error math `ath grade` writes, used by `ath backtest` so the two - * cannot drift (D77). - */ -export function scorePrediction( - predicted: ScoreT, - actual: ScoreT, - scoreType: BenchmarkT["score_type"], - range?: { low: ScoreT; high: ScoreT }, -): GradeT { - const pred = native(predicted, scoreType); - const act = native(actual, scoreType); - const signed = Math.round((pred - act) * 100) / 100; - const absPct = Math.round((Math.abs(signed) / act) * 1000) / 10; - // No stated range means no hit (D61). - const inRange = - range !== undefined && - act >= native(range.low, scoreType) && - act <= native(range.high, scoreType); - return { signed_error: signed, abs_error_pct: absPct, in_range: inRange }; -} - -/** The score in the benchmark's native unit: seconds, reps, or kilos. */ -function native(score: ScoreT, scoreType: BenchmarkT["score_type"]): number { - const value = nativeValue(score, scoreType); - if (value === undefined) { - throw new GradeRefusal(`that score has no ${SCORE_KEY[scoreType]}, which this benchmark is scored by.`); - } - return value; -} - -function describe(score: ScoreT, scoreType: BenchmarkT["score_type"]): string { - const value = native(score, scoreType); - if (scoreType === "time") return formatDuration(value); - if (scoreType === "reps") return `${value} reps`; - return `${value} kg`; -} - -export interface GradeOptions { - date?: string | undefined; - scaling?: "rx" | "scaled" | undefined; - now?: Date | undefined; - confirm?: Confirm | undefined; - /** Grade a second attempt on a day that already has a result (D67). */ - again?: boolean | undefined; -} - -/** - * Work out everything the grade will write, and write none of it. - * - * Two halves, the same way `ath log` works: this one decides, `applyGrade` commits, - * and in between the reader sees what is about to happen and says yes. Grading is a - * write like any other, and a command that writes should not be the one command that - * does it without showing its work first (D65). - */ -export function planGrade( - file: AthleticStandardFileT, - athleteFilePath: string, - benchmark: BenchmarkT, - actualText: string, - options: GradeOptions = {}, -): GradeOutcome { - const now = options.now ?? new Date(); - const day = options.date ?? today(now); - if (!/^\d{4}-\d{2}-\d{2}$/.test(day) || Number.isNaN(Date.parse(`${day}T00:00:00Z`))) { - throw new GradeRefusal(`--date takes a day written as YYYY-MM-DD, not '${day}'.`); - } - - const { score, text } = parseActual(actualText, benchmark.score_type); - - // Logging the result and then grading it is the ordinary way round, so an existing - // result with this score is the one being graded rather than a duplicate to refuse. - // A different score on the same day means one of the two is wrong (D67). - const already = options.again ? undefined : existingResultOn(file, benchmark.id, day); - if (already && !sameScore(already.result, score, benchmark.score_type)) { - throw new GradeRefusal( - `'${benchmark.id}' already has a result on ${day}: ${describe(already.result, benchmark.score_type)}, ` + - `and you are now saying ${text}. One of the two is wrong, and writing both would leave ` + - `the file claiming each. Correct the score, or pass --again if you really attempted it twice.`, - ); - } - - const result: Extract = already ?? { - type: "benchmark_result", - benchmark: benchmark.id, - recorded_at: day === today(now) ? localTimestamp(now) : noonOn(day), - source: manualSource(file), - result: score, - ...(options.scaling ? { scaling: options.scaling } : {}), - }; - const recordedAt = result.recorded_at; - - const draft = draftFor(file, result, already !== undefined, options.confirm ?? "ask"); - - // The most recent prediction still waiting on a result. Nothing open means there - // was no claim to be right or wrong about, so the result is logged and that is all. - const open = file.predictions - .filter((p) => p.benchmark === benchmark.id && p.grade === null) - .sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)) - .pop(); - - if (!open) { - return withSummary({ - benchmark, - draft, - result, - reusedExisting: already !== undefined, - actualText: text, - prediction: null, - grade: null, - severity: null, - errorText: "", - dossier: null, - }, day, options); - } - - if (Date.parse(recordedAt) < Date.parse(open.created_at)) { - throw new GradeRefusal( - `that attempt is dated ${day}, before the prediction was made on ` + - `${open.created_at.slice(0, 10)}. A prediction has to come first, or it is not one. ` + - `Check --date.`, - ); - } - - const grade = scorePrediction(open.predicted, score, benchmark.score_type, open.range); - const severity: Severity = grade.in_range - ? "hit" - : grade.abs_error_pct < 5 - ? "minor" - : grade.abs_error_pct <= 15 - ? "significant" - : "severe"; - - return withSummary({ - benchmark, - draft, - result, - reusedExisting: already !== undefined, - actualText: text, - prediction: open, - grade, - severity, - errorText: amountIn(Math.abs(grade.signed_error), benchmark.score_type), - dossier: severity === "hit" ? null : buildDossier(file, athleteFilePath, recordedAt), - }, day, options); -} - -/** - * What the reader sees before answering. Every guess is on the screen first (D56). - * - * The grade itself is not here. It is the consequence of the write rather than part - * of it, and printing the verdict above the question would be asking permission for - * something already said. - */ -function withSummary(outcome: GradeOutcome, day: string, options: GradeOptions): GradeOutcome { - const kind = outcome.benchmark.score_type; - const block = [ - { label: "kind", value: "workout result" }, - { label: "date", value: `${day}${day === today(options.now ?? new Date()) ? " (today)" : ""}` }, - { label: "score", value: outcome.actualText }, - { label: "name", value: outcome.benchmark.id }, - ]; - if (outcome.reusedExisting) { - block.push({ - label: "result", - value: "already logged on that day, so it is graded rather than written again", - }); - } else { - block.push(sessionBlock(outcome.draft, options.confirm ?? "ask")); - } - block.push({ - label: "grade", - value: outcome.prediction - ? `against the prediction of ${describe(outcome.prediction.predicted, kind)} made on ` + - `${outcome.prediction.created_at.slice(0, 10)}` - : "nothing to grade — no prediction is open on this benchmark", - }); - outcome.draft.blocks = [block]; - return outcome; -} - -/** - * Commit the grade. The caller validates and saves, the same as every other write. - * - * The result goes in through `applyDraft`, so it picks up the session link, the sort - * order and the manual source from the one place that does those (D55). - */ -export function applyGrade(file: AthleticStandardFileT, outcome: GradeOutcome): void { - applyDraft(file, outcome.draft); - if (outcome.prediction && outcome.grade) { - // `recorded_at` and the benchmark are what identify the result, so the prediction - // now points at a record the file holds rather than holding a copy of it (D64). - outcome.prediction.actual = { - result: outcome.result.result, - recorded_at: outcome.result.recorded_at, - }; - outcome.prediction.grade = outcome.grade; - } -} - -/** The result as a draft, so it is written the way `ath log` writes one. */ -function draftFor( - file: AthleticStandardFileT, - result: Extract, - reused: boolean, - confirm: Confirm, -): LogDraft { - const draft: LogDraft = { - // A result already in the file is written again by nobody. Only the grade is new. - hard: reused ? [] : [result], - soft: [], - predictions: [], - newBenchmarks: [], - candidates: result.session ? [] : sessionCandidates(file, result.recorded_at), - chosenCandidate: -1, - blocks: [], - }; - if (!reused && draft.candidates.length > 0) { - draft.chosenCandidate = confirm === "ask" ? 0 : confirm === "assume" && draft.candidates.length === 1 ? 0 : -1; - } - return draft; -} - -/** Do two scores agree in the unit this benchmark is scored by? */ -function sameScore(a: ScoreT, b: ScoreT, scoreType: BenchmarkT["score_type"]): boolean { - return nativeValue(a, scoreType) === nativeValue(b, scoreType); -} - -/** - * The raw material for a miss analysis, in the order v0.1.0 §6 puts it: the day's - * own measurements first because they are the most trusted, then what was - * self-reported in the 72 hours before, then the week's anomalies. - * - * Nothing here is interpreted. A dossier that named a cause would be doing the - * agent's job with none of the agent's context. - */ -function buildDossier(file: AthleticStandardFileT, athleteFilePath: string, attemptAt: string): Dossier { - const attempt = Date.parse(attemptAt); - const day = attemptAt.slice(0, 10); - - const soft = file.soft_signals - .filter((s) => { - const at = Date.parse(s.reported_at); - return at <= attempt && at >= attempt - 72 * 3_600_000; - }) - .sort((a, b) => Date.parse(a.reported_at) - Date.parse(b.reported_at)); - - const dayOf = file.hard_signals - .filter((s) => { - if (s.type === "benchmark_result" || s.type === "series_ref") return false; - if (s.type === "sleep_session") return s.end.slice(0, 10) === day; - if (s.type === "workout_session") return s.start.slice(0, 10) === day; - return s.recorded_at.slice(0, 10) === day && Date.parse(s.recorded_at) <= attempt; - }) - .sort((a, b) => Date.parse(signalAt(a)) - Date.parse(signalAt(b))); - - return { soft, dayOf, anomalies: weekAnomalies(file, athleteFilePath, day) }; -} - -/** - * Days in the last week whose mean sat far from that source's own baseline. - * - * The day's mean is compared against the mean and spread of daily means over the 90 - * days before it, so like is compared with like (D63). Comparing one night's - * thousands of samples against the spread of individual samples would answer a - * different question and answer it with a much wider spread. - */ -function weekAnomalies(file: AthleticStandardFileT, athleteFilePath: string, day: string): Anomaly[] { - const found: Anomaly[] = []; - const weekFrom = shiftDay(day, -6); - const baselineFrom = shiftDay(day, -90); - - for (const source of file.sources.map((s) => s.id)) { - for (const type of TRACKED_TYPES) { - const readings = readingsFor(file, athleteFilePath, type, source, { from: baselineFrom, to: day }); - if (readings.length === 0) continue; - - const perDay = new Map(); - for (const r of readings) { - const d = r.at.slice(0, 10); - perDay.set(d, [...(perDay.get(d) ?? []), r.value]); - } - const means = [...perDay.entries()].map(([d, values]) => ({ - day: d, - mean: values.reduce((a, b) => a + b, 0) / values.length, - })); - if (means.length < 5) continue; - - const mean = means.reduce((a, b) => a + b.mean, 0) / means.length; - const sd = Math.sqrt( - means.reduce((a, b) => a + (b.mean - mean) ** 2, 0) / (means.length - 1), - ); - if (sd === 0) continue; - - const sortedDays = means.map((m) => m.day).sort(); - const coverage: Coverage = { - n: means.length, - from: sortedDays[0]!, - to: sortedDays[sortedDays.length - 1]!, - days_present: means.length, - days_expected: daysBetween(baselineFrom, day), - source, - rule: `spread of daily ${type} means over the 90 days to ${day}, from this source alone`, - }; - - for (const m of means) { - if (m.day < weekFrom) continue; - const sds = (m.mean - mean) / sd; - if (Math.abs(sds) <= ANOMALY_SDS) continue; - found.push({ - source, - type, - unit: readings[0]!.unit, - day: m.day, - value: Math.round(m.mean * 10) / 10, - mean: Math.round(mean * 10) / 10, - sd: Math.round(sd * 10) / 10, - sds: Math.round(sds * 10) / 10, - coverage, - }); - } - } - } - - return found.sort((a, b) => Math.abs(b.sds) - Math.abs(a.sds)); -} - -// --------------------------------------------------------------------------- -// The output -// --------------------------------------------------------------------------- - -export function renderGrade(outcome: GradeOutcome): string { - const lines: string[] = []; - const kind = outcome.benchmark.score_type; - - if (!outcome.prediction || !outcome.grade) { - lines.push( - outcome.reusedExisting - ? `'${outcome.benchmark.id}' already had ${outcome.actualText} recorded on ` + - `${outcome.result.recorded_at.slice(0, 10)}, so nothing was written.` - : `logged ${outcome.actualText} on '${outcome.benchmark.id}'.`, - ); - lines.push(`No prediction was open for it, so there is nothing to grade.`); - lines.push(...sessionHint(outcome)); - return lines.join("\n"); - } - - const p = outcome.prediction; - const grade = outcome.grade; - const range = p.range - ? `${describe(p.range.low, kind)}–${describe(p.range.high, kind)}` - : null; - - const direction = grade.signed_error === 0 ? "exactly" : grade.signed_error > 0 ? "faster" : "slower"; - lines.push( - `Predicted ${describe(p.predicted, kind)}, actual ${outcome.actualText} — ` + - `off by ${outcome.errorText} (${grade.abs_error_pct}%), ${direction === "exactly" ? "exactly right" : direction + " than predicted"}.`, - ); - lines.push( - outcome.severity === "hit" - ? `Inside the stated range of ${range}. Hit.` - : range - ? `Outside the stated range of ${range}. A ${outcome.severity} miss.` - : `No range was stated, so this is graded on the error alone. A ${outcome.severity} miss.`, - ); - lines.push(...sessionHint(outcome)); - - if (!outcome.dossier) return lines.join("\n"); - - const d = outcome.dossier; - lines.push(""); - lines.push(`## The miss dossier`); - lines.push(""); - lines.push( - `Raw material, in the order it should be weighed: the day's own measurements ` + - `first, then what was self-reported in the 72 hours before, then the week's ` + - `unusual days. Nothing here is a cause until an agent shows it is one.`, - ); - - lines.push(""); - lines.push(`### The day of the attempt`); - lines.push(""); - if (d.dayOf.length === 0) lines.push(`Nothing measured that day.`); - for (const sig of d.dayOf) lines.push(`- ${describeSignal(sig)}`); - - lines.push(""); - lines.push(`### Self-reported in the 72 hours before`); - lines.push(""); - if (d.soft.length === 0) lines.push(`Nothing self-reported in that window.`); - for (const s of d.soft) { - const rating = s.rating === undefined ? "" : ` ${s.rating}/${s.scale?.split("-")[1] ?? "?"}`; - const region = s.body_region ? ` ${s.body_region}` : ""; - lines.push(`- ${s.reported_at.slice(0, 10)} ${s.type}${region}${rating}: "${s.note ?? ""}"`); - } - - lines.push(""); - lines.push(`### Unusual days in the last week`); - lines.push(""); - lines.push( - `A day's mean more than ${ANOMALY_SDS} standard deviations from the mean of daily ` + - `means over the 90 days before, for that source alone.`, - ); - lines.push(""); - if (d.anomalies.length === 0) lines.push(`None. Every day sat inside the usual spread.`); - for (const a of d.anomalies) { - lines.push( - `- ${a.day} ${a.source} ${a.type}: ${a.value}${a.unit} against a baseline of ` + - `${a.mean}${a.unit} (sd ${a.sd}) — ${a.sds > 0 ? "+" : ""}${a.sds} standard deviations`, - ); - lines.push(` - ${renderCoverage(a.coverage)}`); - } - - lines.push(""); - lines.push( - `Write the analysis back with \`ath grade ${outcome.benchmark.id} --analysis ''\`. ` + - `Every cause it names has to reference a signal in this file, and where nothing ` + - `explains the miss, set unexplained to true rather than inventing one.`, - ); - - return lines.join("\n"); -} - -/** - * The remaining session, when one was offered and not taken. - * - * The match is offered before the write, the same as `ath log` (D65), so this only - * fires where nobody could be asked or where the answer was no. - */ -function sessionHint(outcome: GradeOutcome): string[] { - const { candidates, chosenCandidate } = outcome.draft; - if (outcome.result.session || chosenCandidate >= 0 || candidates.length === 0) return []; - return [ - `A device session that day is not linked to this result: ` + - `${candidates.map((c) => c.label).join(", ")}. Attach it with ` + - `\`ath link ${outcome.benchmark.id}@${outcome.result.recorded_at.slice(0, 10)} ` + - `${candidates[0]!.start.slice(11, 16)}\`.`, - ]; -} - -function describeSignal(sig: HardSignalT): string { - if (sig.type === "sleep_session") { - const a = sig.aggregates; - const hm = (s?: number) => (s === undefined ? "?" : hoursAndMinutes(s)); - return ( - `${sig.source} sleep: ${hm(a.duration_s)} actual sleep of ${hm(a.time_in_bed_s)} in bed` + - (a.efficiency_pct === undefined ? "" : `, ${a.efficiency_pct}% efficiency`) + - ` (ended ${sig.end.slice(11, 16)})` - ); - } - if (sig.type === "workout_session") { - const a = sig.aggregates; - return ( - `${sig.source} ${a.activity ?? "session"} ${sig.start.slice(11, 16)}–${sig.end.slice(11, 16)}` + - (a.avg_hr_bpm === undefined ? "" : `, avg ${a.avg_hr_bpm} bpm`) - ); - } - if (sig.type === "vendor_score") { - return `${sig.source} ${sig.metric}: ${sig.value} on ${sig.scale} (vendor-computed, not a measurement)`; - } - if ("value" in sig && "unit" in sig) { - return `${sig.source} ${sig.type}: ${sig.value} ${sig.unit} at ${sig.recorded_at.slice(11, 16)}`; - } - return `${sig.source} ${sig.type}`; -} - -export function gradeAsJson(outcome: GradeOutcome, written: boolean): Record { - return { - written, - benchmark: outcome.benchmark.id, - score_type: outcome.benchmark.score_type, - result: outcome.result, - result_already_logged: outcome.reusedExisting, - prediction: outcome.prediction, - severity: outcome.severity, - dossier: outcome.dossier, - session_candidates: outcome.draft.candidates, - session_chosen: - outcome.draft.chosenCandidate < 0 - ? null - : (outcome.draft.candidates[outcome.draft.chosenCandidate] ?? null), - }; -} - -// --------------------------------------------------------------------------- -// Step 3: the analysis coming back -// --------------------------------------------------------------------------- - -export interface AnalysisOutcome { - prediction: PredictionT; - causes: number; - unexplained: boolean; -} - -/** - * Attach an agent's miss analysis to the graded prediction. - * - * One rule is enforced here rather than asked for: every candidate cause must point - * at a signal that exists in the file, by tier, type and day. An invented cause is - * the failure this step is most prone to, and a tool can check it (D46, D62). - */ -export function attachAnalysis( - file: AthleticStandardFileT, - benchmark: BenchmarkT, - json: string, -): AnalysisOutcome { - let parsed: unknown; - try { - parsed = JSON.parse(json); - } catch (e) { - throw new GradeRefusal(`--analysis is not valid JSON: ${(e as Error).message}`); - } - - const analysis = MissAnalysis.safeParse(parsed); - if (!analysis.success) { - throw new GradeRefusal( - `that analysis does not fit the format, so nothing was written:\n` + - analysis.error.issues.map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n"), - ); - } - - const graded = file.predictions - .filter((p) => p.benchmark === benchmark.id && p.grade !== null) - .sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)) - .pop(); - if (!graded) { - throw new GradeRefusal( - `no graded prediction on '${benchmark.id}'. Grade the attempt first with ` + - `\`ath grade ${benchmark.id} --actual \`.`, - ); - } - if (graded.grade!.in_range) { - throw new GradeRefusal( - `the last prediction on '${benchmark.id}' was a hit, and hits are not analysed. ` + - `Explaining a result that landed where it was meant to is a story told afterwards.`, - ); - } - - for (const [i, cause] of analysis.data.candidate_causes.entries()) { - if (!signalExists(file, cause.signal)) { - throw new GradeRefusal( - `candidate_causes.${i} names a ${cause.signal.tier} ${cause.signal.type} on ` + - `${cause.signal.date}, and this file has no such record. Every cause has to ` + - `reference a signal in the file. Where nothing explains the miss, set ` + - `unexplained to true instead.`, - ); - } - } - - graded.miss_analysis = analysis.data; - return { - prediction: graded, - causes: analysis.data.candidate_causes.length, - unexplained: analysis.data.unexplained, - }; -} - -/** - * Whether the file holds a signal of that tier, type and day. - * - * A night of sleep starts on one day and ends on the next, and a reference to either - * day names the same night. So a session matches on any day it covers, rather than - * on the day its start happens to fall in. - */ -function signalExists( - file: AthleticStandardFileT, - ref: { tier: "hard" | "soft"; type: string; date: string }, -): boolean { - if (ref.tier === "soft") { - return file.soft_signals.some((s) => s.type === ref.type && s.reported_at.slice(0, 10) === ref.date); - } - return file.hard_signals.some((s) => { - if (s.type !== ref.type) return false; - if (s.type === "series_ref") return ref.date >= s.from && ref.date <= s.to; - if ("start" in s && "end" in s) { - return ref.date >= s.start.slice(0, 10) && ref.date <= s.end.slice(0, 10); - } - return signalAt(s).slice(0, 10) === ref.date; - }); -} - -export function analysisAsJson(outcome: AnalysisOutcome): Record { - return { - prediction: outcome.prediction.id, - benchmark: outcome.prediction.benchmark, - miss_analysis: outcome.prediction.miss_analysis, - }; -} \ No newline at end of file diff --git a/src/help.ts b/src/help.ts index 43adc3d5..94342f3b 100644 --- a/src/help.ts +++ b/src/help.ts @@ -188,7 +188,25 @@ Examples: Migration never runs silently. A verified SQLite backup is created before the first schema write. Non-interactive commands refuse an outdated database and -point here.`, +point here. + +Requires the \`sqlite3\` command-line tool on PATH for verified backups (same as +\`ath repair\` when repair candidates exist).`, + + repair: ` +Examples: + + Preview provider-encoding repair candidates: + $ ath repair + + Apply key-order-only repair after npm 1.0.0 provider imports: + $ ath repair -y + + Rebuild typed tables from the current revision when direct SQL changed values: + $ ath repair -y --from-revision --confirm-revision-align + +Each confirmed repair creates a new verified SQLite backup. Failed attempts leave +that backup on disk for restore; retry creates another backup.`, export: ` Examples: diff --git a/src/import/detect.ts b/src/import/detect.ts index 0d896141..b3739774 100644 --- a/src/import/detect.ts +++ b/src/import/detect.ts @@ -55,11 +55,12 @@ const OURA_MARKERS = [ "total_sleep_duration", "lowest_heart_rate", "readiness_score", + "contributors", ]; function isOuraHeader(header: string): boolean { const normalized = header.toLowerCase().replace(/\s+/g, "_"); - return OURA_MARKERS.some((m) => normalized.includes(m)); + return OURA_MARKERS.some((marker) => normalized.includes(marker)); } function firstLine(path: string): string { diff --git a/src/import/index.ts b/src/import/index.ts index fd5b1d2e..9243f14b 100644 --- a/src/import/index.ts +++ b/src/import/index.ts @@ -8,11 +8,8 @@ import { ATHLETIC_STANDARD_VERSION, type AthleticStandardFileT, - type SeriesQuantity, - type SeriesRefT, type SourceT, } from "../schema.js"; -import { assembleSeriesRef, writeSeriesFile } from "../series.js"; import { silentProgress, type Progress } from "../progress.js"; import { detectExport, readCsvBundle, type DetectedExport } from "./detect.js"; import { importAppleHealth } from "./apple.js"; @@ -134,55 +131,3 @@ export async function parseProviderExport( return parseProviderExportInto(file, exportPath, progress); } -/** - * Import `exportPath` into `file`, writing sidecars beside `athleteFilePath`. - * Mutates `file`; the caller saves it. - */ -export async function importExport( - file: AthleticStandardFileT, - athleteFilePath: string, - exportPath: string, - progress: Progress = silentProgress, -): Promise { - const pooled = pooledSources(file); - if (pooled.length > 0) throw new PooledFileError(pooled.map((s) => s.id)); - - // Captured before parsing, because sources are created as writers are met (D52). - const knownSources = new Set(file.sources.map((s) => s.id)); - - const parsed = await parseProviderExportInto(file, exportPath, progress); - const { payload, label } = parsed; - - // Sidecars are written before the document is touched, because a coverage record - // hashes every day on disk for its quantity — including days written by earlier - // imports, which only the filesystem knows about (D40). - if (payload.series.length > 0) progress.start("writing series files", payload.series.length); - for (const built of payload.series) { - writeSeriesFile(athleteFilePath, built); - progress.advance(); - } - progress.finish(); - - const touched = new Map(); - for (const built of payload.series) { - touched.set(`${built.quantity}|${built.source}`, { - quantity: built.quantity, - source: built.source, - }); - } - - // Each coverage record re-hashes every sidecar on disk for its quantity, which on a - // long history is the slowest step after the XML itself. - if (touched.size > 0) progress.start("recording coverage", touched.size); - const coverage: SeriesRefT[] = []; - for (const { quantity, source } of touched.values()) { - const ref = assembleSeriesRef(athleteFilePath, quantity, source); - if (ref) coverage.push(ref); - progress.advance(); - } - progress.finish(); - - const summary = mergePayload(file, payload, coverage, knownSources); - - return { summary, label }; -} diff --git a/src/import/oura.ts b/src/import/oura.ts index 788af47d..da43e2fa 100644 --- a/src/import/oura.ts +++ b/src/import/oura.ts @@ -10,7 +10,7 @@ import type { HardSignalT } from "../schema.js"; import type { ProviderReportingPeriodT } from "../v1/schema.js"; import { countSkip, emptyPayload, type ImportPayload, type SourceBook } from "./merge.js"; -import { cell, num, parseCsv, positive, withOffset, type Row } from "./csv.js"; +import { cell, normalizeHeader, num, parseCsv, positive, withOffset, type Row } from "./csv.js"; /** Measurements taken from a sleep row. Oura already reports durations in seconds. */ const SLEEP_POINTS: { columns: string[]; type: string; unit: string }[] = [ @@ -55,6 +55,112 @@ const CONTRIBUTORS = [ "sleep_regularity", ]; +const OURA_SLEEP_SCORE_CONTRIBUTOR_KEYS = new Set([ + "timing", + "latency", + "deep_sleep", + "rem_sleep", + "total_sleep", + "efficiency", + "restfulness", +]); + +const OURA_ACTIVITY_SCORE_CONTRIBUTOR_KEYS = new Set([ + "stay_active", + "move_every_hour", + "meet_daily_targets", + "training_frequency", + "training_volume", + "recovery_time", +]); + +const OURA_READINESS_CONTRIBUTOR_KEYS = new Set(CONTRIBUTORS); + +/** Activity CSV columns we do not import yet; count them as skips when present. */ +const OURA_ACTIVITY_COLUMNS = [ + "steps", + "active_calories", + "total_calories", + "target_calories", + "met_minutes", + "low_activity_met_minutes", + "medium_activity_met_minutes", + "high_activity_met_minutes", + "equivalent_walking_distance", + "target_meters", + "meters_to_target", + "inactivity_alerts", + "resting_time", + "sedentary_met_minutes", + "low_activity_time", + "medium_activity_time", + "high_activity_time", + "sedentary_time", + "non_wear_time", + "average_met_minutes", + "met", + "class_5_min", +]; + +type OuraPortalScoreMetric = "readiness" | "sleep_score" | "activity_score"; + +function contributorKeysFromCell(contributorsJson: string | undefined): string[] | undefined { + if (contributorsJson === undefined) { + return undefined; + } + const trimmed = contributorsJson.trim(); + if (trimmed.length === 0 || trimmed === "{}") { + return []; + } + if (!trimmed.startsWith("{")) { + return undefined; + } + try { + const parsed = JSON.parse(trimmed) as Record; + return Object.keys(parsed); + } catch { + return undefined; + } +} + +function ouraPortalScoreMetricFromContributorKeys( + keys: string[], +): OuraPortalScoreMetric | undefined { + let readiness = 0; + let sleep = 0; + let activity = 0; + for (const key of keys) { + if (OURA_READINESS_CONTRIBUTOR_KEYS.has(key)) readiness++; + if (OURA_SLEEP_SCORE_CONTRIBUTOR_KEYS.has(key)) sleep++; + if (OURA_ACTIVITY_SCORE_CONTRIBUTOR_KEYS.has(key)) activity++; + } + const best = Math.max(readiness, sleep, activity); + if (best === 0) { + return undefined; + } + if (sleep === best && sleep > readiness && sleep >= activity) { + return "sleep_score"; + } + if (activity === best && activity > readiness && activity >= sleep) { + return "activity_score"; + } + return "readiness"; +} + +function detectFilePortalScoreMetric(rows: Row[]): OuraPortalScoreMetric | undefined { + for (const row of rows) { + const keys = contributorKeysFromCell(cell(row, "contributors")); + if (keys === undefined || keys.length === 0) { + continue; + } + const metric = ouraPortalScoreMetricFromContributorKeys(keys); + if (metric !== undefined) { + return metric; + } + } + return undefined; +} + function ouraTimestampReceipt(timestamp: string) { const offset = /(Z|[+-]\d{2}:\d{2})$/i.exec(timestamp.trim())?.[1]; return { @@ -69,6 +175,29 @@ function ouraTimestampReceipt(timestamp: string) { }; } +function parseJsonNumber(value: string | undefined): number | undefined { + if (value === undefined) { + return undefined; + } + const trimmed = value.trim(); + if (!trimmed.startsWith("{")) { + const direct = Number(trimmed.replace(/,/g, "")); + return Number.isFinite(direct) ? direct : undefined; + } + try { + const parsed = JSON.parse(trimmed) as Record; + if (typeof parsed.average === "number" && Number.isFinite(parsed.average)) { + return parsed.average; + } + if (typeof parsed.score === "number" && Number.isFinite(parsed.score)) { + return parsed.score; + } + } catch { + return undefined; + } + return undefined; +} + function ouraPeriod( day: string | undefined, periodType: @@ -108,6 +237,7 @@ export function importOura(files: Map, sources: SourceBook): Imp */ function importRows(rows: Row[], sourceId: string, payload: ImportPayload, name: string): void { let used = 0; + const filePortalScoreMetric = detectFilePortalScoreMetric(rows); for (const row of rows) { const bedtimeStartText = cell(row, "bedtime_start", "Bedtime Start"); @@ -128,16 +258,44 @@ function importRows(rows: Row[], sourceId: string, payload: ImportPayload, name: } used++; + const spo2Cell = cell(row, "spo2_percentage", "Average SpO2", "spo2"); + if (spo2Cell !== undefined && spo2Cell.startsWith("{")) { + const spo2FromJson = parseJsonNumber(spo2Cell); + if (spo2FromJson !== undefined && spo2FromJson > 0) { + const signal: HardSignalT = { + type: "oxygen_saturation", + value: Math.round(spo2FromJson * 100) / 100, + unit: "%", + recorded_at: anchor, + source: sourceId, + }; + payload.inputReceipts.set(signal, { + input_value: spo2FromJson, + input_unit: "%", + ...(unspecifiedPeriods === undefined + ? {} + : { provider_reporting_periods: unspecifiedPeriods }), + }); + payload.hardSignals.push(signal); + } + } + for (const mapping of SLEEP_POINTS) { + if (mapping.type === "oxygen_saturation") { + const raw = cell(row, ...mapping.columns); + if (raw !== undefined && raw.trim().startsWith("{")) { + continue; + } + } const value = positive(row, ...mapping.columns); if (value === undefined) continue; - const signal = { - type: mapping.type, + const signal: HardSignalT = { + type: mapping.type as HardSignalT["type"], value: Math.round(value * 100) / 100, unit: mapping.unit, recorded_at: anchor, source: sourceId, - } as unknown as HardSignalT; + } as HardSignalT; payload.inputReceipts.set(signal, { ...(bedtimeEndText === undefined ? {} @@ -221,6 +379,66 @@ function importRows(rows: Row[], sourceId: string, payload: ImportPayload, name: payload.hardSignals.push(session); } + const memberPortalScore = num(row, "score", "Score"); + const contributorsJson = cell(row, "contributors"); + const hasContributorsColumn = contributorsJson !== undefined; + const contributorKeys = contributorKeysFromCell(contributorsJson); + if ( + memberPortalScore !== undefined && + hasContributorsColumn && + (contributorKeys === undefined || contributorKeys.length === 0) + ) { + countSkip(payload, `${name}: score row with empty contributors`); + } + if ( + memberPortalScore !== undefined && + hasContributorsColumn && + contributorKeys !== undefined && + contributorKeys.length > 0 && + filePortalScoreMetric !== undefined + ) { + const periodType = + filePortalScoreMetric === "sleep_score" + ? "oura_sleep_day" + : filePortalScoreMetric === "activity_score" + ? "oura_activity_day" + : "oura_day_unspecified"; + const periods = + periodType === "oura_sleep_day" + ? sleepPeriods + : periodType === "oura_activity_day" + ? activityPeriods + : unspecifiedPeriods; + const signal: HardSignalT = { + type: "vendor_score", + metric: filePortalScoreMetric, + value: memberPortalScore, + scale: "0-100", + recorded_at: anchor, + source: sourceId, + }; + payload.inputReceipts.set(signal, { + input_value: memberPortalScore, + input_unit_missing_reason: "not_provided_by_source", + ...(periods === undefined ? {} : { provider_reporting_periods: periods }), + }); + payload.hardSignals.push(signal); + } + + if (num(row, "breathing_disturbance_index", "breathing_disturbance") !== undefined) { + countSkip(payload, `${name}: breathing disturbance column`); + } + if (num(row, "cardiovascular_age") !== undefined) { + countSkip(payload, `${name}: cardiovascular age column`); + } + for (const column of OURA_ACTIVITY_COLUMNS) { + const present = + column === "met" ? cell(row, column) !== undefined : num(row, column) !== undefined; + if (present) { + countSkip(payload, `${name}: activity column ${column}`); + } + } + for (const score of VENDOR_SCORES) { const value = num(row, ...score.columns); if (value === undefined) continue; @@ -257,8 +475,28 @@ function importRows(rows: Row[], sourceId: string, payload: ImportPayload, name: payload.hardSignals.push(signal); } + const contributorValues = new Map(); + if (contributorsJson !== undefined && contributorsJson.startsWith("{")) { + try { + const parsed = JSON.parse(contributorsJson) as Record; + for (const [key, value] of Object.entries(parsed)) { + if (CONTRIBUTORS.includes(key)) { + if (typeof value === "number" && Number.isFinite(value)) { + contributorValues.set(key, value); + } + } else if (typeof value === "number" && Number.isFinite(value)) { + countSkip(payload, `${name}: contributor column ${key}`); + } + } + } catch { + countSkip(payload, `${name}: contributors cell is not valid JSON`); + } + } + for (const contributor of CONTRIBUTORS) { - const value = num(row, `contributor_${contributor}`, `contributors_${contributor}`); + const value = + contributorValues.get(contributor) ?? + num(row, `contributor_${contributor}`, `contributors_${contributor}`); if (value === undefined) continue; const signal: HardSignalT = { type: "vendor_score", diff --git a/src/log.ts b/src/log.ts deleted file mode 100644 index a1c7228f..00000000 --- a/src/log.ts +++ /dev/null @@ -1,815 +0,0 @@ -/** - * `ath log` — the write path for a person and for a harness (D55). - * When the CLI itself produced a number, `ath predict` writes it (D76). - * - * Four kinds of record go through here: a measurement, a self-reported entry, a - * benchmark result, and a prediction. One write path is one thing to learn, one - * place to enforce validation, and one surface to test. - * - * Nothing is written until the summary has been shown and the one question answered - * (D56). The tool guesses — at the score, at the kind, at the subtype — and every - * guess it makes appears on the screen first. That is what separates this from the - * three silent parser failures that cost this project the most (D34, D42, D44). - */ -import { - ATHLETIC_STANDARD_VERSION, - Benchmark, - HardSignal, - Prediction, - SoftSignal, - SoftSignalType, - type AthleticStandardFileT, - type BenchmarkT, - type HardSignalT, - type PredictionT, - type ScoreT, - type SoftSignalT, -} from "./schema.js"; -import { parseEntry, ParseRefusal, type Entry } from "./logparse.js"; -import { describeScore } from "./score.js"; -import { manualSource, signalAt, sortHardSignals } from "./signals.js"; - -export { describeScore } from "./score.js"; - -/** Raised when input cannot be written, with the remedy in the message. */ -export class LogRefusal extends Error { - constructor(message: string) { - super(message); - this.name = "LogRefusal"; - } -} - -// --------------------------------------------------------------------------- -// Dates -// --------------------------------------------------------------------------- - -const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; - -/** - * A date written in an order nobody can settle. - * - * `09-04-2026` is the 4th of September in the United States and the 9th of April - * almost everywhere else, and the string itself does not decide. Every other guess - * this tool makes is shown in the summary and can be checked; this one cannot, since - * `2026-09-04` looks right under either intent. So it is refused (D56). - */ -const AMBIGUOUS_DATE = /^(\d{1,2})[-/](\d{1,2})[-/](\d{4})$/; - -/** The machine's UTC offset, written the way a timestamp states it. */ -function localOffset(at: Date): string { - const minutes = -at.getTimezoneOffset(); - const sign = minutes < 0 ? "-" : "+"; - const abs = Math.abs(minutes); - const pad = (n: number) => String(n).padStart(2, "0"); - return `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`; -} - -/** An instant written with this machine's offset, so the local day is readable. */ -export function localTimestamp(at: Date): string { - const pad = (n: number) => String(n).padStart(2, "0"); - return ( - `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}` + - `T${pad(at.getHours())}:${pad(at.getMinutes())}:${pad(at.getSeconds())}${localOffset(at)}` - ); -} - -/** Midday on a past date, since a day with no time still has to be an instant. */ -export function noonOn(day: string): string { - const [y, m, d] = day.split("-").map(Number); - return localTimestamp(new Date(y!, m! - 1, d!, 12, 0, 0)); -} - -export function today(now: Date = new Date()): string { - return localTimestamp(now).slice(0, 10); -} - -/** - * Pull a leading date off the text, and refuse one written ambiguously. - * - * Returns the day and the rest of the text. No date means today, because most - * workouts are logged the day they happen and the day is shown in the summary before - * anything is written. - */ -export function takeDate(text: string, now: Date = new Date()): { day: string; rest: string; wasToday: boolean } { - const match = /^(\S+)([\s\S]*)$/.exec(text.trim()); - const first = match?.[1] ?? ""; - - if (ISO_DATE.test(first)) { - if (Number.isNaN(Date.parse(`${first}T00:00:00Z`))) { - throw new LogRefusal(`'${first}' is not a real date.`); - } - return { day: first, rest: (match?.[2] ?? "").trim(), wasToday: first === today(now) }; - } - - const ambiguous = AMBIGUOUS_DATE.exec(first); - if (ambiguous) { - const [, a, b, year] = ambiguous; - const pad = (n: string) => n.padStart(2, "0"); - throw new LogRefusal( - `'${first}' could be ${year}-${pad(a!)}-${pad(b!)} or ${year}-${pad(b!)}-${pad(a!)}, and ` + - `nothing in it says which. Write it as ${year}-${pad(a!)}-${pad(b!)} — year, month, day.`, - ); - } - - return { day: today(now), rest: text.trim(), wasToday: true }; -} - -// --------------------------------------------------------------------------- -// The draft: what will be written, before anything is -// --------------------------------------------------------------------------- - -export interface SessionCandidate { - source: string; - start: string; - end: string; - /** How it reads in the summary: "17:25 to 17:48 on whoop-1". */ - label: string; -} - -export interface LogDraft { - hard: HardSignalT[]; - soft: SoftSignalT[]; - predictions: PredictionT[]; - /** Benchmarks that do not exist yet and will be created alongside the result. */ - newBenchmarks: BenchmarkT[]; - /** Sessions the benchmark result may have happened in, best first. */ - candidates: SessionCandidate[]; - /** - * Which candidate will be saved, or -1 for none. - * - * A match is made by asking, never by inference (D53), so it starts at -1 wherever - * there is nobody to ask. The extra key on the question moves it. - */ - chosenCandidate: number; - /** One block per record, for the summary. */ - blocks: { label: string; value: string }[][]; -} - -const SOFT_TYPES = new Set(SoftSignalType.options as readonly string[]); - -/** A benchmark id from a name a person or an agent supplied. */ -export function benchmarkId(name: string): string { - const slug = name - .toLowerCase() - .replace(/[^a-z0-9]+/g, "-") - .replace(/^-+|-+$/g, ""); - if (slug === "") throw new LogRefusal(`'${name}' has nothing in it that can be an id.`); - return /^[a-z0-9]/.test(slug) ? slug : `b-${slug}`; -} - -/** - * The sessions a result may have happened in. - * - * Same calendar day, from any source, best first — a workout logged at 6pm and a - * session at 6pm are probably the same effort, and probably is exactly why the tool - * offers them rather than picking one (D53). - */ -export function sessionCandidates(file: AthleticStandardFileT, recordedAt: string): SessionCandidate[] { - const day = recordedAt.slice(0, 10); - const at = Date.parse(recordedAt); - return file.hard_signals - .filter((s): s is Extract => s.type === "workout_session") - .filter((s) => s.start.slice(0, 10) === day) - .map((s) => ({ - source: s.source, - start: s.start, - end: s.end, - label: `${s.start.slice(11, 16)} to ${s.end.slice(11, 16)} on ${s.source}`, - })) - .sort( - (a, b) => - Math.abs(Date.parse(a.start) - at) - Math.abs(Date.parse(b.start) - at) || - a.start.localeCompare(b.start), - ); -} - -/** - * Who, if anyone, will answer the one question. - * - * `ask` — a terminal is there, the question will be put, and the reader can change - * the answer. `assume` — `--yes` was passed, so the caller has agreed in advance to - * what the tool would have shown. `none` — no terminal and no `--yes`, so there is - * nobody to agree to anything. - * - * These are three different amounts of consent, and the session match respects the - * difference (D68). - */ -export type Confirm = "ask" | "assume" | "none"; - -export interface LogInput { - /** What the person typed or pasted, or the JSON an agent passed. */ - text: string; - /** A benchmark name, which an agent supplies after recognising the workout (D54). */ - benchmark?: string | undefined; - date?: string | undefined; - scaling?: "rx" | "scaled" | undefined; - now?: Date | undefined; - confirm?: Confirm | undefined; - /** Record a second result on a day that already has one, on purpose (D67). */ - again?: boolean | undefined; -} - -/** A result already recorded for this benchmark on this day, if there is one. */ -export function existingResultOn( - file: AthleticStandardFileT, - benchmark: string, - day: string, -): Extract | undefined { - return file.hard_signals.find( - (s): s is Extract => - s.type === "benchmark_result" && s.benchmark === benchmark && s.recorded_at.slice(0, 10) === day, - ); -} - -/** - * Refuse a second result for a benchmark on a day that already has one. - * - * Almost every repeat is the same command run twice, and the cost is not a tidiness - * one: a duplicate result is counted by every baseline, every trend and every - * prediction that reads the benchmark's history, and nothing about the file looks - * wrong afterwards. A real second attempt says so with `--again` (D67). - */ -export function refuseDuplicate( - file: AthleticStandardFileT, - benchmark: string, - day: string, - again: boolean | undefined, -): void { - if (again) return; - const clash = existingResultOn(file, benchmark, day); - if (!clash) return; - throw new LogRefusal( - `'${benchmark}' already has a result on ${day}: ${describeScore(clash.result)}, recorded at ` + - `${clash.recorded_at.slice(11, 16)}. Two results for one attempt would both be counted by ` + - `every baseline and every prediction after it. If you really did it twice that day, pass ` + - `--again.`, - ); -} - -/** - * Which session the tool will attach without being told, given who is answering. - * - * One candidate under `--yes` is the ordinary case and is attached. Two candidates - * under `--yes` is a choice between two real efforts, and `--yes` means "I agree with - * what you would have shown me", not "choose for me" (D68). - */ -function defaultCandidate(confirm: Confirm, candidates: SessionCandidate[]): number { - if (confirm === "ask") return candidates.length > 0 ? 0 : -1; - if (confirm === "assume") return candidates.length === 1 ? 0 : -1; - return -1; -} - -/** Is this an agent's structured input rather than something a person typed? */ -export function looksLikeJson(text: string): boolean { - const first = text.trim()[0]; - return first === "{" || first === "["; -} - -/** - * Build everything that will be written, without writing any of it. - * - * Every guess made here lands in `blocks`, which is what the reader sees above the - * one question. Nothing reaches the file until that question is answered. - */ -export function buildDraft(file: AthleticStandardFileT, input: LogInput): LogDraft { - const now = input.now ?? new Date(); - const confirm: Confirm = input.confirm ?? "ask"; - const draft: LogDraft = { - hard: [], - soft: [], - predictions: [], - newBenchmarks: [], - candidates: [], - chosenCandidate: -1, - blocks: [], - }; - - if (looksLikeJson(input.text)) { - buildFromJson(file, draft, input.text, now, confirm, input.again); - return draft; - } - - const { day, rest, wasToday } = input.date - ? { day: checkedDay(input.date), rest: input.text.trim(), wasToday: input.date === today(now) } - : takeDate(input.text, now); - - if (rest === "") { - throw new LogRefusal( - `nothing to log. Type the entry on the line — \`ath log slept badly, about 5 hours\` — ` + - `or run \`ath log\` on its own and paste it, ending with Ctrl-D.`, - ); - } - - const recordedAt = wasToday ? localTimestamp(now) : noonOn(day); - const source = manualSource(file); - - let entries: Entry[]; - try { - entries = parseEntry(rest, { - knownBenchmarks: file.benchmarks.map((b) => b.id), - benchmark: input.benchmark, - }); - } catch (e) { - if (e instanceof ParseRefusal) throw new LogRefusal(e.message); - throw e; - } - - const dateNote = wasToday ? " (today)" : ""; - - for (const entry of entries) { - if (entry.kind === "measurement") { - draft.hard.push({ - type: entry.type, - value: entry.value, - unit: entry.unit, - recorded_at: recordedAt, - source, - ...(entry.text.trim() ? { note: entry.text.trim() } : {}), - } as HardSignalT); - draft.blocks.push([ - { label: "kind", value: "measurement (typed in by hand, not read by a device)" }, - { label: "date", value: `${day}${dateNote}` }, - { label: "reading", value: `${entry.type} ${entry.value} ${entry.unit}` }, - { label: "source", value: source }, - ]); - continue; - } - - if (entry.kind === "self-reported") { - draft.soft.push({ - type: entry.type, - reported_at: recordedAt, - ...(entry.rating !== undefined ? { rating: entry.rating, scale: entry.scale! } : {}), - ...(entry.bodyRegion ? { body_region: entry.bodyRegion } : {}), - note: entry.text, - provenance: { via: "text" }, - }); - const detail = [ - entry.type, - entry.bodyRegion, - entry.rating !== undefined ? `${entry.rating} out of ${entry.scale!.split("-")[1]}` : undefined, - ] - .filter(Boolean) - .join(", "); - draft.blocks.push([ - { label: "kind", value: "self-reported (how it felt, not what was measured)" }, - { label: "date", value: `${day}${dateNote}` }, - { label: "entry", value: detail }, - { label: "text", value: entry.text }, - ]); - continue; - } - - // A workout result. The benchmark is named by the agent, by the text, or by the - // day, in that order (D54). An unknown one is created rather than refused, - // because logging a workout nobody has done before is the ordinary case. - const named = input.benchmark ? benchmarkId(input.benchmark) : entry.namedBenchmark; - const id = named ?? freeDateName(file, draft, day, entry.text); - - const existing = file.benchmarks.find((b) => b.id === id) ?? draft.newBenchmarks.find((b) => b.id === id); - if (!existing) { - draft.newBenchmarks.push({ - id, - kind: "custom", - score_type: entry.scoreType, - definition: entry.text, - }); - } else if (existing.score_type !== entry.scoreType) { - throw new LogRefusal( - `'${id}' is scored by ${existing.score_type} and this reads as ${entry.scoreType}. ` + - `Give it a different name with --benchmark, or check the score.`, - ); - } - - refuseDuplicate(file, id, day, input.again); - - const candidates = sessionCandidates(file, recordedAt); - const result: HardSignalT = { - type: "benchmark_result", - benchmark: id, - recorded_at: recordedAt, - source, - result: entry.score, - ...(entry.segments?.length ? { segments: entry.segments } : {}), - ...(input.scaling ?? entry.scaling ? { scaling: (input.scaling ?? entry.scaling)! } : {}), - }; - draft.hard.push(result); - draft.candidates = candidates; - draft.chosenCandidate = defaultCandidate(confirm, candidates); - - const block = [ - { label: "kind", value: "workout result" }, - { label: "date", value: `${day}${dateNote}` }, - { label: "score", value: entry.scoreText }, - { label: "name", value: id }, - sessionBlock(draft, confirm), - { label: "workout", value: entry.text }, - ]; - draft.blocks.push(block); - } - - return draft; -} - -/** How the session line reads in the summary, including why nothing was chosen. */ -export function sessionBlock(draft: LogDraft, confirm: Confirm): { label: string; value: string } { - const { candidates, chosenCandidate } = draft; - if (candidates.length === 0) { - return { - label: "attach", - value: "no device recording that day yet — link it after your next import", - }; - } - if (chosenCandidate >= 0) return { label: "attach", value: candidates[chosenCandidate]!.label }; - return { - label: "attach", - value: - confirm === "assume" - ? `${candidates.length} recordings that day — not linked, because picking one is a guess. ` + - `Attach it with \`ath link\`` - : `${candidates[0]!.label} — not linked, because there is nobody to confirm it with`, - }; -} - -/** - * A date-shaped name that is free, or the same one again if the workout matches. - * - * Two different workouts on one day would otherwise share a benchmark and be - * compared against each other, which is the one thing a benchmark is for. Repeating - * the same workout keeps the same name, so the comparison still works. - */ -function freeDateName(file: AthleticStandardFileT, draft: LogDraft, day: string, text: string): string { - const all = [...file.benchmarks, ...draft.newBenchmarks]; - for (let n = 1; ; n++) { - const id = n === 1 ? day : `${day}-${n}`; - const taken = all.find((b) => b.id === id); - if (!taken || taken.definition === text) return id; - } -} - -function checkedDay(day: string): string { - if (!ISO_DATE.test(day)) { - throw new LogRefusal(`--date takes a day written as YYYY-MM-DD, not '${day}'.`); - } - return day; -} - -/** - * An agent's input, dispatched on shape rather than guessed at (D57). - * - * A `type` from the hard list is a measurement, a `type` from the soft list is - * self-reported, and `predicted` with `confidence` and no `type` is a prediction. - * The three do not overlap, so nothing here reads words. - */ -function buildFromJson( - file: AthleticStandardFileT, - draft: LogDraft, - text: string, - now: Date, - confirm: Confirm, - again: boolean | undefined, -): void { - let parsed: unknown; - try { - parsed = JSON.parse(text); - } catch (e) { - throw new LogRefusal(`that is not valid JSON: ${(e as Error).message}`); - } - - for (const raw of Array.isArray(parsed) ? parsed : [parsed]) { - if (raw === null || typeof raw !== "object") { - throw new LogRefusal("each record has to be an object."); - } - const record = raw as Record; - const type = typeof record.type === "string" ? record.type : undefined; - - if (type === undefined && "predicted" in record && "confidence" in record) { - const prediction = Prediction.safeParse({ - actual: null, - grade: null, - miss_analysis: null, - ...record, - // The version is a fact the tool knows and the agent would be guessing at, so - // the tool writes it and ignores what was passed (D66). - ath_version: ATHLETIC_STANDARD_VERSION, - }); - if (!prediction.success) throw new LogRefusal(explain("prediction", prediction.error.issues)); - if (!file.benchmarks.some((b) => b.id === prediction.data.benchmark)) { - throw new LogRefusal( - `no benchmark called '${prediction.data.benchmark}'. Predict against one that exists, ` + - `or log a result for it first.`, - ); - } - // A prediction is a claim, and a claim with no author cannot be weighed against - // the next one. The model and the program it ran in are things only the caller - // knows, so they are asked for rather than inferred (D66). - if (!prediction.data.agent?.trim()) { - throw new LogRefusal( - `that prediction does not say which agent made it, so nothing was written. ` + - `Add "agent": "" alongside ` + - `"model". Six months from now, a prediction nobody signed cannot be weighed ` + - `against the ones that were right.`, - ); - } - draft.predictions.push(prediction.data); - draft.blocks.push([ - { label: "kind", value: "prediction" }, - { label: "benchmark", value: prediction.data.benchmark }, - { label: "predicted", value: describeScore(prediction.data.predicted) }, - { label: "confidence", value: prediction.data.confidence }, - { label: "by", value: `${prediction.data.agent} running ${prediction.data.model}` }, - { label: "ath", value: ATHLETIC_STANDARD_VERSION }, - ]); - continue; - } - - if (type !== undefined && SOFT_TYPES.has(type)) { - const soft = SoftSignal.safeParse({ reported_at: localTimestamp(now), ...record }); - if (!soft.success) throw new LogRefusal(explain("self-reported entry", soft.error.issues)); - draft.soft.push(soft.data); - draft.blocks.push([ - { label: "kind", value: "self-reported" }, - { label: "date", value: soft.data.reported_at.slice(0, 10) }, - { label: "entry", value: soft.data.type }, - { label: "text", value: soft.data.note ?? "(no text)" }, - ]); - continue; - } - - const hard = HardSignal.safeParse({ - recorded_at: localTimestamp(now), - source: manualSource(file), - ...record, - }); - if (!hard.success) { - throw new LogRefusal( - explain("record", hard.error.issues) + - `\n A measurement needs a type from the hard list, a value and its unit. A ` + - `self-reported entry needs a type from the soft list. A prediction needs ` + - `predicted and confidence, and no type.`, - ); - } - const signal = hard.data; - draft.hard.push(signal); - - if (signal.type === "benchmark_result") { - if (!file.benchmarks.some((b) => b.id === signal.benchmark)) { - throw new LogRefusal( - `no benchmark called '${signal.benchmark}'. Add one by logging the workout as text, ` + - `or include a benchmarks entry first.`, - ); - } - refuseDuplicate(file, signal.benchmark, signal.recorded_at.slice(0, 10), again); - draft.candidates = signal.session ? [] : sessionCandidates(file, signal.recorded_at); - draft.chosenCandidate = defaultCandidate(confirm, draft.candidates); - draft.blocks.push([ - { label: "kind", value: "workout result" }, - { label: "date", value: signal.recorded_at.slice(0, 10) }, - { label: "score", value: describeScore(signal.result) }, - { label: "name", value: signal.benchmark }, - signal.session - ? { - label: "attach", - value: `${signal.session.start.slice(11, 16)} on ${signal.session.source}`, - } - : sessionBlock(draft, confirm), - ]); - continue; - } - - draft.blocks.push([ - { label: "kind", value: "measurement" }, - { label: "date", value: describeWhen(signal) }, - { label: "reading", value: describeHard(signal) }, - { label: "source", value: signal.source }, - ]); - } -} - -function explain(what: string, issues: { path: PropertyKey[]; message: string }[]): string { - return ( - `that ${what} does not fit the format, so nothing was written:\n` + - issues.map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n") - ); -} - -function describeWhen(sig: HardSignalT): string { - return ("recorded_at" in sig ? sig.recorded_at : sig.type === "series_ref" ? sig.from : sig.start).slice(0, 10); -} - -function describeHard(sig: HardSignalT): string { - if ("value" in sig && "unit" in sig) return `${sig.type} ${sig.value} ${sig.unit}`; - return sig.type; -} - -// --------------------------------------------------------------------------- -// The summary, and writing -// --------------------------------------------------------------------------- - -export function renderDraft(draft: LogDraft): string { - const lines: string[] = []; - const width = Math.max(...draft.blocks.flat().map((r) => r.label.length), 7); - draft.blocks.forEach((block, i) => { - if (i > 0) lines.push(""); - for (const row of block) { - const parts = row.value.split("\n"); - lines.push(` ${row.label.padEnd(width)} ${parts[0]}`); - for (const extra of parts.slice(1)) lines.push(` ${"".padEnd(width)} ${extra}`); - } - }); - return lines.join("\n"); -} - -/** Start–end as it appears on a question key: `17:45–18:13`. */ -function clockRange(c: SessionCandidate): string { - return `${c.start.slice(11, 16)}–${c.end.slice(11, 16)}`; -} - -/** - * How another recording is named on the extra key. - * - * Start and end always. The source only when two recordings share a start clock, - * so the keys stay distinct without repeating the source on every line (D74). - */ -function extraSessionLabel(c: SessionCandidate, all: SessionCandidate[]): string { - const range = `${clockRange(c)} session`; - const start = c.start.slice(11, 16); - const clash = all.some((other) => other !== c && other.start.slice(11, 16) === start); - return clash ? `${range} on ${c.source}` : range; -} - -/** - * The one question, with the extra keys the session match needs. - * - * A second candidate becomes a key on this question rather than a second question, - * because two questions in a row is how a person stops reading them (D53). Each - * choice is on its own line so the labels stay readable (D74). - */ -export function renderQuestion(draft: LogDraft): string { - const chosen = draft.chosenCandidate >= 0 ? draft.candidates[draft.chosenCandidate] : undefined; - const lines = ["Save this?", chosen ? ` [y] yes, on the ${clockRange(chosen)} session` : " [y] yes", " [n] no"]; - for (const [i, c] of draft.candidates.slice(1, 4).entries()) { - lines.push(` [${i + 2}] the ${extraSessionLabel(c, draft.candidates)} instead`); - } - return lines.join("\n"); -} - -/** Apply the draft to the file. The caller validates and saves. */ -export function applyDraft(file: AthleticStandardFileT, draft: LogDraft): void { - for (const benchmark of draft.newBenchmarks) { - const checked = Benchmark.safeParse(benchmark); - if (!checked.success) throw new LogRefusal(explain("benchmark", checked.error.issues)); - file.benchmarks.push(checked.data); - } - - const chosen = draft.chosenCandidate < 0 ? undefined : draft.candidates[draft.chosenCandidate]; - for (const signal of draft.hard) { - if (signal.type === "benchmark_result" && chosen && !signal.session) { - signal.session = { source: chosen.source, start: chosen.start }; - } - file.hard_signals.push(signal); - } - file.soft_signals.push(...draft.soft); - file.predictions.push(...draft.predictions); - - sortHardSignals(file); - file.soft_signals.sort((a, b) => Date.parse(a.reported_at) - Date.parse(b.reported_at)); -} - -/** One line per record written, echoed back so the reader sees what landed. */ -export function renderWritten(draft: LogDraft): string { - const lines: string[] = []; - for (const benchmark of draft.newBenchmarks) { - lines.push(`created benchmark '${benchmark.id}' (scored by ${benchmark.score_type})`); - } - const chosen = draft.chosenCandidate < 0 ? undefined : draft.candidates[draft.chosenCandidate]; - for (const signal of draft.hard) { - if (signal.type === "benchmark_result") { - lines.push( - `logged ${describeScore(signal.result)} on '${signal.benchmark}'` + - (signal.session ? `, linked to the ${signal.session.start.slice(11, 16)} session` : ", not linked to a session"), - ); - if (!signal.session) { - lines.push( - ` link it after your next import, or with ` + - `\`ath link ${signal.benchmark}@${signal.recorded_at.slice(0, 10)}