Files
phaseflow/IMPLEMENTATION_PLAN.md
Petru Paler 00b84d0b22 Fix E2E test reliability issues and stale data bugs
- Fix race conditions: Set workers: 1 since all tests share test user state
- Fix stale data: GET /api/user and /api/cycle/current now fetch fresh data
  from database instead of returning stale PocketBase auth store cache
- Fix timing: Replace waitForTimeout with retry-based Playwright assertions
- Fix mobile test: Use exact heading match to avoid strict mode violation
- Add test user setup: Include notificationTime and update rule for users

All 1014 unit tests and 190 E2E tests pass.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:23:32 +00:00

8.1 KiB

PhaseFlow Implementation Plan

This file is maintained by Ralph. Run ./ralph-sandbox.sh plan 3 to generate tasks.

Current Status: Feature Complete

Test Coverage: 1014 unit tests (51 files) + 204 E2E tests (14 files) = 1218 total tests

All P0-P5 items are complete. The project is feature complete.


Architecture Summary

Tech Stack

Layer Choice
Framework Next.js 16 (App Router)
Runtime Node.js 24
Database PocketBase
Validation Zod
Testing Vitest + jsdom + Playwright
Linting Biome

Critical Business Rules

  1. Override Priority: flare > stress > sleep > pms (enforced in order)
  2. HRV Unbalanced: ALWAYS forces REST (highest algorithmic priority, non-overridable)
  3. Phase Limits: Strictly enforced per phase configuration
  4. Token Expiration Warnings: Email at 14 days and 7 days before expiry
  5. ICS Feed: Generates 90 days of phase events for calendar subscription

Completed Implementation

Library Files (12 files, 250+ tests)

File Tests Key Functions
cycle.ts 22 getCycleDay, getPhase, getPhaseConfig, dynamic phase boundaries
nutrition.ts 17 getNutritionGuidance, getSeedSwitchAlert, phase-specific guidance
email.ts 32 sendDailyEmail, sendPeriodConfirmationEmail, sendTokenExpirationWarning
ics.ts 33 generateIcsFeed, 90-day events, period prediction feedback, CATEGORIES
encryption.ts 14 AES-256-GCM encrypt/decrypt
decision-engine.ts 24 getTrainingDecision, getDecisionWithOverrides, 8 priority rules
garmin.ts 33 fetchHrvStatus, fetchBodyBattery, fetchIntensityMinutes, token validation
pocketbase.ts 10 createPocketBaseClient, isAuthenticated, getCurrentUser, loadAuthFromCookies
auth-middleware.ts 12 withAuth() wrapper, structured logging, IP logging
middleware.ts 12 Next.js page protection, redirects
logger.ts 16 Pino JSON output, log levels, child loggers
metrics.ts 33 Prometheus metrics, counters, gauges, histograms

API Routes (21 endpoints, 350+ tests)

Route Tests Purpose
POST /api/auth/logout 5 Session logout
GET /api/user 4 User profile
PATCH /api/user 17 Update preferences
POST /api/cycle/period 13 Log period start with prediction tracking
GET /api/cycle/current 10 Current cycle state
GET /api/today 24 Daily snapshot with decision
POST/DELETE /api/overrides 14 Override management
POST/DELETE /api/garmin/tokens 15 Token storage
GET /api/garmin/status 11 Connection status
POST /api/cron/garmin-sync 32 Daily data sync
POST /api/cron/notifications 20 Email notifications
GET /api/calendar/[userId]/[token].ics 11 ICS feed
POST /api/calendar/regenerate-token 9 Token regeneration
GET /api/history 19 Daily log history
GET /api/period-history 18 Period log history
PATCH/DELETE /api/period-logs/[id] 16 Period log management
GET /api/health 14 Health check
GET /metrics 15 Prometheus metrics

Pages (8 pages, 230+ tests)

Page Tests Features
Dashboard (/) 28 Decision card, data panel, nutrition, overrides, mini calendar
Login (/login) 32 OIDC + email/password, rate limiting
Settings (/settings) 34 Preferences, logout
Settings/Garmin 27 Token management, status
Calendar (/calendar) 23 Month view, ICS subscription
History (/history) 26 Daily log table
Period History 27 Period log table, edit/delete
Plan (/plan) 16 Phase overview, training reference

