Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .github/ci-filters.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"worker": [
"apps/worker/**",
"packages/api/**",
"packages/db/**",
".github/workflows/ci.yml",
".github/ci-filters.json",
Expand All @@ -10,6 +11,7 @@
],
"server": [
"apps/server/**",
"packages/api/**",
"packages/db/**",
".github/workflows/ci.yml",
".github/ci-filters.json",
Expand Down Expand Up @@ -64,6 +66,7 @@
],
"contracts": [
"docs/testing/fixtures/**",
"packages/api/**",
"apps/server/**",
"packages/db/**",
"apps/collection/lib/collection/**",
Expand Down
98 changes: 98 additions & 0 deletions .github/workflows/api-rewrite.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
name: API rewrite
on:
pull_request:
paths:
- "apps/api/**"
- "apps/server/**"
- "packages/api/**"
- "packages/db/**"
- "packages/games/**"
- ".github/workflows/api-rewrite.yml"
push:
branches: [main]
paths:
- "apps/api/**"
- "packages/api/**"
- "packages/db/**"
- "packages/games/**"
- ".github/workflows/api-rewrite.yml"
permissions:
contents: read
jobs:
contracts-and-api:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: lovat_test
POSTGRES_PASSWORD: lovat_test
POSTGRES_DB: lovat_test
ports: ["5432:5432"]
options: >-
--health-cmd "pg_isready -U lovat_test" --health-interval 5s --health-timeout 5s --health-retries 10
redis:
image: redis:7.4
ports: ["6379:6379"]
options: >-
--health-cmd "redis-cli ping" --health-interval 5s --health-timeout 5s --health-retries 10
env:
DATABASE_URL: postgresql://lovat_test:lovat_test@127.0.0.1:5432/lovat_test
REDIS_URL: redis://127.0.0.1:6379
LOVAT_DB_TEST: "1"
LOVAT_REDIS_TEST: "1"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22.20.0
cache: npm
cache-dependency-path: |
packages/api/package-lock.json
packages/db/package-lock.json
packages/games/package-lock.json

- run: npm ci
working-directory: packages/db
- run: npm run build
working-directory: packages/db
- run: npm run db:deploy
working-directory: packages/db
- run: npm ci
working-directory: packages/api
- run: npm test && npm run generate:check && npm run lint && npm run format:check
working-directory: packages/api
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
- run: bun install --frozen-lockfile
working-directory: apps/api
- run: npm test && npm run lint && npm run format:check
working-directory: packages/games
- run: bun run test && bun run test:integration && bun run lint && bun run format:check && bun run inventory:check
working-directory: apps/api

- name: Build legacy Server for local rollback rehearsal
run: npm ci && npm run build
working-directory: apps/server
- name: Rehearse traffic rollback without schema rollback
run: bun run test:rollout
working-directory: apps/api
- name: Build production Bun image
run: docker build -t lovat-api:qualification -f apps/api/Dockerfile .
- name: Smoke test bounded container and graceful shutdown
shell: bash
run: |
set -euo pipefail
trap 'docker logs lovat-api-smoke; docker rm -f lovat-api-smoke' EXIT
docker run --detach --name lovat-api-smoke --network host --memory=512m --cpus=1 \
--env DATABASE_URL --env REDIS_URL \
--env AUTH0_ISSUER=https://auth.test.invalid/ \
--env AUTH0_AUDIENCE=https://api.lovat.app \
--env REDIS_KEY_PREFIX=lovat:container:${{ github.run_id }}: \
--env HOST=127.0.0.1 --env PORT=3001 lovat-api:qualification
node apps/api/tools/smoke-container.mjs http://127.0.0.1:3001
docker stats --no-stream lovat-api-smoke
docker image inspect --format '{{.Size}}' lovat-api:qualification
docker stop --time 20 lovat-api-smoke
test "$(docker inspect --format '{{.State.ExitCode}}' lovat-api-smoke)" = 0
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ jobs:
cache: npm
cache-dependency-path: |
apps/server/package-lock.json
packages/api/package-lock.json
packages/db/package-lock.json
- run: npm ci
- run: npm run format:check
Expand Down Expand Up @@ -205,6 +206,8 @@ jobs:
bun-version: 1.3.14
- run: npm --prefix ../../packages/db ci --include=dev
- run: npm --prefix ../../packages/db run build
- run: npm --prefix ../../packages/api ci --include=dev
- run: npm --prefix ../../packages/api run build
- run: bun install --frozen-lockfile --ignore-scripts
- run: bun run typecheck
- name: Test worker against disposable PostgreSQL
Expand Down
14 changes: 12 additions & 2 deletions .railway/railway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,12 @@ export default defineRailway((ctx) => {
...(!production
? { nixpacksPlan: { repo: "MangoSwirl/lovat-server" } }
: {}),
watchPatterns: ["/apps/server/**", "/packages/db/**", "/.railway/**"],
watchPatterns: [
"/apps/server/**",
"/packages/api/**",
"/packages/db/**",
"/.railway/**",
],
},
deploy: {
runtime: "V2",
Expand Down Expand Up @@ -163,7 +168,12 @@ export default defineRailway((ctx) => {
build: {
builder: "DOCKERFILE",
dockerfilePath: "apps/worker/Dockerfile",
watchPatterns: ["/apps/worker/**", "/packages/db/**", "/.railway/**"],
watchPatterns: [
"/apps/worker/**",
"/packages/api/**",
"/packages/db/**",
"/.railway/**",
],
},
deploy: {
runtime: "V2",
Expand Down
16 changes: 16 additions & 0 deletions apps/api/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
DATABASE_URL=postgresql://lovat_test:lovat_test@127.0.0.1:5432/lovat_test
AUTH0_ISSUER=https://your-tenant.auth0.com/
AUTH0_AUDIENCE=https://api.lovat.app
PORT=3001
CORS_ALLOWED_ORIGINS=http://localhost:8080

REDIS_URL=redis://127.0.0.1:6379
REDIS_KEY_PREFIX=lovat:rewrite:
BASE_URL=http://localhost:3001
LOVAT_WEBSITE=https://lovat.app
# Optional external integrations; use private local values when exercising them.
# TBA_KEY=
# LOVAT_SIGNING_KEY=
# SLACK_SIGNING_SECRET=
# SLACK_CLIENT_ID=
# SLACK_CLIENT_SECRET=
3 changes: 3 additions & 0 deletions apps/api/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dist/
node_modules/
legacy-routes.json
7 changes: 7 additions & 0 deletions apps/api/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Replacement API

- This is the independent replacement for apps/server. Never import legacy handlers across application boundaries.
- Consume public schemas from @lovat/api and database models from @lovat/db.
- Run bun run build, bun test ./test/*.test.mjs, bun run lint, bun run format:check, and bun run inventory:check. Use Bun 1.4.4 and Hono; preserve the app Bun lockfile.
- Keep analysis data access behind the scoped repository; preserve training, reliability, source-team, tournament, and season restrictions.
- Treat v3 metric semantics as versioned. Add fixtures and document intentional differences from legacy outputs.
28 changes: 28 additions & 0 deletions apps/api/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Build from repository root; production traffic stays on apps/server until cutover.
FROM oven/bun:1.4.4 AS bun
FROM node:22.20.0-bookworm-slim AS build
COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun
RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY packages/api ./packages/api
COPY packages/games ./packages/games
COPY packages/db ./packages/db
COPY apps/api ./apps/api
# Shared packages retain their independent npm lockfiles.
RUN npm --prefix packages/api ci --ignore-scripts && npm --prefix packages/api run build
RUN npm --prefix packages/games ci --ignore-scripts && npm --prefix packages/games run build
RUN npm --prefix packages/db ci --include=dev && npm --prefix packages/db run build
WORKDIR /app/apps/api
RUN bun install --frozen-lockfile --ignore-scripts && bun run build
# Remove compilers, Prisma tooling and test dependencies from the runtime image.
RUN npm --prefix /app/packages/api prune --omit=dev --ignore-scripts && npm --prefix /app/packages/games prune --omit=dev --ignore-scripts && npm --prefix /app/packages/db prune --omit=dev --ignore-scripts && bun install --production --frozen-lockfile --ignore-scripts

FROM oven/bun:1.4.4-debian AS runtime
RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build --chown=bun:bun /app/packages ./packages
COPY --from=build --chown=bun:bun /app/apps/api ./apps/api
WORKDIR /app/apps/api
ENV NODE_ENV=production
USER bun
CMD ["bun", "--smol", "dist/server.js"]
6 changes: 6 additions & 0 deletions apps/api/Dockerfile.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
**/node_modules
**/dist
**/coverage
**/.env
**/.env.*
.git
90 changes: 90 additions & 0 deletions apps/api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Replacement Lovat API

Ground-up implementation for [LVT-243](https://linear.app/highlander-robotics/issue/LVT-243). This application does not import or delegate to legacy handlers. Existing production deployment still uses `apps/server`; changing the traffic target is a separate release action.

## Structure

- `app.ts` registers Hono routes and `runtime.ts` serves them with Bun. `http/` owns endpoint declarations, payload limits and authorization policies.
- `services/` owns accounts, API keys, Collection, reports, schedules, onboarding, training, analysis, predictions, events, exports and Slack. The composition root lists each module and records route ownership.
- `repository.ts` owns source-scoped analysis reads and dataset limits.
- `@lovat/games` owns versioned rules, report validation, metrics, facts, aggregation and prediction. `metrics/` exposes 2026 compatibility adapters.
- `domain/` owns report validation/persistence, grading and transactional effect creation.
- `identity.ts`, `state.ts`, `signatures.ts` and `sockets.ts` provide identity, Redis, signed callbacks and training transport.
- `@lovat/api` owns reusable report, Collection lifecycle, training, metric and error schemas. Its optional legacy export supplies the extracted OpenAPI definitions; its effects export defines the worker protocol.

All 137 inventoried HTTP routes have registered replacement handlers, plus v3 analysis/metadata and the training WebSocket transport. Registration coverage is checked automatically. It does not establish complete behavioral parity: see [qualification evidence](../../docs/server-rewrite-qualification.md).

## Local setup

Use Bun 1.4.4 for this app and Node 22.20.0 for shared package tooling. Run `npm ci && npm run build` in `packages/db` with a verified database URL, then `bun install --frozen-lockfile && bun run build` here. The install script installs/builds the API and games packages using their own npm lockfiles. Bun path links ensure that rebuilding a game cannot leave copied code stale. Copy `.env.example` to a private `.env`, verify the database URL, and apply reviewed migrations through the release/database owner. The API never runs migrations or provider imports during startup or requests.

Start with `bun run start` (Bun loads the private local environment). Readiness probes PostgreSQL and Redis; liveness remains available while draining. Configure the worker with `API_EFFECTS_ENABLED=true`, matching Redis URL/prefix, and the relevant delivery credentials when testing the replacement. The existing Server does not enable this flag automatically.

Auth0 JWT signatures use cached JWKS. Existing users require one authoritative local identity read; only a new subject fetches its initial profile. API keys are hashed and checked against current ownership on every request, so revocation takes effect immediately. Collection uses a team code and scout identity independently of Auth0. Training browser/attempt tokens are stored as hashes. v1 signed-in analysts retain analysis access without team membership; v3 requires a verified team.

Slack callbacks verify the raw request HMAC. OAuth states are random, expire after ten minutes and are consumed atomically. Configure the exact allowed browser origins for HTTP and training sockets. Native clients may omit Origin.

## Resource and latency controls

The API admits four HTTP requests and uses a four-connection PostgreSQL pool with an eight-second statement timeout. Expensive cold analyses share one work slot and at most four queued calculations, with a five-second queue wait. Cache hits bypass that queue. The executable uses Bun `--smol` mode for slower heap growth and more frequent garbage collection. This is not a hard memory cap; qualify RSS and set deployment/container limits separately.

Analysis reads at most 5,000 reports and 100,000 events, with at most 10,000 events per report. Legacy events are hydrated in batches of at most 1,000 reports / 20,000 events. Short repeatable-read snapshots recheck source visibility before payload reads, then release the SQL connection before calculating metrics. Generic JSON reports use 512 KiB payload batches (up to 2 MiB for an individual stored report) and a 16 MiB dataset preflight. Detailed exports also check the combined note/description size before loading text, with a 4 MiB limit. Oversized requests return 413 rather than silently averaging a truncated dataset. Analysis bodies are limited to 64 KiB; report/lifecycle/legacy bodies to 1 MiB. Catalog requests are paginated, with a maximum page of 500.

Source, role, team, formula version and dataset revisions participate in analysis cache keys. Cache lifetime is 15 seconds, in-flight requests coalesce, and Redis cache failures fall back to current calculations. Report writes and invalidation revisions commit together in PostgreSQL. The worker publishes monotonic revisions and delivers durable email/Slack effects with retries. Training submissions create neither competition revisions nor robot warnings.

Identity and public recovery/Collection rate limits use atomic Redis budgets and fail closed if controls are unavailable. Public limits currently use the socket peer address; a reverse proxy must be considered during deployment qualification.

## Adding a metric or feature

Define a metric with `defineMetric` or `defineDerivedMetric`:

1. Declare its stable ID, aliases, season, formula version, unit, precision and required facts.
2. Supply its Zod output schema, including structured output when needed.
3. Calculate a pure per-report state.
4. Reduce report states into a match value.
5. Define how match and tournament values combine.

Register it in the season registry and add representative fixtures. The registry publishes output JSON Schema, resolves dependencies once, detects cycles and exposes the metric through the generic endpoint. The loader fetches events only when required, and shared facts avoid scanning the same timeline for each metric.

For a new API feature, put reusable request/response definitions in `packages/api`, add its owning service module, register its authorization policy in the composition root, and add behavior coverage. Do not import another application's source.

## Annual game updates

See [game-module development](../../packages/games/README.md). The v3 game catalog, report envelope, analysis and prediction endpoints select a game contract. New payloads use versioned JSON storage. Legacy uploads reject non-2026 seasons with a client-update error. Clients and 2026-specific training/schedule adapters still need deliberate annual updates.

## Metric semantics

All 22 numeric metrics and nine categorical breakdowns are implemented for 2026. Reports contribute equally within a match; matches contribute equally within a tournament. Rates pool quantities and valid durations before dividing. Later tournaments receive 80% weight at each recency step, ordered by date and key. Missing values stay distinct from measured zero. Points apply the accuracy scale once and keep climb bonuses separate.

Autonomous ends at 23 elapsed seconds. Successful climb timing uses time remaining. Multi-select categories describe prevalence and can sum above one. Internal calculations retain precision; v3 rounds at the response boundary. These consistent formulas resolve legacy endpoint disagreements, so v1 analysis/CSV differences must be reviewed before switching existing clients.

## Verification

Run:

```sh
bun run test
bun run lint
bun run format:check
bun run inventory:check
```

For disposable loopback services named `lovat_test`:

```sh
LOVAT_DB_TEST=1 LOVAT_REDIS_TEST=1 DATABASE_URL=postgresql://lovat_test:lovat_test@127.0.0.1:5432/lovat_test REDIS_URL=redis://127.0.0.1:6379 bun run test:integration
```

The database suite exercises native HTTP, lifecycle retries, tenant denial, analysis, exports, API keys, signed verification, joining, training and authenticated WebSockets. Redis tests cover atomic budgets, one-time OAuth state and cache expiry. CI provisions disposable PostgreSQL and Redis.

`bun run inventory` records each legacy route's replacement module and policy. Its coverage field explicitly describes registration only. `bun run benchmark` measures the pure engine. `tools/benchmark-http.mjs` measures local HTTP, PostgreSQL and Redis with synthetic identity; use the same disposable-service guard above. Neither benchmark establishes production latency or an old/new comparison.

Build the image from the repository root with `docker build -f apps/api/Dockerfile .`. External-provider staging, consumer compatibility, soak tests, rollback rehearsal and traffic cutover remain release gates.

## Local rollout qualification

Build the legacy Server with its Node 22.20.0 toolchain, then run `bun run test:rollout` here with the disposable-service flags above. Node 22.20.0 must be on PATH (or set LOVAT_NODE_EXECUTABLE). The test runs both real server compositions over loopback HTTP, checks report/key/tenant compatibility, stops the replacement gracefully and verifies the legacy server can continue without a schema rollback. Helpers use a clean scratch directory and explicit synthetic configuration; external HTTP is blocked.

The API workflow also builds the pruned production image, starts it under a 512 MiB / one-CPU container limit, checks readiness/catalog/authentication and verifies clean shutdown. This is local/CI qualification; live Auth0, Slack, email and production traffic changes are separately deferred.

The HTTP benchmark now measures a separate server process. BENCHMARK_MATCHES controls unique team/match groups; BENCHMARK_SOAK_SECONDS adds cold/warm soak and liveness checks. Fixture setup and the HTTP client are excluded from server RSS/CPU. See the qualification document for exact workloads and observed limits.
Loading
Loading