01System Overview01
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.
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
02Module Architecture02
Three complementary views instead of one unreadable monolith graph. Each diagram tells a different story.
Vertical dependency flow. Layers only depend downward. IC and MG never import each other — they share infrastructure.
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.
IC and MG are independent packages that never import each other.
Coupling is unidirectional toward infrastructure modules in src/.
| Module | Responsibility | Pattern |
|---|---|---|
| logging_config.py | configure_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.py | init_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.py | Offline 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.py | RateLimiter — 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.py | register_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.py | Single 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__.py | Discipline registry (IC/YG/MG), lookup by code/slug. Package structure facilitates plugin system imports. | Frozen dataclass registry |
| discipline_protocol.py | DisciplinePlugin 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.py | discover_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.py | AppContainer — 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.py | CoreContainer — 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.py | In-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.py | Persistence of done/error results in tasks.db with TTL 24h. Allows retrieving results from completed generations. | SQLite repository + TTL |
| idempotency.py | Idempotency-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.py | IC domain models with invariant validation (cadence, phases) | Pydantic v2 + validators |
| ai_client.py | Shared 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.py | enum_values(enum_cls) and format_validation_error(exc) — pure functions shared between agent.py and mg/generator.py. | Pure functions (DRY) |
| agent.py | Claude API IC integration: generate_class_raw(). Delegates to ai_client.call_with_cb() — protected by circuit breaker. | tool_use, tool_choice=any |
| generator.py | High-level interface; iter_tree() for IC plan traversal | Façade + generator fn |
| class_repository.py | Class file I/O: next_filename(), load_classes() | Repository pattern |
| web_utils.py | Shared pure functions: plan_to_timeline_dict(), safe_download_filename() (RFC 6266 — Content-Disposition with filename*=UTF-8). | Pure functions (RFC 6266) |
| serializers.py | ClassPlan → JSON / CSV (pure serialization — consumed by ic/exports.py) | Pure functions |
| generation_orchestrator.py | start_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.py | SQLite tracks + audio_configs; matching by BPM/energy (_BASE_SCORE=5.0) | Repository + Pydantic models |
| task_queue.py | Thread-safe TaskQueue; TTL cleanup; 20 concurrent task limit | In-memory registry + Lock + Timer |
| task_registry.py | Shared singleton: task_queue, push(), sse_response() | Module-level singleton |
| settings.py | Persistence of API keys and user configuration | Key/value JSON store |
| api/__init__.py | api_v1_bp at /api/v1/: GET /tasks/<id>/result (retrieve persisted result), GET /disciplines (list registered disciplines). | Flask Blueprint + @inject |
| Module | Responsibility | Pattern |
|---|---|---|
| ic/schemas.py | GenerateClassRequest — 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.py | ic_bp = Blueprint("ic", __name__) — Blueprint singleton | Blueprint singleton |
| ic/helpers.py | _bad_filename() shared by class_routes + audio_routes | Shared helper |
| ic/pages.py | 3 HTML routes (music-library, audio-editor, instructor/play) — no @inject | Page routes |
| ic/gen_routes.py | generate_start + generate_stream + _run_generation. @inject providers: idempotency_store, lib_factory, result_store_factory | Generation SSE |
| ic/class_routes.py | 12 CRUD/export routes + _repair_for_preview, _recompute_parent_durations, _absorb_duration_delta | Class CRUD + export |
| ic/music_routes.py | 9 music library routes (tracks CRUD, upload, peaks) + drive sync + _run_drive_sync | Music library + Drive sync |
| ic/audio_routes.py | 5 audio config/render routes + _run_audio_render | Audio config + SSE render |
| ic/routes.py | Thin assembler (~12 lines). Imports sub-modules to register @ic_bp.route. Re-exports ic_bp for plugin.py | Thin assembler |
| ic/container.py | ICContainer — music_library Factory. For IC standalone sub-app without MG. | Modular DI (sub-app ready) |
| ic/class_storage.py | Secondary 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 |
| Module | Responsibility | Pattern |
|---|---|---|
| mg/validators.py | Standalone validation functions: coerce_int(), coerce_int_optional(), coerce_restricciones(). Shared by schemas.py and models.py — eliminates triplication (DRY). | Pure functions (DRY) |
| mg/models.py | MG 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.py | build_mg_prompt() — testable without the Anthropic SDK dependency | Pure function |
| mg/kb_port.py | Secondary 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.py | Secondary 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.py | JSON 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.py | MuscleGenerationService: 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.py | 4 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.py | Native SQLite UPSERT (ON CONFLICT DO UPDATE RETURNING id) — 1 round-trip | Repository pattern |
| mg/member_repo_ddl.py | 5 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.py | HTTP request validation: MemberSaveRequest, GenerateRequest. Validators delegate to validators.py. | Pydantic v2 wire models |
| mg/formatters.py | Text 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.py | Generates self-contained HTML for MG plans. Accordion with native <details>/<summary> — no JS, universally compatible with iOS/Android. | HTML generation (native accordion) |
| mg/bp.py | mg_bp = Blueprint("mg", __name__) — Blueprint singleton | Blueprint singleton |
| mg/member_routes.py | 5 member CRUD routes + _save_member_from_request. @inject on all. | Member CRUD |
| mg/plan_routes.py | 5 plan routes (history, get, HTML export, update, manual create). @inject on all. | Plan management |
| mg/gen_routes.py | api_mg_generate_start + api_mg_generate_stream + _run_mg_generation. Idempotency-Key + result persistence. | Generation SSE |
| mg/routes.py | Thin assembler (~12 lines). Re-exports mg_bp for plugin.py. | Thin assembler |
| mg/container.py | MGContainer — member_repo Factory. For MG standalone sub-app without IC or MusicLibrary. | Modular DI (sub-app ready) |
| mg/app_container.py | MGAppContainer — 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) |
session_log.js — split into 5 modules
| File | Responsibility |
|---|---|
session_log.js | Core: MgSessionLog class + globals _timerInterval / _timerEl |
sl_storage.js | localStorage persistence: _logStorageKey, mgPersistLog, mgRestoreLog |
sl_timer.js | Rest-timer overlay: mgStartTimer, mgStopTimer |
sl_history.js | Exercise history hints: mgLoadHistory |
sl_interactions.js | User action handlers: mgCompleteSet, mgSaveSession, et al. |
workout_mode.js — split into 5 modules
| File | Responsibility |
|---|---|
workout_mode.js | Core: _workout state + mgOpenWorkout / mgCloseWorkout(force?) — _workoutHasProgress() guard prevents accidental close; force=true bypasses it post-save |
wk_wellness.js | Pre-workout wellness screen |
wk_exercise_view.js | Exercise rendering + set interactions |
wk_history.js | Background history loading |
wk_summary.js | End-of-session screen + save |
utils.js — shared pure functions (DRY)
| Function | Description |
|---|---|
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) |
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.
| Attribute | Computed from |
|---|---|
| CLASS_FILENAME_RE | build_filename_re(get_plugins(), "json") |
| CLASS_MP3_RE | build_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.
| Order | Decorator | Reason |
|---|---|---|
| 1 (outer) | @bp.route(...) | Flask route registration |
| 2 | @rate_limited() | Runs first at call time — rejects before DI |
| 3 (inner) | @inject | DI 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.
| Step | Action |
|---|---|
| 1 | configure_logging() — before everything |
| 2 | _init_container() + _init_plugins() |
| 3 | container.wire(modules=[...]) |
| 4 | register_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.
| File | Role |
|---|---|
ic/class_storage.py | Port (ClassStoragePort) + adapter (FilesystemClassStorage) |
ic/generation_service.py | Constructor: storage: ClassStoragePort | None = None |
tests/integration/test_services.py | TestClassGenerationServiceWithFakeStorage — 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.
| File | Role |
|---|---|
mg/kb_port.py | Secondary port Protocol (KnowledgeBasePort) |
mg/kb_filesystem.py | Filesystem adapter + module-level _default_kb singleton |
mg/generator.py | kb: KnowledgeBasePort | None = None in both public functions |
mg/service.py | kb: KnowledgeBasePort | None = None forwarded through service |
tests/unit/test_mg_service.py | 3 tests with _FakeKnowledgeBase — zero filesystem |
03Domain Models03
4-level tree. Domain invariants are validated by Pydantic at construction time.
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.
MEGATLON IC Phases (3360s total)
| Phase | Duration | Seconds |
|---|---|---|
| presentation | 6 min | 360s |
| activation | 3 min | 180s |
| main_work | 35 min | 2100s |
| cool_down | 2 min | 120s |
| stretching | 10 min | 600s |
Domain Invariants
| Rule | Value |
|---|---|
| Min cadence (IC work) | 60 RPM |
| Max cadence IC | 110 RPM |
| IC cool_down cadence | 80–90 RPM |
| IC music BPM | = RPM × 2 |
| IC position 3 | Only when standing=true |
| MG weekly frequency | 1–7 days |
| MG member age | 14–99 years |
| MG sets | 1–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.
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.
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.
05SQLite Schema05
Exclusive access via MusicLibrary — never direct SQL in app.py.
Exclusive access via MemberRepository (Protocol MemberRepositoryBase). Native upsert with ON CONFLICT DO UPDATE RETURNING id.
Shared by TaskResultStore and IdempotencyStore. Configurable path via TASKS_DB env var.
TaskResultStore
| Pattern | Detail |
|---|---|
| TTL | 24h — automatic cleanup on get() |
| Persistence | Only "done" / "error" events — no intermediate status |
| Access | GET /api/v1/tasks/<id>/result post-stream |
IdempotencyStore
| Pattern | Detail |
|---|---|
| Insertion | INSERT OR IGNORE — idempotent by definition |
| TTL | 48h — window for client to retry with same key |
| Scope | Per Idempotency-Key header — optional per client |
Access patterns — music_library.db
| Pattern | Detail |
|---|---|
| Migrations | ALTER TABLE in _init_db() with try/except — idempotent |
| Atomicity | add_track() INSERT + UPDATE filename in a single with conn: block |
| Matching | find_matching_tracks() — _BASE_SCORE=5.0 + BPM + genre + terrain |
| Thread safety | Each method opens its own connection — no shared state |
Access patterns — members.db
| Pattern | Detail |
|---|---|
| Native UPSERT | INSERT … ON CONFLICT(dni) DO UPDATE … RETURNING id — 1 query |
| CASCADE | DELETE members removes training_plans + goal_tracking via FK |
| Normalization | apto_medico 0/1 → bool in _member_row_to_dict() |
| Protocol | MemberRepositoryBase (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.
📁 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
| Script | Description | When it runs |
|---|---|---|
scripts/lint_frontend.py | Python 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.toml | Local pre-commit hook |
Registered disciplines
| Code | Slug | Status |
|---|---|---|
| IC | indoor-cycling | ✅ Full production |
| MG | musculacion | ✅ Full production |
| YG | yoga | Placeholder |
Environment variables
| Variable | Default |
|---|---|
| ANTHROPIC_API_KEY | — (required) |
| DATA_DIR | PROJECT_ROOT (dev) |
| MUSIC_DIR | PROJECT_ROOT/static/music |
| MUSIC_DB | PROJECT_ROOT/music_library.db |
| MEMBERS_DB | PROJECT_ROOT/members.db |
| TASKS_DB | PROJECT_ROOT/tasks.db |
| FLASK_PORT | 5000 |
| FLASK_HOST | 127.0.0.1 |
| FLASK_DEBUG | 1 (dev), 0 (docker) |
| FLASK_LOG_LEVEL | INFO |
| MEGAS_API_KEY | — (empty = sessions only) |
| MEGAS_RATE_LIMIT | 10 (requests per window) |
| MEGAS_RATE_WINDOW_SEC | 60 (window in seconds) |
| FLASK_SECRET_KEY | — (required in production) |
| SESSION_HOURS | 8 |
| AUTH_DB | auth.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.
app.py
9 routes
| Route | Description | |
|---|---|---|
| GET | / | Redirect → /instructor |
| GET | /setup | setup.html |
| GET | /creator | discipline_select.html |
| GET | /creator/ic | creator.html |
| GET | /creator/musculacion | mg_creator.html |
| GET | /instructor | instructor.html |
| GET | /socios | socios.html |
| GET | /api/settings | Redacted configuration |
| POST | /api/settings | Save API keys and settings |
| POST | /api/setup | Initial setup |
ic/pages.py (Blueprint ic_bp)
3 routes
| Route | Description | |
|---|---|---|
| GET | /music-library | music_library.html |
| GET | /audio-editor/<fn> | audio_editor.html |
| GET | /instructor/play/<fn> | instructor_play.html |
ic/gen_routes.py (Blueprint ic_bp)
SSE
| Route | Description | |
|---|---|---|
| POST | /api/generate-start | Starts IC task → {task_id}. Idempotency-Key header. |
| SSE | /api/generate-stream/<tid> | SSE: status / done / error |
ic/class_routes.py (Blueprint ic_bp)
12 routes
| Route | Description | |
|---|---|---|
| GET | /api/classes | List 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-preview | Preview doc from JSON (no I/O) |
ic/music_routes.py (Blueprint ic_bp)
9 routes
| Route | Description | |
|---|---|---|
| POST | /api/music/upload | Upload track (magic bytes validation) |
| GET | /api/music/tracks | List 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-sync | Sync Google Drive → {task_id} |
ic/audio_routes.py (Blueprint ic_bp)
SSE
| Route | Description | |
|---|---|---|
| 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_routes.py (Blueprint mg_bp)
5 routes
| Route | Description | |
|---|---|---|
| GET | /api/mg/members | List members (search ?q=) |
| GET | /api/mg/members/<dni> | Full profile by ID |
| POST | /api/mg/members | Create/upsert member |
| PUT | /api/mg/members/<dni> | Update profile |
| DELETE | /api/mg/members/<dni> | Delete + CASCADE |
mg/plan_routes.py (Blueprint mg_bp)
5 routes
| Route | Description | |
|---|---|---|
| GET | /api/mg/members/<dni>/plans | Member plan history |
| GET | /api/mg/plans/<id> | Full plan by ID |
| GET | /api/mg/plans/<id>/export | Export plan → self-contained HTML |
| PUT | /api/mg/plans/<id> | Update existing plan |
| POST | /api/mg/plans | Create manual plan |
mg/gen_routes.py (Blueprint mg_bp)
SSE
| Route | Description | |
|---|---|---|
| POST | /api/mg/generate-start | Start generation → {task_id}. Idempotency-Key header. |
| SSE | /api/mg/generate-stream/<tid> | SSE: status / done / error |
api/__init__.py (Blueprint api_v1_bp, prefix /api/v1/)
2 routes
| Route | Description | |
|---|---|---|
| GET | /api/v1/disciplines | List registered disciplines (code, slug, label) |
| GET | /api/v1/tasks/<id>/result | Persisted 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.
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
| Aspect | Detail |
|---|---|
| Activation | Set MEGAS_API_KEY=<key> in .env |
| Headers | Authorization: Bearer <key> or X-API-Key: <key> |
| Exempt paths | /setup, /api/setup, /static/*, any path with -stream/ (SSE) |
| SSE exemption | Regex -stream/ — requires hyphen to prevent crafted bypass paths |
| Rejection | HTTP 401 + {"error": "Unauthorized"} |
| Dev mode | Unset env var → auth disabled, no code change needed |
Rate Limiting — src/rate_limiter.py + rate_limit_middleware.py
| Aspect | Detail |
|---|---|
| Algorithm | Sliding window per-IP using collections.deque |
| Config | MEGAS_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 detection | X-Forwarded-For header or remote_addr |
| Rejection | HTTP 429 + {"error": "Rate limit exceeded. Try again in Xs."} |
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.
Errors counted as failures
| Type | Typical cause |
|---|---|
| RateLimitError (429) | API quota exhausted |
| APIStatusError 529 | Claude overloaded |
| APIConnectionError | Network down / DNS timeout |
| APITimeoutError | Response > 300s |
Behavior when OPEN
| Layer | Behavior |
|---|---|
| ai_client.call_with_cb() | Raises CircuitBreakerOpen immediately |
| ClassGenerationService | Catches → push(task_id, "error", msg) |
| SSE stream | Emits {type:"error", payload:msg} |
| Frontend | Shows error toast to instructor |
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)
| Source | Priority |
|---|---|
| os.environ / .env | 1st (load_dotenv at start) |
| settings.json | 2nd (via ai_client.build_client) |
| Neither | EnvironmentError when calling Claude |
Optional variables documented in .env.example
| Variable | Default |
|---|---|
| MUSIC_DIR | PROJECT_ROOT/static/music |
| MUSIC_DB | PROJECT_ROOT/music_library.db |
| MEMBERS_DB | PROJECT_ROOT/members.db |
| TASKS_DB | PROJECT_ROOT/tasks.db |
| DATA_DIR | PROJECT_ROOT |
| FLASK_PORT | 5000 |
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:
ClassStoragePortProtocol +FilesystemClassStorageadapter —ClassGenerationServiceis now filesystem-free in tests via_FakeStorageinjection (4 new integration tests, zero disk I/O) - Hexagonal secondary port MG:
KnowledgeBasePortProtocol +FilesystemKnowledgeBaseadapter — replaces inline_load_mg_knowledge_base();MuscleGenerationServiceandgenerate_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/MemberRepositoryalready 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, alwaysvar(--*)(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.jsIIFE 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_COLUMNSkeyed 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)
| Area | Status | Notes |
|---|---|---|
| Separation of concerns | ✅ Good | Flask routes contain no business logic — delegate to Services / Blueprint |
| Single source of truth | ✅ Good | config.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 | ✅ Good | Shared ai_client.py eliminates MG→IC dependency. MuscleGenerationService receives repo via constructor. |
| ISP — Interface Segregation | ✅ Good | MemberRepositoryBase → 4 Protocols. MuscleGenerationService receives PlanCreationRepo (2 methods), not the full interface. |
| DRY — Don't Repeat Yourself | ✅ Good | validators.py eliminates triplication. utils.py shares enum_values + format_validation_error. web_utils.safe_download_filename shared IC+MG. |
| Feature Envy | ✅ Eliminated | MemberProfile.to_repo_dict() — service._save() no longer manually extracts 11 fields from the model. |
| IC domain model | ✅ Complete | ClassPlan + Pydantic validators + MEGATLON invariants + ic/schemas.py GenerateClassRequest |
| MG domain model | ✅ Complete | TrainingPlan + MemberProfile + to_repo_dict() + schemas + validators.py |
| IC data access | ✅ Good | MusicLibrary abstracts SQLite; no SQL in app.py |
| MG data access | ✅ Good | MemberRepository with Protocol + native UPSERT; no SQL in routes.py |
| Thread safety | ✅ Good | TaskQueue uses Lock; circuit_breaker uses Lock; Services are stateless; repos open connection per method |
| Blueprint architecture | ✅ Good | ic_bp + mg_bp + api_v1_bp registered dynamically post-plugins |
| IC sub-module split | ✅ v2.4 | ic/ split into 6 modules: bp, helpers, pages, gen_routes, class_routes, music_routes, audio_routes + thin assembler routes.py |
| MG sub-module split | ✅ v2.4 | mg/ split into 4 route modules: bp, member_routes, plan_routes, gen_routes + thin assembler routes.py |
| Frontend accordion | ✅ Good | html_export.py uses native <details>/<summary> — no JS, works in iOS Safari, Android Chrome |
| Unicode handling | ✅ Good | muscle_group_key() normalizes NFD — accented chars (glúteo, bíceps) match correctly |
| Discipline extensibility | ✅ Good | Add discipline: src/disciplines/slug/plugin.py + DisciplinePlugin Protocol + agents/slug.md |
| Docker readiness | ✅ Good | DATA_DIR, MUSIC_DIR, MEMBERS_DB, TASKS_DB, FLASK_* env vars implemented |
| Frontend architecture | ✅ Good | Vanilla 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 | ✅ Fixed | threading.Event per task — ev.wait(timeout) replaces sleep loop (Sprint 6b) |
| Modular containers | ✅ Sprint 7 | CoreContainer + ICContainer + MGContainer — foundation for sub-apps. MG standalone viable. |
| Flask-free orchestrator | ✅ Sprint 7 | start_task() → (task_id, bool). No flask.Response — reusable in CLI/tests. |
| Centralized logging | ✅ Sprint 8 | configure_logging() idempotent. FLASK_LOG_LEVEL env var. Silences anthropic/httpx/urllib3. Called once before any import. |
| Staff login system | ✅ Sprint 10 | auth_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 10 | GET/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 8 | RateLimiter sliding-window per-IP. @rate_limited() shared across IC+MG+drive-sync. Critical decorator order enforced. |
| DRY middleware registration | ✅ Sprint 8 | app_factory.register_shared_middleware() — single call for container + auth + logging + api_v1_bp. |
| PEP 562 lazy module attrs | ✅ Sprint 9 | discipline_registry __getattr__: CLASS_FILENAME_RE/CLASS_MP3_RE computed on first access. _plugins_cache=None at import. |
| TYPE_CHECKING decoupling | ✅ Sprint 9 | discipline_protocol.py: Flask import under TYPE_CHECKING. Protocol has zero Flask runtime dependency. |
| MGAppContainer | ✅ Sprint 9 | Reserved DI container for MG spin-off. Provider names mirror AppContainer — route files need no changes when activated. |
| IC secondary port (storage) | ✅ Hexagonal | ClassStoragePort 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) | ✅ Hexagonal | KnowledgeBasePort 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 11 | session_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 12 | static/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 13 | CustomFieldsRepo (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 14 | scripts/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 14 | showCriticalError(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 14 | mg/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). |