Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=<generated-port>
# CLICKHOUSE_HTTP_PORT=<generated-port>
# CLICKHOUSE_NATIVE_PORT=<generated-port>
# REDIS_PORT=<generated-port>
# CLICKHOUSE_URL=http://default:health@127.0.0.1:<assigned-port>
# DATABASE_URL=postgres://health:health@127.0.0.1:<assigned-port>/health
# REDIS_URL=redis://127.0.0.1:<assigned-port>

# OAuth callback — set to your public URL
# OAUTH_REDIRECT_URI=https://health.yourdomain.com/callback

Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<source>.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.
Expand Down
17 changes: 4 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions STANDARDS.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 5 additions & 5 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -61,7 +61,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:
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
174 changes: 174 additions & 0 deletions packages/server/src/repositories/pmc-chart-calculator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { describe, expect, it } from "vitest";
import { PmcChartCalculator } from "./pmc-chart-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> = {}): 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,
};
}

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 = makeCalculator();

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 = makeCalculator();

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 enough paired activities fit", () => {
const calculator = makeCalculator();
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", () => {
const lowRestingCalculator = makeCalculator();
const highRestingCalculator = makeCalculator();

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);
});
});
99 changes: 99 additions & 0 deletions packages/server/src/repositories/pmc-chart-calculator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { PmcEwmaCalculator } from "./pmc-ewma-calculator.ts";
import type {
PmcActivityRow,
PmcNormalizedPowerRow,
PmcTrainingLoadCalculator,
} from "./pmc-training-load-calculator.ts";

interface PmcChartCalculatorOptions {
chronicTrainingLoadDays: number;
acuteTrainingLoadDays: number;
trainingLoadCalculator: PmcTrainingLoadCalculator;
}

interface PmcChartInput {
activityRows: PmcActivityRow[];
normalizedPowerRows: PmcNormalizedPowerRow[];
queryDays: number;
displayDays: number;
}

interface PmcChartModel {
type: "learned" | "generic";
pairedActivities: number;
r2: number | null;
ftp: number | null;
}

interface PmcChart {
data: ReturnType<PmcEwmaCalculator["compute"]>;
model: PmcChartModel;
}

export class PmcChartCalculator {
readonly #trainingLoadCalculator: PmcTrainingLoadCalculator;
readonly #ewmaCalculator: PmcEwmaCalculator;

constructor(options: PmcChartCalculatorOptions) {
this.#trainingLoadCalculator = options.trainingLoadCalculator;
this.#ewmaCalculator = new PmcEwmaCalculator({
chronicTrainingLoadDays: options.chronicTrainingLoadDays,
acuteTrainingLoadDays: options.acuteTrainingLoadDays,
});
}

buildChart(input: PmcChartInput): PmcChart {
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 = this.#trainingLoadCalculator.estimateThresholdPower(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: PmcChartModel =
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 };
}
}
Loading
Loading