MEGA TRAINING SYSTEM

Architecture Report v3.4 — May 2026
775 tests ✅
2 blueprints
41 routes
3 SQLite DBs
⚡ circuit breaker active
⬡ ports & adapters (IC + MG)

01System Overview01

IC — Indoor Cycling
MG — Strength Training
YG — Yoga (placeholder)

Multi-discipline Flask application for AI-powered training plan generation using the Claude API. 4-layer architecture: Presentation → Application (Blueprints) → Services → Data. IC and MG are independent packages (src/ic/, src/mg/) each with their own Blueprint. app.py contains 9 global routes, DI container bootstrap (AppContainer) and dynamic plugin registration via discipline_registry.py. Sprint 4 adds: plugin system, DI with dependency-injector, api_v1_bp (/api/v1/), idempotency + result persistence, circuit breaker for Claude API, and env check at startup. Sprint 8+9 adds: Security layer — src/auth.py (opt-in API key auth), src/rate_limiter.py + src/rate_limit_middleware.py (sliding-window per-IP rate limiting), src/logging_config.py (idempotent centralized logging), src/app_factory.py (DRY shared middleware registration), PEP 562 lazy __getattr__ in discipline_registry, Sprint 10 adds: staff login system (auth_user/ package, Flask signed-cookie sessions, auth_cli.py offline CLI), admin panel at /admin/users, auth.py rewritten as always-on with TESTING bypass, FLASK_SECRET_KEY session support. and TYPE_CHECKING decoupling in discipline_protocol. Hexagonal (ports & adapters): secondary ports ClassStoragePort (IC) and KnowledgeBasePort (MG) with filesystem adapters — services are now fully Flask-free and filesystem-free under test injection.

