From ef57084e146ab6c4d706b26036776b39b8dd2d2a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 23 Oct 2026 04:30:40 +0000 Subject: [PATCH 01/12] fix: data safety, migration, repair, and 1.1.0 release prep - SQL schema 2 migration repairs npm 1.0.0 provider-import typed-table bytes - Durable atomic export, locale-independent JSON key order, ath repair command - Unify interactive migrate with confirmed backup path and database ID prompt - Oura member-portal CSV scores and JSON contributors; remove dead 0.x modules - Split CLI runtime helpers; CI on Node 22/24; D130-D143 build history Co-authored-by: Michael Whitham --- .github/workflows/ci.yml | 6 +- .github/workflows/release-cross-platform.yml | 2 +- .gitignore | 2 + README.md | 5 +- build-history/v1.0.0/decisions.md | 100 ++ build-history/v1.0.0/progress.md | 17 +- examples/demo-athlete/athlete.ath.sqlite | Bin 471040 -> 471040 bytes package.json | 2 +- scripts/check-public-data.ts | 10 +- skill/SKILL.md | 1 + skill/references/cli.md | 20 + spec/sql/contract.json | 9 +- src/backtest.ts | 353 ----- src/cli/preview-render.ts | 106 ++ src/cli/runtime.ts | 150 ++ src/context.ts | 404 ----- src/db/backup.ts | 2 +- src/db/check-tables.ts | 26 + src/db/check.ts | 28 +- src/db/client.ts | 2 +- src/db/durable-write.ts | 32 + src/db/export.ts | 49 +- src/db/index.ts | 5 + src/db/migrate.ts | 43 +- src/db/repair.ts | 102 ++ src/db/sql-contract.ts | 6 + src/db/stable-json.ts | 28 + src/grade.ts | 741 ---------- src/import/detect.ts | 2 + src/import/index.ts | 55 - src/import/oura.ts | 103 +- src/log.ts | 815 ----------- src/logparse.ts | 544 ------- src/predict.ts | 572 -------- src/program.ts | 339 +---- src/readings.ts | 101 -- src/score.ts | 113 -- src/seriesview.ts | 191 --- src/signals.ts | 66 - src/stats.ts | 378 ----- tests/backtest.test.ts | 129 -- tests/cli.test.ts | 4 +- tests/docs.test.ts | 59 - .../member-portal-dailyreadiness.csv | 3 + .../member-portal-dailysleep.csv | 3 + tests/grade.test.ts | 493 ------- tests/import.test.ts | 1304 ----------------- tests/keyring.test.ts | 23 +- tests/log.test.ts | 465 ------ tests/predict.test.ts | 382 ----- tests/schema.test.ts | 441 ------ tests/seriesview.test.ts | 97 -- tests/stats.test.ts | 163 --- tests/v1-db.test.ts | 4 +- tests/v1-migrate.test.ts | 18 +- tests/v1-provider-import.test.ts | 33 + tests/v1-repair.test.ts | 115 ++ vitest.config.ts | 13 +- 58 files changed, 1037 insertions(+), 8242 deletions(-) delete mode 100644 src/backtest.ts create mode 100644 src/cli/preview-render.ts create mode 100644 src/cli/runtime.ts delete mode 100644 src/context.ts create mode 100644 src/db/check-tables.ts create mode 100644 src/db/durable-write.ts create mode 100644 src/db/repair.ts create mode 100644 src/db/stable-json.ts delete mode 100644 src/grade.ts delete mode 100644 src/log.ts delete mode 100644 src/logparse.ts delete mode 100644 src/predict.ts delete mode 100644 src/readings.ts delete mode 100644 src/score.ts delete mode 100644 src/seriesview.ts delete mode 100644 src/signals.ts delete mode 100644 src/stats.ts delete mode 100644 tests/backtest.test.ts delete mode 100644 tests/docs.test.ts create mode 100644 tests/fixtures/exports/oura-member-portal/member-portal-dailyreadiness.csv create mode 100644 tests/fixtures/exports/oura-member-portal/member-portal-dailysleep.csv delete mode 100644 tests/grade.test.ts delete mode 100644 tests/import.test.ts delete mode 100644 tests/log.test.ts delete mode 100644 tests/predict.test.ts delete mode 100644 tests/schema.test.ts delete mode 100644 tests/seriesview.test.ts delete mode 100644 tests/stats.test.ts create mode 100644 tests/v1-repair.test.ts 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..f7cd1072 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,8 @@ 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/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..f8d53785 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,10 @@ 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`) uses the `sqlite3` command-line tool for verified +backups. Install it and ensure it is on `PATH` before running a migration. ```sh npm install -g athleticstandard diff --git a/build-history/v1.0.0/decisions.md b/build-history/v1.0.0/decisions.md index 58b02da1..a06bceae 100644 --- a/build-history/v1.0.0/decisions.md +++ b/build-history/v1.0.0/decisions.md @@ -1286,3 +1286,103 @@ 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 that copies +`record_json` into `data_json` when the parsed JSON matches, then bumps +`sql_schema_version` and `PRAGMA user_version` to 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 repair as migration step 2 when +the SQL schema is already current. It opens with `allowOutdatedSchema` so a database +that still needs SQL schema 2 can be repaired after an explicit migrate. + +## D133. Migration backup uses inode checks and honest WAL failure text + +After a verified `sqlite3` backup, `executeConfirmedDatabaseMigration` re-checks the +database file inode before enabling WAL and before applying migrations. If migration +fails after WAL was enabled, the error message says WAL may already be on and points +to the backup instead of claiming the file was untouched. + +## 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. + +## D135. Package export uses locale-independent key order and durable writes + +Export JSON sorts object keys with UTF-8 byte order, not `localeCompare`. Package +files are written through a temporary file, `fsync`, and `rename` so a crash cannot +leave a half-written package in the destination directory. + +## D136. Oura member-portal CSV columns (`score`, JSON `contributors`, JSON SpO2) + +The Oura importer accepts `score` in daily readiness and sleep exports, parses JSON +`contributors` cells, and reads `spo2_percentage.average` from JSON object cells. + +## D137. Document the `sqlite3` CLI dependency for migration backup + +README and `skill/references/cli.md` state that `ath migrate` needs the `sqlite3` +command on `PATH`. The backup error no longer claims a minimum SQLite version that +the tool does not enforce. + +## 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. + +## 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. + +## 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. + +## 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. + +## D142. Record prior build-history folder violations without rewriting old folders + +Earlier pull requests #3, #4, #6, #10, #12, #14, and #25 diverged from +`build-history/README.md` in ways this entry does not undo. #25 published npm 1.1.0 +code without a matching build-history folder at merge time. v1.0.0 `progress.md` still +lists release gates that 1.0.0 passed without cross-platform CI; that waiver is noted +here rather than rewriting the step table in place. + +## D143. 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. diff --git a/build-history/v1.0.0/progress.md b/build-history/v1.0.0/progress.md index 25ccc18f..7622e0d9 100644 --- a/build-history/v1.0.0/progress.md +++ b/build-history/v1.0.0/progress.md @@ -68,9 +68,14 @@ 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. 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. +npm `athleticstandard@1.0.0` is the latest published package on the registry. +`main` carries npm `1.1.0` code (D130) preparing the next publish: migrate and +repair for SQL schema 2, provider-encoding repair, durable export, Oura member-portal +CSV, `ath repair`, default model path beside the database, structured log envelope, +and docs. The record format stays `1.0.0`. + +Release step 10 cross-platform CI is wired to `v*` tags and `workflow_dispatch` +(D141). Step 12 remains open until Mike publishes `1.1.0` to npm after review. + +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 659f09f6098d4662d62a6f7aae0aa68b648a80d9..3c863cb0efd36fddc97a5e5468717614758a5a79 100644 GIT binary patch delta 72 zcmZp8Ak*+bW`aE<(?*A5{45(8_&07AR9Mc>=gY{>Aj&8nYU>!{VaU|HU%q|6JR=Y@ V0WmWWvj8zG5VLLHFVF5M002YY7Lxz~ delta 65 zcmZp8Ak*+bW`aE<<3@*L{M*?YSl01#vonZtiig@dhIkk@@0V}iFV6_XOhC*G#4JF} O3dC&N_sg?83IG7h6BRZ9 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..471bc971 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,14 @@ 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", + "d7cb830bfd08717aaf7038ce7b6b4e0586d24ad58748a998a131b357554361aa", + ], [ "tests/fixtures/exports/whoop/journal_entries.csv", "db60258f8c69f115afe427fdc442e6c97c85b9cc96b3d086e5aabc52157701d9", diff --git a/skill/SKILL.md b/skill/SKILL.md index 1e474061..f660810d 100644 --- a/skill/SKILL.md +++ b/skill/SKILL.md @@ -91,6 +91,7 @@ Set up: | `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 repair` | Repair typed-table JSON bytes left by npm 1.0.0 provider imports | Import, export, and create: diff --git a/skill/references/cli.md b/skill/references/cli.md index 6dd0024b..f4a2e070 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 @@ -161,6 +163,24 @@ Options: -h, --help display help for command ``` +## 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 + --dry-run show how many records would change and write nothing + --json structured preview only + -h, --help display help for command +``` + ## ath import ``` 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/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/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..a4a4275c --- /dev/null +++ b/src/cli/runtime.ts @@ -0,0 +1,150 @@ +import { createInterface } from "node:readline/promises"; +import { findFile } from "../file.js"; +import { + executeConfirmedDatabaseMigration, + MigrationRequiredError, + openDatabase, + type AthleticDatabase, + type MigrationPreview, +} from "../db/index.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 function fail(message: string): never { + console.error(`ath: ${message}`); + process.exit(1); +} + +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) { + database.close(); + return fail((error as Error).message); + } +} + +export async function openOrFail(path: string, json = false): Promise { + try { + return await openDatabase(path, { + 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..bd1624c4 100644 --- a/src/db/backup.ts +++ b/src/db/backup.ts @@ -23,7 +23,7 @@ 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.", ); } } 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..9551ed61 100644 --- a/src/db/check.ts +++ b/src/db/check.ts @@ -27,6 +27,7 @@ import { currentRecordPayloadFromRow, recordRevisionPayloadFromRow, } from "./revision-encoding.js"; +import { typedTables } from "./check-tables.js"; export interface DatabaseCheckIssue { severity: "error" | "warning"; @@ -63,33 +64,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) { diff --git a/src/db/client.ts b/src/db/client.ts index 2550355f..35b25057 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; diff --git a/src/db/durable-write.ts b/src/db/durable-write.ts new file mode 100644 index 00000000..d6f435cf --- /dev/null +++ b/src/db/durable-write.ts @@ -0,0 +1,32 @@ +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); + 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.ts b/src/db/export.ts index cbdf5406..f3abc753 100644 --- a/src/db/export.ts +++ b/src/db/export.ts @@ -1,11 +1,5 @@ import { createHash } from "node:crypto"; -import { - lstat, - mkdir, - open as openFile, - readFile, - rm, -} from "node:fs/promises"; +import { lstat, mkdir, readFile, rm } from "node:fs/promises"; import { dirname, join } from "node:path"; import type { Transaction } from "@libsql/client"; import { @@ -41,6 +35,8 @@ import { currentRecordPayloadFromRow, recordRevisionPayloadFromRow, } from "./revision-encoding.js"; +import { writeOwnerOnlyDurable } from "./durable-write.js"; +import { compareUtf8Keys, deterministicJson } from "./stable-json.js"; export interface ExportDatabaseOptions { exported_at?: string; @@ -53,37 +49,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)); } @@ -543,7 +514,7 @@ export async function exportRecords( record_import_keys: history.importKeys, }); const bytes = deterministicJson(series); - await writeOwnerOnly(join(outputDirectory, relativePath), bytes); + await writeOwnerOnlyDurable(join(outputDirectory, relativePath), bytes); const hash = sha256(bytes); files.push({ file: relativePath, @@ -577,7 +548,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 +565,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(outputDirectory, relativePath), bytes); files.push({ file: relativePath, sha256: attachment.data.sha256, @@ -615,7 +586,7 @@ export async function exportRecords( }); const packageBytes = deterministicJson(packageDocument); const packagePath = join(outputDirectory, "athlete.ath.json"); - await writeOwnerOnly(packagePath, packageBytes); + await writeOwnerOnlyDurable(packagePath, packageBytes); files.push({ file: "athlete.ath.json", sha256: sha256(packageBytes), @@ -627,12 +598,12 @@ 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( + await writeOwnerOnlyDurable( join(outputDirectory, "export-manifest.json"), manifestBytes, ); diff --git a/src/db/index.ts b/src/db/index.ts index 4ed37b26..3ee9230e 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -61,6 +61,11 @@ export { type DatabaseCheckIssue, type DatabaseCheckResult, } from "./check.js"; +export { + countProviderEncodingRepairCandidates, + repairProviderEncoding, + type ProviderEncodingRepairResult, +} from "./repair.js"; export { databaseStats, renderDatabaseStats, diff --git a/src/db/migrate.ts b/src/db/migrate.ts index 34bf61c3..c7dbfe75 100644 --- a/src/db/migrate.ts +++ b/src/db/migrate.ts @@ -1,4 +1,7 @@ import { lstat, mkdir, open as openFile, unlink } from "node:fs/promises"; +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 { @@ -515,6 +518,26 @@ 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); + if (repaired > 0) { + await incrementDatabaseRevision(transaction); + } + await transaction.execute({ + sql: ` + UPDATE database_metadata + SET sql_schema_version = ? + WHERE singleton_id = 1 + `, + args: [targetVersion], + }); + if (database.isLocal) { + await transaction.execute(`PRAGMA user_version = ${targetVersion}`); + } + }); + return; + } throw new Error( `Migration ${step.file} is not implemented in this ath build (target SQL schema ${targetVersion})`, ); @@ -588,13 +611,31 @@ 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, + })); await createVerifiedSqliteBackup(database, database.localPath, backupPath, metadata); + if (fileIdentity !== undefined && database.localPath !== undefined) { + await assertSameFile(database.localPath, fileIdentity); + } + let walEnabled = false; try { await enableLocalWal(database); + walEnabled = true; + if (fileIdentity !== undefined && database.localPath !== undefined) { + await assertSameFile(database.localPath, fileIdentity); + } await applyPendingDatabaseMigrations(database); } catch (error) { + const detail = walEnabled + ? "WAL mode may already be enabled on the original database; restore from the backup if the file no longer opens cleanly." + : "The original database was not modified."; 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/repair.ts b/src/db/repair.ts new file mode 100644 index 00000000..0fe43035 --- /dev/null +++ b/src/db/repair.ts @@ -0,0 +1,102 @@ +import type { Transaction } from "@libsql/client"; +import { databaseClient, type AthleticDatabase } from "./client.js"; +import { typedTables } from "./check-tables.js"; +import { incrementDatabaseRevision } from "./records.js"; +import { withWriteTransaction } from "./transaction.js"; + +export interface ProviderEncodingRepairResult { + repaired_record_count: number; + database_revision: number; +} + +function jsonDeepEqual(left: string, right: string): boolean { + try { + return JSON.stringify(JSON.parse(left)) === JSON.stringify(JSON.parse(right)); + } catch { + return false; + } +} + +export async function countProviderEncodingRepairCandidates( + database: AthleticDatabase, +): Promise { + const client = databaseClient(database); + let total = 0; + for (const [recordType, table] of Object.entries(typedTables)) { + const result = await client.execute({ + sql: ` + SELECT COUNT(*) AS count + 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], + }); + total += Number(result.rows[0]?.count ?? 0); + } + return total; +} + +export async function repairProviderEncodingRows( + transaction: Transaction, +): Promise { + let repaired = 0; + for (const [recordType, table] of Object.entries(typedTables)) { + const mismatches = await transaction.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 mismatches.rows) { + const recordId = String(row.record_id); + const recordJson = String(row.record_json); + const typedJson = String(row.typed_json); + if (!jsonDeepEqual(recordJson, typedJson)) { + throw new Error( + `record ${recordId} has a typed-table mismatch that is not key-order only`, + ); + } + await transaction.execute({ + sql: `UPDATE ${table} SET data_json = ? WHERE record_id = ?`, + args: [recordJson, recordId], + }); + repaired++; + } + } + return repaired; +} + +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..d18e0369 100644 --- a/src/db/sql-contract.ts +++ b/src/db/sql-contract.ts @@ -247,6 +247,12 @@ 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 function publishedMigrationSql(): string { diff --git a/src/db/stable-json.ts b/src/db/stable-json.ts new file mode 100644 index 00000000..5c5f0a27 --- /dev/null +++ b/src/db/stable-json.ts @@ -0,0 +1,28 @@ +/** Locale-independent UTF-8 key order for deterministic JSON export. */ +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"); +} 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/import/detect.ts b/src/import/detect.ts index 0d896141..b7b81d7e 100644 --- a/src/import/detect.ts +++ b/src/import/detect.ts @@ -55,6 +55,8 @@ const OURA_MARKERS = [ "total_sleep_duration", "lowest_heart_rate", "readiness_score", + "score", + "contributors", ]; function isOuraHeader(header: string): boolean { 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..9c555f4c 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 }[] = [ @@ -69,6 +69,40 @@ 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 ouraScoreMetricFromFile(fileName: string): "readiness" | "sleep_score" | undefined { + const base = normalizeHeader(fileName.replace(/\.[^.]+$/, "")); + if (base.includes("readiness")) { + return "readiness"; + } + if (base.includes("sleep") && !base.includes("sleepmodel") && !base.includes("heartrate")) { + return "sleep_score"; + } + return undefined; +} + function ouraPeriod( day: string | undefined, periodType: @@ -128,6 +162,25 @@ function importRows(rows: Row[], sourceId: string, payload: ImportPayload, name: } used++; + const spo2FromJson = parseJsonNumber(cell(row, "spo2_percentage", "Average SpO2", "spo2")); + if (spo2FromJson !== undefined && spo2FromJson > 0) { + const signal = { + type: "oxygen_saturation", + value: Math.round(spo2FromJson * 100) / 100, + unit: "%", + recorded_at: anchor, + source: sourceId, + } as unknown as HardSignalT; + 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) { const value = positive(row, ...mapping.columns); if (value === undefined) continue; @@ -221,6 +274,34 @@ function importRows(rows: Row[], sourceId: string, payload: ImportPayload, name: payload.hardSignals.push(session); } + const fileScoreMetric = ouraScoreMetricFromFile(name); + if (fileScoreMetric !== undefined) { + const value = num(row, "score", "Score"); + if (value !== undefined) { + const signal: HardSignalT = { + type: "vendor_score", + metric: fileScoreMetric, + value, + scale: "0-100", + recorded_at: anchor, + source: sourceId, + }; + const periodType = + fileScoreMetric === "sleep_score" ? "oura_sleep_day" : "oura_day_unspecified"; + const periods = + periodType === "oura_sleep_day" ? sleepPeriods : unspecifiedPeriods; + payload.inputReceipts.set(signal, { + ...(bedtimeEndText === undefined + ? {} + : { input_timestamp: ouraTimestampReceipt(bedtimeEndText) }), + input_value: value, + input_unit_missing_reason: "not_provided_by_source", + ...(periods === undefined ? {} : { provider_reporting_periods: periods }), + }); + payload.hardSignals.push(signal); + } + } + for (const score of VENDOR_SCORES) { const value = num(row, ...score.columns); if (value === undefined) continue; @@ -257,8 +338,26 @@ function importRows(rows: Row[], sourceId: string, payload: ImportPayload, name: payload.hardSignals.push(signal); } + const contributorsJson = cell(row, "contributors"); + const contributorValues = new Map(); + if (contributorsJson !== undefined && contributorsJson.startsWith("{")) { + try { + const parsed = JSON.parse(contributorsJson) as Record; + for (const contributor of CONTRIBUTORS) { + const value = parsed[contributor]; + if (typeof value === "number" && Number.isFinite(value)) { + contributorValues.set(contributor, value); + } + } + } 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)}