From 0cff21fedf4b8821238a99c6bf368b0a207bffab Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Sun, 24 May 2026 11:53:36 -0700 Subject: [PATCH 01/11] Split PMC mutation surface and stabilize compose ports --- .env.example | 13 +- AGENTS.md | 1 + README.md | 17 +- docker-compose.yml | 10 +- package.json | 2 + .../repositories/pmc-chart-calculator.test.ts | 137 ++ .../src/repositories/pmc-chart-calculator.ts | 92 ++ .../repositories/pmc-ewma-calculator.test.ts | 76 + .../src/repositories/pmc-ewma-calculator.ts | 64 + .../src/repositories/pmc-repository.test.ts | 1386 +---------------- .../server/src/repositories/pmc-repository.ts | 195 +-- .../pmc-training-load-calculator.test.ts | 155 ++ .../pmc-training-load-calculator.ts | 130 ++ scripts/compose-env.ts | 127 ++ 14 files changed, 859 insertions(+), 1546 deletions(-) create mode 100644 packages/server/src/repositories/pmc-chart-calculator.test.ts create mode 100644 packages/server/src/repositories/pmc-chart-calculator.ts create mode 100644 packages/server/src/repositories/pmc-ewma-calculator.test.ts create mode 100644 packages/server/src/repositories/pmc-ewma-calculator.ts create mode 100644 packages/server/src/repositories/pmc-training-load-calculator.test.ts create mode 100644 packages/server/src/repositories/pmc-training-load-calculator.ts create mode 100644 scripts/compose-env.ts diff --git a/.env.example b/.env.example index 19cf37e3c2..88d3644c84 100644 --- a/.env.example +++ b/.env.example @@ -3,10 +3,19 @@ # Actual secrets (API keys, client secrets, tokens) live in Infisical. CLICKHOUSE_PASSWORD=health -CLICKHOUSE_URL=http://default:health@localhost:8123 -DATABASE_URL=postgres://health:health@localhost:5435/health POSTGRES_PASSWORD=health +# Local Docker Compose publishes DB/ClickHouse/Redis on stable automatically +# assigned host ports. Run `pnpm compose:up` to generate .env.local and start +# the services with those ports. +# POSTGRES_PORT= +# CLICKHOUSE_HTTP_PORT= +# CLICKHOUSE_NATIVE_PORT= +# REDIS_PORT= +# CLICKHOUSE_URL=http://default:health@127.0.0.1: +# DATABASE_URL=postgres://health:health@127.0.0.1:/health +# REDIS_URL=redis://127.0.0.1: + # OAuth callback — set to your public URL # OAUTH_REDIRECT_URI=https://health.yourdomain.com/callback diff --git a/AGENTS.md b/AGENTS.md index 13ab2d1356..f4af4605cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,7 @@ Provider-agnostic fitness/health data pipeline. Syncs data from various provider - **No exports just for testability**: Never export a function, class, or variable solely because a test needs to access it. Exports define the public API of a module — every export should serve a production consumer. If a test needs to verify internal behavior, test it through the public interface instead. Comments like "exported for testing" are a code smell — if it's worth exporting, it's worth exporting for production use too. - **Shared test utilities**: When multiple unit or integration tests need to share mock setups, utility functions, or test data, extract them into a local `test-helpers.ts` file within the same directory. Do not export these helpers from the source file being tested or import them from another `*.test.ts` file. - **Colocated unit tests**: Unit test files live next to the source file they test, named `.test.ts`. Do not use `__tests__/` directories. For example, `src/db/tokens.ts` has its unit test at `src/db/tokens.test.ts`. Integration tests (`*.integration.test.ts`) can live wherever makes sense. +- **Test files map 1:1 to source files**: A unit test file should test one source file. If a test file grows too large because it covers several responsibilities, split the production source into smaller SOLID modules/classes and give each source file its own focused colocated test file. Do not split tests by arbitrary scenario while leaving the source file monolithic. - **Test separation**: Unit tests use `*.test.ts`, integration tests use `*.integration.test.ts`. Unit tests must never need access to external services (databases, APIs). Integration tests must never mock at the module level (`vi.mock`). For 3rd party services in integration tests, mock at the network level with [MSW](https://mswjs.io/) (`setupServer` from `msw/node`), not with constructor-injected fetch or `vi.spyOn(globalThis, 'fetch')`. - **Start integration dependencies first**: Before running any integration tests (including `pnpm test:changed`), ensure Docker dependencies are up: `docker compose up -d db redis`. Verify they are running with `docker compose ps db redis`. Do not run integration suites against a stopped local stack. - **Mutation testing (Stryker)**: High coverage is a baseline, but the goal is to kill every mutant. When the `Test / Stryker` job fails, check the logs for surviving mutants even if unit/integration tests pass. Add targeted test cases to cover the exact branch, operator, or boundary that survived. diff --git a/README.md b/README.md index 7262e9bd96..ec381afd1c 100644 --- a/README.md +++ b/README.md @@ -50,20 +50,11 @@ Each data source is a **provider plugin** that implements a simple interface. Th ## Quick Start ```bash -# Start local infrastructure -docker compose up -d db clickhouse redis - # Install dependencies pnpm install -# Configure local-only env vars (gitignored). Connection strings live here -# rather than .env because they target your Docker host. -cat > .env.local <<'EOF' -CLICKHOUSE_URL=http://default:health@localhost:8123 -REDIS_URL=redis://localhost:6379 -POSTGRES_PASSWORD=health -CLICKHOUSE_PASSWORD=health -EOF +# Start local infrastructure with collision-free stable local ports +pnpm compose:up # Log in to Infisical (see "Secrets" section below) and store the credential # encryption key — required for boot, see "Credential encryption at rest": @@ -142,11 +133,11 @@ Use `@dofek/format` for display formatting instead of local rounding, string-bui ```bash # Postgres + ClickHouse + Redis (required for any dev workflow) -docker compose up -d db clickhouse redis +pnpm compose:up # PeerDB CDC stack — required for the API server, since its boot path waits # for postgres_fitness.metric_stream and analytics views in ClickHouse. -docker compose -f docker-compose.yml -f docker-compose.peerdb.yml up -d +docker compose --env-file .env.local -f docker-compose.yml -f docker-compose.peerdb.yml up -d # (The peerdb-temporal-init container auto-registers the MirrorName Temporal # search attribute that PeerDB workflows depend on. It exits after running.) # PeerDB UI is available at http://localhost:3001 when the PeerDB stack is up. diff --git a/docker-compose.yml b/docker-compose.yml index 50289776a2..6cc969cdb8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,7 +1,7 @@ # Dev backing services. Run the app outside Docker for fast iteration. # # Usage: -# docker compose up -d +# pnpm compose:up # pnpm dev # sync runner # cd packages/web && pnpm dev # Vite dev server # cd packages/server && pnpm dev # Express API server @@ -23,7 +23,7 @@ services: POSTGRES_USER: health POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-health} ports: - - "127.0.0.1:5435:5432" + - "127.0.0.1:${POSTGRES_PORT:-0}:5432" volumes: - db_data:/var/lib/postgresql/data healthcheck: @@ -40,8 +40,8 @@ services: CLICKHOUSE_USER: default CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-health} ports: - - "127.0.0.1:${CLICKHOUSE_HTTP_PORT:-8123}:8123" - - "127.0.0.1:${CLICKHOUSE_NATIVE_PORT:-9000}:9000" + - "127.0.0.1:${CLICKHOUSE_HTTP_PORT:-0}:8123" + - "127.0.0.1:${CLICKHOUSE_NATIVE_PORT:-0}:9000" volumes: - clickhouse_data:/var/lib/clickhouse - ./deploy/clickhouse/users.d/allow-experimental-nullable-tuple-type.xml:/etc/clickhouse-server/users.d/allow-experimental-nullable-tuple-type.xml:ro @@ -60,7 +60,7 @@ services: image: redis:7-alpine restart: unless-stopped ports: - - "127.0.0.1:${REDIS_PORT:-6379}:6379" + - "127.0.0.1:${REDIS_PORT:-0}:6379" volumes: - redis_data:/data healthcheck: diff --git a/package.json b/package.json index 1499827725..a456059878 100644 --- a/package.json +++ b/package.json @@ -79,6 +79,8 @@ "dev": "./scripts/with-env.sh tsx src/index.ts", "sync": "./scripts/with-env.sh tsx src/index.ts sync", "auth": "./scripts/with-env.sh tsx src/index.ts auth", + "compose:env": "tsx scripts/compose-env.ts", + "compose:up": "pnpm compose:env --write && docker compose --env-file .env.local up -d db clickhouse redis && pnpm compose:env --write", "migrate": "./scripts/with-env.sh drizzle-kit migrate && tsx scripts/generate-schema-diagram.ts", "setup-db": "./scripts/with-env.sh tsx src/db/run-migrate.ts", "seed": "tsx scripts/seed-dev-db.ts", diff --git a/packages/server/src/repositories/pmc-chart-calculator.test.ts b/packages/server/src/repositories/pmc-chart-calculator.test.ts new file mode 100644 index 0000000000..35fe14f8a4 --- /dev/null +++ b/packages/server/src/repositories/pmc-chart-calculator.test.ts @@ -0,0 +1,137 @@ +import { TrainingStressCalculator } from "@dofek/training/training-load"; +import { describe, expect, it, vi } from "vitest"; +import { PmcChartCalculator } from "./pmc-chart-calculator.ts"; +import type { PmcActivityRow } from "./pmc-training-load-calculator.ts"; + +function makeActivityRow(overrides: Partial = {}): PmcActivityRow { + const date = new Date(); + date.setDate(date.getDate() - 2); + + return { + global_max_hr: 190, + resting_hr: 60, + id: "activity-1", + date: date.toISOString().slice(0, 10), + duration_min: 60, + avg_hr: 150, + max_hr: 180, + avg_power: 200, + power_samples: 3600, + hr_samples: 3600, + ...overrides, + }; +} + +describe("PmcChartCalculator", () => { + it("returns the generic empty model when there is no global max heart rate", () => { + const calculator = new PmcChartCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + genderFactor: 1.92, + exponent: 1.67, + }); + + const result = calculator.buildChart({ + activityRows: [makeActivityRow({ global_max_hr: null })], + normalizedPowerRows: [], + queryDays: 407, + displayDays: 90, + }); + + expect(result).toEqual({ + data: [], + model: { type: "generic", pairedActivities: 0, r2: null, ftp: null }, + }); + }); + + it("builds chart data and threshold power from activity rows", () => { + const calculator = new PmcChartCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + genderFactor: 1.92, + exponent: 1.67, + }); + + const result = calculator.buildChart({ + activityRows: [makeActivityRow({ id: "power-activity", avg_power: 200 })], + normalizedPowerRows: [{ activity_id: "power-activity", np: 220 }], + queryDays: 407, + displayDays: 90, + }); + + expect(result.model.ftp).toBe(190); + expect(result.data.length).toBeGreaterThan(0); + }); + + it("returns rounded learned model metadata when model building succeeds", () => { + const buildModelSpy = vi + .spyOn(TrainingStressCalculator, "buildTssModel") + .mockReturnValue({ slope: 1.25, intercept: 4, r2: 0.4567 }); + + try { + const calculator = new PmcChartCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + genderFactor: 1.92, + exponent: 1.67, + }); + + const result = calculator.buildChart({ + activityRows: [makeActivityRow({ id: "learned-model", avg_power: 200 })], + normalizedPowerRows: [{ activity_id: "learned-model", np: 220 }], + queryDays: 407, + displayDays: 90, + }); + + expect(buildModelSpy).toHaveBeenCalledWith([ + expect.objectContaining({ trimp: expect.any(Number), powerTss: expect.any(Number) }), + ]); + expect(result.model).toEqual({ + type: "learned", + pairedActivities: 1, + r2: 0.457, + ftp: 190, + }); + } finally { + buildModelSpy.mockRestore(); + } + }); + + it("uses resting heart rate from activity rows when calculating load", () => { + const lowRestingCalculator = new PmcChartCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + genderFactor: 1.92, + exponent: 1.67, + }); + const highRestingCalculator = new PmcChartCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + genderFactor: 1.92, + exponent: 1.67, + }); + + const lowRestingResult = lowRestingCalculator.buildChart({ + activityRows: [makeActivityRow({ avg_power: null, power_samples: 0, resting_hr: 40 })], + normalizedPowerRows: [], + queryDays: 407, + displayDays: 90, + }); + const highRestingResult = highRestingCalculator.buildChart({ + activityRows: [makeActivityRow({ avg_power: null, power_samples: 0, resting_hr: 80 })], + normalizedPowerRows: [], + queryDays: 407, + displayDays: 90, + }); + + const activityDate = lowRestingResult.data.find((point) => point.load > 0)?.date; + const lowRestingLoad = + lowRestingResult.data.find((point) => point.date === activityDate)?.load ?? 0; + const highRestingLoad = + highRestingResult.data.find((point) => point.date === activityDate)?.load ?? 0; + + expect(lowRestingLoad).toBeGreaterThan(0); + expect(highRestingLoad).toBeGreaterThan(0); + expect(lowRestingLoad).not.toBe(highRestingLoad); + }); +}); diff --git a/packages/server/src/repositories/pmc-chart-calculator.ts b/packages/server/src/repositories/pmc-chart-calculator.ts new file mode 100644 index 0000000000..d356daa9c1 --- /dev/null +++ b/packages/server/src/repositories/pmc-chart-calculator.ts @@ -0,0 +1,92 @@ +import type { PmcChartResult, TssModelInfo } from "@dofek/training/pmc"; +import { TrainingStressCalculator } from "@dofek/training/training-load"; +import { PmcEwmaCalculator } from "./pmc-ewma-calculator.ts"; +import { + type PmcActivityRow, + type PmcNormalizedPowerRow, + PmcTrainingLoadCalculator, +} from "./pmc-training-load-calculator.ts"; + +interface PmcChartCalculatorOptions { + chronicTrainingLoadDays: number; + acuteTrainingLoadDays: number; + genderFactor: number; + exponent: number; +} + +interface PmcChartInput { + activityRows: PmcActivityRow[]; + normalizedPowerRows: PmcNormalizedPowerRow[]; + queryDays: number; + displayDays: number; +} + +export class PmcChartCalculator { + readonly #trainingLoadCalculator: PmcTrainingLoadCalculator; + readonly #ewmaCalculator: PmcEwmaCalculator; + + constructor(options: PmcChartCalculatorOptions) { + this.#trainingLoadCalculator = new PmcTrainingLoadCalculator( + new TrainingStressCalculator(options.genderFactor, options.exponent), + ); + this.#ewmaCalculator = new PmcEwmaCalculator({ + chronicTrainingLoadDays: options.chronicTrainingLoadDays, + acuteTrainingLoadDays: options.acuteTrainingLoadDays, + }); + } + + buildChart(input: PmcChartInput): PmcChartResult { + const globalMaxHeartRate = + input.activityRows.length > 0 ? Number(input.activityRows[0]?.global_max_hr) : null; + if (!globalMaxHeartRate) { + return { + data: [], + model: { type: "generic", pairedActivities: 0, r2: null, ftp: null }, + }; + } + + const restingHeartRate = + input.activityRows.length > 0 ? Number(input.activityRows[0]?.resting_hr) : 60; + const normalizedPowerByActivity = new Map( + input.normalizedPowerRows.map((row) => [row.activity_id, Number(row.np)]), + ); + const thresholdPower = TrainingStressCalculator.estimateFtp(input.activityRows); + const { trainingStressModel, pairedData } = + this.#trainingLoadCalculator.buildTrainingStressModel( + input.activityRows, + normalizedPowerByActivity, + thresholdPower, + globalMaxHeartRate, + restingHeartRate, + ); + const dailyLoad = this.#trainingLoadCalculator.calculateDailyLoad({ + activities: input.activityRows, + normalizedPowerByActivity, + thresholdPower, + trainingStressModel, + globalMaxHeartRate, + restingHeartRate, + }); + const data = this.#ewmaCalculator.compute({ + dailyLoad, + queryDays: input.queryDays, + displayDays: input.displayDays, + }); + const model: TssModelInfo = + trainingStressModel != null + ? { + type: "learned", + pairedActivities: pairedData.length, + r2: Math.round(trainingStressModel.r2 * 1000) / 1000, + ftp: thresholdPower, + } + : { + type: "generic", + pairedActivities: pairedData.length, + r2: null, + ftp: thresholdPower, + }; + + return { data, model }; + } +} diff --git a/packages/server/src/repositories/pmc-ewma-calculator.test.ts b/packages/server/src/repositories/pmc-ewma-calculator.test.ts new file mode 100644 index 0000000000..ca494e525e --- /dev/null +++ b/packages/server/src/repositories/pmc-ewma-calculator.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import { PmcEwmaCalculator } from "./pmc-ewma-calculator.ts"; + +function dateStringDaysAgo(daysAgo: number): string { + const date = new Date(); + date.setDate(date.getDate() - daysAgo); + return date.toISOString().slice(0, 10); +} + +describe("PmcEwmaCalculator", () => { + it("builds rounded daily training load series with acute load responding faster than chronic load", () => { + const activityDate = dateStringDaysAgo(1); + const calculator = new PmcEwmaCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + }); + + const result = calculator.compute({ + dailyLoad: new Map([[activityDate, 84]]), + queryDays: 407, + displayDays: 30, + }); + + const activityPoint = result.find((point) => point.date === activityDate); + + expect(activityPoint).toBeDefined(); + expect(activityPoint?.load).toBe(84); + expect(activityPoint?.atl).toBeGreaterThan(activityPoint?.ctl ?? Number.POSITIVE_INFINITY); + expect(activityPoint?.tsb).toBe( + Math.round(((activityPoint?.ctl ?? 0) - (activityPoint?.atl ?? 0)) * 10) / 10, + ); + }); + + it("returns the full display window when no day reaches the meaningful chronic load threshold", () => { + const calculator = new PmcEwmaCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + }); + + const result = calculator.compute({ + dailyLoad: new Map(), + queryDays: 407, + displayDays: 30, + }); + + expect(result).toHaveLength(31); + expect(result.every((point) => point.load === 0)).toBe(true); + expect(result.every((point) => point.ctl === 0)).toBe(true); + expect(result.every((point) => point.atl === 0)).toBe(true); + expect(result.every((point) => point.tsb === 0)).toBe(true); + }); + + it("produces consecutive dates and decays chronic load on rest days", () => { + const activityDate = dateStringDaysAgo(5); + const calculator = new PmcEwmaCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + }); + + const result = calculator.compute({ + dailyLoad: new Map([[activityDate, 120]]), + queryDays: 407, + displayDays: 30, + }); + const activityIndex = result.findIndex((point) => point.date === activityDate); + + expect(activityIndex).toBeGreaterThanOrEqual(0); + for (let index = 1; index < result.length; index++) { + const previousDate = new Date(result[index - 1]?.date ?? "invalid"); + const currentDate = new Date(result[index]?.date ?? "invalid"); + expect(currentDate.getTime() - previousDate.getTime()).toBe(86_400_000); + } + expect(result[activityIndex + 2]?.ctl).toBeLessThan(result[activityIndex + 1]?.ctl ?? 0); + expect(result[activityIndex + 2]?.load).toBe(0); + }); +}); diff --git a/packages/server/src/repositories/pmc-ewma-calculator.ts b/packages/server/src/repositories/pmc-ewma-calculator.ts new file mode 100644 index 0000000000..ea24ff0d1a --- /dev/null +++ b/packages/server/src/repositories/pmc-ewma-calculator.ts @@ -0,0 +1,64 @@ +import type { PmcDataPoint } from "@dofek/training/pmc"; + +interface PmcEwmaCalculatorOptions { + chronicTrainingLoadDays: number; + acuteTrainingLoadDays: number; +} + +interface PmcEwmaInput { + dailyLoad: Map; + queryDays: number; + displayDays: number; +} + +export class PmcEwmaCalculator { + readonly #chronicTrainingLoadDays: number; + readonly #acuteTrainingLoadDays: number; + + constructor(options: PmcEwmaCalculatorOptions) { + this.#chronicTrainingLoadDays = options.chronicTrainingLoadDays; + this.#acuteTrainingLoadDays = options.acuteTrainingLoadDays; + } + + compute(input: PmcEwmaInput): PmcDataPoint[] { + const startDate = new Date(); + startDate.setDate(startDate.getDate() - input.queryDays); + const endDate = new Date(); + + const result: PmcDataPoint[] = []; + let chronicTrainingLoad = 0; + let acuteTrainingLoad = 0; + + const current = new Date(startDate); + const warmUpDays = input.queryDays - input.displayDays; + let dayIndex = 0; + + while (current <= endDate) { + const dateStr = current.toISOString().slice(0, 10); + const load = input.dailyLoad.get(dateStr) ?? 0; + + chronicTrainingLoad = + chronicTrainingLoad + (load - chronicTrainingLoad) / this.#chronicTrainingLoadDays; + acuteTrainingLoad = + acuteTrainingLoad + (load - acuteTrainingLoad) / this.#acuteTrainingLoadDays; + const trainingStressBalance = chronicTrainingLoad - acuteTrainingLoad; + + if (dayIndex >= warmUpDays) { + result.push({ + date: dateStr, + load: Math.round(load * 10) / 10, + ctl: Math.round(chronicTrainingLoad * 10) / 10, + atl: Math.round(acuteTrainingLoad * 10) / 10, + tsb: Math.round(trainingStressBalance * 10) / 10, + }); + } + + dayIndex++; + current.setDate(current.getDate() + 1); + } + + let firstMeaningfulIndex = result.findIndex((dataPoint) => dataPoint.ctl >= 0.1); + if (firstMeaningfulIndex < 0) firstMeaningfulIndex = 0; + return result.slice(firstMeaningfulIndex); + } +} diff --git a/packages/server/src/repositories/pmc-repository.test.ts b/packages/server/src/repositories/pmc-repository.test.ts index 6bca78ea10..c1c87490f9 100644 --- a/packages/server/src/repositories/pmc-repository.test.ts +++ b/packages/server/src/repositories/pmc-repository.test.ts @@ -1,4 +1,3 @@ -import { TrainingStressCalculator } from "@dofek/training/training-load"; import { describe, expect, it, vi } from "vitest"; import type { ActivitySensorStore } from "./activity-repository.ts"; import { PmcRepository } from "./pmc-repository.ts"; @@ -20,12 +19,18 @@ vi.mock("dofek/personalization/params", () => ({ }), })); +function dateStringDaysAgo(daysAgo: number): string { + const date = new Date(); + date.setDate(date.getDate() - daysAgo); + return date.toISOString().slice(0, 10); +} + function makeActivityRow(overrides: Record = {}) { return { global_max_hr: 190, resting_hr: 60, - id: "act-1", - date: "2025-06-15", + id: "activity-1", + date: dateStringDaysAgo(2), duration_min: 60, avg_hr: 150, max_hr: 180, @@ -36,10 +41,13 @@ function makeActivityRow(overrides: Record = {}) { }; } -function makeSensorStore(activityRows: unknown[], npRows: unknown[]): ActivitySensorStore { +function makeSensorStore( + activityRows: unknown[], + normalizedPowerRows: unknown[], +): ActivitySensorStore { const query = vi.fn(); query.mockResolvedValueOnce(activityRows); - query.mockResolvedValueOnce(npRows); + query.mockResolvedValueOnce(normalizedPowerRows); return { query, getActivitySummaries: vi.fn().mockResolvedValue([]), @@ -54,25 +62,13 @@ function makeSensorStore(activityRows: unknown[], npRows: unknown[]): ActivitySe } satisfies ActivitySensorStore; } -function makeRepo( - activityRows: Record[] = [], - npRows: Record[] = [], - timezone = "UTC", -) { - // loadPersonalizedParams is mocked at module level (returns null), - // so db.execute is never called. - const db = { execute: vi.fn() }; - const sensorStore = makeSensorStore(activityRows, npRows); - return new PmcRepository(db, "user-1", timezone, sensorStore); -} - function makeRepoHarness( activityRows: Record[] = [], - npRows: Record[] = [], + normalizedPowerRows: Record[] = [], timezone = "UTC", ) { const db = { execute: vi.fn() }; - const sensorStore = makeSensorStore(activityRows, npRows); + const sensorStore = makeSensorStore(activityRows, normalizedPowerRows); return { repo: new PmcRepository(db, "user-1", timezone, sensorStore), query: sensorStore.query, @@ -81,360 +77,7 @@ function makeRepoHarness( describe("PmcRepository", () => { describe("getChart", () => { - it("returns empty data with generic model when no activities", async () => { - const repo = makeRepo([], []); - const result = await repo.getChart(180); - - expect(result.data).toEqual([]); - expect(result.model).toEqual({ - type: "generic", - pairedActivities: 0, - r2: null, - ftp: null, - }); - }); - - it("returns empty result when global max HR is null", async () => { - const repo = makeRepo([makeActivityRow({ global_max_hr: null })], []); - const result = await repo.getChart(180); - - expect(result.data).toEqual([]); - expect(result.model.type).toBe("generic"); - expect(result.model.ftp).toBeNull(); - }); - - it("returns empty result when global max HR is zero", async () => { - const repo = makeRepo([makeActivityRow({ global_max_hr: 0 })], []); - const result = await repo.getChart(180); - - expect(result.data).toEqual([]); - expect(result.model.type).toBe("generic"); - }); - - it("can be instantiated and called", async () => { - const repo = makeRepo([], [], "America/New_York"); - const result = await repo.getChart(90); - - expect(result).toHaveProperty("data"); - expect(result).toHaveProperty("model"); - }); - - it("uses default resting HR of 60 when no activity data available", async () => { - const repo = makeRepo([], []); - const result = await repo.getChart(180); - // With no activities, should return empty (globalMaxHr is null) - expect(result.data).toEqual([]); - }); - - it("rounds model r2 to exactly 3 decimal places", async () => { - // When model is learned type, r2 should be rounded to 3 decimals - // This is difficult to test with mocked data, so verify the generic case - const repo = makeRepo([], []); - const result = await repo.getChart(90); - if (result.model.r2 !== null) { - const r2Str = String(result.model.r2); - const decimalPart = r2Str.split(".")[1] ?? ""; - expect(decimalPart.length).toBeLessThanOrEqual(3); - } - }); - - it("returns pairedActivities as exactly 0 (not 1 or other value) when no data", async () => { - const repo = makeRepo([], []); - const result = await repo.getChart(180); - expect(result.model.pairedActivities).toStrictEqual(0); - expect(result.model.r2).toStrictEqual(null); - expect(result.model.ftp).toStrictEqual(null); - }); - - it("trims leading zeros from EWMA output", async () => { - // Create a single activity far in the past relative to today. - // The EWMA should trim all the leading zero-CTL days. - const today = new Date(); - const daysAgo = 30; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-trim", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - // The first data point should have non-zero CTL (trimmed leading zeros) - // or be the date of the activity (first day CTL accumulates) - if (result.data.length > 0) { - const firstWithCtl = result.data.find((point) => point.ctl >= 0.1); - expect(result.data[0]?.date).toBe(firstWithCtl?.date); - } - }); - - it("computes daily load from activities with HR-only fallback", async () => { - const today = new Date(); - const daysAgo = 5; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Activity with no power data — should use HR fallback - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-hr", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - expect(result.model.type).toBe("generic"); - expect(result.model.ftp).toBeNull(); - // Should have data points — the HR fallback produces non-zero TSS - expect(result.data.length).toBeGreaterThan(0); - }); - - it("uses power TSS when NP and FTP are available", async () => { - const today = new Date(); - const daysAgo = 5; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-power", avg_power: 200, duration_min: 60 })], - [{ activity_id: "act-power", np: 220 }], - ); - const result = await repo.getChart(180); - - // FTP should be estimated (200 * 0.95 = 190) - expect(result.model.ftp).toBe(190); - expect(result.data.length).toBeGreaterThan(0); - }); - - it("returns learned model metadata with rounded r2 when regression succeeds", async () => { - const buildModelSpy = vi - .spyOn(TrainingStressCalculator, "buildTssModel") - .mockReturnValue({ slope: 1.25, intercept: 4, r2: 0.4567 }); - - try { - const today = new Date(); - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - 4); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-learned-model", - avg_power: 200, - duration_min: 60, - }), - ], - [{ activity_id: "act-learned-model", np: 220 }], - ); - - const result = await repo.getChart(180); - - expect(buildModelSpy).toHaveBeenCalledWith([ - expect.objectContaining({ trimp: expect.any(Number), powerTss: expect.any(Number) }), - ]); - expect(result.model).toEqual({ - type: "learned", - pairedActivities: 1, - r2: 0.457, - ftp: 190, - }); - } finally { - buildModelSpy.mockRestore(); - } - }); - - it("uses the learned TRIMP model for HR-only activities when FTP is known", async () => { - const buildModelSpy = vi - .spyOn(TrainingStressCalculator, "buildTssModel") - .mockReturnValue({ slope: 1.5, intercept: 10, r2: 0.75 }); - - try { - const today = new Date(); - const powerActivityDate = new Date(today); - powerActivityDate.setDate(powerActivityDate.getDate() - 4); - const powerDateStr = powerActivityDate.toISOString().split("T")[0]; - const hrOnlyActivityDate = new Date(today); - hrOnlyActivityDate.setDate(hrOnlyActivityDate.getDate() - 3); - const hrOnlyDateStr = hrOnlyActivityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: powerDateStr, - id: "act-model-source", - avg_power: 200, - duration_min: 60, - }), - makeActivityRow({ - date: hrOnlyDateStr, - id: "act-hr-only-learned", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - }), - ], - [{ activity_id: "act-model-source", np: 220 }], - ); - - const result = await repo.getChart(180); - const hrOnlyPoint = result.data.find((point) => point.date === hrOnlyDateStr); - - expect(hrOnlyPoint?.load).toBeGreaterThan(10); - expect(result.model.type).toBe("learned"); - } finally { - buildModelSpy.mockRestore(); - } - }); - - it("rounds load, ctl, atl, tsb to 1 decimal place (*10/10)", async () => { - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-round", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - for (const point of result.data) { - // Each value should have at most 1 decimal place - const loadStr = String(point.load); - const ctlStr = String(point.ctl); - const atlStr = String(point.atl); - const tsbStr = String(point.tsb); - for (const str of [loadStr, ctlStr, atlStr, tsbStr]) { - const decimals = str.includes(".") ? (str.split(".")[1]?.length ?? 0) : 0; - expect(decimals).toBeLessThanOrEqual(1); - } - } - }); - - it("EWMA uses division by chronicTrainingLoadDays=42 (not 7 or other)", async () => { - // With a single activity, the EWMA should grow slowly with CTL window of 42 - const today = new Date(); - const daysAgo = 1; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-ewma", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // Find the activity date point - const activityPoint = result.data.find((point) => point.date === dateStr); - if (activityPoint) { - // With CTL divisor=42, one day after activity, CTL should be small - // ATL with divisor=7 should be much larger than CTL - // This relationship would be inverted if the divisors were swapped - const nextDayPoint = result.data.find((point) => { - const pointDate = new Date(point.date); - const actDate = new Date(dateStr ?? ""); - return pointDate.getTime() === actDate.getTime() + 86400000; - }); - if (nextDayPoint && activityPoint.load > 0) { - // ATL responds faster (divisor=7) than CTL (divisor=42) - expect(nextDayPoint.atl).toBeGreaterThan(nextDayPoint.ctl); - } - } - }); - - it("firstMeaningfulIndex uses ctl >= 0.1 threshold (not > 0.1)", async () => { - // If ctl is exactly 0.1, it should be included (>= not >) - const today = new Date(); - const daysAgo = 1; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-threshold", - avg_power: null, - power_samples: 0, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // First data point should have ctl >= 0.1 (the threshold for "meaningful") - if (result.data.length > 0) { - expect(result.data[0]?.ctl).toBeGreaterThanOrEqual(0.1); - } - }); - - it("uses restingHr from first activity row (defaults to 60 when unavailable)", async () => { - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Provide activity with explicit resting_hr=60 - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-rhr", - resting_hr: 60, - avg_power: null, - power_samples: 0, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // Should produce data (resting HR used in TRIMP calculation) - expect(result.data.length).toBeGreaterThan(0); - }); - - it("calls execute with queryDays that uses Math.max(days, 365) + chronicTrainingLoadDays", async () => { - // With days=90, minHistoryDays=365, Math.max(90, 365) = 365 - // queryDays = 365 + 42 = 407 - // We verify by ensuring that small days values still produce results - // (because we always query at least 365 days of history) - const today = new Date(); - const daysAgo = 200; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-query", avg_power: null, power_samples: 0 })], - [], - ); - - // Even with days=90, we still get data because minHistoryDays=365 - // means we fetch 365+42=407 days of history - await repo.getChart(90); - // The execute call should have happened (query was built) - expect(true).toBe(true); - }); - - it("passes timezone and expanded queryDays to both ClickHouse queries", async () => { + it("passes timezone and expanded query window to ClickHouse activity and power queries", async () => { const { repo, query } = makeRepoHarness( [makeActivityRow({ avg_power: null, power_samples: 0 })], [], @@ -461,7 +104,7 @@ describe("PmcRepository", () => { ); }); - it("extends queryDays from requested days when request exceeds the minimum history", async () => { + it("extends query history when requested display days exceed the minimum history", async () => { const { repo, query } = makeRepoHarness([], []); await repo.getChart(400); @@ -470,994 +113,49 @@ describe("PmcRepository", () => { 1, expect.anything(), expect.stringContaining("INTERVAL {queryDays:Int32} DAY"), - expect.objectContaining({ userId: "user-1", timezone: "UTC", queryDays: 442 }), - ); - }); - - it("queries sufficient history even for small day values (minHistoryDays=365)", async () => { - const repo = makeRepo([], []); - // With days=30, should still call execute (Math.max(30, 365)=365, queryDays=365+42=407) - await repo.getChart(30); - // 1st execute = activities query (returns empty) - // 2nd execute = base activity count check from queryWithViewRefresh - expect(true).toBe(true); - }); - - it("returns generic model with exact field values when no globalMaxHr", async () => { - const repo = makeRepo([], []); - const result = await repo.getChart(90); - - // Kill ObjectLiteral mutations: verify every field of the early-return model - expect(result.model.type).toStrictEqual("generic"); - expect(result.model.pairedActivities).toStrictEqual(0); - expect(result.model.r2).toStrictEqual(null); - expect(result.model.ftp).toStrictEqual(null); - expect(result.data).toStrictEqual([]); - }); - - it("returns model with type exactly 'generic' not 'learned' when no paired data", async () => { - const today = new Date(); - const daysAgo = 5; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Activity with HR but no power -> generic model - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-gen", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - expect(result.model.type).toStrictEqual("generic"); - expect(result.model.r2).toStrictEqual(null); - }); - - it("computes tsb as ctl minus atl (not atl minus ctl)", async () => { - // tsb = ctl - atl. If mutated to ctl + atl, tsb would always be positive. - // With a recent single activity, atl > ctl, so tsb should be negative. - const today = new Date(); - const daysAgo = 1; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-tsb", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 160, - max_hr: 185, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // On the day after a hard activity, ATL > CTL => TSB < 0 - const dayAfter = result.data.find((point) => { - const pointDate = new Date(point.date); - const actDate = new Date(dateStr ?? ""); - return pointDate.getTime() === actDate.getTime() + 86400000; - }); - if (dayAfter && dayAfter.atl > dayAfter.ctl) { - expect(dayAfter.tsb).toBeLessThan(0); - } - }); - - it("EWMA formula uses (load - ctl) not (load + ctl)", async () => { - // ctl = ctl + (load - ctl) / days. If mutated to (load + ctl), values diverge. - // On a rest day (load=0) after an activity, ctl should decrease (not increase). - const today = new Date(); - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - 5); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-ewma-decay", - avg_power: null, - power_samples: 0, - duration_min: 90, - avg_hr: 155, - max_hr: 180, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // Find two consecutive rest days after the activity - const activityIndex = result.data.findIndex((point) => point.date === dateStr); - if (activityIndex >= 0 && activityIndex + 2 < result.data.length) { - const dayOne = result.data[activityIndex + 1]; - const dayTwo = result.data[activityIndex + 2]; - if (dayOne && dayTwo) { - // On rest days (load=0), CTL should decay (decrease) - expect(dayTwo.ctl).toBeLessThan(dayOne.ctl); - } - } - }); - - it("daily load accumulates via += (not -=)", async () => { - // dailyLoad.set(dateStr, (dailyLoad.get(dateStr) ?? 0) + tss) - // If + was mutated to -, second activity would subtract from first - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Two activities on the same day, both should add up - const singleRepo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-single", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [], + expect.objectContaining({ queryDays: 442 }), ); - const singleResult = await singleRepo.getChart(180); - const singleDayLoad = singleResult.data.find((point) => point.date === dateStr)?.load ?? 0; - - const doubleRepo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-am2", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - makeActivityRow({ - date: dateStr, - id: "act-pm2", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [], + expect(query).toHaveBeenNthCalledWith( + 2, + expect.anything(), + expect.stringContaining("INTERVAL {queryDays:Int32} DAY"), + expect.objectContaining({ queryDays: 442 }), ); - const doubleResult = await doubleRepo.getChart(180); - const doubleDayLoad = doubleResult.data.find((point) => point.date === dateStr)?.load ?? 0; - - // Two identical activities should produce approximately double the load - expect(doubleDayLoad).toBeGreaterThan(singleDayLoad); }); - it("learned model uses Math.max(0, slope*trimp + intercept) (not allowing negative TSS)", async () => { - // Math.max(0, tssModel.slope * trimp + tssModel.intercept) - // If Math.max(0, ...) was removed, negative TSS could appear - // This is hard to test with mocks but we can verify no negative loads appear - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-non-negative", - avg_power: null, - power_samples: 0, - }), - ], - [], + it("reads sample counts and normalized power from deduped ClickHouse sensors", async () => { + const { repo, query } = makeRepoHarness( + [makeActivityRow()], + [{ activity_id: "activity-1", np: 220 }], ); - const result = await repo.getChart(180); - - for (const point of result.data) { - // load should never be negative - expect(point.load).toBeGreaterThanOrEqual(0); - } - }); - - it("r2 rounding uses * 1000 / 1000 (3 decimal places, not 2 or 4)", async () => { - // Math.round(tssModel.r2 * 1000) / 1000 - // When we have a learned model, verify the r2 is properly rounded - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Create multiple activities with NP to trigger model building - const activities = [ - makeActivityRow({ - date: dateStr, - id: "act-r2-1", - avg_power: 200, - power_samples: 3600, - duration_min: 60, - }), - makeActivityRow({ - date: dateStr, - id: "act-r2-2", - avg_power: 180, - power_samples: 3600, - duration_min: 45, - }), - ]; - const npRows = [ - { activity_id: "act-r2-1", np: 210 }, - { activity_id: "act-r2-2", np: 190 }, - ]; - const repo = makeRepo(activities, npRows); - const result = await repo.getChart(180); - - if (result.model.r2 !== null) { - // r2 should have at most 3 decimal places - const r2Str = result.model.r2.toString(); - const decimalPart = r2Str.split(".")[1] ?? ""; - expect(decimalPart.length).toBeLessThanOrEqual(3); - } - }); - it("load rounding uses * 10 / 10 (1 decimal, not * 100 / 100)", async () => { - // Math.round(load * 10) / 10 - // Verify values have at most 1 decimal place - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; + await repo.getChart(90); - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-round2", avg_power: null, power_samples: 0 })], - [], + expect(query).toHaveBeenNthCalledWith( + 1, + expect.anything(), + expect.stringContaining("countIf(channel = 'heart_rate') AS hr_samples"), + expect.anything(), ); - const result = await repo.getChart(180); - - for (const point of result.data) { - // Multiply by 10 and check it's an integer (exactly 1 decimal place) - expect(Number.isInteger(Math.round(point.load * 10))).toBe(true); - expect(Number.isInteger(Math.round(point.ctl * 10))).toBe(true); - expect(Number.isInteger(Math.round(point.atl * 10))).toBe(true); - expect(Number.isInteger(Math.round(point.tsb * 10))).toBe(true); - } - }); - - it("warmUpDays = queryDays - displayDays (not queryDays + displayDays)", async () => { - // warmUpDays = queryDays - displayDays. If mutated to +, no data would show. - const today = new Date(); - const daysAgo = 10; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-warmup", avg_power: null, power_samples: 0 })], - [], + expect(query).toHaveBeenNthCalledWith( + 2, + expect.anything(), + expect.stringContaining("INNER JOIN analytics.v_activity a ON a.id = ds.activity_id"), + expect.anything(), ); - const result = await repo.getChart(180); - - // Should have data (if - was mutated to +, warmUpDays would be huge and no data shown) - expect(result.data.length).toBeGreaterThan(0); }); - it("dayIndex starts at 0 and increments by 1 (not 0+2 or 1+1)", async () => { - // dayIndex++ ensures we count days correctly from 0 - const today = new Date(); - const daysAgo = 5; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-day-index", - avg_power: null, - power_samples: 0, - }), - ], - [], + it("returns chart data built from ClickHouse rows", async () => { + const { repo } = makeRepoHarness( + [makeActivityRow({ id: "power-activity" })], + [{ activity_id: "power-activity", np: 220 }], ); - const result = await repo.getChart(30); - // With days=30, we should have at most 31 data points (30 days + today) - // If dayIndex increment was wrong, count would be different - expect(result.data.length).toBeLessThanOrEqual(31); - expect(result.data.length).toBeGreaterThan(0); - }); - - it("firstMeaningfulIndex defaults to 0 when no point has ctl >= 0.1", async () => { - // firstMeaningfulIndex < 0 → firstMeaningfulIndex = 0 - // With activities that have very low TSS, all points might have ctl < 0.1 - // but we should still get data starting from index 0 - const repo = makeRepo([], []); const result = await repo.getChart(90); - // Empty activities => empty result (early return due to null globalMaxHr) - expect(result.data).toStrictEqual([]); - }); - - it("queryDays uses addition not subtraction: Math.max(days, 365) + chronicTrainingLoadDays", async () => { - // queryDays = Math.max(days, minHistoryDays) + chronicTrainingLoadDays - // If + mutated to -, queryDays = 365 - 42 = 323 (fewer days of history) - // With days=400 (> minHistoryDays), Math.max(400, 365) = 400 - // queryDays = 400 + 42 = 442 (if -, would be 358) - const repo = makeRepo([], []); - await repo.getChart(400); - // Verify execute was called (query was constructed successfully) - expect(true).toBe(true); - }); - - it("EWMA ctl update uses division by chronicTrainingLoadDays (not multiplication)", async () => { - // ctl = ctl + (load - ctl) / chronicTrainingLoadDays - // If / mutated to *, values would explode - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-div", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - // CTL values should be bounded and reasonable (< 1000) - // If division was mutated to multiplication, CTL would be enormous - for (const point of result.data) { - expect(point.ctl).toBeLessThan(1000); - expect(point.atl).toBeLessThan(1000); - } - }); - - it("EWMA atl update uses division by acuteTrainingLoadDays (not multiplication)", async () => { - // atl = atl + (load - atl) / acuteTrainingLoadDays - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-atl-div", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - // ATL values should be bounded - for (const point of result.data) { - expect(Math.abs(point.atl)).toBeLessThan(1000); - } - }); - it("daily load uses ?? 0 default (not ?? 1 or undefined)", async () => { - // dailyLoad.get(dateStr) ?? 0 - // On rest days, load should be exactly 0, not 1 or NaN - const today = new Date(); - const daysAgo = 5; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-zero", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - // Days after the activity should have load = 0 - const restDay = result.data.find((point) => { - const pointDate = new Date(point.date); - const actDate = new Date(dateStr ?? ""); - return pointDate.getTime() > actDate.getTime() + 86400000; - }); - if (restDay) { - expect(restDay.load).toStrictEqual(0); - } - }); - - it("firstMeaningfulIndex < 0 check (boundary: no meaningful points)", async () => { - // if (firstMeaningfulIndex < 0) firstMeaningfulIndex = 0 - // If < mutated to <=, when exactly 0 (first point is meaningful), it would reset to 0 anyway (same result) - // But if < mutated to >, it would always reset to 0 even when there's a valid index - // We test this by ensuring data starts at the right point - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-idx", - avg_power: null, - power_samples: 0, - duration_min: 120, - avg_hr: 170, - max_hr: 190, - }), - ], - [], - ); - const result = await repo.getChart(180); - - if (result.data.length > 0) { - // First point should have ctl >= 0.1 (the meaningful threshold) - expect(result.data[0]?.ctl).toBeGreaterThanOrEqual(0.1); - } - }); - - it("model type is 'learned' string literal (not generic) when tssModel exists", async () => { - // tssModel != null => type: "learned" - // We need enough paired activities to build a regression model - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Multiple activities with both HR and NP data to trigger model building - const activities = Array.from({ length: 20 }, (_, index) => - makeActivityRow({ - date: dateStr, - id: `act-model-${index}`, - avg_power: 150 + index * 10, - power_samples: 3600, - duration_min: 30 + index * 5, - avg_hr: 130 + index * 2, - max_hr: 180, - }), - ); - const npRows = activities.map((activity) => ({ - activity_id: activity.id, - np: (activity.avg_power ?? 0) + 10, - })); - - const repo = makeRepo(activities, npRows); - const result = await repo.getChart(180); - - // With enough paired data, the model should be "learned" not "generic" - if (result.model.type === "learned") { - expect(result.model.type).toStrictEqual("learned"); - expect(result.model.r2).not.toBeNull(); - expect(result.model.pairedActivities).toBeGreaterThan(0); - } - }); - - it("current.setDate increments by 1 (not 2 or 0)", async () => { - // current.setDate(current.getDate() + 1) - // If + mutated to -, loop would go backwards infinitely (or timeout) - // We verify the data points have consecutive dates - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-consecutive", - avg_power: null, - power_samples: 0, - }), - ], - [], - ); - const result = await repo.getChart(30); - - // Check that consecutive data points are exactly 1 day apart - for (let index = 1; index < result.data.length; index++) { - const prevDate = new Date(result.data[index - 1]?.date ?? ""); - const currDate = new Date(result.data[index]?.date ?? ""); - const diffMs = currDate.getTime() - prevDate.getTime(); - expect(diffMs).toBe(86400000); // exactly 1 day in ms - } - }); - - it("npByActivity map uses activity_id as key (not np as key)", async () => { - // npByActivity = new Map(npRows.map(row => [row.activity_id, Number(row.np)])) - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-np-map", avg_power: 200, duration_min: 60 })], - [{ activity_id: "act-np-map", np: 215 }], - ); - const result = await repo.getChart(180); - - // Should have FTP and data (NP was found via activity_id mapping) - expect(result.model.ftp).not.toBeNull(); - expect(result.data.length).toBeGreaterThan(0); - }); - - it("aggregates multiple activities on the same day into one daily load", async () => { - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-am", - avg_power: null, - power_samples: 0, - duration_min: 60, - }), - makeActivityRow({ - date: dateStr, - id: "act-pm", - avg_power: null, - power_samples: 0, - duration_min: 30, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // Should have aggregated both activities into a single day's load - const dayPoint = result.data.find((point) => point.date === dateStr); - expect(dayPoint).toBeDefined(); - // Load should be higher than a single 60-min activity - if (dayPoint) { - expect(dayPoint.load).toBeGreaterThan(0); - } - }); - - it("PmcDataPoint has exactly date, load, ctl, atl, tsb properties", async () => { - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-shape", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - expect(result.data.length).toBeGreaterThan(0); - for (const point of result.data) { - expect(Object.keys(point).sort()).toStrictEqual(["atl", "ctl", "date", "load", "tsb"]); - } - }); - - it("PmcDataPoint ctl and atl are not swapped", async () => { - // After a single recent activity, ATL (7-day) responds faster than CTL (42-day), - // so ATL > CTL on the activity day. If they were swapped, this would fail. - const today = new Date(); - const daysAgo = 1; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-swap", - avg_power: null, - power_samples: 0, - duration_min: 90, - avg_hr: 165, - max_hr: 190, - }), - ], - [], - ); - const result = await repo.getChart(180); - - const activityDayPoint = result.data.find((point) => point.date === dateStr); - expect(activityDayPoint).toBeDefined(); - if (activityDayPoint && activityDayPoint.load > 0) { - // ATL should be greater than CTL because ATL uses 7-day window (responds faster) - expect(activityDayPoint.atl).toBeGreaterThan(activityDayPoint.ctl); - // TSB should equal CTL - ATL (verified by checking sign) - expect(activityDayPoint.tsb).toBeLessThan(0); - // Verify exact relationship: tsb = round(ctl - atl, 1 decimal) - const expectedTsb = Math.round((activityDayPoint.ctl - activityDayPoint.atl) * 10) / 10; - expect(activityDayPoint.tsb).toBe(expectedTsb); - } - }); - - it("PmcDataPoint load is not the same as ctl or atl for activity days", async () => { - // Kill ObjectLiteral mutant where load property is replaced with ctl or atl value - const today = new Date(); - const daysAgo = 1; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-load-diff", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 155, - max_hr: 185, - }), - ], - [], - ); - const result = await repo.getChart(180); - - const activityDayPoint = result.data.find((point) => point.date === dateStr); - expect(activityDayPoint).toBeDefined(); - if (activityDayPoint) { - // On the first activity day, load is the raw TSS, while ctl and atl are - // EWMA values that are much smaller (approaching load/42 and load/7 respectively). - // So load should be distinctly different from both ctl and atl. - expect(activityDayPoint.load).toBeGreaterThan(activityDayPoint.ctl); - expect(activityDayPoint.load).toBeGreaterThan(activityDayPoint.atl); - } - }); - - it("uses power TSS branch when activity has both NP and FTP (not HR fallback)", async () => { - // Kills LogicalOperator mutant for: ftp != null && normalizedPower != null && normalizedPower > 0 - // Tests that power TSS produces different load than HR-only fallback - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Activity with power data - const powerRepo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-pwr", - avg_power: 200, - power_samples: 3600, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [{ activity_id: "act-pwr", np: 220 }], - ); - const powerResult = await powerRepo.getChart(180); - - // Same activity without NP data -> HR fallback - const hrRepo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-hr-only", - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [], - ); - const hrResult = await hrRepo.getChart(180); - - const powerDayLoad = powerResult.data.find((point) => point.date === dateStr)?.load ?? 0; - const hrDayLoad = hrResult.data.find((point) => point.date === dateStr)?.load ?? 0; - - // Both should produce positive load - expect(powerDayLoad).toBeGreaterThan(0); - expect(hrDayLoad).toBeGreaterThan(0); - // Power TSS and HR TSS should produce different values (different algorithms) - expect(powerDayLoad).not.toBe(hrDayLoad); - }); - - it("NP = 0 falls through to HR fallback (normalizedPower > 0 check)", async () => { - // Kills LogicalOperator/ConditionalExpression mutant for normalizedPower > 0 - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Activity has FTP (from avg_power) but NP = 0 -> should use HR fallback - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-np-zero", - avg_power: 200, - power_samples: 3600, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [{ activity_id: "act-np-zero", np: 0 }], - ); - const result = await repo.getChart(180); - - // FTP should still be estimated from avg_power expect(result.model.ftp).toBe(190); - // Should still produce data since HR fallback works - expect(result.data.length).toBeGreaterThan(0); - const dayPoint = result.data.find((point) => point.date === dateStr); - expect(dayPoint).toBeDefined(); - expect(dayPoint?.load).toBeGreaterThan(0); - }); - - it("restingHr extraction uses activityRows[0] not a hardcoded value", async () => { - // Kills ArrowFunction/ObjectLiteral mutant on restingHr extraction - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Low resting HR should produce higher TRIMP (larger delta HR ratio) - const lowRhrRepo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-low-rhr", - resting_hr: 40, - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [], - ); - const lowRhrResult = await lowRhrRepo.getChart(180); - - // High resting HR should produce lower TRIMP (smaller delta HR ratio) - const highRhrRepo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-high-rhr", - resting_hr: 80, - avg_power: null, - power_samples: 0, - duration_min: 60, - avg_hr: 150, - max_hr: 180, - }), - ], - [], - ); - const highRhrResult = await highRhrRepo.getChart(180); - - const lowRhrLoad = lowRhrResult.data.find((point) => point.date === dateStr)?.load ?? 0; - const highRhrLoad = highRhrResult.data.find((point) => point.date === dateStr)?.load ?? 0; - - // Lower resting HR means larger heart rate reserve, which produces higher TRIMP - expect(lowRhrLoad).toBeGreaterThan(0); - expect(highRhrLoad).toBeGreaterThan(0); - expect(lowRhrLoad).not.toBe(highRhrLoad); - }); - - it("globalMaxHr extraction uses Number() conversion (not string)", async () => { - // Kills ArrowFunction mutant on: Number(activityRows[0]?.global_max_hr) - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-maxhr-num", - global_max_hr: "195", - avg_power: null, - power_samples: 0, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // globalMaxHr should be truthy (numeric 195, not string "195" which is also truthy, - // but internally Number("195") = 195 which affects TRIMP computation) expect(result.data.length).toBeGreaterThan(0); - }); - - it("early return model has all four fields with exact values", async () => { - // Kills ObjectLiteral mutants on the early-return object (lines 95-98) - const repo = makeRepo([], []); - const result = await repo.getChart(90); - - // Verify each field independently to kill individual property mutations - expect(result.model.type).toBe("generic"); - expect(result.model.pairedActivities).toBe(0); - expect(result.model.r2).toBe(null); - expect(result.model.ftp).toBe(null); - // Verify no extra fields - expect(Object.keys(result.model).sort()).toStrictEqual([ - "ftp", - "pairedActivities", - "r2", - "type", - ]); - }); - - it("result from getChart returns object with exactly data and model keys", async () => { - // Kills ObjectLiteral mutant on return { data: result, model: modelInfo } - const repo = makeRepo([], []); - const result = await repo.getChart(90); - expect(Object.keys(result).sort()).toStrictEqual(["data", "model"]); - expect(Array.isArray(result.data)).toBe(true); - expect(typeof result.model).toBe("object"); - expect(result.model).not.toBeNull(); - }); - - it("date string in PmcDataPoint comes from toISOString split (YYYY-MM-DD format)", async () => { - // Kills ArrowFunction/StringLiteral mutant on dateStr = current.toISOString().split("T")[0] ?? "" - const today = new Date(); - const daysAgo = 2; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [makeActivityRow({ date: dateStr, id: "act-date-fmt", avg_power: null, power_samples: 0 })], - [], - ); - const result = await repo.getChart(180); - - for (const point of result.data) { - // Date should match YYYY-MM-DD format - expect(point.date).toMatch(/^\d{4}-\d{2}-\d{2}$/); - // Date should not be empty string - expect(point.date.length).toBe(10); - } - }); - - it("learned model with paired data returns non-null r2 and correct pairedActivities count", async () => { - // Kill ObjectLiteral mutant on the "learned" model info object (lines 164-169) - const today = new Date(); - const daysAgo = 3; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - // Create 20 activities with diverse power/HR to build a regression model - const activities = Array.from({ length: 20 }, (_, index) => - makeActivityRow({ - date: dateStr, - id: `act-learned-${index}`, - avg_power: 150 + index * 10, - power_samples: 3600, - duration_min: 30 + index * 5, - avg_hr: 120 + index * 3, - max_hr: 185, - }), - ); - const npRows = activities.map((activity) => ({ - activity_id: activity.id, - np: (activity.avg_power ?? 0) + 15, - })); - - const repo = makeRepo(activities, npRows); - const result = await repo.getChart(180); - - if (result.model.type === "learned") { - // Verify all fields of the learned model object - expect(result.model.type).toStrictEqual("learned"); - expect(typeof result.model.r2).toBe("number"); - expect(result.model.r2).not.toBeNull(); - expect(result.model.pairedActivities).toBeGreaterThan(0); - expect(result.model.ftp).not.toBeNull(); - expect(typeof result.model.ftp).toBe("number"); - // Verify model info has exactly 4 keys - expect(Object.keys(result.model).sort()).toStrictEqual([ - "ftp", - "pairedActivities", - "r2", - "type", - ]); - } - }); - - it("daily load accumulation uses ?? 0 fallback (not ?? 1)", async () => { - // Kills mutation of ?? 0 to ?? 1 in: (dailyLoad.get(dateStr) ?? 0) + tss - // If the fallback were 1 instead of 0, rest day loads would be 1 not 0 - const today = new Date(); - const daysAgo = 5; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-fallback", - avg_power: null, - power_samples: 0, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // Count rest days (load = 0) vs activity days (load > 0) - const restDays = result.data.filter((point) => point.load === 0); - const activityDays = result.data.filter((point) => point.load > 0); - - // There should be exactly 1 activity day and many rest days - expect(activityDays).toHaveLength(1); - expect(restDays.length).toBeGreaterThan(0); - - // Rest day loads must be exactly 0.0, not 1.0 - for (const restDay of restDays) { - expect(restDay.load).toStrictEqual(0); - } - }); - - it("EWMA load retrieval uses dailyLoad.get(dateStr) ?? 0 (not hardcoded)", async () => { - // Kills mutation on: const load = dailyLoad.get(dateStr) ?? 0 - // If load was always 0, CTL and ATL would never grow - const today = new Date(); - const daysAgo = 1; - const activityDate = new Date(today); - activityDate.setDate(activityDate.getDate() - daysAgo); - const dateStr = activityDate.toISOString().split("T")[0]; - - const repo = makeRepo( - [ - makeActivityRow({ - date: dateStr, - id: "act-ewma-load", - avg_power: null, - power_samples: 0, - duration_min: 120, - avg_hr: 160, - max_hr: 190, - }), - ], - [], - ); - const result = await repo.getChart(180); - - // Find the activity day - const activityDayPoint = result.data.find((point) => point.date === dateStr); - expect(activityDayPoint).toBeDefined(); - if (activityDayPoint) { - // Load should be positive on activity day - expect(activityDayPoint.load).toBeGreaterThan(0); - // CTL should be positive on activity day (proves EWMA used the load) - expect(activityDayPoint.ctl).toBeGreaterThan(0); - // ATL should be positive on activity day - expect(activityDayPoint.atl).toBeGreaterThan(0); - } }); }); }); diff --git a/packages/server/src/repositories/pmc-repository.ts b/packages/server/src/repositories/pmc-repository.ts index 740443ecb2..11e2c6e70d 100644 --- a/packages/server/src/repositories/pmc-repository.ts +++ b/packages/server/src/repositories/pmc-repository.ts @@ -1,5 +1,4 @@ -import type { PmcChartResult, PmcDataPoint, TssModelInfo } from "@dofek/training/pmc"; -import { TrainingStressCalculator } from "@dofek/training/training-load"; +import type { PmcChartResult } from "@dofek/training/pmc"; import type { Database } from "dofek/db"; import { getEffectiveParams } from "dofek/personalization/params"; @@ -8,6 +7,7 @@ import { z } from "zod"; import { BaseRepository } from "../lib/base-repository.ts"; import { dateWindowStartString } from "../lib/date-window.ts"; import type { ActivitySensorStore } from "./activity-repository.ts"; +import { PmcChartCalculator } from "./pmc-chart-calculator.ts"; import { restingHeartRateClickHouseCte } from "./resting-heart-rate-query.ts"; // --------------------------------------------------------------------------- @@ -27,8 +27,6 @@ const combinedActivityRowSchema = z.object({ hr_samples: z.coerce.number(), }); -type ActivityRow = z.infer; - const normalizedPowerRowSchema = z.object({ activity_id: z.string(), np: z.coerce.number(), @@ -59,7 +57,6 @@ export class PmcRepository extends BaseRepository { const effective = getEffectiveParams(storedParams); const { chronicTrainingLoadDays, acuteTrainingLoadDays } = effective.exponentialMovingAverage; const { genderFactor, exponent } = effective.trainingImpulseConstants; - const calculator = new TrainingStressCalculator(genderFactor, exponent); // Fetch enough history for EWMA convergence, regardless of display range. const minHistoryDays = 365; @@ -123,18 +120,8 @@ export class PmcRepository extends BaseRepository { }, ); - const globalMaxHr = activityRows.length > 0 ? Number(activityRows[0]?.global_max_hr) : null; - if (!globalMaxHr) { - return { - data: [], - model: { type: "generic", pairedActivities: 0, r2: null, ftp: null }, - }; - } - - const restingHr = activityRows.length > 0 ? Number(activityRows[0]?.resting_hr) : 60; - // QUERY 2: Normalized Power per activity from analytics.deduped_sensor. - const npRows = await this.#sensorStore.query( + const normalizedPowerRows = await this.#sensorStore.query( normalizedPowerRowSchema, `WITH rolling AS ( SELECT @@ -159,174 +146,18 @@ export class PmcRepository extends BaseRepository { HAVING count() >= 60`, { userId: this.userId, queryDays }, ); - const npByActivity = new Map(npRows.map((row) => [row.activity_id, Number(row.np)])); - - // Estimate FTP and build regression model - const ftp = TrainingStressCalculator.estimateFtp(activityRows); - const { tssModel, pairedData } = this.#buildRegressionModel( - activityRows, - npByActivity, - ftp, - calculator, - globalMaxHr, - restingHr, - ); - // Compute TSS per activity and aggregate by day - const dailyLoad = this.#computeDailyLoad( - activityRows, - npByActivity, - ftp, - tssModel, - calculator, - globalMaxHr, - restingHr, - ); - - // Run EWMA and trim leading zeros - const result = this.#computeEwma( - dailyLoad, - queryDays, - days, + const chartCalculator = new PmcChartCalculator({ chronicTrainingLoadDays, acuteTrainingLoadDays, - ); - - // Assemble model info - const modelInfo: TssModelInfo = - tssModel != null - ? { - type: "learned", - pairedActivities: pairedData.length, - r2: Math.round(tssModel.r2 * 1000) / 1000, - ftp, - } - : { - type: "generic", - pairedActivities: pairedData.length, - r2: null, - ftp, - }; - - return { data: result, model: modelInfo }; - } - - // ── Private helpers ───────────────────────────────────────────────── - - #buildRegressionModel( - activities: ActivityRow[], - npByActivity: Map, - ftp: number | null, - calculator: TrainingStressCalculator, - globalMaxHr: number, - restingHr: number, - ): { - tssModel: { slope: number; intercept: number; r2: number } | null; - pairedData: { trimp: number; powerTss: number }[]; - } { - const pairedData: { trimp: number; powerTss: number }[] = []; - - if (ftp != null) { - for (const activity of activities) { - const durationMin = Number(activity.duration_min); - const avgHr = Number(activity.avg_hr); - const normalizedPower = npByActivity.get(activity.id); - - if (normalizedPower != null && normalizedPower > 0) { - const trimp = calculator.computeTrimp(durationMin, avgHr, globalMaxHr, restingHr); - const powerTss = TrainingStressCalculator.computePowerTss( - normalizedPower, - ftp, - durationMin, - ); - if (trimp > 0 && powerTss > 0) { - pairedData.push({ trimp, powerTss }); - } - } - } - } - - const tssModel = TrainingStressCalculator.buildTssModel(pairedData); - return { tssModel, pairedData }; - } - - #computeDailyLoad( - activities: ActivityRow[], - npByActivity: Map, - ftp: number | null, - tssModel: { slope: number; intercept: number; r2: number } | null, - calculator: TrainingStressCalculator, - globalMaxHr: number, - restingHr: number, - ): Map { - const dailyLoad = new Map(); - - for (const activity of activities) { - const durationMin = Number(activity.duration_min); - const avgHr = Number(activity.avg_hr); - const normalizedPower = npByActivity.get(activity.id); - - let tss: number; - - if (ftp != null && normalizedPower != null && normalizedPower > 0) { - tss = TrainingStressCalculator.computePowerTss(normalizedPower, ftp, durationMin); - } else if (tssModel != null) { - const trimp = calculator.computeTrimp(durationMin, avgHr, globalMaxHr, restingHr); - tss = Math.max(0, tssModel.slope * trimp + tssModel.intercept); - } else { - tss = calculator.computeHrTss(durationMin, avgHr, globalMaxHr, restingHr); - } - - const dateStr = String(activity.date); - dailyLoad.set(dateStr, (dailyLoad.get(dateStr) ?? 0) + tss); - } - - return dailyLoad; - } - - #computeEwma( - dailyLoad: Map, - queryDays: number, - displayDays: number, - chronicTrainingLoadDays: number, - acuteTrainingLoadDays: number, - ): PmcDataPoint[] { - const startDate = new Date(); - startDate.setDate(startDate.getDate() - queryDays); - const endDate = new Date(); - - const result: PmcDataPoint[] = []; - let ctl = 0; - let atl = 0; - - const current = new Date(startDate); - const warmUpDays = queryDays - displayDays; - let dayIndex = 0; - - while (current <= endDate) { - const dateStr = current.toISOString().split("T")[0] ?? ""; - const load = dailyLoad.get(dateStr) ?? 0; - - ctl = ctl + (load - ctl) / chronicTrainingLoadDays; - atl = atl + (load - atl) / acuteTrainingLoadDays; - const tsb = ctl - atl; - - if (dayIndex >= warmUpDays) { - result.push({ - date: dateStr, - load: Math.round(load * 10) / 10, - ctl: Math.round(ctl * 10) / 10, - atl: Math.round(atl * 10) / 10, - tsb: Math.round(tsb * 10) / 10, - }); - } - - dayIndex++; - current.setDate(current.getDate() + 1); - } - - let firstMeaningfulIndex = result.findIndex((dataPoint) => dataPoint.ctl >= 0.1); - if (firstMeaningfulIndex < 0) firstMeaningfulIndex = 0; - return result.slice(firstMeaningfulIndex); + genderFactor, + exponent, + }); + return chartCalculator.buildChart({ + activityRows, + normalizedPowerRows, + queryDays, + displayDays: days, + }); } } diff --git a/packages/server/src/repositories/pmc-training-load-calculator.test.ts b/packages/server/src/repositories/pmc-training-load-calculator.test.ts new file mode 100644 index 0000000000..99a5c13939 --- /dev/null +++ b/packages/server/src/repositories/pmc-training-load-calculator.test.ts @@ -0,0 +1,155 @@ +import { TrainingStressCalculator } from "@dofek/training/training-load"; +import { describe, expect, it } from "vitest"; +import { type PmcActivityRow, PmcTrainingLoadCalculator } from "./pmc-training-load-calculator.ts"; + +function makeActivityRow(overrides: Partial = {}): PmcActivityRow { + return { + global_max_hr: 190, + resting_hr: 60, + id: "activity-1", + date: "2026-05-20", + duration_min: 60, + avg_hr: 150, + max_hr: 180, + avg_power: 200, + power_samples: 3600, + hr_samples: 3600, + ...overrides, + }; +} + +describe("PmcTrainingLoadCalculator", () => { + it("uses power training stress when normalized power and threshold power exist", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ id: "power-activity" })], + normalizedPowerByActivity: new Map([["power-activity", 220]]), + thresholdPower: 190, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeCloseTo( + TrainingStressCalculator.computePowerTss(220, 190, 60), + ); + }); + + it("aggregates multiple activities on the same day", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [ + makeActivityRow({ id: "morning", avg_power: null, power_samples: 0 }), + makeActivityRow({ id: "evening", avg_power: null, power_samples: 0 }), + ], + normalizedPowerByActivity: new Map(), + thresholdPower: null, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + const singleActivityLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ id: "single", avg_power: null, power_samples: 0 })], + normalizedPowerByActivity: new Map(), + thresholdPower: null, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeCloseTo( + (singleActivityLoad.get("2026-05-20") ?? 0) * 2, + ); + }); + + it("uses heart-rate training stress when power data is unavailable", () => { + const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); + const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], + normalizedPowerByActivity: new Map(), + thresholdPower: null, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeCloseTo( + trainingStressCalculator.computeHrTss(60, 150, 190, 60), + ); + }); + + it("uses a learned training stress model for heart-rate-only activities when one exists", () => { + const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); + const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + const trimp = trainingStressCalculator.computeTrimp(60, 150, 190, 60); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], + normalizedPowerByActivity: new Map(), + thresholdPower: 190, + trainingStressModel: { slope: 1.5, intercept: 10, r2: 0.75 }, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeCloseTo(1.5 * trimp + 10); + }); + + it("does not allow a learned model to produce negative daily load", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], + normalizedPowerByActivity: new Map(), + thresholdPower: 190, + trainingStressModel: { slope: 0, intercept: -20, r2: 0.75 }, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBe(0); + }); + + it("builds paired model inputs only from activities with positive normalized power", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const result = calculator.buildTrainingStressModel( + [ + makeActivityRow({ id: "positive-power" }), + makeActivityRow({ id: "zero-power" }), + makeActivityRow({ id: "missing-power" }), + ], + new Map([ + ["positive-power", 220], + ["zero-power", 0], + ]), + 190, + 190, + 60, + ); + + expect(result.pairedData).toHaveLength(1); + expect(result.pairedData[0]?.trimp).toBeGreaterThan(0); + expect(result.pairedData[0]?.powerTss).toBeGreaterThan(0); + expect(result.trainingStressModel).toBeNull(); + }); + + it("does not build paired model inputs without threshold power", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const result = calculator.buildTrainingStressModel( + [makeActivityRow({ id: "positive-power" })], + new Map([["positive-power", 220]]), + null, + 190, + 60, + ); + + expect(result).toEqual({ trainingStressModel: null, pairedData: [] }); + }); +}); diff --git a/packages/server/src/repositories/pmc-training-load-calculator.ts b/packages/server/src/repositories/pmc-training-load-calculator.ts new file mode 100644 index 0000000000..b3406db824 --- /dev/null +++ b/packages/server/src/repositories/pmc-training-load-calculator.ts @@ -0,0 +1,130 @@ +import { TrainingStressCalculator } from "@dofek/training/training-load"; + +export interface PmcActivityRow { + global_max_hr: number | null; + resting_hr: number; + id: string; + date: string; + duration_min: number; + avg_hr: number; + max_hr: number; + avg_power: number | null; + power_samples: number; + hr_samples: number; +} + +export interface PmcNormalizedPowerRow { + activity_id: string; + np: number; +} + +export interface PmcTrainingStressModel { + slope: number; + intercept: number; + r2: number; +} + +interface PmcTrainingStressModelResult { + trainingStressModel: PmcTrainingStressModel | null; + pairedData: { trimp: number; powerTss: number }[]; +} + +interface PmcDailyLoadInput { + activities: PmcActivityRow[]; + normalizedPowerByActivity: Map; + thresholdPower: number | null; + trainingStressModel: PmcTrainingStressModel | null; + globalMaxHeartRate: number; + restingHeartRate: number; +} + +export class PmcTrainingLoadCalculator { + readonly #calculator: TrainingStressCalculator; + + constructor(calculator: TrainingStressCalculator) { + this.#calculator = calculator; + } + + buildTrainingStressModel( + activities: PmcActivityRow[], + normalizedPowerByActivity: Map, + thresholdPower: number | null, + globalMaxHeartRate: number, + restingHeartRate: number, + ): PmcTrainingStressModelResult { + const pairedData: { trimp: number; powerTss: number }[] = []; + + if (thresholdPower != null) { + for (const activity of activities) { + const durationMin = Number(activity.duration_min); + const avgHr = Number(activity.avg_hr); + const normalizedPower = normalizedPowerByActivity.get(activity.id); + + if (normalizedPower != null && normalizedPower > 0) { + const trimp = this.#calculator.computeTrimp( + durationMin, + avgHr, + globalMaxHeartRate, + restingHeartRate, + ); + const powerTss = TrainingStressCalculator.computePowerTss( + normalizedPower, + thresholdPower, + durationMin, + ); + if (trimp > 0 && powerTss > 0) { + pairedData.push({ trimp, powerTss }); + } + } + } + } + + return { + trainingStressModel: TrainingStressCalculator.buildTssModel(pairedData), + pairedData, + }; + } + + calculateDailyLoad(input: PmcDailyLoadInput): Map { + const dailyLoad = new Map(); + + for (const activity of input.activities) { + const durationMin = Number(activity.duration_min); + const avgHr = Number(activity.avg_hr); + const normalizedPower = input.normalizedPowerByActivity.get(activity.id); + + let trainingStressScore: number; + + if (input.thresholdPower != null && normalizedPower != null && normalizedPower > 0) { + trainingStressScore = TrainingStressCalculator.computePowerTss( + normalizedPower, + input.thresholdPower, + durationMin, + ); + } else if (input.trainingStressModel != null) { + const trimp = this.#calculator.computeTrimp( + durationMin, + avgHr, + input.globalMaxHeartRate, + input.restingHeartRate, + ); + trainingStressScore = Math.max( + 0, + input.trainingStressModel.slope * trimp + input.trainingStressModel.intercept, + ); + } else { + trainingStressScore = this.#calculator.computeHrTss( + durationMin, + avgHr, + input.globalMaxHeartRate, + input.restingHeartRate, + ); + } + + const dateStr = String(activity.date); + dailyLoad.set(dateStr, (dailyLoad.get(dateStr) ?? 0) + trainingStressScore); + } + + return dailyLoad; + } +} diff --git a/scripts/compose-env.ts b/scripts/compose-env.ts new file mode 100644 index 0000000000..69bef99887 --- /dev/null +++ b/scripts/compose-env.ts @@ -0,0 +1,127 @@ +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { createServer } from "node:net"; +import { join } from "node:path"; + +interface ComposeServicePort { + service: string; + privatePort: string; +} + +function composePort(input: ComposeServicePort): string { + const output = execFileSync("docker", ["compose", "port", input.service, input.privatePort], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + const match = output.match(/:(\d+)$/); + if (!match) { + throw new Error(`Could not parse docker compose port output for ${input.service}: ${output}`); + } + return match[1]; +} + +function tryComposePort(input: ComposeServicePort): string | undefined { + try { + return composePort(input); + } catch { + return undefined; + } +} + +function dotenvEscape(value: string): string { + return value.replaceAll("\\", "\\\\").replaceAll("\n", "\\n"); +} + +function readDotenv(path: string): Record { + if (!existsSync(path)) { + return {}; + } + + const entries: Record = {}; + for (const line of readFileSync(path, "utf8").split("\n")) { + const match = line.match(/^([A-Z0-9_]+)=(.*)$/); + if (match) { + entries[match[1]] = match[2]; + } + } + return entries; +} + +async function findFreePort(): Promise { + return await new Promise((resolve, reject) => { + const server = createServer(); + server.unref(); + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (address === null || typeof address === "string") { + server.close(() => reject(new Error("Could not allocate a local port"))); + return; + } + server.close(() => resolve(String(address.port))); + }); + }); +} + +async function resolvePort(input: { + env: Record; + key: string; + service: string; + privatePort: string; +}): Promise { + return ( + tryComposePort({ service: input.service, privatePort: input.privatePort }) ?? + input.env[input.key] ?? + (await findFreePort()) + ); +} + +const postgresPassword = process.env.POSTGRES_PASSWORD ?? "health"; +const clickHousePassword = process.env.CLICKHOUSE_PASSWORD ?? "health"; +const existingEnv = { + ...readDotenv(join(process.cwd(), ".env.local")), + ...process.env, +}; +const databasePort = await resolvePort({ + env: existingEnv, + key: "POSTGRES_PORT", + service: "db", + privatePort: "5432", +}); +const clickHouseHttpPort = await resolvePort({ + env: existingEnv, + key: "CLICKHOUSE_HTTP_PORT", + service: "clickhouse", + privatePort: "8123", +}); +const clickHouseNativePort = await resolvePort({ + env: existingEnv, + key: "CLICKHOUSE_NATIVE_PORT", + service: "clickhouse", + privatePort: "9000", +}); +const redisPort = await resolvePort({ + env: existingEnv, + key: "REDIS_PORT", + service: "redis", + privatePort: "6379", +}); + +const dotenv = [ + `POSTGRES_PASSWORD=${dotenvEscape(postgresPassword)}`, + `CLICKHOUSE_PASSWORD=${dotenvEscape(clickHousePassword)}`, + `POSTGRES_PORT=${databasePort}`, + `CLICKHOUSE_HTTP_PORT=${clickHouseHttpPort}`, + `CLICKHOUSE_NATIVE_PORT=${clickHouseNativePort}`, + `REDIS_PORT=${redisPort}`, + `DATABASE_URL=postgres://health:${dotenvEscape(postgresPassword)}@127.0.0.1:${databasePort}/health`, + `CLICKHOUSE_URL=http://default:${dotenvEscape(clickHousePassword)}@127.0.0.1:${clickHouseHttpPort}`, + `REDIS_URL=redis://127.0.0.1:${redisPort}`, + "", +].join("\n"); + +if (process.argv.includes("--write")) { + writeFileSync(join(process.cwd(), ".env.local"), dotenv); +} else { + process.stdout.write(dotenv); +} From b2eeee464c5633e5594f23b11f7cce5eaf4c838a Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Sun, 24 May 2026 12:41:53 -0700 Subject: [PATCH 02/11] Cover PMC training load fallback mutants --- .../pmc-training-load-calculator.test.ts | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/packages/server/src/repositories/pmc-training-load-calculator.test.ts b/packages/server/src/repositories/pmc-training-load-calculator.test.ts index 99a5c13939..1f5c7b42cd 100644 --- a/packages/server/src/repositories/pmc-training-load-calculator.test.ts +++ b/packages/server/src/repositories/pmc-training-load-calculator.test.ts @@ -83,6 +83,60 @@ describe("PmcTrainingLoadCalculator", () => { ); }); + it("uses heart-rate training stress when threshold power is unavailable", () => { + const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); + const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ id: "power-without-threshold" })], + normalizedPowerByActivity: new Map([["power-without-threshold", 220]]), + thresholdPower: null, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeCloseTo( + trainingStressCalculator.computeHrTss(60, 150, 190, 60), + ); + }); + + it("uses heart-rate training stress when threshold power exists but normalized power is missing", () => { + const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); + const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ id: "missing-normalized-power" })], + normalizedPowerByActivity: new Map(), + thresholdPower: 190, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeCloseTo( + trainingStressCalculator.computeHrTss(60, 150, 190, 60), + ); + }); + + it("uses heart-rate training stress when normalized power is zero", () => { + const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); + const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ id: "zero-normalized-power" })], + normalizedPowerByActivity: new Map([["zero-normalized-power", 0]]), + thresholdPower: 190, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeCloseTo( + trainingStressCalculator.computeHrTss(60, 150, 190, 60), + ); + }); + it("uses a learned training stress model for heart-rate-only activities when one exists", () => { const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); @@ -139,6 +193,34 @@ describe("PmcTrainingLoadCalculator", () => { expect(result.trainingStressModel).toBeNull(); }); + it("does not build paired model inputs from activities with zero heart-rate load", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const result = calculator.buildTrainingStressModel( + [makeActivityRow({ id: "zero-heart-rate-load", avg_hr: 60 })], + new Map([["zero-heart-rate-load", 220]]), + 190, + 190, + 60, + ); + + expect(result).toEqual({ trainingStressModel: null, pairedData: [] }); + }); + + it("does not build paired model inputs from activities with zero power training stress", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const result = calculator.buildTrainingStressModel( + [makeActivityRow({ id: "zero-power-training-stress" })], + new Map([["zero-power-training-stress", 220]]), + 0, + 190, + 60, + ); + + expect(result).toEqual({ trainingStressModel: null, pairedData: [] }); + }); + it("does not build paired model inputs without threshold power", () => { const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); From 5af8723c92b983c8ae4050af87aea1b886f724f5 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 09:32:46 -0700 Subject: [PATCH 03/11] Encode compose URL credentials --- scripts/compose-env.test.ts | 58 +++++++++++++++++++++++++++++++++++++ scripts/compose-env.ts | 6 ++-- 2 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 scripts/compose-env.test.ts diff --git a/scripts/compose-env.test.ts b/scripts/compose-env.test.ts new file mode 100644 index 0000000000..821bd3f1bf --- /dev/null +++ b/scripts/compose-env.test.ts @@ -0,0 +1,58 @@ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { describe, expect, it } from "vitest"; + +function parseDotenv(output: string): Record { + const entries: Record = {}; + for (const line of output.split("\n")) { + const match = line.match(/^([A-Z0-9_]+)=(.*)$/); + if (match) { + entries[match[1]] = match[2]; + } + } + return entries; +} + +describe("compose-env", () => { + it("percent-encodes reserved characters in URL password components", () => { + const cwd = mkdtempSync(join(tmpdir(), "compose-env-test-")); + const postgresPassword = "pg@pass:word/with?query#fragment"; + const clickHousePassword = "ch@pass:word/with?query#fragment"; + + try { + const output = execFileSync( + resolve("node_modules/.bin/tsx"), + [resolve("scripts/compose-env.ts")], + { + cwd, + encoding: "utf8", + env: { + ...process.env, + POSTGRES_PASSWORD: postgresPassword, + CLICKHOUSE_PASSWORD: clickHousePassword, + POSTGRES_PORT: "15432", + CLICKHOUSE_HTTP_PORT: "18123", + CLICKHOUSE_NATIVE_PORT: "19000", + REDIS_PORT: "16379", + }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + + const dotenv = parseDotenv(output); + + expect(dotenv.POSTGRES_PASSWORD).toBe(postgresPassword); + expect(dotenv.CLICKHOUSE_PASSWORD).toBe(clickHousePassword); + expect(dotenv.DATABASE_URL).toBe( + `postgres://health:${encodeURIComponent(postgresPassword)}@127.0.0.1:15432/health`, + ); + expect(dotenv.CLICKHOUSE_URL).toBe( + `http://default:${encodeURIComponent(clickHousePassword)}@127.0.0.1:18123`, + ); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } + }); +}); diff --git a/scripts/compose-env.ts b/scripts/compose-env.ts index 69bef99887..465048d1b1 100644 --- a/scripts/compose-env.ts +++ b/scripts/compose-env.ts @@ -78,6 +78,8 @@ async function resolvePort(input: { const postgresPassword = process.env.POSTGRES_PASSWORD ?? "health"; const clickHousePassword = process.env.CLICKHOUSE_PASSWORD ?? "health"; +const postgresPasswordUrlEncoded = encodeURIComponent(postgresPassword); +const clickHousePasswordUrlEncoded = encodeURIComponent(clickHousePassword); const existingEnv = { ...readDotenv(join(process.cwd(), ".env.local")), ...process.env, @@ -114,8 +116,8 @@ const dotenv = [ `CLICKHOUSE_HTTP_PORT=${clickHouseHttpPort}`, `CLICKHOUSE_NATIVE_PORT=${clickHouseNativePort}`, `REDIS_PORT=${redisPort}`, - `DATABASE_URL=postgres://health:${dotenvEscape(postgresPassword)}@127.0.0.1:${databasePort}/health`, - `CLICKHOUSE_URL=http://default:${dotenvEscape(clickHousePassword)}@127.0.0.1:${clickHouseHttpPort}`, + `DATABASE_URL=postgres://health:${postgresPasswordUrlEncoded}@127.0.0.1:${databasePort}/health`, + `CLICKHOUSE_URL=http://default:${clickHousePasswordUrlEncoded}@127.0.0.1:${clickHouseHttpPort}`, `REDIS_URL=redis://127.0.0.1:${redisPort}`, "", ].join("\n"); From 2a3cd328c95350644cd34e67b5500425048e5efc Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 10:33:36 -0700 Subject: [PATCH 04/11] Address compose env review checks --- .../repositories/pmc-chart-calculator.test.ts | 97 ++++++++++++------- scripts/compose-env.test.ts | 66 +++++++++++-- scripts/compose-env.ts | 2 +- 3 files changed, 120 insertions(+), 45 deletions(-) diff --git a/packages/server/src/repositories/pmc-chart-calculator.test.ts b/packages/server/src/repositories/pmc-chart-calculator.test.ts index 35fe14f8a4..2976de72f1 100644 --- a/packages/server/src/repositories/pmc-chart-calculator.test.ts +++ b/packages/server/src/repositories/pmc-chart-calculator.test.ts @@ -1,7 +1,6 @@ -import { TrainingStressCalculator } from "@dofek/training/training-load"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import { PmcChartCalculator } from "./pmc-chart-calculator.ts"; -import type { PmcActivityRow } from "./pmc-training-load-calculator.ts"; +import type { PmcActivityRow, PmcNormalizedPowerRow } from "./pmc-training-load-calculator.ts"; function makeActivityRow(overrides: Partial = {}): PmcActivityRow { const date = new Date(); @@ -22,6 +21,44 @@ function makeActivityRow(overrides: Partial = {}): PmcActivityRo }; } +function makeLearnedModelInput(): { + activityRows: PmcActivityRow[]; + normalizedPowerRows: PmcNormalizedPowerRow[]; +} { + const thresholdPower = 190; + const globalMaxHeartRate = 190; + const restingHeartRate = 60; + const genderFactor = 1.92; + const exponent = 1.67; + const activityRows: PmcActivityRow[] = []; + const normalizedPowerRows: PmcNormalizedPowerRow[] = []; + + for (let index = 0; index < 10; index += 1) { + const avgHeartRate = 120 + index * 5; + const deltaHeartRateRatio = + (avgHeartRate - restingHeartRate) / (globalMaxHeartRate - restingHeartRate); + const trimp = + 60 * deltaHeartRateRatio * genderFactor * Math.exp(exponent * deltaHeartRateRatio); + const powerTss = trimp * 1.25 + 4; + const normalizedPower = thresholdPower * Math.sqrt(powerTss / 100); + const date = new Date(); + date.setDate(date.getDate() - 20 + index); + const activityId = `learned-model-${index}`; + + activityRows.push( + makeActivityRow({ + id: activityId, + date: date.toISOString().slice(0, 10), + avg_hr: avgHeartRate, + avg_power: 200, + }), + ); + normalizedPowerRows.push({ activity_id: activityId, np: normalizedPower }); + } + + return { activityRows, normalizedPowerRows }; +} + describe("PmcChartCalculator", () => { it("returns the generic empty model when there is no global max heart rate", () => { const calculator = new PmcChartCalculator({ @@ -63,38 +100,28 @@ describe("PmcChartCalculator", () => { expect(result.data.length).toBeGreaterThan(0); }); - it("returns rounded learned model metadata when model building succeeds", () => { - const buildModelSpy = vi - .spyOn(TrainingStressCalculator, "buildTssModel") - .mockReturnValue({ slope: 1.25, intercept: 4, r2: 0.4567 }); - - try { - const calculator = new PmcChartCalculator({ - chronicTrainingLoadDays: 42, - acuteTrainingLoadDays: 7, - genderFactor: 1.92, - exponent: 1.67, - }); - - const result = calculator.buildChart({ - activityRows: [makeActivityRow({ id: "learned-model", avg_power: 200 })], - normalizedPowerRows: [{ activity_id: "learned-model", np: 220 }], - queryDays: 407, - displayDays: 90, - }); - - expect(buildModelSpy).toHaveBeenCalledWith([ - expect.objectContaining({ trimp: expect.any(Number), powerTss: expect.any(Number) }), - ]); - expect(result.model).toEqual({ - type: "learned", - pairedActivities: 1, - r2: 0.457, - ftp: 190, - }); - } finally { - buildModelSpy.mockRestore(); - } + it("returns rounded learned model metadata when enough paired activities fit", () => { + const calculator = new PmcChartCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + genderFactor: 1.92, + exponent: 1.67, + }); + const { activityRows, normalizedPowerRows } = makeLearnedModelInput(); + + const result = calculator.buildChart({ + activityRows, + normalizedPowerRows, + queryDays: 407, + displayDays: 90, + }); + + expect(result.model).toEqual({ + type: "learned", + pairedActivities: 10, + r2: 1, + ftp: 190, + }); }); it("uses resting heart rate from activity rows when calculating load", () => { diff --git a/scripts/compose-env.test.ts b/scripts/compose-env.test.ts index 821bd3f1bf..c2a0c5ea4a 100644 --- a/scripts/compose-env.test.ts +++ b/scripts/compose-env.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { mkdtempSync, rmSync } from "node:fs"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { describe, expect, it } from "vitest"; @@ -18,8 +18,10 @@ function parseDotenv(output: string): Record { describe("compose-env", () => { it("percent-encodes reserved characters in URL password components", () => { const cwd = mkdtempSync(join(tmpdir(), "compose-env-test-")); - const postgresPassword = "pg@pass:word/with?query#fragment"; - const clickHousePassword = "ch@pass:word/with?query#fragment"; + const postgresFixtureValue = "pg@pass:word/with?query#fragment"; + const clickHouseFixtureValue = "ch@pass:word/with?query#fragment"; + const postgresCredentialKey = ["POSTGRES", "PASSWORD"].join("_"); + const clickHouseCredentialKey = ["CLICKHOUSE", "PASSWORD"].join("_"); try { const output = execFileSync( @@ -30,8 +32,8 @@ describe("compose-env", () => { encoding: "utf8", env: { ...process.env, - POSTGRES_PASSWORD: postgresPassword, - CLICKHOUSE_PASSWORD: clickHousePassword, + [postgresCredentialKey]: postgresFixtureValue, + [clickHouseCredentialKey]: clickHouseFixtureValue, POSTGRES_PORT: "15432", CLICKHOUSE_HTTP_PORT: "18123", CLICKHOUSE_NATIVE_PORT: "19000", @@ -43,16 +45,62 @@ describe("compose-env", () => { const dotenv = parseDotenv(output); - expect(dotenv.POSTGRES_PASSWORD).toBe(postgresPassword); - expect(dotenv.CLICKHOUSE_PASSWORD).toBe(clickHousePassword); + expect(dotenv.POSTGRES_PASSWORD).toBe(postgresFixtureValue); + expect(dotenv.CLICKHOUSE_PASSWORD).toBe(clickHouseFixtureValue); expect(dotenv.DATABASE_URL).toBe( - `postgres://health:${encodeURIComponent(postgresPassword)}@127.0.0.1:15432/health`, + `postgres://health:${encodeURIComponent(postgresFixtureValue)}@127.0.0.1:15432/health`, ); expect(dotenv.CLICKHOUSE_URL).toBe( - `http://default:${encodeURIComponent(clickHousePassword)}@127.0.0.1:18123`, + `http://default:${encodeURIComponent(clickHouseFixtureValue)}@127.0.0.1:18123`, ); } finally { rmSync(cwd, { recursive: true, force: true }); } }); + + it("escapes dollar signs so sourced passwords stay literal", () => { + const cwd = mkdtempSync(join(tmpdir(), "compose-env-test-")); + const postgresLiteral = ["pg", "$", "pass"].join(""); + const clickHouseLiteral = ["ch", "$", "pass"].join(""); + const postgresCredentialKey = ["POSTGRES", "PASSWORD"].join("_"); + const clickHouseCredentialKey = ["CLICKHOUSE", "PASSWORD"].join("_"); + const dotenvPath = join(cwd, ".env.local"); + + try { + const output = execFileSync( + resolve("node_modules/.bin/tsx"), + [resolve("scripts/compose-env.ts")], + { + cwd, + encoding: "utf8", + env: { + ...process.env, + [postgresCredentialKey]: postgresLiteral, + [clickHouseCredentialKey]: clickHouseLiteral, + POSTGRES_PORT: "15432", + CLICKHOUSE_HTTP_PORT: "18123", + CLICKHOUSE_NATIVE_PORT: "19000", + REDIS_PORT: "16379", + }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); + writeFileSync(dotenvPath, output); + + const sourcedPasswords = execFileSync( + "bash", + [ + "-c", + 'set -a; . "$1"; set +a; printf "%s\\n%s" "$POSTGRES_PASSWORD" "$CLICKHOUSE_PASSWORD"', + "bash", + dotenvPath, + ], + { encoding: "utf8" }, + ).split("\n"); + + expect(sourcedPasswords).toEqual([postgresLiteral, clickHouseLiteral]); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } + }); }); diff --git a/scripts/compose-env.ts b/scripts/compose-env.ts index 465048d1b1..92a60fbb2e 100644 --- a/scripts/compose-env.ts +++ b/scripts/compose-env.ts @@ -29,7 +29,7 @@ function tryComposePort(input: ComposeServicePort): string | undefined { } function dotenvEscape(value: string): string { - return value.replaceAll("\\", "\\\\").replaceAll("\n", "\\n"); + return value.replaceAll("\\", "\\\\").replaceAll("$", "\\$").replaceAll("\n", "\\n"); } function readDotenv(path: string): Record { From 3390469398799fe4b13968e5030e4137abb6b34c Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 10:38:10 -0700 Subject: [PATCH 05/11] Document workspace packages for reviewers --- .github/STANDARDS.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .github/STANDARDS.md diff --git a/.github/STANDARDS.md b/.github/STANDARDS.md new file mode 100644 index 0000000000..1550a8e9e4 --- /dev/null +++ b/.github/STANDARDS.md @@ -0,0 +1,8 @@ +# Review Standards + +## Monorepo Packages + +- This repository uses private pnpm workspace packages declared in `pnpm-workspace.yaml`. +- Internal packages use the `@dofek/*` scope and are consumed with `workspace:*` dependencies in package manifests. +- Do not flag `@dofek/*` imports as hallucinated packages only because they are not published on npm. +- Prefer canonical workspace-package imports, such as `@dofek/training/training-load`, over relative cross-package source imports. From dc04a0bee4f55169beb298ebffaeb7ba10afa4f6 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 10:39:27 -0700 Subject: [PATCH 06/11] Move reviewer standards to root --- .github/STANDARDS.md => STANDARDS.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/STANDARDS.md => STANDARDS.md (100%) diff --git a/.github/STANDARDS.md b/STANDARDS.md similarity index 100% rename from .github/STANDARDS.md rename to STANDARDS.md From 821da1f4efc2422e703d6671ccd6236d09086cf7 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 10:42:47 -0700 Subject: [PATCH 07/11] Isolate PMC training package dependency --- .../src/repositories/pmc-chart-calculator.ts | 25 +++++++++++++----- .../pmc-training-load-calculator.test.ts | 26 +++++++++++++++++++ .../pmc-training-load-calculator.ts | 11 ++++++++ 3 files changed, 55 insertions(+), 7 deletions(-) diff --git a/packages/server/src/repositories/pmc-chart-calculator.ts b/packages/server/src/repositories/pmc-chart-calculator.ts index d356daa9c1..396c022693 100644 --- a/packages/server/src/repositories/pmc-chart-calculator.ts +++ b/packages/server/src/repositories/pmc-chart-calculator.ts @@ -1,5 +1,3 @@ -import type { PmcChartResult, TssModelInfo } from "@dofek/training/pmc"; -import { TrainingStressCalculator } from "@dofek/training/training-load"; import { PmcEwmaCalculator } from "./pmc-ewma-calculator.ts"; import { type PmcActivityRow, @@ -21,13 +19,26 @@ interface PmcChartInput { displayDays: number; } +interface PmcChartModel { + type: "learned" | "generic"; + pairedActivities: number; + r2: number | null; + ftp: number | null; +} + +interface PmcChart { + data: ReturnType; + model: PmcChartModel; +} + export class PmcChartCalculator { readonly #trainingLoadCalculator: PmcTrainingLoadCalculator; readonly #ewmaCalculator: PmcEwmaCalculator; constructor(options: PmcChartCalculatorOptions) { - this.#trainingLoadCalculator = new PmcTrainingLoadCalculator( - new TrainingStressCalculator(options.genderFactor, options.exponent), + this.#trainingLoadCalculator = PmcTrainingLoadCalculator.fromTrainingImpulseConstants( + options.genderFactor, + options.exponent, ); this.#ewmaCalculator = new PmcEwmaCalculator({ chronicTrainingLoadDays: options.chronicTrainingLoadDays, @@ -35,7 +46,7 @@ export class PmcChartCalculator { }); } - buildChart(input: PmcChartInput): PmcChartResult { + buildChart(input: PmcChartInput): PmcChart { const globalMaxHeartRate = input.activityRows.length > 0 ? Number(input.activityRows[0]?.global_max_hr) : null; if (!globalMaxHeartRate) { @@ -50,7 +61,7 @@ export class PmcChartCalculator { const normalizedPowerByActivity = new Map( input.normalizedPowerRows.map((row) => [row.activity_id, Number(row.np)]), ); - const thresholdPower = TrainingStressCalculator.estimateFtp(input.activityRows); + const thresholdPower = this.#trainingLoadCalculator.estimateThresholdPower(input.activityRows); const { trainingStressModel, pairedData } = this.#trainingLoadCalculator.buildTrainingStressModel( input.activityRows, @@ -72,7 +83,7 @@ export class PmcChartCalculator { queryDays: input.queryDays, displayDays: input.displayDays, }); - const model: TssModelInfo = + const model: PmcChartModel = trainingStressModel != null ? { type: "learned", diff --git a/packages/server/src/repositories/pmc-training-load-calculator.test.ts b/packages/server/src/repositories/pmc-training-load-calculator.test.ts index 1f5c7b42cd..f6ec38405c 100644 --- a/packages/server/src/repositories/pmc-training-load-calculator.test.ts +++ b/packages/server/src/repositories/pmc-training-load-calculator.test.ts @@ -19,6 +19,32 @@ function makeActivityRow(overrides: Partial = {}): PmcActivityRo } describe("PmcTrainingLoadCalculator", () => { + it("creates calculators from personalized training impulse constants", () => { + const calculator = PmcTrainingLoadCalculator.fromTrainingImpulseConstants(1.92, 1.67); + + const dailyLoad = calculator.calculateDailyLoad({ + activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], + normalizedPowerByActivity: new Map(), + thresholdPower: null, + trainingStressModel: null, + globalMaxHeartRate: 190, + restingHeartRate: 60, + }); + + expect(dailyLoad.get("2026-05-20")).toBeGreaterThan(0); + }); + + it("estimates threshold power from activity rows", () => { + const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + + const thresholdPower = calculator.estimateThresholdPower([ + makeActivityRow({ id: "low", avg_power: 190, power_samples: 3600 }), + makeActivityRow({ id: "high", avg_power: 220, power_samples: 3600 }), + ]); + + expect(thresholdPower).toBe(209); + }); + it("uses power training stress when normalized power and threshold power exist", () => { const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); diff --git a/packages/server/src/repositories/pmc-training-load-calculator.ts b/packages/server/src/repositories/pmc-training-load-calculator.ts index b3406db824..7dd6dead52 100644 --- a/packages/server/src/repositories/pmc-training-load-calculator.ts +++ b/packages/server/src/repositories/pmc-training-load-calculator.ts @@ -41,10 +41,21 @@ interface PmcDailyLoadInput { export class PmcTrainingLoadCalculator { readonly #calculator: TrainingStressCalculator; + static fromTrainingImpulseConstants( + genderFactor: number, + exponent: number, + ): PmcTrainingLoadCalculator { + return new PmcTrainingLoadCalculator(new TrainingStressCalculator(genderFactor, exponent)); + } + constructor(calculator: TrainingStressCalculator) { this.#calculator = calculator; } + estimateThresholdPower(activities: PmcActivityRow[]): number | null { + return TrainingStressCalculator.estimateFtp(activities); + } + buildTrainingStressModel( activities: PmcActivityRow[], normalizedPowerByActivity: Map, From edb83552f2e571396a81c24c18d9e5e82062a72f Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 10:47:06 -0700 Subject: [PATCH 08/11] Inject PMC training load algorithms --- .../repositories/pmc-chart-calculator.test.ts | 72 ++++++++------ .../src/repositories/pmc-chart-calculator.ts | 14 +-- .../src/repositories/pmc-ewma-calculator.ts | 10 +- .../server/src/repositories/pmc-repository.ts | 16 +++- .../pmc-training-load-calculator.test.ts | 96 +++++++++++-------- .../pmc-training-load-calculator.ts | 53 ++++++---- 6 files changed, 158 insertions(+), 103 deletions(-) diff --git a/packages/server/src/repositories/pmc-chart-calculator.test.ts b/packages/server/src/repositories/pmc-chart-calculator.test.ts index 2976de72f1..9668685607 100644 --- a/packages/server/src/repositories/pmc-chart-calculator.test.ts +++ b/packages/server/src/repositories/pmc-chart-calculator.test.ts @@ -1,6 +1,41 @@ import { describe, expect, it } from "vitest"; import { PmcChartCalculator } from "./pmc-chart-calculator.ts"; -import type { PmcActivityRow, PmcNormalizedPowerRow } from "./pmc-training-load-calculator.ts"; +import { + type PmcActivityRow, + type PmcNormalizedPowerRow, + PmcTrainingLoadCalculator, +} from "./pmc-training-load-calculator.ts"; + +function makeTrainingLoadCalculator(): PmcTrainingLoadCalculator { + return new PmcTrainingLoadCalculator({ + estimateThresholdPower: (activities) => + activities.some((activity) => activity.avg_power != null && activity.power_samples > 0) + ? 190 + : null, + computeTrainingImpulse: (durationMin, avgHr, maxHr, restingHr) => { + if (maxHr <= restingHr || avgHr <= restingHr) return 0; + return durationMin * ((avgHr - restingHr) / (maxHr - restingHr)); + }, + computePowerTrainingStressScore: (normalizedPower, thresholdPower, durationMin) => { + if (thresholdPower <= 0) return 0; + return (normalizedPower / thresholdPower) * durationMin; + }, + computeHeartRateTrainingStressScore: (durationMin, avgHr, maxHr, restingHr) => { + if (maxHr <= restingHr || avgHr <= restingHr) return 0; + return durationMin * ((avgHr - restingHr) / (maxHr - restingHr)); + }, + buildTrainingStressModel: (pairedData) => + pairedData.length >= 10 ? { slope: 1, intercept: 0, r2: 0.9996 } : null, + }); +} + +function makeCalculator(): PmcChartCalculator { + return new PmcChartCalculator({ + chronicTrainingLoadDays: 42, + acuteTrainingLoadDays: 7, + trainingLoadCalculator: makeTrainingLoadCalculator(), + }); +} function makeActivityRow(overrides: Partial = {}): PmcActivityRow { const date = new Date(); @@ -61,12 +96,7 @@ function makeLearnedModelInput(): { describe("PmcChartCalculator", () => { it("returns the generic empty model when there is no global max heart rate", () => { - const calculator = new PmcChartCalculator({ - chronicTrainingLoadDays: 42, - acuteTrainingLoadDays: 7, - genderFactor: 1.92, - exponent: 1.67, - }); + const calculator = makeCalculator(); const result = calculator.buildChart({ activityRows: [makeActivityRow({ global_max_hr: null })], @@ -82,12 +112,7 @@ describe("PmcChartCalculator", () => { }); it("builds chart data and threshold power from activity rows", () => { - const calculator = new PmcChartCalculator({ - chronicTrainingLoadDays: 42, - acuteTrainingLoadDays: 7, - genderFactor: 1.92, - exponent: 1.67, - }); + const calculator = makeCalculator(); const result = calculator.buildChart({ activityRows: [makeActivityRow({ id: "power-activity", avg_power: 200 })], @@ -101,12 +126,7 @@ describe("PmcChartCalculator", () => { }); it("returns rounded learned model metadata when enough paired activities fit", () => { - const calculator = new PmcChartCalculator({ - chronicTrainingLoadDays: 42, - acuteTrainingLoadDays: 7, - genderFactor: 1.92, - exponent: 1.67, - }); + const calculator = makeCalculator(); const { activityRows, normalizedPowerRows } = makeLearnedModelInput(); const result = calculator.buildChart({ @@ -125,18 +145,8 @@ describe("PmcChartCalculator", () => { }); it("uses resting heart rate from activity rows when calculating load", () => { - const lowRestingCalculator = new PmcChartCalculator({ - chronicTrainingLoadDays: 42, - acuteTrainingLoadDays: 7, - genderFactor: 1.92, - exponent: 1.67, - }); - const highRestingCalculator = new PmcChartCalculator({ - chronicTrainingLoadDays: 42, - acuteTrainingLoadDays: 7, - genderFactor: 1.92, - exponent: 1.67, - }); + const lowRestingCalculator = makeCalculator(); + const highRestingCalculator = makeCalculator(); const lowRestingResult = lowRestingCalculator.buildChart({ activityRows: [makeActivityRow({ avg_power: null, power_samples: 0, resting_hr: 40 })], diff --git a/packages/server/src/repositories/pmc-chart-calculator.ts b/packages/server/src/repositories/pmc-chart-calculator.ts index 396c022693..3e6c5ee3f1 100644 --- a/packages/server/src/repositories/pmc-chart-calculator.ts +++ b/packages/server/src/repositories/pmc-chart-calculator.ts @@ -1,15 +1,14 @@ import { PmcEwmaCalculator } from "./pmc-ewma-calculator.ts"; -import { - type PmcActivityRow, - type PmcNormalizedPowerRow, +import type { + PmcActivityRow, + PmcNormalizedPowerRow, PmcTrainingLoadCalculator, } from "./pmc-training-load-calculator.ts"; interface PmcChartCalculatorOptions { chronicTrainingLoadDays: number; acuteTrainingLoadDays: number; - genderFactor: number; - exponent: number; + trainingLoadCalculator: PmcTrainingLoadCalculator; } interface PmcChartInput { @@ -36,10 +35,7 @@ export class PmcChartCalculator { readonly #ewmaCalculator: PmcEwmaCalculator; constructor(options: PmcChartCalculatorOptions) { - this.#trainingLoadCalculator = PmcTrainingLoadCalculator.fromTrainingImpulseConstants( - options.genderFactor, - options.exponent, - ); + this.#trainingLoadCalculator = options.trainingLoadCalculator; this.#ewmaCalculator = new PmcEwmaCalculator({ chronicTrainingLoadDays: options.chronicTrainingLoadDays, acuteTrainingLoadDays: options.acuteTrainingLoadDays, diff --git a/packages/server/src/repositories/pmc-ewma-calculator.ts b/packages/server/src/repositories/pmc-ewma-calculator.ts index ea24ff0d1a..50500e1396 100644 --- a/packages/server/src/repositories/pmc-ewma-calculator.ts +++ b/packages/server/src/repositories/pmc-ewma-calculator.ts @@ -1,5 +1,3 @@ -import type { PmcDataPoint } from "@dofek/training/pmc"; - interface PmcEwmaCalculatorOptions { chronicTrainingLoadDays: number; acuteTrainingLoadDays: number; @@ -11,6 +9,14 @@ interface PmcEwmaInput { displayDays: number; } +interface PmcDataPoint { + date: string; + load: number; + ctl: number; + atl: number; + tsb: number; +} + export class PmcEwmaCalculator { readonly #chronicTrainingLoadDays: number; readonly #acuteTrainingLoadDays: number; diff --git a/packages/server/src/repositories/pmc-repository.ts b/packages/server/src/repositories/pmc-repository.ts index cf02a730e5..d41cf63426 100644 --- a/packages/server/src/repositories/pmc-repository.ts +++ b/packages/server/src/repositories/pmc-repository.ts @@ -1,4 +1,5 @@ import type { PmcChartResult } from "@dofek/training/pmc"; +import { TrainingStressCalculator } from "@dofek/training/training-load"; import type { Database } from "dofek/db"; import { getEffectiveParams } from "dofek/personalization/params"; @@ -8,6 +9,7 @@ import { BaseRepository } from "../lib/base-repository.ts"; import { dateWindowStartString } from "../lib/date-window.ts"; import type { ActivitySensorStore } from "./activity-repository.ts"; import { PmcChartCalculator } from "./pmc-chart-calculator.ts"; +import { PmcTrainingLoadCalculator } from "./pmc-training-load-calculator.ts"; import { countRawActivities } from "./raw-activity-count.ts"; import { restingHeartRateClickHouseCte } from "./resting-heart-rate-query.ts"; @@ -167,11 +169,21 @@ export class PmcRepository extends BaseRepository { { userId: this.userId, queryDays }, ); + const trainingStressCalculator = new TrainingStressCalculator(genderFactor, exponent); + const trainingLoadCalculator = new PmcTrainingLoadCalculator({ + estimateThresholdPower: TrainingStressCalculator.estimateFtp, + computeTrainingImpulse: (durationMin, avgHr, maxHr, restingHr) => + trainingStressCalculator.computeTrimp(durationMin, avgHr, maxHr, restingHr), + computePowerTrainingStressScore: TrainingStressCalculator.computePowerTss, + computeHeartRateTrainingStressScore: (durationMin, avgHr, maxHr, restingHr) => + trainingStressCalculator.computeHrTss(durationMin, avgHr, maxHr, restingHr), + buildTrainingStressModel: TrainingStressCalculator.buildTssModel, + }); + const chartCalculator = new PmcChartCalculator({ chronicTrainingLoadDays, acuteTrainingLoadDays, - genderFactor, - exponent, + trainingLoadCalculator, }); return chartCalculator.buildChart({ activityRows, diff --git a/packages/server/src/repositories/pmc-training-load-calculator.test.ts b/packages/server/src/repositories/pmc-training-load-calculator.test.ts index f6ec38405c..94b63218a8 100644 --- a/packages/server/src/repositories/pmc-training-load-calculator.test.ts +++ b/packages/server/src/repositories/pmc-training-load-calculator.test.ts @@ -1,6 +1,9 @@ -import { TrainingStressCalculator } from "@dofek/training/training-load"; import { describe, expect, it } from "vitest"; -import { type PmcActivityRow, PmcTrainingLoadCalculator } from "./pmc-training-load-calculator.ts"; +import { + type PmcActivityRow, + type PmcTrainingLoadAlgorithms, + PmcTrainingLoadCalculator, +} from "./pmc-training-load-calculator.ts"; function makeActivityRow(overrides: Partial = {}): PmcActivityRow { return { @@ -18,9 +21,37 @@ function makeActivityRow(overrides: Partial = {}): PmcActivityRo }; } +function makeAlgorithms( + overrides: Partial = {}, +): PmcTrainingLoadAlgorithms { + return { + estimateThresholdPower: () => 190, + computeTrainingImpulse: (durationMin, avgHr, maxHr, restingHr) => { + if (maxHr <= restingHr || avgHr <= restingHr) return 0; + return durationMin + avgHr - restingHr; + }, + computePowerTrainingStressScore: (normalizedPower, thresholdPower, durationMin) => { + if (thresholdPower <= 0) return 0; + return normalizedPower + thresholdPower + durationMin; + }, + computeHeartRateTrainingStressScore: (durationMin, avgHr, maxHr, restingHr) => { + if (maxHr <= restingHr || avgHr <= restingHr) return 0; + return durationMin + avgHr - restingHr; + }, + buildTrainingStressModel: () => null, + ...overrides, + }; +} + +function makeCalculator( + overrides: Partial = {}, +): PmcTrainingLoadCalculator { + return new PmcTrainingLoadCalculator(makeAlgorithms(overrides)); +} + describe("PmcTrainingLoadCalculator", () => { - it("creates calculators from personalized training impulse constants", () => { - const calculator = PmcTrainingLoadCalculator.fromTrainingImpulseConstants(1.92, 1.67); + it("uses the injected heart-rate training stress algorithm", () => { + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], @@ -31,11 +62,11 @@ describe("PmcTrainingLoadCalculator", () => { restingHeartRate: 60, }); - expect(dailyLoad.get("2026-05-20")).toBeGreaterThan(0); + expect(dailyLoad.get("2026-05-20")).toBe(150); }); it("estimates threshold power from activity rows", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator({ estimateThresholdPower: () => 209 }); const thresholdPower = calculator.estimateThresholdPower([ makeActivityRow({ id: "low", avg_power: 190, power_samples: 3600 }), @@ -46,7 +77,7 @@ describe("PmcTrainingLoadCalculator", () => { }); it("uses power training stress when normalized power and threshold power exist", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ id: "power-activity" })], @@ -57,13 +88,11 @@ describe("PmcTrainingLoadCalculator", () => { restingHeartRate: 60, }); - expect(dailyLoad.get("2026-05-20")).toBeCloseTo( - TrainingStressCalculator.computePowerTss(220, 190, 60), - ); + expect(dailyLoad.get("2026-05-20")).toBe(470); }); it("aggregates multiple activities on the same day", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [ @@ -92,8 +121,7 @@ describe("PmcTrainingLoadCalculator", () => { }); it("uses heart-rate training stress when power data is unavailable", () => { - const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); - const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], @@ -104,14 +132,11 @@ describe("PmcTrainingLoadCalculator", () => { restingHeartRate: 60, }); - expect(dailyLoad.get("2026-05-20")).toBeCloseTo( - trainingStressCalculator.computeHrTss(60, 150, 190, 60), - ); + expect(dailyLoad.get("2026-05-20")).toBe(150); }); it("uses heart-rate training stress when threshold power is unavailable", () => { - const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); - const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ id: "power-without-threshold" })], @@ -122,14 +147,11 @@ describe("PmcTrainingLoadCalculator", () => { restingHeartRate: 60, }); - expect(dailyLoad.get("2026-05-20")).toBeCloseTo( - trainingStressCalculator.computeHrTss(60, 150, 190, 60), - ); + expect(dailyLoad.get("2026-05-20")).toBe(150); }); it("uses heart-rate training stress when threshold power exists but normalized power is missing", () => { - const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); - const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ id: "missing-normalized-power" })], @@ -140,14 +162,11 @@ describe("PmcTrainingLoadCalculator", () => { restingHeartRate: 60, }); - expect(dailyLoad.get("2026-05-20")).toBeCloseTo( - trainingStressCalculator.computeHrTss(60, 150, 190, 60), - ); + expect(dailyLoad.get("2026-05-20")).toBe(150); }); it("uses heart-rate training stress when normalized power is zero", () => { - const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); - const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ id: "zero-normalized-power" })], @@ -158,15 +177,12 @@ describe("PmcTrainingLoadCalculator", () => { restingHeartRate: 60, }); - expect(dailyLoad.get("2026-05-20")).toBeCloseTo( - trainingStressCalculator.computeHrTss(60, 150, 190, 60), - ); + expect(dailyLoad.get("2026-05-20")).toBe(150); }); it("uses a learned training stress model for heart-rate-only activities when one exists", () => { - const trainingStressCalculator = new TrainingStressCalculator(1.92, 1.67); - const calculator = new PmcTrainingLoadCalculator(trainingStressCalculator); - const trimp = trainingStressCalculator.computeTrimp(60, 150, 190, 60); + const calculator = makeCalculator(); + const trainingImpulse = 150; const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], @@ -177,11 +193,11 @@ describe("PmcTrainingLoadCalculator", () => { restingHeartRate: 60, }); - expect(dailyLoad.get("2026-05-20")).toBeCloseTo(1.5 * trimp + 10); + expect(dailyLoad.get("2026-05-20")).toBe(1.5 * trainingImpulse + 10); }); it("does not allow a learned model to produce negative daily load", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator(); const dailyLoad = calculator.calculateDailyLoad({ activities: [makeActivityRow({ avg_power: null, power_samples: 0 })], @@ -196,7 +212,7 @@ describe("PmcTrainingLoadCalculator", () => { }); it("builds paired model inputs only from activities with positive normalized power", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator(); const result = calculator.buildTrainingStressModel( [ @@ -220,7 +236,7 @@ describe("PmcTrainingLoadCalculator", () => { }); it("does not build paired model inputs from activities with zero heart-rate load", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator(); const result = calculator.buildTrainingStressModel( [makeActivityRow({ id: "zero-heart-rate-load", avg_hr: 60 })], @@ -234,7 +250,7 @@ describe("PmcTrainingLoadCalculator", () => { }); it("does not build paired model inputs from activities with zero power training stress", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator(); const result = calculator.buildTrainingStressModel( [makeActivityRow({ id: "zero-power-training-stress" })], @@ -248,7 +264,7 @@ describe("PmcTrainingLoadCalculator", () => { }); it("does not build paired model inputs without threshold power", () => { - const calculator = new PmcTrainingLoadCalculator(new TrainingStressCalculator(1.92, 1.67)); + const calculator = makeCalculator(); const result = calculator.buildTrainingStressModel( [makeActivityRow({ id: "positive-power" })], diff --git a/packages/server/src/repositories/pmc-training-load-calculator.ts b/packages/server/src/repositories/pmc-training-load-calculator.ts index 7dd6dead52..93ad7468b2 100644 --- a/packages/server/src/repositories/pmc-training-load-calculator.ts +++ b/packages/server/src/repositories/pmc-training-load-calculator.ts @@ -1,5 +1,3 @@ -import { TrainingStressCalculator } from "@dofek/training/training-load"; - export interface PmcActivityRow { global_max_hr: number | null; resting_hr: number; @@ -29,6 +27,30 @@ interface PmcTrainingStressModelResult { pairedData: { trimp: number; powerTss: number }[]; } +export interface PmcTrainingLoadAlgorithms { + estimateThresholdPower(activities: PmcActivityRow[]): number | null; + computeTrainingImpulse( + durationMin: number, + avgHr: number, + maxHr: number, + restingHr: number, + ): number; + computePowerTrainingStressScore( + normalizedPower: number, + thresholdPower: number, + durationMin: number, + ): number; + computeHeartRateTrainingStressScore( + durationMin: number, + avgHr: number, + maxHr: number, + restingHr: number, + ): number; + buildTrainingStressModel( + pairedData: { trimp: number; powerTss: number }[], + ): PmcTrainingStressModel | null; +} + interface PmcDailyLoadInput { activities: PmcActivityRow[]; normalizedPowerByActivity: Map; @@ -39,21 +61,14 @@ interface PmcDailyLoadInput { } export class PmcTrainingLoadCalculator { - readonly #calculator: TrainingStressCalculator; - - static fromTrainingImpulseConstants( - genderFactor: number, - exponent: number, - ): PmcTrainingLoadCalculator { - return new PmcTrainingLoadCalculator(new TrainingStressCalculator(genderFactor, exponent)); - } + readonly #algorithms: PmcTrainingLoadAlgorithms; - constructor(calculator: TrainingStressCalculator) { - this.#calculator = calculator; + constructor(algorithms: PmcTrainingLoadAlgorithms) { + this.#algorithms = algorithms; } estimateThresholdPower(activities: PmcActivityRow[]): number | null { - return TrainingStressCalculator.estimateFtp(activities); + return this.#algorithms.estimateThresholdPower(activities); } buildTrainingStressModel( @@ -72,13 +87,13 @@ export class PmcTrainingLoadCalculator { const normalizedPower = normalizedPowerByActivity.get(activity.id); if (normalizedPower != null && normalizedPower > 0) { - const trimp = this.#calculator.computeTrimp( + const trimp = this.#algorithms.computeTrainingImpulse( durationMin, avgHr, globalMaxHeartRate, restingHeartRate, ); - const powerTss = TrainingStressCalculator.computePowerTss( + const powerTss = this.#algorithms.computePowerTrainingStressScore( normalizedPower, thresholdPower, durationMin, @@ -91,7 +106,7 @@ export class PmcTrainingLoadCalculator { } return { - trainingStressModel: TrainingStressCalculator.buildTssModel(pairedData), + trainingStressModel: this.#algorithms.buildTrainingStressModel(pairedData), pairedData, }; } @@ -107,13 +122,13 @@ export class PmcTrainingLoadCalculator { let trainingStressScore: number; if (input.thresholdPower != null && normalizedPower != null && normalizedPower > 0) { - trainingStressScore = TrainingStressCalculator.computePowerTss( + trainingStressScore = this.#algorithms.computePowerTrainingStressScore( normalizedPower, input.thresholdPower, durationMin, ); } else if (input.trainingStressModel != null) { - const trimp = this.#calculator.computeTrimp( + const trimp = this.#algorithms.computeTrainingImpulse( durationMin, avgHr, input.globalMaxHeartRate, @@ -124,7 +139,7 @@ export class PmcTrainingLoadCalculator { input.trainingStressModel.slope * trimp + input.trainingStressModel.intercept, ); } else { - trainingStressScore = this.#calculator.computeHrTss( + trainingStressScore = this.#algorithms.computeHeartRateTrainingStressScore( durationMin, avgHr, input.globalMaxHeartRate, From 5e4bb9931641aa6322406403fa397cbfd94ab017 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 10:49:29 -0700 Subject: [PATCH 09/11] Avoid workspace package false positive in PMC diff --- packages/server/src/repositories/pmc-repository.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/server/src/repositories/pmc-repository.ts b/packages/server/src/repositories/pmc-repository.ts index d41cf63426..a7d9fa4ac4 100644 --- a/packages/server/src/repositories/pmc-repository.ts +++ b/packages/server/src/repositories/pmc-repository.ts @@ -1,10 +1,9 @@ -import type { PmcChartResult } from "@dofek/training/pmc"; -import { TrainingStressCalculator } from "@dofek/training/training-load"; - import type { Database } from "dofek/db"; import { getEffectiveParams } from "dofek/personalization/params"; import { loadPersonalizedParams } from "dofek/personalization/storage"; import { z } from "zod"; +import type { PmcChartResult } from "../../../training/src/pmc.ts"; +import { TrainingStressCalculator } from "../../../training/src/training-load.ts"; import { BaseRepository } from "../lib/base-repository.ts"; import { dateWindowStartString } from "../lib/date-window.ts"; import type { ActivitySensorStore } from "./activity-repository.ts"; From 6f21a238ef76ce697f64bdb1775bf965a0a736d1 Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 11:11:18 -0700 Subject: [PATCH 10/11] Strengthen PMC EWMA mutation coverage --- .../repositories/pmc-ewma-calculator.test.ts | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/packages/server/src/repositories/pmc-ewma-calculator.test.ts b/packages/server/src/repositories/pmc-ewma-calculator.test.ts index ca494e525e..2b14b40939 100644 --- a/packages/server/src/repositories/pmc-ewma-calculator.test.ts +++ b/packages/server/src/repositories/pmc-ewma-calculator.test.ts @@ -8,6 +8,62 @@ function dateStringDaysAgo(daysAgo: number): string { } describe("PmcEwmaCalculator", () => { + it("applies exact exponential moving average formulas for chronic and acute load", () => { + const firstDate = dateStringDaysAgo(2); + const secondDate = dateStringDaysAgo(1); + const thirdDate = dateStringDaysAgo(0); + const calculator = new PmcEwmaCalculator({ + chronicTrainingLoadDays: 4, + acuteTrainingLoadDays: 2, + }); + + const result = calculator.compute({ + dailyLoad: new Map([[firstDate, 100]]), + queryDays: 2, + displayDays: 2, + }); + + expect(result).toEqual([ + { date: firstDate, load: 100, ctl: 25, atl: 50, tsb: -25 }, + { date: secondDate, load: 0, ctl: 18.8, atl: 25, tsb: -6.2 }, + { date: thirdDate, load: 0, ctl: 14.1, atl: 12.5, tsb: 1.6 }, + ]); + }); + + it("trims leading display days before chronic load becomes meaningful", () => { + const firstMeaningfulDate = dateStringDaysAgo(2); + const calculator = new PmcEwmaCalculator({ + chronicTrainingLoadDays: 10, + acuteTrainingLoadDays: 5, + }); + + const result = calculator.compute({ + dailyLoad: new Map([[firstMeaningfulDate, 10]]), + queryDays: 4, + displayDays: 4, + }); + + expect(result[0]?.date).toBe(firstMeaningfulDate); + expect(result[0]?.ctl).toBe(1); + expect(result).toHaveLength(3); + }); + + it("keeps a day whose rounded chronic load is exactly the meaningful threshold", () => { + const thresholdDate = dateStringDaysAgo(0); + const calculator = new PmcEwmaCalculator({ + chronicTrainingLoadDays: 100, + acuteTrainingLoadDays: 50, + }); + + const result = calculator.compute({ + dailyLoad: new Map([[thresholdDate, 10]]), + queryDays: 1, + displayDays: 1, + }); + + expect(result).toEqual([{ date: thresholdDate, load: 10, ctl: 0.1, atl: 0.2, tsb: -0.1 }]); + }); + it("builds rounded daily training load series with acute load responding faster than chronic load", () => { const activityDate = dateStringDaysAgo(1); const calculator = new PmcEwmaCalculator({ From 46541d0e26d3ae77dac525cbb8fcff83b8d6b41f Mon Sep 17 00:00:00 2001 From: Asher Cohen Date: Mon, 25 May 2026 11:29:19 -0700 Subject: [PATCH 11/11] Restore PMC training public imports --- packages/server/src/repositories/pmc-repository.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/server/src/repositories/pmc-repository.ts b/packages/server/src/repositories/pmc-repository.ts index a7d9fa4ac4..c0cc164b81 100644 --- a/packages/server/src/repositories/pmc-repository.ts +++ b/packages/server/src/repositories/pmc-repository.ts @@ -1,9 +1,10 @@ +import type { PmcChartResult, PmcDataPoint, TssModelInfo } from "@dofek/training/pmc"; +import { TrainingStressCalculator } from "@dofek/training/training-load"; + import type { Database } from "dofek/db"; import { getEffectiveParams } from "dofek/personalization/params"; import { loadPersonalizedParams } from "dofek/personalization/storage"; import { z } from "zod"; -import type { PmcChartResult } from "../../../training/src/pmc.ts"; -import { TrainingStressCalculator } from "../../../training/src/training-load.ts"; import { BaseRepository } from "../lib/base-repository.ts"; import { dateWindowStartString } from "../lib/date-window.ts"; import type { ActivitySensorStore } from "./activity-repository.ts"; @@ -34,6 +35,11 @@ const normalizedPowerRowSchema = z.object({ np: z.coerce.number(), }); +type PmcRepositoryChartResult = PmcChartResult & { + data: PmcDataPoint[]; + model: TssModelInfo; +}; + // --------------------------------------------------------------------------- // Repository // --------------------------------------------------------------------------- @@ -53,7 +59,7 @@ export class PmcRepository extends BaseRepository { this.#sensorStore = sensorStore; } - async getChart(days: number): Promise { + async getChart(days: number): Promise { // Load personalized algorithm parameters const storedParams = await loadPersonalizedParams(this.db, this.userId); const effective = getEffectiveParams(storedParams);