✦ OPEN TO WORK // SENIOR FULL-STACK & APPLIED AI ✦ REAL-TIME WEBSOCKETS & DISTRIBUTED SYSTEMS ✦ MUMBAI, INDIA [UTC +5:30] ✦ OPEN TO WORK // SENIOR FULL-STACK & APPLIED AI ✦ REAL-TIME WEBSOCKETS & DISTRIBUTED SYSTEMS ✦ MUMBAI, INDIA [UTC +5:30] ✦ OPEN TO WORK // SENIOR FULL-STACK & APPLIED AI ✦ REAL-TIME WEBSOCKETS & DISTRIBUTED SYSTEMS ✦ MUMBAI, INDIA [UTC +5:30]
APPLIED AI TRAINING COPILOT GEMINI TOOL CALLING

Gymflow

Adaptive Training Scheduler & AI Coaching Engine

ROLE Creator & Full-Stack Developer
CORE TECHNOLOGIES
Next.js 15 TypeScript Google GenAI SDK Upstash Redis
PRIMARY HIGHLIGHT Automated timetable diffing & cancellation alerts Deterministic Gemini tool calling for schedule replanning
LINKS & ACCESS

01. Context & Overview

Gymflow is an adaptive training scheduler and autonomous AI coaching engine built to solve a recurring real-world problem: gym class timetables frequently change mid-week, requiring tedious manual schedule reshuffling around work commutes and fatigue.

The application connects live with a private gym scheduling API via a reverse-engineered OTP authentication bridge, detects schedule cancellations by diffing weekly timetable snapshots in Upstash Redis, and triggers a stateful Gemini agent to dynamically replan the week around real-world constraints—including Work From Office (WFO) commute shifts, systemic fatigue, fueling nutrition, and combat sports sessions (Kickboxing, BJJ, Boxing Conditioning).

Built with Next.js 15 App Router, TypeScript strict mode, and the Google GenAI SDK, Gymflow operates on a $0/month serverless footprint while supporting full offline testability through a mock fixture adapter (GYM_USE_MOCK=true).

02. The Constraints & Needs

Automating dynamic athletic scheduling with production LLMs introduces distinct architectural requirements:

  1. Reverse-Engineered Third-Party Ingestion: Gym scheduling APIs lack official public developer webhooks and rely on mobile OTP SMS auth. The backend must securely proxy OTP exchanges and manage 24-hour bearer tokens in Upstash Redis without leaking credentials to client browsers.
  2. Automated Mid-Week Timetable Diffing: Timetable shifts occur unexpectedly. Ingested live schedules (/member/schedules/by-tier) must be diffed against weekly Redis snapshots to immediately isolate canceled or shifted training sessions.
  3. Deterministic Agent Replanning: Free-form LLM chat output is too volatile for calendar mutations. The system requires deterministic tool calling (replan_week_schedule, log_constraint) enforced by strict Zod schema contracts rather than unconstrained text generation.
  4. Spec-Driven Architecture & Zero Operational Cost: Built following Spec-Driven Development (SDD) blueprints (specs/) and verified against deterministic evaluation harnesses (evals/), all while running on edge serverless infrastructure with zero monthly hosting costs.
ToolCall_ReplanWeekSchedule
ZOD CONTRACT
// Contract schema definition
{
"target_date": *req <iso8601_date> // Calendar date affected by schedule shift or fatigue
"canceled_slot_id": *req <string> // Identifier of the canceled or conflicting class session
"replacement_modality": *req <enum(kickboxing, bjj, boxing_conditioning, recovery, strength)> // Selected athletic modality for the replacement block
"commute_constraint": *req <enum(wfo_60m, wfo_standard, wfh_remote)> // Work From Office travel overhead constraint for the day
"fatigue_score": *req <integer (1-10)> // User-reported systemic fatigue level guiding volume adjustment
"adaptation_reasoning": *req <string> // Deterministic rationale synthesized for the coaching feedback banner
}

03. System Architecture & Data Flow

Gymflow coordinates authentication, timetable ingestion, snapshot diffing, and agent execution across a clean serverless pipeline:

[ Next.js 15 App Router (Frontend UI + Edge API) ]
                 │
                 ▼ (HttpOnly Session)
┌──────────────────────────────────────────────────────────────┐
│ BACKEND SERVICES & ORCHESTRATION                             │
├──────────────────────────────────────────────────────────────┤
│ 1. Auth Bridge       ──► Proxies OTP / Exchanges Bearer JWT  │
│ 2. Gym Ingestion     ──► Fetches /member/schedules/by-tier   │
│ 3. Diff Engine       ──► Detects mid-week class shifts       │
│ 4. Agent Tool Runner ──► Executes structured LLM tool calls  │
└──────────────┬───────────────────────────────┬───────────────┘
               │                               │
               ▼                               ▼
     [ Upstash Redis ]               [ Google GenAI SDK ]
  (Tokens, Cache, Snapshots)         (Gemini 2.5/3 Pro & Flash)