Components (10 components, 200+ tests)

Component Tests Purpose
DecisionCard 19 Status display with color coding
DataPanel 29 Biometrics display, HRV color coding, progress bar
NutritionPanel 16 Seeds, carbs, keto guidance
OverrideToggles 18 Override buttons
DayCell 32 Calendar day with phase colors, period indicator
MiniCalendar 23 Dashboard calendar widget
OnboardingBanner 16 Setup prompts
MonthView 31 Full calendar with navigation, keyboard nav
PeriodDateModal 22 Period input modal
Skeletons 29 Loading states with shimmer

E2E Tests (14 files, 204 tests)

File Tests Coverage
smoke.spec.ts 3 Basic app functionality
auth.spec.ts 20 Login, protected routes, OIDC flow, session persistence
dashboard.spec.ts 40 Dashboard display, overrides, accessibility
settings.spec.ts 27 Settings form, validation, persistence, error recovery
garmin.spec.ts 16 Garmin connection, expiry warnings, network error recovery
period-logging.spec.ts 19 Period history, logging, modal flows
calendar.spec.ts 34 Calendar view, ICS feed, content validation, accessibility
decision-engine.spec.ts 8 Decision priority chain
cycle.spec.ts 11 Cycle tracking
history.spec.ts 7 History page
plan.spec.ts 7 Plan page
health.spec.ts 3 Health/observability
mobile.spec.ts 7 Mobile viewport behavior, responsive layout, calendar mobile
dark-mode.spec.ts 2 System preference detection, light/dark theme application

E2E Test Enhancement Opportunities

These are optional enhancements to improve E2E coverage. Not required for feature completeness.

Note: notifications.spec.ts was considered but determined to be redundant with existing settings.spec.ts coverage which already tests notification time and timezone preferences thoroughly.

Completed Enhancements

File Tests Added Focus Area
dark-mode.spec.ts +2 System preference detection (light/dark mode)
garmin.spec.ts +4 Network error recovery (save, disconnect, status fetch, retry)
calendar.spec.ts +4 Accessibility (ARIA, keyboard nav)
settings.spec.ts +1 Error recovery on failed save
mobile.spec.ts +3 Calendar responsive behavior

Notes

  1. TDD Approach: Write failing tests first, then implement
  2. Auth First: P0 items unlock all other work
  3. No Mock Mode: Use real data and APIs only
  4. ABOUTME Comments: All files start with 2-line ABOUTME
  5. Commit Format: Descriptive message + Claude footer
  6. Never use --no-verify: All commits go through pre-commit hooks

Revision History

  • 2026-01-13: Fixed E2E test reliability issues:
    • Race conditions: Changed to single worker execution (tests share test user state)
    • Stale data: GET /api/user and GET /api/cycle/current now fetch fresh data from database instead of stale auth cache
    • Timing: Replaced fixed waitForTimeout calls with retry-based Playwright assertions
    • Mobile test: Fixed strict mode violation by using exact heading match
  • 2026-01-13: Marked notifications.spec.ts as redundant (notification preferences already covered in settings.spec.ts)
  • 2026-01-13: Added dark-mode.spec.ts with 2 E2E tests (system preference detection for light/dark mode)
  • 2026-01-13: Added 4 Garmin E2E tests (network error recovery for save, disconnect, status fetch, retry)
  • 2026-01-13: Added 8 E2E tests (calendar accessibility, settings error recovery, calendar mobile behavior)
  • 2026-01-13: Added mobile.spec.ts with 4 E2E tests (mobile viewport behavior, responsive layout)
  • 2026-01-13: Added 6 auth E2E tests (OIDC button display, loading states, session persistence across pages/refresh)
  • 2026-01-13: Added 5 settings persistence E2E tests (notification time, timezone, multi-field persistence)
  • 2026-01-13: Added 5 period-logging E2E tests (modal flow, future date restriction, edit/delete flows)
  • 2026-01-13: Added 5 Garmin E2E tests (expiry warnings, expired state, persistence, reconnection)
  • 2026-01-13: Condensed plan after feature completion (reduced from 1514 to ~170 lines)
  • 2026-01-12: Fixed spec gaps (email format, HRV colors, progress bar, emojis)
  • 2026-01-11: Completed P5.1-P5.4 (period history, toast, CI, E2E)