graph TB subgraph FRONTEND["🖥 FRONTEND (Vanilla JS + CSS vars)"] direction LR CR["creator.html
IC Class Generator"] MG_CR["mg_creator.html
MG Plan Generator"] IN["instructor.html
Class Browser"] AE["audio_editor.html
Audio Timeline"] PL["instructor_play.html
Live Class HUD"] ML["music_library.html
Track Management"] DS["discipline_select.html
Landing Page"] end subgraph FLASK["⚙ FLASK (app.py + Blueprints + DI)"] direction LR PAGES["app.py — 9 global routes
/creator /instructor /socios
/setup /api/settings"] DI["AppContainer (DI)
Factory providers
wired post-plugins"] PLUG["discipline_registry
discover_plugins()
startup_validate()"] ICBP["Blueprint ic_bp (src/ic/)
@inject providers
/api/class* /api/music/* /api/audio-*"] MGBP["Blueprint mg_bp (src/mg/)
@inject providers
/api/mg/*"] APIV1["Blueprint api_v1_bp
/api/v1/tasks/<id>/result
/api/v1/disciplines"] SSE["SSE via task_registry
push() / sse_response()"] end subgraph INFRA["🛡 INFRASTRUCTURE (src/)"] direction LR CB["circuit_breaker.py
CLOSED/OPEN/HALF_OPEN
singleton thread-safe"] IDEM["idempotency.py
Idempotency-Key header
INSERT OR IGNORE TTL 48h"] TRS["task_result_store.py
persist done/error
TTL 24h"] AUTH_N["auth.py
init_auth() always-on
session + MEGAS_API_KEY fallback"] RATE["rate_limit_middleware.py
@rate_limited() decorator
sliding-window per-IP"] LOGC["logging_config.py
configure_logging()
FLASK_LOG_LEVEL"] FACT["app_factory.py
register_shared_middleware()
DRY entry points"] end subgraph SERVICES["📦 SERVICES (src/ + src/mg/)"] direction LR CGS["ClassGenerationService"] ARS["AudioRenderService"] MUS["MusicUploadService"] MGS["MuscleGenerationService"] REPO_IC["MusicLibrary
(IC)"] REPO_MG["MemberRepository
(MG)"] end subgraph AI["🤖 CLAUDE API + Shared Infrastructure"] AIC["ai_client.py
call_with_cb() ← CB
resolve_anthropic_client()"] AG_IC["agent.py
generate_class() (IC)"] AG_MG["mg/generator.py
generate_mg_plan()"] SYS_IC["agents/alexandre_indoor_cycling.md"] SYS_MG["agents/musculacion.md"] end subgraph DATA["💾 DATA"] DB_ML["SQLite
music_library.db"] DB_MB["SQLite
members.db"] DB_TK["SQLite
tasks.db
(results + idempotency)"] FS["Filesystem
CLASES/discipline/"] ENV["settings.json / .env"] end FRONTEND -->|HTTP / SSE| FLASK FLASK --> INFRA FLASK --> SERVICES SERVICES --> AI AI --> CB SERVICES --> DATA INFRA --> DATA FLASK --> DATA style FRONTEND fill:#1a1a2e,stroke:#4da6ff,color:#e8e8e8 style FLASK fill:#1a2e1a,stroke:#00c864,color:#e8e8e8 style INFRA fill:#1e1a2e,stroke:#cc44ff,color:#e8e8e8 style SERVICES fill:#2e1a00,stroke:#ff8c00,color:#e8e8e8 style AI fill:#2e1a2e,stroke:#cc44ff,color:#e8e8e8 style DATA fill:#1a1e2e,stroke:#4da6ff,color:#e8e8e8
Python 3.10+ Flask + Blueprints Pydantic v2 Claude claude-sonnet-4-6 tool_choice=any SQLite via Repository pydub + ffmpeg Vanilla JS SSE streaming Always-on Auth (session + MEGAS_API_KEY fallback) Rate Limiting (sliding window) PEP 562 lazy __getattr__ TYPE_CHECKING decoupling Idempotent configure_logging() DRY app_factory

02Module Architecture02

Three complementary views instead of one unreadable monolith graph. Each diagram tells a different story.

A — Layered Architecture

Vertical dependency flow. Layers only depend downward. IC and MG never import each other — they share infrastructure.

graph TD subgraph PRES["Presentation Layer — HTTP / SSE"] APP["app.py\n9 global routes · DI bootstrap · plugin registry"] IC_BP["ic_bp (src/ic/)\n6 route modules · @inject providers"] MG_BP["mg_bp (src/mg/)\n3 route modules · @inject providers"] API1["api_v1_bp\n/api/v1/disciplines · /api/v1/tasks/…/result"] end subgraph SEC["Security Layer — Sprint 8+9"] AUTH["auth.py\ninit_auth() · always-on · session + API key fallback\nExempt: /login /logout /setup /static/* *-stream/*"] RL["rate_limiter.py\nRateLimiter sliding-window per-IP\nMEGAS_RATE_LIMIT · MEGAS_RATE_WINDOW_SEC"] RLM["rate_limit_middleware.py\n@rate_limited() decorator\norder: @route → @rate_limited() → @inject"] LOG["logging_config.py\nconfigure_logging() idempotent\nFLASK_LOG_LEVEL · silences anthropic/httpx/urllib3"] FAC["app_factory.py\nregister_shared_middleware()\nDRY: container + auth + request logging + api_v1_bp"] end subgraph APP_LAYER["Application Layer — Orchestration"] ORCH["generation_orchestrator.py\nstart_task() · persist_and_complete()"] TQR["task_registry.py (singleton)\npush() · sse_response()"] IDEM["idempotency.py\nInsert-or-ignore · TTL 48h"] TRS["task_result_store.py\nTTL 24h · GET /api/v1/tasks"] end subgraph SVC["Service Layer — Business Logic"] IC_SVC["IC Services\nClassGenerationService · AudioRenderService\nMusicUploadService · DriveSyncService"] MG_SVC["MG Services\nMuscleGenerationService\n(receives PlanCreationRepo — ISP)"] end subgraph INFRA["Infrastructure Layer — shared IC + MG"] AI_CLIENT["ai_client.py\ncall_with_cb() ←→ circuit_breaker.py"] REPOS["Repositories\nMusicLibrary (IC) · MemberRepository (MG)"] CONFIG["config.py\nconstants · validate() · check_dotenv()"] end subgraph DATA["Data"] CLAUDE["Claude API\nclaude-sonnet-4-6"] DBS["SQLite\nmusic_library.db · members.db · tasks.db"] FS["Filesystem\nCLASES/*/ · settings.json"] end PRES --> SEC SEC --> APP_LAYER PRES --> SVC APP_LAYER --> INFRA SVC --> INFRA INFRA --> DATA style PRES fill:#1a2e1a,stroke:#00c864,color:#e8e8e8 style SEC fill:#2e1a1a,stroke:#ff4d4d,color:#e8e8e8 style APP_LAYER fill:#1e1a2e,stroke:#cc44ff,color:#e8e8e8 style SVC fill:#2e1a00,stroke:#ff8c00,color:#e8e8e8 style INFRA fill:#1a1e2e,stroke:#4da6ff,color:#e8e8e8 style DATA fill:#1a1a1a,stroke:#555,color:#e8e8e8
B — Blueprint Internal Structure

Each Blueprint is a thin assembler that imports focused sub-modules. Dashed lines indicate "imports from" (not inheritance). The Blueprint singleton (bp.py) is the only coupling point between sub-modules.

flowchart TD PLUGIN_IC["disciplines/indoor_cycling/plugin.py"] PLUGIN_MG["disciplines/musculacion/plugin.py"] subgraph IC["ic_bp — src/ic/"] IC_ASSM["routes.py\nthin assembler"] IC_P["pages.py\n3 HTML · no @inject"] IC_G["gen_routes.py\n2 SSE · _run_generation"] IC_C["class_routes.py\n12 CRUD/export"] IC_M["music_routes.py\n9 music · drive sync"] IC_A["audio_routes.py\n5 audio · _run_render"] IC_ASSM --> IC_P IC_ASSM --> IC_G IC_ASSM --> IC_C IC_ASSM --> IC_M IC_ASSM --> IC_A end subgraph MG["mg_bp — src/mg/"] MG_ASSM["routes.py\nthin assembler"] MG_MR["member_routes.py\n5 member CRUD"] MG_PR["plan_routes.py\n5 plans"] MG_GR["gen_routes.py\n2 SSE · _run_generation"] MG_ASSM --> MG_MR MG_ASSM --> MG_PR MG_ASSM --> MG_GR end PLUGIN_IC -->|from src.ic.routes import ic_bp| IC_ASSM PLUGIN_MG -->|from src.mg.routes import mg_bp| MG_ASSM style IC fill:#1a2e1a,stroke:#00c864,color:#e8e8e8 style MG fill:#2e1a00,stroke:#ff8c00,color:#e8e8e8 style PLUGIN_IC fill:#1e1e1e,stroke:#444,color:#888 style PLUGIN_MG fill:#1e1e1e,stroke:#444,color:#888
C — Shared Infrastructure (IC ↔ MG without coupling)

IC and MG are independent packages that never import each other. Coupling is unidirectional toward infrastructure modules in src/.

flowchart LR subgraph DISC["Disciplines — no coupling between them"] direction TB IC_GEN_R["ic/gen_routes.py"] MG_GEN_R["mg/gen_routes.py"] IC_AGENT["ic/agent.py\nIC generation pipeline"] MG_AGENT["mg/generator.py\nMG generation pipeline"] end subgraph SHARED["src/ — shared infrastructure"] direction TB ORCH["generation_orchestrator.py\nstart_task() · persist_and_complete()"] TQ["task_registry.py\npush() · sse_response()"] IDEM["idempotency.py + task_result_store.py"] AI["ai_client.py\ncall_with_cb()"] CB["circuit_breaker.py\nCLOSED / OPEN / HALF_OPEN\nshared singleton"] ORCH --> TQ ORCH --> IDEM AI --> CB CB -.->|CircuitBreakerOpen| TQ end CLAUDE["☁ Claude API\nclaude-sonnet-4-6"] IC_GEN_R --> ORCH MG_GEN_R --> ORCH IC_AGENT --> AI MG_AGENT --> AI AI --> CLAUDE style DISC fill:#0e150e,stroke:#555,color:#e8e8e8 style SHARED fill:#1a1e2e,stroke:#4da6ff,color:#e8e8e8 style IC_GEN_R fill:#1a2e1a,stroke:#00c864,color:#e8e8e8 style IC_AGENT fill:#1a2e1a,stroke:#00c864,color:#e8e8e8 style MG_GEN_R fill:#2e1a00,stroke:#ff8c00,color:#e8e8e8 style MG_AGENT fill:#2e1a00,stroke:#ff8c00,color:#e8e8e8 style CLAUDE fill:#2e1a2e,stroke:#cc44ff,color:#e8e8e8
Core modules (src/)
ModuleResponsibilityPattern
logging_config.pyconfigure_logging() — idempotent centralized setup. Reads FLASK_LOG_LEVEL env var (default INFO). Silences noisy third-party loggers: anthropic, httpx, urllib3. Called once at app startup before any module import.Idempotent startup configuration
auth.pyinit_auth(app) — always-on (no opt-in). Priority: TESTING bypass → exempt paths → session["user_id"] → MEGAS_API_KEY header (CLI/API fallback) → redirect /login or 401. Exempt: /login, /logout, /setup, /api/setup, /static/*, paths with -stream/ (SSE). _is_api_request() differentiates JSON vs HTML response.before_request hook (always-on)
auth_user/Staff user management package. models.py: UserRecord(BaseModel). repo_port.py: UserRepoPort(Protocol). repository.py: SQLiteUserRepository (auth.db, WAL, timeout=10). login_routes.py: GET/POST /login, POST /logout, _safe_next() anti-open-redirect. admin_routes.py: CRUD /admin/users — only "admin" user can access. guards.py: login_required() + current_user().Staff auth package (Sprint 10)
auth_cli.pyOffline CLI for user management: create-user, list-users, set-active, reset-password. No server required. ASCII output (OK/ERR) — Windows console compatible.Offline CLI tool
rate_limiter.pyRateLimiter — thread-safe in-memory sliding-window per-IP rate limiter. No external dependencies. Config: MEGAS_RATE_LIMIT (default 10 req) / MEGAS_RATE_WINDOW_SEC (default 60s). Returns RateResult(allowed, retry_after). Uses collections.deque + threading.Lock.Sliding window + Lock
rate_limit_middleware.py@rate_limited() decorator factory for Flask endpoints. _gen_limiter is a module-level singleton shared across IC, MG, and drive-sync — global Claude API quota. Critical decorator order: @route → @rate_limited() → @inject. Returns 429 JSON with Retry-After seconds. IP resolved from X-Forwarded-For or remote_addr.Decorator factory + shared singleton
app_factory.pyregister_shared_middleware(flask_app, container) — DRY registration of: container extension, _configure_secret_key() (FLASK_SECRET_KEY + session lifetime), init_auth(), auth_bp, request timing logs (before/after_request), and api_v1_bp. Called after container.wire().Factory function (DRY)
config.pySingle source of truth: paths, RE, env vars, MEMBERS_DB, TASKS_DB, AUTH_DB, FLASK_SECRET_KEY, SESSION_HOURS. validate() fail-fast. check_dotenv() compares .env vs .env.example at startup (envcheck pattern).Constants + startup checks
disciplines/__init__.pyDiscipline registry (IC/YG/MG), lookup by code/slug. Package structure facilitates plugin system imports.Frozen dataclass registry
discipline_protocol.pyDisciplinePlugin Protocol (@runtime_checkable): code, slug, blueprint, creator_template, startup_validate(), classes_subdir. from flask import Blueprint moved to TYPE_CHECKING block — zero Flask dependency at runtime. Protocol usable in non-Flask contexts.Protocol (PEP 544) + TYPE_CHECKING
discipline_registry.pydiscover_plugins() via pkgutil — dynamic discovery in src/disciplines/*/plugin.py. OCP: add a discipline without touching app.py. PEP 562: module-level __getattr__ — CLASS_FILENAME_RE and CLASS_MP3_RE are lazy attributes computed on first access. _plugins_cache = None at import time — zero cost until first use. get_plugins() lazy singleton wraps discover_plugins().Plugin registry (OCP) + PEP 562 lazy attrs
container.pyAppContainer — flat DI container, composes all providers. For sub-apps: CoreContainer (src/core/container.py), ICContainer (src/ic/container.py), MGContainer (src/mg/container.py). Adds task_queue Singleton.dependency-injector DeclarativeContainer
core/container.pyCoreContainer — shared providers (task_result_store, idempotency_store, task_queue). For standalone sub-app: CoreContainer + MGContainer with zero IC dependency.Modular DI (sub-app ready)
circuit_breaker.pyIn-memory thread-safe circuit breaker for Claude API. States: CLOSED → OPEN (3 failures) → HALF_OPEN (60s). Module-level singleton shared by IC+MG. CircuitBreakerOpen surfaces as SSE error event.State machine + singleton
task_result_store.pyPersistence of done/error results in tasks.db with TTL 24h. Allows retrieving results from completed generations.SQLite repository + TTL
idempotency.pyIdempotency-Key header — INSERT OR IGNORE in tasks.db, TTL 48h. Second request with same key returns {cached: true, task_id} without re-launching generation.INSERT OR IGNORE + TTL
models.pyIC domain models with invariant validation (cadence, phases)Pydantic v2 + validators
ai_client.pyShared Claude API infrastructure IC+MG: resolve_anthropic_client(), load_system_prompt(), call_with_cb() (circuit breaker wrapper), _is_transient() (classifies 429/529/timeout errors).Shared infrastructure (DIP)
utils.pyenum_values(enum_cls) and format_validation_error(exc) — pure functions shared between agent.py and mg/generator.py.Pure functions (DRY)
agent.pyClaude API IC integration: generate_class_raw(). Delegates to ai_client.call_with_cb() — protected by circuit breaker.tool_use, tool_choice=any
generator.pyHigh-level interface; iter_tree() for IC plan traversalFaçade + generator fn
class_repository.pyClass file I/O: next_filename(), load_classes()Repository pattern
web_utils.pyShared pure functions: plan_to_timeline_dict(), safe_download_filename() (RFC 6266 — Content-Disposition with filename*=UTF-8).Pure functions (RFC 6266)
serializers.pyClassPlan → JSON / CSV (pure serialization — consumed by ic/exports.py)Pure functions
generation_orchestrator.pystart_task() → (task_id, cached: bool) — Flask-free (does not import flask.Response). Caller builds the HTTP response. idem_store=None skips idempotency (drive sync).Application layer (shared)
music_library.pySQLite tracks + audio_configs; matching by BPM/energy (_BASE_SCORE=5.0)Repository + Pydantic models
task_queue.pyThread-safe TaskQueue; TTL cleanup; 20 concurrent task limitIn-memory registry + Lock + Timer
task_registry.pyShared singleton: task_queue, push(), sse_response()Module-level singleton
settings.pyPersistence of API keys and user configurationKey/value JSON store
api/__init__.pyapi_v1_bp at /api/v1/: GET /tasks/<id>/result (retrieve persisted result), GET /disciplines (list registered disciplines).Flask Blueprint + @inject
Package src/ic/ — 6 sub-modules
ModuleResponsibilityPattern
ic/schemas.pyGenerateClassRequest — validates HTTP POST /api/generate-start body (zone, difficulty, interval params). to_domain() maps wire fields → domain GenerationRequest. Same architectural pattern as mg/schemas.py.Pydantic v2 wire schema
ic/bp.pyic_bp = Blueprint("ic", __name__) — Blueprint singletonBlueprint singleton
ic/helpers.py_bad_filename() shared by class_routes + audio_routesShared helper
ic/pages.py3 HTML routes (music-library, audio-editor, instructor/play) — no @injectPage routes
ic/gen_routes.pygenerate_start + generate_stream + _run_generation. @inject providers: idempotency_store, lib_factory, result_store_factoryGeneration SSE
ic/class_routes.py12 CRUD/export routes + _repair_for_preview, _recompute_parent_durations, _absorb_duration_deltaClass CRUD + export
ic/music_routes.py9 music library routes (tracks CRUD, upload, peaks) + drive sync + _run_drive_syncMusic library + Drive sync
ic/audio_routes.py5 audio config/render routes + _run_audio_renderAudio config + SSE render
ic/routes.pyThin assembler (~12 lines). Imports sub-modules to register @ic_bp.route. Re-exports ic_bp for plugin.pyThin assembler
ic/container.pyICContainer — music_library Factory. For IC standalone sub-app without MG.Modular DI (sub-app ready)
ic/class_storage.pySecondary port + adapter. ClassStoragePort — @runtime_checkable Protocol with save(plan, filename). FilesystemClassStorage — concrete adapter that writes JSON + CSV to CLASES/indoor-cycling/. Injected into ClassGenerationService(storage=...); defaults to FilesystemClassStorage() when omitted. Enables fully I/O-free unit tests via _FakeStorage.Hexagonal secondary port + filesystem adapter
Package src/mg/ — 4 sub-modules
ModuleResponsibilityPattern
mg/validators.pyStandalone validation functions: coerce_int(), coerce_int_optional(), coerce_restricciones(). Shared by schemas.py and models.py — eliminates triplication (DRY).Pure functions (DRY)
mg/models.pyMG domain models: MemberProfile, TrainingPlan, Mesocycle, ExerciseBlock. from_generate_request() classmethod. to_repo_dict() eliminates Feature Envy in service._save(). ExerciseBlock adds two new optional fields: descripcion: Optional[str] = None and notas_entrenador: Optional[str] = None — populated by the plan editor via DB autocomplete.Pydantic v2 + field_validator
mg/prompt_builder.pybuild_mg_prompt() — testable without the Anthropic SDK dependencyPure function
mg/kb_port.pySecondary port. KnowledgeBasePort — pure @runtime_checkable Protocol with load() -> str. Zero filesystem coupling; testable with _FakeKnowledgeBase in unit tests.Hexagonal secondary port (Protocol)
mg/kb_filesystem.pySecondary adapter. FilesystemKnowledgeBase — reads .txt docs from Base de conocimiento/musculacion/ and concatenates them. Previously inlined as _load_mg_knowledge_base() + _kb_cache in generator.py. Module-level singleton _default_kb provides backward-compatible default.Hexagonal filesystem adapter (lazy singleton)
mg/generator.pyJSON schemas + Claude API call + TrainingPlan validation. Imports from ai_client.py (not agent.py) — decoupled from IC module. generate_training_plan_raw() and generate_mg_plan() accept kb: KnowledgeBasePort | None = None; defaults to module-level _default_kb = FilesystemKnowledgeBase(). Removed _load_mg_knowledge_base(), _kb_cache, and _enum_values alias.tool_use + ai_client.py (DIP) + KB port
mg/service.pyMuscleGenerationService: SSE pipeline parse→generate→save. Receives PlanCreationRepo (2 methods) — not the full 10-method interface (ISP). Constructor also accepts kb: KnowledgeBasePort | None = None and forwards it to generate_mg_plan() — service is filesystem-free when a fake KB is injected.Service object + DI repo (ISP) + KB port
mg/member_repo_base.py4 ISP Protocols (PEP 544): MemberCRUDRepo (5), PlanRepo (4), TrackingRepo (2), PlanCreationRepo (2 — minimum for MuscleGenerationService). MemberRepositoryBase = union of the first three.ISP — Structural subtyping
mg/member_repository.pyNative SQLite UPSERT (ON CONFLICT DO UPDATE RETURNING id) — 1 round-tripRepository pattern
mg/member_repo_ddl.py5 DDL constants (CREATE TABLE strings) extracted from member_repository.py — SRP: the adapter no longer mixes schema DDL with data-access logic.DDL constants (SRP)
mg/html_export_css.py_EXPORT_CSS constant (~265 lines of CSS) extracted from html_export.py — reduces noise in the HTML generation module; CSS is independently versionable.CSS constant (SRP)
mg/schemas.pyHTTP request validation: MemberSaveRequest, GenerateRequest. Validators delegate to validators.py.Pydantic v2 wire models
mg/formatters.pyText formatting for HTML export. muscle_group_key() normalizes NFD before matching — fixes silent accent bug (glúteo → piernas).Pure functions + Unicode NFD
mg/html_export.pyGenerates self-contained HTML for MG plans. Accordion with native <details>/<summary> — no JS, universally compatible with iOS/Android.HTML generation (native accordion)
mg/bp.pymg_bp = Blueprint("mg", __name__) — Blueprint singletonBlueprint singleton
mg/member_routes.py5 member CRUD routes + _save_member_from_request. @inject on all.Member CRUD
mg/plan_routes.py5 plan routes (history, get, HTML export, update, manual create). @inject on all.Plan management
mg/gen_routes.pyapi_mg_generate_start + api_mg_generate_stream + _run_mg_generation. Idempotency-Key + result persistence.Generation SSE
mg/routes.pyThin assembler (~12 lines). Re-exports mg_bp for plugin.py.Thin assembler
mg/container.pyMGContainer — member_repo Factory. For MG standalone sub-app without IC or MusicLibrary.Modular DI (sub-app ready)
mg/app_container.pyMGAppContainer — flat DI container reserved for future MG spin-off app. Provider names identical to AppContainer so Provide[AppContainer.xxx] resolves by name from whichever container calls .wire() — no route file changes required. music_library intentionally absent (MG has no audio). Not used by any entry point today.Reserved DI container (future sub-app)
MG Frontend — JS Modules (static/js/mg/)

session_log.js — split into 5 modules

FileResponsibility
session_log.jsCore: MgSessionLog class + globals _timerInterval / _timerEl
sl_storage.jslocalStorage persistence: _logStorageKey, mgPersistLog, mgRestoreLog
sl_timer.jsRest-timer overlay: mgStartTimer, mgStopTimer
sl_history.jsExercise history hints: mgLoadHistory
sl_interactions.jsUser action handlers: mgCompleteSet, mgSaveSession, et al.

workout_mode.js — split into 5 modules

FileResponsibility
workout_mode.jsCore: _workout state + mgOpenWorkout / mgCloseWorkout(force?) — _workoutHasProgress() guard prevents accidental close; force=true bypasses it post-save
wk_wellness.jsPre-workout wellness screen
wk_exercise_view.jsExercise rendering + set interactions
wk_history.jsBackground history loading
wk_summary.jsEnd-of-session screen + save

utils.js — shared pure functions (DRY)

FunctionDescription
flatExercises(day)Flattens exercises for a day including circuits — previously duplicated in session_log.js and workout_mode.js
fetchExerciseHistory(dni, ejercicio, limit=1)Fetch helper for the exercise-history endpoint — previously duplicated in 3 files
makeSerieEntry(ejercicioNombre, serieNum, peso, rpe, reps, done)Builds a session payload entry — previously duplicated in sl_interactions.js and wk_summary.js
_optInt(val, radix?)Replaces parseInt(x)||null — preserves 0, returns null on NaN. Prevents zero being silently swallowed in optional numeric fields
_optFloat(val)Replaces parseFloat(x)||null — same correction for decimal values (peso_kg, grasa_pct)
New patterns introduced in Sprint 8+9 / Hexagonal

PEP 562 — Module-level __getattr__

discipline_registry.py uses __getattr__(name) at module level. CLASS_FILENAME_RE and CLASS_MP3_RE are computed only on first attribute access — _plugins_cache = None at import time means zero discovery cost until a consumer actually needs the regex.

AttributeComputed from
CLASS_FILENAME_REbuild_filename_re(get_plugins(), "json")
CLASS_MP3_REbuild_filename_re(get_plugins(), "mp3")

Decorator order — @rate_limited() + @inject

The order of decorators on Flask endpoints with both rate limiting and DI is critical. @inject annotations live on the inner function; functools.wraps preserves them so DI resolves correctly. Rate check runs before dependency injection.

OrderDecoratorReason
1 (outer)@bp.route(...)Flask route registration
2@rate_limited()Runs first at call time — rejects before DI
3 (inner)@injectDI resolves only if rate check passes

TYPE_CHECKING — runtime Flask decoupling

discipline_protocol.py moves from flask import Blueprint inside an if TYPE_CHECKING: block. At runtime the import never executes — the Protocol annotation is a string forward reference. This makes DisciplinePlugin usable in contexts where Flask is not installed (e.g., CLI tools, type-check-only environments).

Startup security order

register_shared_middleware() must be called after container.wire() so that @inject decorators in src.api are patched before api_v1_bp is registered. Auth and request logging hooks are registered in the same call for DRY consistency.

StepAction
1configure_logging() — before everything
2_init_container() + _init_plugins()
3container.wire(modules=[...])
4register_shared_middleware(app, container)

Ports & Adapters — IC (ClassStoragePort)

ic/class_storage.py introduces the first hexagonal secondary port for IC. ClassStoragePort is a @runtime_checkable Protocol; FilesystemClassStorage is the production adapter (writes JSON + CSV to disk). ClassGenerationService(storage=None) defaults to the filesystem adapter; tests inject _FakeStorage — no disk I/O, no temp directories.

FileRole
ic/class_storage.pyPort (ClassStoragePort) + adapter (FilesystemClassStorage)
ic/generation_service.pyConstructor: storage: ClassStoragePort | None = None
tests/integration/test_services.pyTestClassGenerationServiceWithFakeStorage — 4 tests, zero disk I/O

Ports & Adapters — MG (KnowledgeBasePort)

mg/kb_port.py defines KnowledgeBasePort (Protocol, load() -> str). mg/kb_filesystem.py provides FilesystemKnowledgeBase — replaces the previously inline _load_mg_knowledge_base() + _kb_cache in generator.py. Both MuscleGenerationService and generate_mg_plan() accept kb: KnowledgeBasePort | None = None; _FakeKnowledgeBase in tests returns a fixed string — no filesystem access at all.

FileRole
mg/kb_port.pySecondary port Protocol (KnowledgeBasePort)
mg/kb_filesystem.pyFilesystem adapter + module-level _default_kb singleton
mg/generator.pykb: KnowledgeBasePort | None = None in both public functions
mg/service.pykb: KnowledgeBasePort | None = None forwarded through service
tests/unit/test_mg_service.py3 tests with _FakeKnowledgeBase — zero filesystem

03Domain Models03

Indoor Cycling — ClassPlan (src/models.py)

4-level tree. Domain invariants are validated by Pydantic at construction time.

classDiagram class ClassPlan { +ClassMetadata metadata +list~ClassSection~ sections +int total_duration_seconds validate_structure() validate_total_duration() «3360s» } class ClassSection { +ClassPhase phase +int duration_seconds +MusicSuggestion music_suggestion +list~SubSection~ subsections +str cadence_range_rpm «60-110 RPM» validate_cycling_fields() } class SubSection { +str stage_name +int duration_seconds +list~MicroSegment~ micro_segments } class MicroSegment { +bool standing +list~Movement~ movements +list~HandPosition~ hand_positions +str cadence_range_rpm validate_hand_positions() } class MusicSuggestion { +str bpm_range «RPM×2» +str energy_level +str suno_prompt +int track_id } ClassPlan "1" *-- "5..*" ClassSection ClassSection "1" *-- "0..*" SubSection ClassSection "1" *-- "1" MusicSuggestion SubSection "1" *-- "0..*" MicroSegment
Strength Training — TrainingPlan (src/mg/models.py)

3-level tree. A Mesocycle with weeks=None = fixed routine; N Mesocycles with weeks = periodization. Fields nivel, subdisciplina, objetivo and frecuencia_semanal are ephemeral plan properties (sent in the generation payload) — not persisted in the member profile. MemberProfile only contains demographic and body composition data.

classDiagram class MemberProfile { +str dni +str nombre, apellido +int edad «14-99» +str sexo +list~str~ restricciones +str notas_adicionales «optional» +float peso_kg «optional — composition» +float grasa_pct «optional — composition» +float estatura_cm «optional — composition» +bool apto_medico from_generate_request(data) «classmethod» to_repo_dict() «→ dict for MemberRepository» _coerce_int() «field_validator — via validators.py» } note for MemberProfile "nivel / subdisciplina / objetivo /\nfrecuencia_semanal are ephemeral\nper plan — NOT member fields" class TrainingPlan { +str titulo +TrainingObjective objetivo +int duracion_semanas «optional» +list~Mesocycle~ mesocycles +str notas_entrenador +list~str~ coaching_notes is_fixed_routine «property» total_training_days «property» validate_periodization_consistency() } class Mesocycle { +str nombre +int semanas «optional — None=fixed routine» +str enfoque +list~TrainingDay~ dias +str notas_progresion } class TrainingDay { +str nombre +list~str~ grupos_musculares +list~ExerciseBlock~ ejercicios } class ExerciseBlock { +str nombre +int series «1-20» +str reps_range +int descanso_segundos «0-600» +str rpe_target «optional» +list~str~ notas_tecnicas +str sustitucion «optional» } MemberProfile ..> TrainingPlan : "generates" TrainingPlan "1" *-- "1..*" Mesocycle Mesocycle "1" *-- "1..*" TrainingDay TrainingDay "1" *-- "1..*" ExerciseBlock

MEGATLON IC Phases (3360s total)

PhaseDurationSeconds
presentation6 min360s
activation3 min180s
main_work35 min2100s
cool_down2 min120s
stretching10 min600s

Domain Invariants

RuleValue
Min cadence (IC work)60 RPM
Max cadence IC110 RPM
IC cool_down cadence80–90 RPM
IC music BPM= RPM × 2
IC position 3Only when standing=true
MG weekly frequency1–7 days
MG member age14–99 years
MG sets1–20 per exercise

04SSE + Threading Flow04

All long-running tasks (IC generation, audio render, MG generation) use the same pattern: POST → {task_id} → GET SSE stream. The task_registry.py singleton provides task_queue, push() and sse_response() to both ic_bp and mg_bp.

sequenceDiagram participant B as Browser participant F as Flask participant TR as task_registry participant T as Worker Thread participant CL as Claude API participant DB as SQLite Note over TR: TaskQueue — lock + TTL 300s — max 20 tasks B->>F: POST /api/mg/generate-start F->>F: GenerateRequest.model_validate F->>TR: task_queue.create(task_id) F->>T: Thread _run_mg_generation F-->>B: task_id B->>F: GET /api/mg/generate-stream/task_id [SSE] Note over F: sse_response — ev.wait(timeout) T->>TR: push status phase=parsing T->>T: MemberProfile.from_generate_request T->>TR: push status phase=generating T->>CL: generate_mg_plan Note over CL: musculacion.md system prompt — tool_choice=any CL-->>T: TrainingPlan via tool_use T->>TR: push status phase=saving T->>DB: repo.save_member UPSERT T->>DB: repo.save_plan T->>TR: push done payload TR-->>F: snapshot events F-->>B: SSE done event F-->>B: stream closes cleanup
task_registry.py is the singleton shared between ic_bp and mg_bp. Import from src.task_registry import task_queue, push, sse_response in any Blueprint. The SSE consumer performs cleanup when closing the stream; the TTL Timer (300s) is the fallback.
Idempotency + Result Persistence (Sprint 4)

Generation endpoints accept the Idempotency-Key header. If the key already exists in tasks.db, they return {task_id, cached: true} without launching a new task. On completion, the result (done/error + payload) is persisted in TaskResultStore with TTL 24h and is retrievable via GET /api/v1/tasks/<id>/result even after the SSE stream has closed.

sequenceDiagram participant B as Browser participant F as Flask participant ID as IdempotencyStore participant TQ as TaskQueue participant BG as Background Thread participant TRS as TaskResultStore participant CB as CircuitBreaker B->>F: POST /api/generate-start Note over B,F: Optional Idempotency-Key header F->>ID: check(idem_key) alt Key already exists ID-->>F: previous task_id F-->>B: task_id cached=true else New key F->>ID: store(idem_key, task_id) F->>TQ: create(task_id) F->>BG: Thread _run_generation F-->>B: task_id end B->>F: GET /api/generate-stream/task_id loop SSE events BG->>CB: call_with_cb CB-->>BG: response or CircuitBreakerOpen BG->>TQ: push status/done/error TQ-->>F: snapshot F-->>B: SSE event end BG->>TRS: persist done/error payload F-->>B: stream closes Note over B,TRS: GET /api/v1/tasks/task_id/result retrieves result for 24h

05SQLite Schema05

music_library.db — tracks + audio

Exclusive access via MusicLibrary — never direct SQL in app.py.

erDiagram tracks { INTEGER id PK TEXT filename UK TEXT title INTEGER duration_sec INTEGER bpm_min INTEGER bpm_max TEXT energy_level TEXT genre TEXT mood_tags "JSON array" TEXT section_use "JSON array" TEXT tonality TEXT terrain INTEGER intensity_level TEXT cadence_range TEXT original_ext INTEGER file_size_bytes } audio_configs { INTEGER id PK TEXT class_filename TEXT version_name REAL global_crossfade_sec TEXT rendered_mp3 TEXT created_at } audio_sections { INTEGER id PK INTEGER config_id FK INTEGER section_index INTEGER subsection_index "-1=top-level" INTEGER track_id FK REAL start_sec INTEGER loop REAL fade_in_sec REAL fade_out_sec REAL volume REAL overlap_sec } audio_configs ||--o{ audio_sections : "has sections" tracks ||--o{ audio_sections : "assigned to"
members.db — MG members

Exclusive access via MemberRepository (Protocol MemberRepositoryBase). Native upsert with ON CONFLICT DO UPDATE RETURNING id.

erDiagram members { INTEGER id PK TEXT dni UK TEXT nombre TEXT apellido INTEGER edad TEXT sexo TEXT nivel TEXT subdisciplina TEXT objetivo INTEGER frecuencia_semanal TEXT restricciones "JSON array" TEXT notas_adicionales REAL peso_kg "optional" REAL grasa_pct "optional" INTEGER apto_medico "0 or 1" TEXT created_at TEXT updated_at } training_plans { INTEGER id PK INTEGER member_id FK TEXT plan_json "serialized TrainingPlan" TEXT titulo TEXT notas TEXT created_at } goal_tracking { INTEGER id PK INTEGER member_id FK TEXT metric_type "peso_kg|grasa_pct|rm_kg" REAL value TEXT fecha TEXT notas } members ||--o{ training_plans : "has plans" members ||--o{ goal_tracking : "tracks metrics"
tasks.db — results + idempotency

Shared by TaskResultStore and IdempotencyStore. Configurable path via TASKS_DB env var.

erDiagram task_results { TEXT task_id PK TEXT event_type "done | error" TEXT payload "JSON" TEXT created_at } idempotency_keys { TEXT key PK TEXT task_id TEXT created_at }

TaskResultStore

PatternDetail
TTL24h — automatic cleanup on get()
PersistenceOnly "done" / "error" events — no intermediate status
AccessGET /api/v1/tasks/<id>/result post-stream

IdempotencyStore

PatternDetail
InsertionINSERT OR IGNORE — idempotent by definition
TTL48h — window for client to retry with same key
ScopePer Idempotency-Key header — optional per client

Access patterns — music_library.db

PatternDetail
MigrationsALTER TABLE in _init_db() with try/except — idempotent
Atomicityadd_track() INSERT + UPDATE filename in a single with conn: block
Matchingfind_matching_tracks() — _BASE_SCORE=5.0 + BPM + genre + terrain
Thread safetyEach method opens its own connection — no shared state

Access patterns — members.db

PatternDetail
Native UPSERTINSERT … ON CONFLICT(dni) DO UPDATE … RETURNING id — 1 query
CASCADEDELETE members removes training_plans + goal_tracking via FK
Normalizationapto_medico 0/1 → bool in _member_row_to_dict()
ProtocolMemberRepositoryBase (PEP 544) — swap backend without touching service

06Filesystem & Disciplines06

DATA_DIR separates mutable data from read-only assets — Docker-ready out of the box. config.validate() is called at startup and fails fast if critical files are missing.

graph TD subgraph DOCKER_VOL["📦 Docker Volume (/data) ←→ DATA_DIR env var"] CLASES["CLASES/
📁 indoor-cycling/
IC-001_endurance.json + .csv + .mp3
📁 yoga/
YG-NNN_style.json
📁 musculacion/
MG-NNN_type.json"] MUSIC["static/music/
track-001.mp3 …"] DB_ML["music_library.db"] DB_MB["members.db
← MEMBERS_DB env var"] SETTINGS["settings.json / .env"] end subgraph BUNDLE["📋 Bundle Root (read-only in Docker)"] TMPL["templates/
creator.html · mg_creator.html
instructor.html · audio_editor.html
instructor_play.html · music_library.html
discipline_select.html"] STATIC["static/css/ static/js/"] AGENTS["agents/
alexandre_indoor_cycling.md ✅
musculacion.md ✅
yoga.md (placeholder)"] SRC["src/ + src/mg/ (Python)"] end subgraph RESOLUTION["🔑 class_path(filename)"] FN["'MG-001_fuerza.json'"] PREFIX["extract prefix → 'MG'"] DISC_LK["discipline_for_code('MG') → musculacion"] FULL["CLASES/musculacion/MG-001_fuerza.json"] FN --> PREFIX --> DISC_LK --> FULL end style DOCKER_VOL fill:#1a2e1a,stroke:#00c864,color:#e8e8e8 style BUNDLE fill:#1a1a2e,stroke:#4da6ff,color:#e8e8e8 style RESOLUTION fill:#2e1a00,stroke:#ff8c00,color:#e8e8e8

Development Tools / Scripts

ScriptDescriptionWhen it runs
scripts/lint_frontend.pyPython linter for JS and CSS. Rules: JS-01 (no hardcoded user-visible strings in JS), JS-02 (no empty catch{}), CSS-01 (no hardcoded colors), CSS-02 (no !important outside tokens), CSS-03 (undefined tokens). Reports per file and rule.Pre-commit alongside ruff check .
ruff check .Python linter — configured in pyproject.tomlLocal pre-commit hook

Registered disciplines

CodeSlugStatus
ICindoor-cycling✅ Full production
MGmusculacion✅ Full production
YGyogaPlaceholder

Environment variables

VariableDefault
ANTHROPIC_API_KEY— (required)
DATA_DIRPROJECT_ROOT (dev)
MUSIC_DIRPROJECT_ROOT/static/music
MUSIC_DBPROJECT_ROOT/music_library.db
MEMBERS_DBPROJECT_ROOT/members.db
TASKS_DBPROJECT_ROOT/tasks.db
FLASK_PORT5000
FLASK_HOST127.0.0.1
FLASK_DEBUG1 (dev), 0 (docker)
FLASK_LOG_LEVELINFO
MEGAS_API_KEY— (empty = sessions only)
MEGAS_RATE_LIMIT10 (requests per window)
MEGAS_RATE_WINDOW_SEC60 (window in seconds)
FLASK_SECRET_KEY— (required in production)
SESSION_HOURS8
AUTH_DBauth.db (relative to DATA_DIR)

07API Routes07

app.py has only 9 global routes (pages + settings + setup). IC routes are distributed across specialized sub-modules: pages.py, gen_routes.py, class_routes.py, music_routes.py, audio_routes.py. MG routes are in member_routes.py, plan_routes.py, gen_routes.py. All REST routes follow: validate → get resource → return jsonify(). Long-running tasks: POST → {task_id} → GET SSE stream.

Global pages — app.py 9 routes
RouteDescription
GET/Redirect → /instructor
GET/setupsetup.html
GET/creatordiscipline_select.html
GET/creator/iccreator.html
GET/creator/musculacionmg_creator.html
GET/instructorinstructor.html
GET/sociossocios.html
GET/api/settingsRedacted configuration
POST/api/settingsSave API keys and settings
POST/api/setupInitial setup
IC pages — ic/pages.py (Blueprint ic_bp) 3 routes
RouteDescription
GET/music-librarymusic_library.html
GET/audio-editor/<fn>audio_editor.html
GET/instructor/play/<fn>instructor_play.html
IC SSE generation — ic/gen_routes.py (Blueprint ic_bp) SSE
RouteDescription
POST/api/generate-startStarts IC task → {task_id}. Idempotency-Key header.
SSE/api/generate-stream/<tid>SSE: status / done / error
IC class CRUD — ic/class_routes.py (Blueprint ic_bp) 12 routes
RouteDescription
GET/api/classesList all classes
GET/api/class/<fn>Timeline dict for HUD
GET/api/class-doc/<fn>Full instructor document
GET/api/class-raw/<fn>Raw ClassPlan JSON
POST/api/class-save/<fn>Validate + persist edit
DELETE/api/class/<fn>Delete JSON + CSV
GET/api/class-csv/<fn>Download CSV
GET/api/class-pdf/<fn>Instructor PDF
GET/api/class-html/<fn>Self-contained instructor HTML
GET/api/class-mp3/<fn>Stream rendered MP3
POST/api/class-doc-previewPreview doc from JSON (no I/O)
IC music + Drive sync — ic/music_routes.py (Blueprint ic_bp) 9 routes
RouteDescription
POST/api/music/uploadUpload track (magic bytes validation)
GET/api/music/tracksList tracks with filters
GET/api/music/tracks/<id>Track metadata
PATCH/api/music/tracks/<id>Update metadata (whitelist)
DELETE/api/music/tracks/<id>Delete track
GET/api/music/peaks/<fn>Cached waveform peaks
POST/api/music/drive-syncSync Google Drive → {task_id}
IC audio config/render — ic/audio_routes.py (Blueprint ic_bp) SSE
RouteDescription
GET/api/audio-configs/<fn>List all audio versions
GET/api/audio-config/<fn>Saved audio config
POST/api/audio-config/<fn>Save audio sections
POST/api/audio-render/<fn>Start render → {task_id}
SSE/api/audio-render-stream/<tid>SSE: progress / done / error
MG member CRUD — mg/member_routes.py (Blueprint mg_bp) 5 routes
RouteDescription
GET/api/mg/membersList members (search ?q=)
GET/api/mg/members/<dni>Full profile by ID
POST/api/mg/membersCreate/upsert member
PUT/api/mg/members/<dni>Update profile
DELETE/api/mg/members/<dni>Delete + CASCADE
MG plans — mg/plan_routes.py (Blueprint mg_bp) 5 routes
RouteDescription
GET/api/mg/members/<dni>/plansMember plan history
GET/api/mg/plans/<id>Full plan by ID
GET/api/mg/plans/<id>/exportExport plan → self-contained HTML
PUT/api/mg/plans/<id>Update existing plan
POST/api/mg/plansCreate manual plan
MG SSE generation — mg/gen_routes.py (Blueprint mg_bp) SSE
RouteDescription
POST/api/mg/generate-startStart generation → {task_id}. Idempotency-Key header.
SSE/api/mg/generate-stream/<tid>SSE: status / done / error
API v1 — api/__init__.py (Blueprint api_v1_bp, prefix /api/v1/) 2 routes
RouteDescription
GET/api/v1/disciplinesList registered disciplines (code, slug, label)
GET/api/v1/tasks/<id>/resultPersisted result (done/error) — retrievable 24h post-generation

08Resilience & Startup08

Four complementary mechanisms protect the app: security middleware (auth + rate limiting), circuit breaker for Claude API, and environment variable check at startup. Sprint 8+9 adds the Security layer on top of the existing resilience stack.

Security Layer (Sprint 8+9) — Auth + Rate Limiting

Both mechanisms are opt-in / zero-config safe: auth is disabled when MEGAS_API_KEY is unset; rate limiter uses sensible defaults (10 req/60s) configurable via env vars.

Auth — src/auth.py

AspectDetail
ActivationSet MEGAS_API_KEY=<key> in .env
HeadersAuthorization: Bearer <key> or X-API-Key: <key>
Exempt paths/setup, /api/setup, /static/*, any path with -stream/ (SSE)
SSE exemptionRegex -stream/ — requires hyphen to prevent crafted bypass paths
RejectionHTTP 401 + {"error": "Unauthorized"}
Dev modeUnset env var → auth disabled, no code change needed

Rate Limiting — src/rate_limiter.py + rate_limit_middleware.py

AspectDetail
AlgorithmSliding window per-IP using collections.deque
ConfigMEGAS_RATE_LIMIT (default 10) / MEGAS_RATE_WINDOW_SEC (default 60)
Shared limiter_gen_limiter singleton: IC + MG + drive-sync share global Claude quota
Decorator order@route → @rate_limited() → @inject — critical for DI to work
IP detectionX-Forwarded-For header or remote_addr
RejectionHTTP 429 + {"error": "Rate limit exceeded. Try again in Xs."}
Startup sequence (app.py)

Order is critical: logging must be first; DI wiring must precede register_shared_middleware so that @inject decorators in src.api are already patched when api_v1_bp is registered.

flowchart LR A["configure_logging()"] --> B["load_dotenv + config.validate()"] B --> C["_init_container()"] C --> D["_init_plugins(app)"] D --> E["container.wire(modules=[...])"] E --> F["register_shared_middleware()"] F --> G1["init_auth(app)"] F --> G2["_register_request_logging(app)"] F --> G3["app.register_blueprint(api_v1_bp)"] style A fill:#2e1a1a,stroke:#ff4d4d,color:#e8e8e8 style F fill:#2e1a1a,stroke:#ff4d4d,color:#e8e8e8 style G1 fill:#2e1a1a,stroke:#ff4d4d,color:#e8e8e8
Circuit Breaker — src/circuit_breaker.py
stateDiagram-v2 [*] --> CLOSED CLOSED --> OPEN : 3 consecutive failures OPEN --> HALF_OPEN : 60s elapsed HALF_OPEN --> CLOSED : successful probe HALF_OPEN --> OPEN : failed probe CLOSED : CLOSED\nCalls normally OPEN : OPEN\nImmediate CircuitBreakerOpen HALF_OPEN : HALF_OPEN\nOne probe allowed

Errors counted as failures

TypeTypical cause
RateLimitError (429)API quota exhausted
APIStatusError 529Claude overloaded
APIConnectionErrorNetwork down / DNS timeout
APITimeoutErrorResponse > 300s

Behavior when OPEN

LayerBehavior
ai_client.call_with_cb()Raises CircuitBreakerOpen immediately
ClassGenerationServiceCatches → push(task_id, "error", msg)
SSE streamEmits {type:"error", payload:msg}
FrontendShows error toast to instructor
Startup Check — check_dotenv() (envcheck pattern)

Called in app.py after load_dotenv(). Parses .env.example, compares against os.environ, and logs WARNING for each unset variable. Does not block startup — ANTHROPIC_API_KEY can come from settings.json and the app already redirects to /setup if not configured.

Critical variables (ANTHROPIC_API_KEY)

SourcePriority
os.environ / .env1st (load_dotenv at start)
settings.json2nd (via ai_client.build_client)
NeitherEnvironmentError when calling Claude

Optional variables documented in .env.example

VariableDefault
MUSIC_DIRPROJECT_ROOT/static/music
MUSIC_DBPROJECT_ROOT/music_library.db
MEMBERS_DBPROJECT_ROOT/members.db
TASKS_DBPROJECT_ROOT/tasks.db
DATA_DIRPROJECT_ROOT
FLASK_PORT5000

09Architectural Assessment09

Current state post-refactor v3.4 + hexagonal ports & adapters. Sprints 1–14 applied. Sprint 4: OCP-compliant plugin system, DI with dependency-injector, idempotency + result persistence, Claude API circuit breaker, envcheck startup, IC creator drag-and-drop/collapse/duplicate, audio editor resetToDefault. v2.4: IC Blueprint split into 6 specialized sub-modules; MG Blueprint split into 4 sub-modules. v2.5 (Sprint 6b/7): TaskQueue event-driven (threading.Event), DriveSyncService configurable timeouts, api_music_drive_sync migrated to start_task(), generation_orchestrator Flask-free, modular containers CoreContainer + ICContainer + MGContainer. v3.0 (Sprint 8+9): Security layer (auth.py, rate_limiter.py, rate_limit_middleware.py), centralized logging (logging_config.py), DRY app_factory.py, PEP 562 lazy discipline_registry, TYPE_CHECKING in discipline_protocol, MGAppContainer (reserved), app_mg.py removed, print() calls removed from agent.py and config.py. +35 tests (222 total). Hexagonal (ports & adapters): ClassStoragePort + FilesystemClassStorage (IC); KnowledgeBasePort + FilesystemKnowledgeBase (MG). Services are now filesystem-free and Flask-free under test injection. +7 tests (229 total). v3.2 (Sprint 10): staff login system with Flask signed sessions (auth_user/ package, auth.db SQLite), admin panel /admin/users (user "admin" only), offline CLI auth_cli.py. auth.py rewritten as always-on with TESTING bypass. +4 tests (233 total). v3.3 (Sprint 11): MG JS split into 10 cohesive modules (session_log × 5 + workout_mode × 5); shared pure functions in utils.js (flatExercises, fetchExerciseHistory, makeSerieEntry); DDL constants extracted to member_repo_ddl.py; CSS export to html_export_css.py (SRP). +504 tests (737 total). v3.4 (Sprints 12–14): full i18n (248+ keys × 2 langs, window.I18n); AirTable custom fields (CustomFieldsRepo, custom_data on 4 tables, FieldManager.js); /admin/tables panel; frontend linter (scripts/lint_frontend.py JS-01/02 CSS-01/02/03); member search with autocomplete; showCriticalError() + offline banner in sidebar; ExerciseBlock.descripcion/notas_entrenador; _optInt/_optFloat in utils.js; expanded CSS tokens (--purple, --cyan, overlays, shadows). +38 tests (775 total).

Strengths

  • OCP-compliant plugin system: discipline_registry.discover_plugins() — add discipline without touching app.py
  • AppContainer (dependency-injector) — providers.Factory, wiring post-plugins, zero flask.g in threads
  • @inject + Provide[AppContainer.*] in handlers — deps declared in signature, not in magic strings
  • Factory providers (.provider) passed as explicit args to background threads — thread-safe without Flask context
  • circuit_breaker.py — CLOSED/OPEN/HALF_OPEN in-memory, shared singleton IC+MG, CircuitBreakerOpen surfaces via SSE
  • call_with_cb() + _is_transient() — distinguishes quota/network errors (counted) from domain errors (not counted)
  • IdempotencyStore + TaskResultStore — Idempotency-Key header + results persisted 24h in tasks.db
  • api_v1_bp (/api/v1/) — disciplines + task result endpoints
  • check_dotenv() + complete .env.example — immediate developer feedback at startup
  • config.py as single source of truth — MEMBERS_DB, TASKS_DB, validate() + check_dotenv() fail-fast
  • DisciplinePlugin Protocol — startup_validate() per discipline, lazy blueprint registration
  • Pydantic v2 with hard domain invariants (IC cadence, MG age, sets)
  • Thread-safe TaskQueue with TTL + 20 concurrent task limit
  • task_registry.py shared singleton — ic_bp and mg_bp use the same SSE infrastructure
  • IC Blueprint split into 6 specialized sub-modules — high cohesion, low coupling
  • MG Blueprint split into 4 sub-modules — member_routes, plan_routes, gen_routes, thin assembler
  • MG Blueprint fully decoupled from IC: uses ai_client.py as shared infrastructure (DIP)
  • ai_client.py — call_with_cb() + resolve_anthropic_client() + load_system_prompt(); single point of change for Claude
  • ISP split: MemberRepositoryBase → 4 Protocols — MuscleGenerationService only sees PlanCreationRepo (2 methods)
  • validators.py standalone — coerce_int(), coerce_restricciones() shared — eliminates triplication
  • ic/schemas.py GenerateClassRequest.to_domain() — IC validation at architectural parity with MG
  • web_utils.safe_download_filename() — RFC 6266 (filename*=UTF-8) shared IC+MG
  • MemberProfile.to_repo_dict() — Feature Envy eliminated in service._save()
  • html_export.py accordion with native <details>/<summary> — no JS, universally compatible iOS/Android
  • formatters.muscle_group_key() with Unicode NFD — accented characters (glúteo → piernas) match correctly
  • MemberRepository native UPSERT (ON CONFLICT DO UPDATE RETURNING id) — 1 round-trip
  • prompt_builder.py separate — testable without Anthropic SDK dependency
  • Services decoupled from Flask via push_fn callbacks — testable without HTTP
  • DATA_DIR + MEMBERS_DB + TASKS_DB env vars — Docker-ready without code changes
  • IC creator: drag-and-drop (mousedown/draggable pattern), collapse/expand, duplicate class, applyEdit re-render
  • _repair_for_preview() — normalizes durations bottom-up for /api/class-doc-preview without blocking validation
  • Audio editor: _defaultClips + resetToDefault() — restores empty containers matching the class
  • TaskQueue event-driven: threading.Event per task — SSE consumer uses ev.wait(timeout) instead of sleep loop (Sprint 6b)
  • DriveSyncService: configurable request_timeout + download_timeout — propagated throughout the chain (Sprint 6b)
  • api_music_drive_sync now uses start_task() + persist_and_complete() — consistent with IC/MG (Sprint 7)
  • Flask-free generation_orchestrator: start_task() returns (task_id, cached: bool) — reusable without Flask context (Sprint 7)
  • Modular containers: CoreContainer + ICContainer + MGContainer — foundation for standalone sub-apps. MG standalone = CoreContainer + MGContainer, zero IC dependency (Sprint 7)
  • logging_config.configure_logging() — idempotent, FLASK_LOG_LEVEL env var, silences anthropic/httpx/urllib3 noise (Sprint 8)
  • auth.py init_auth() — opt-in API key auth; zero code change in dev (MEGAS_API_KEY unset); SSE paths auto-exempt via -stream/ regex (Sprint 8)
  • RateLimiter sliding-window per-IP: no external dependency, thread-safe deque+Lock, configurable via env vars (Sprint 8)
  • @rate_limited() decorator: _gen_limiter shared singleton enforces global Claude API quota across IC+MG+drive-sync (Sprint 8)
  • app_factory.register_shared_middleware() — DRY: one call registers container + auth + request logging + api_v1_bp for any entry point (Sprint 8)
  • discipline_registry PEP 562 __getattr__: CLASS_FILENAME_RE and CLASS_MP3_RE computed lazily on first access — zero import cost (Sprint 9)
  • discipline_protocol TYPE_CHECKING: Flask import removed from runtime path — Protocol usable without Flask installed (Sprint 9)
  • MGAppContainer reserved for future MG spin-off: provider names mirror AppContainer so route files need zero changes (Sprint 9)
  • app_mg.py removed (premature) — spin-off will be a separate project when the need is concrete (Sprint 9)
  • Hexagonal secondary port IC: ClassStoragePort Protocol + FilesystemClassStorage adapter — ClassGenerationService is now filesystem-free in tests via _FakeStorage injection (4 new integration tests, zero disk I/O)
  • Hexagonal secondary port MG: KnowledgeBasePort Protocol + FilesystemKnowledgeBase adapter — replaces inline _load_mg_knowledge_base(); MuscleGenerationService and generate_mg_plan() are KB-free in tests via _FakeKnowledgeBase (3 new unit tests)
  • Both ports follow the same ISP pattern as member_repo_base.py / MemberRepository already established in MG — consistent hexagonal style across the codebase
  • session_log.js split into 5 modules (core + sl_storage + sl_timer + sl_history + sl_interactions) — high cohesion, single responsibility per file (Sprint 11)
  • workout_mode.js split into 5 modules (core + wk_wellness + wk_exercise_view + wk_history + wk_summary) — same naming convention as session_log (Sprint 11)
  • utils.js shared pure functions: flatExercises(), fetchExerciseHistory(), makeSerieEntry() — eliminates duplication between session_log and workout_mode (DRY, Sprint 11)
  • member_repo_ddl.py — 5 CREATE TABLE constants extracted from member_repository.py; SRP: adapter no longer mixes DDL with data-access logic (Sprint 11)
  • html_export_css.py — _EXPORT_CSS constant extracted from html_export.py; CSS independently versionable from the HTML generator (Sprint 11)
  • i18n.js 248+ keys × 2 langs — window.I18n.t(key), setLang, apply(); prefixes per domain (mg.*, audio.*, sidebar.*, at.field.*); zero hardcoded user-visible strings in JS/templates (Sprint 12)
  • tokens.css expanded — new tokens --purple, --cyan, --white, --black, --overlay-sm/md, --shadow-sm/md/lg; rule: NEVER hardcode colors in CSS, always var(--*) (Sprint 12–14)
  • AirTable custom fields: CustomFieldsRepo + custom_data TEXT DEFAULT '{}' column on 4 tables (members, training_plans, exercises, users); native Tabulator dot-notation; FieldManager.js IIFE init/buildColumns/setErrorHandler (Sprint 13)
  • /admin/tables — AirTable-style panel with 4 tabs; RID column visibility persisted in localStorage (no server round-trip); hidden-fields per table; BUILTIN_COLUMNS keyed by API name (Sprint 13)
  • scripts/lint_frontend.py — Python pre-commit linter for JS/CSS: JS-01 (hardcoded strings), JS-02 (empty catch{}), CSS-01 (hardcoded colors), CSS-02 (!important), CSS-03 (undefined tokens); runs alongside ruff (Sprint 14)
  • showCriticalError(msg, retryFn) in ui.js — fixed-bottom red banner, z-index 9000, optional retry button; UX guarantee on network or API failures (Sprint 14)
  • MegaSidebar.setActiveMember(name, dni) / clearActiveMember() — cross-page localStorage mega-active-member; offline banner IIFE with online/offline events (Sprint 14)
  • member.js unified search — digits → direct DNI lookup; text → /api/mg/members?q= + dropdown autocomplete (Sprint 14)
  • plan_editor.js DB-only selection — autocomplete enforced; on blur without selection: field clears + state cleared; descripcion + notas_entrenador synced via setNestedPath() (Sprint 14)
  • _optInt(val, radix?) / _optFloat(val) in utils.js — replaces parseInt(x)||null (swallows 0); correct pattern for optional numeric fields (Sprint 14)

Areas of attention (pending)

  • audio_render.py: crossfade dual-slot can produce subjective desync at certain BPM
  • YG (Yoga) without domain models or agent — placeholder only
  • MGAppContainer exists but is not wired to any entry point — reserved for future MG spin-off app

Architectural consistency — Diagnosis v3.4 (post Sprint 1–14)

AreaStatusNotes
Separation of concerns✅ GoodFlask routes contain no business logic — delegate to Services / Blueprint
Single source of truth✅ Goodconfig.py, disciplines/__init__.py are the roots; task_registry.py is the SSE singleton; ai_client.py is the sole Claude API entry point
OCP — Plugin system✅ Resolved (Sprint 4)discipline_registry.discover_plugins() — add discipline without touching app.py. OCP-compliant plugin protocol.
DI — Dependency Injection✅ Implemented (Sprint 4)AppContainer (dependency-injector). @inject + Provide in handlers. Factory providers passed to threads as args — no flask.g.
Claude API resilience✅ Implemented (Sprint 4)circuit_breaker.py — CLOSED/OPEN/HALF_OPEN, shared singleton IC+MG. call_with_cb() with _is_transient().
Idempotency + Result persistence✅ Implemented (Sprint 4)Idempotency-Key header. TaskResultStore TTL 24h. GET /api/v1/tasks/<id>/result.
Startup checks✅ Implemented (Sprint 4)check_dotenv() compares .env vs .env.example. .env.example documents all vars.
DIP — Dependency Inversion✅ GoodShared ai_client.py eliminates MG→IC dependency. MuscleGenerationService receives repo via constructor.
ISP — Interface Segregation✅ GoodMemberRepositoryBase → 4 Protocols. MuscleGenerationService receives PlanCreationRepo (2 methods), not the full interface.
DRY — Don't Repeat Yourself✅ Goodvalidators.py eliminates triplication. utils.py shares enum_values + format_validation_error. web_utils.safe_download_filename shared IC+MG.
Feature Envy✅ EliminatedMemberProfile.to_repo_dict() — service._save() no longer manually extracts 11 fields from the model.
IC domain model✅ CompleteClassPlan + Pydantic validators + MEGATLON invariants + ic/schemas.py GenerateClassRequest
MG domain model✅ CompleteTrainingPlan + MemberProfile + to_repo_dict() + schemas + validators.py
IC data access✅ GoodMusicLibrary abstracts SQLite; no SQL in app.py
MG data access✅ GoodMemberRepository with Protocol + native UPSERT; no SQL in routes.py
Thread safety✅ GoodTaskQueue uses Lock; circuit_breaker uses Lock; Services are stateless; repos open connection per method
Blueprint architecture✅ Goodic_bp + mg_bp + api_v1_bp registered dynamically post-plugins
IC sub-module split✅ v2.4ic/ split into 6 modules: bp, helpers, pages, gen_routes, class_routes, music_routes, audio_routes + thin assembler routes.py
MG sub-module split✅ v2.4mg/ split into 4 route modules: bp, member_routes, plan_routes, gen_routes + thin assembler routes.py
Frontend accordion✅ Goodhtml_export.py uses native <details>/<summary> — no JS, works in iOS Safari, Android Chrome
Unicode handling✅ Goodmuscle_group_key() normalizes NFD — accented chars (glúteo, bíceps) match correctly
Discipline extensibility✅ GoodAdd discipline: src/disciplines/slug/plugin.py + DisciplinePlugin Protocol + agents/slug.md
Docker readiness✅ GoodDATA_DIR, MUSIC_DIR, MEMBERS_DB, TASKS_DB, FLASK_* env vars implemented
Frontend architecture✅ GoodVanilla JS, flat state, render*() functions, DnD mousedown/draggable pattern
CB HALF_OPEN concurrency✅ Fixed_probe_in_flight flag — serializes probes under lock; single thread probes in HALF_OPEN
TaskQueue polling✅ Fixedthreading.Event per task — ev.wait(timeout) replaces sleep loop (Sprint 6b)
Modular containers✅ Sprint 7CoreContainer + ICContainer + MGContainer — foundation for sub-apps. MG standalone viable.
Flask-free orchestrator✅ Sprint 7start_task() → (task_id, bool). No flask.Response — reusable in CLI/tests.
Centralized logging✅ Sprint 8configure_logging() idempotent. FLASK_LOG_LEVEL env var. Silences anthropic/httpx/urllib3. Called once before any import.
Staff login system✅ Sprint 10auth_user/ package — Flask signed-cookie sessions (FLASK_SECRET_KEY). SQLiteUserRepository (auth.db). auth_cli.py offline CLI. Priority: TESTING bypass → exempt → session → MEGAS_API_KEY → redirect/401.
Admin panel✅ Sprint 10GET/POST /admin/users + toggle + reset-password. _require_admin() guard — username=="admin". Optimistic UI, inline password change, auto-dismiss toasts, XSS-safe escapeHtml().
Rate limiting✅ Sprint 8RateLimiter sliding-window per-IP. @rate_limited() shared across IC+MG+drive-sync. Critical decorator order enforced.
DRY middleware registration✅ Sprint 8app_factory.register_shared_middleware() — single call for container + auth + logging + api_v1_bp.
PEP 562 lazy module attrs✅ Sprint 9discipline_registry __getattr__: CLASS_FILENAME_RE/CLASS_MP3_RE computed on first access. _plugins_cache=None at import.
TYPE_CHECKING decoupling✅ Sprint 9discipline_protocol.py: Flask import under TYPE_CHECKING. Protocol has zero Flask runtime dependency.
MGAppContainer✅ Sprint 9Reserved DI container for MG spin-off. Provider names mirror AppContainer — route files need no changes when activated.
IC secondary port (storage)✅ HexagonalClassStoragePort Protocol + FilesystemClassStorage adapter in ic/class_storage.py. ClassGenerationService(storage=None) — filesystem-free under test injection. 4 integration tests, zero disk I/O.
MG secondary port (KB)✅ HexagonalKnowledgeBasePort Protocol in mg/kb_port.py + FilesystemKnowledgeBase in mg/kb_filesystem.py. Replaces inline _load_mg_knowledge_base(). MuscleGenerationService and generate_mg_plan() accept kb=None. 3 unit tests, zero filesystem.
MG JS module split✅ Sprint 11session_log.js and workout_mode.js each split into 5 cohesive modules. utils.js centralizes shared pure functions (flatExercises, fetchExerciseHistory, makeSerieEntry) and helpers _optInt/_optFloat. member_repo_ddl.py + html_export_css.py extract DDL and CSS constants (SRP).
Full i18n✅ Sprint 12static/js/i18n.js — 248+ keys × 2 langs (ES/EN). window.I18n.t(key), setLang, apply(), tFmt(key, values). Prefixes: mg.*, audio.*, sidebar.*, at.field.* (38 keys). Zero hardcoded user-visible strings in JS/HTML.
AirTable custom fields✅ Sprint 13CustomFieldsRepo (custom_fields table, CRUD). Column custom_data TEXT DEFAULT '{}' migrated on members, training_plans, exercises, users. Native Tabulator dot-notation — no flattening. Reusable FieldManager.js IIFE: init(tableName, rebuildFn), buildColumns(), setErrorHandler(fn).
Admin tables panel✅ Sprint 13/admin/tables — 4 tabs (members/exercises/trainers/plans). BUILTIN_COLUMNS keyed by API name. RID column in localStorage (no server round-trip). Hidden-fields per table. Tabulator 6.3.0 (single version in template).
Frontend linter✅ Sprint 14scripts/lint_frontend.py — rules JS-01/02 and CSS-01/02/03. Runs in pre-commit alongside ruff. Blocks commit on violations. Documented in CLAUDE.md under Frontend Quality Rules.
UX guards + offline✅ Sprint 14showCriticalError(msg, retryFn) in ui.js — fixed-bottom red banner. mgCloseWorkout(force?) with _workoutHasProgress() guard. MegaSidebar.setActiveMember() / clearActiveMember() via localStorage. Offline banner IIFE (online/offline events).
ExerciseBlock new fields✅ Sprint 14mg/models.py ExerciseBlock: descripcion: Optional[str] = None and notas_entrenador: Optional[str] = None. Synced from DB via autocomplete in plan_editor.js. Read-only .ex-desc-preview snapshot.
Test coverage✅ 775 tests+35 Sprint 8+9 (auth, rate limiting, logging, app_factory, lazy attrs). +7 hexagonal (4 IC storage + 3 MG KB). +4 Sprint 10 (auth rewrite). +504 Sprint 11. +38 Sprints 12–14 (i18n, custom fields, admin tables, UX guards).