ARCHITECTURE SCHEMATIC

Gymflow Live Sync & Adaptive Replanning Pipeline

01
Secure OTP Auth Bridge HTTPONLY SESSION

Proxies OTP verification, exchanges third-party bearer JWT, and delegates 24-hour token refresh into Upstash Redis.

arrow_downward
02
Live Timetable Ingestion REST ADAPTER

Queries gym endpoints (/member/schedules/by-tier) or loads fixtures/ when running in offline mock mode (GYM_USE_MOCK=true).

arrow_downward
03
Upstash Redis State Diff Engine REDIS SNAPSHOTS

Compares freshly fetched timetable against the weekly schedule snapshot in Redis, identifying canceled or shifted training slots.

arrow_downward
04
Deterministic Tool Calling (Gemini) GOOGLE GENAI SDK

Feeds detected diffs alongside WFO commute hours and fatigue constraints into Gemini Pro/Flash to invoke replan_week_schedule.

arrow_downward
05
Calendar Rehydration & User Notification NEXT.JS 15 RSC

Persists updated training week state into Redis and re-renders adaptive calendar views and fueling recommendations.

04. Protocol & Sequence Lifecycle

The trace below illustrates how Gymflow detects a mid-week cancellation (e.g. Kickboxing canceled on Tuesday) and autonomously coordinates with the Gemini agent to replan around office commute hours:

PROTOCOL LIFECYCLE

Timetable Diffing & Dynamic Replanning Trace

Client UI
Next.js Edge API
Upstash Redis
Gym API / Mock
Gemini 2.5/3
#1 Client UI → Next.js Edge API : Trigger daily sync or timetable refresh
1ms
#2 Next.js Edge API → Gym API / Mock : GET /member/schedules/by-tier with delegated bearer token
140ms
#3 Next.js Edge API → Upstash Redis : GET schedule:snapshot:current_week: Retrieve previous baseline
18ms
#4 Next.js Edge API → Next.js Edge API : Diff detected: Tuesday Kickboxing class canceled by facility
2ms
#5 Next.js Edge API → Gemini 2.5/3 : Prompt with diff + constraints (WFO 60m commute, fatigue: 7)
220ms
#6 Gemini 2.5/3 → Next.js Edge API : Emit verified tool call: replan_week_schedule(Boxing Conditioning)
15ms
#7 Next.js Edge API → Upstash Redis : SET schedule:snapshot:current_week: Save updated weekly plan
12ms
#8 Next.js Edge API → Client UI : Stream timetable diff alert & adapted calendar view
6ms

05. Benchmark & Evaluation Matrix

Key architecture trade-offs evaluated across the Gymflow system design:

ARCHITECTURE MATRIX

Gymflow Architecture Decisions & Trade-Offs

Comparative evaluation across design constraints and implementations

swipe Swipe horizontally to inspect full matrix
Technical Decision Alternative Approach Chosen Solution Result & Trade-Off
Timetable Sync Strategy Direct client polling on every page view Edge proxy + Redis diff engine with 24h token cache Zero token leakage to client; isolates diffs before invoking LLM
Agent Replanning Execution Free-form text generation Deterministic tool calling (Zod + GenAI SDK) 100% Valid schema compliance; eliminates time-slot hallucinations
Development & Testing Velocity Direct dependency on private gym API credentials Offline mock fixture adapter (GYM_USE_MOCK=true) Fully reproducible local development and CI eval testing
Operating Footprint Dedicated always-on server ($20–$40/mo) Next.js 15 Serverless Edge + Upstash REST Redis $0.00/mo operating footprint

06. Key Engineering Learnings

  1. Enforce Deterministic Tool Calling Over Raw Text: For calendar and booking workflows, never rely on conversational text generation. Using structured function calls (replan_week_schedule, log_constraint) paired with Zod contracts guarantees schema integrity.
  2. State Diffing Preserves Explanatory Context: Comparing live API responses against cached snapshots before calling the LLM allows the system to articulate precisely why a replan occurred (e.g., “Tuesday Kickboxing canceled; shifted to Boxing Conditioning to accommodate 60m WFO commute”).
  3. Protect Private Third-Party Tokens: Never expose reverse-engineered bearer tokens to frontend clients. Maintain an HttpOnly session boundary and delegate token refreshes to an edge Redis store.
  4. Spec-Driven Blueprints and Mock Fixtures Enable Reliable Evals: Designing architectural blueprints in specs/ and running automated eval suites (npm run eval against evals/test-scenarios.json) ensures prompt iterations never break core scheduling invariants.