Commit Graph

163 Commits

Author SHA1 Message Date
1fdf91cb50 fix: Migration 027 - health mode missing dimensions
All checks were successful
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Fixed health mode calculation to include all 6 dimensions.
Simplified CASE statements (single CASE instead of multiple additions).

Before: health mode only set flexibility (15%) + health (55%) = 70% 
After:  health mode sets all dimensions = 100% 
  - weight_loss: 5%
  - muscle_gain: 0%
  - strength: 10%
  - endurance: 20%
  - flexibility: 15%
  - health: 50%

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 10:56:53 +01:00
80d57918ae fix: Migration 027 constraint violation - health mode sum
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Fixed health mode calculation in focus_areas migration.
Changed health_pct from 50 to 55 to ensure sum equals 100%.

Before: 0+0+10+20+15+50 = 95% (constraint violation)
After:  0+0+10+20+15+55 = 100% (valid)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 10:53:39 +01:00
4a11d20c4d feat: Goal System v2.0 - Focus Areas with weighted priorities
All checks were successful
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
BREAKING: Replaces single 'primary goal' with weighted multi-goal system

Migration 027:
- New table: focus_areas (6 dimensions with percentages)
- Constraint: Sum must equal 100%
- Auto-migration: goal_mode → focus_areas for existing users
- Unique constraint: One active focus_areas per profile

Backend:
- get_focus_weights() V2: Reads from focus_areas table
- Fallback: Uses goal_mode if focus_areas not set
- New endpoints: GET/PUT /api/goals/focus-areas
- Validation: Sum=100, range 0-100

API:
- getFocusAreas() - Get current weights
- updateFocusAreas(data) - Update weights (upsert)

Focus dimensions:
1. weight_loss_pct   (Fettabbau)
2. muscle_gain_pct   (Muskelaufbau)
3. strength_pct      (Kraftsteigerung)
4. endurance_pct     (Ausdauer)
5. flexibility_pct   (Beweglichkeit)
6. health_pct        (Allgemeine Gesundheit)

Benefits:
- Multiple goals with custom priorities
- More flexible than single primary goal
- KI can use weighted scores
- Ready for Phase 0b placeholder integration

UI: Coming in next commit (slider interface)
2026-03-27 08:38:03 +01:00
2303c04123 feat: filtered goal types - count specific training types
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
NEW FEATURE: Filter conditions for goal types
Enables counting/aggregating specific subsets of data.

Example use case: Count only strength training sessions per week
- Create goal type with filter: {"training_type": "strength"}
- count_7d now counts only strength training, not all activities

Implementation:
- Migration 026: filter_conditions JSONB column
- Backend: Dynamic WHERE clause building from JSON filters
- Supports single value: {"training_type": "strength"}
- Supports multiple values: {"training_type": ["strength", "hiit"]}
- Works with all 8 aggregation methods (count, avg, sum, min, max)
- Frontend: JSON textarea with example + validation
- Pydantic models: filter_conditions field added

Technical details:
- SQL injection safe (parameterized queries)
- Graceful degradation (invalid JSON ignored with warning)
- Backward compatible (NULL filters = no filtering)

Answers user question: 'Kann ich Trainingstypen wie Krafttraining separat zählen?'
Answer: YES! 🎯
2026-03-27 08:14:22 +01:00
2c978bf948 feat: dynamic schema dropdowns for goal type admin UI
All checks were successful
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Admin can now easily create custom goal types:
- New endpoint /api/goals/schema-info with table/column metadata
- 9 tables documented (weight, caliper, activity, nutrition, sleep, vitals, BP, rest_days, circumference)
- Table dropdown with descriptions (e.g., 'activity_log - Trainingseinheiten')
- Column dropdown dependent on selected table
- All columns documented in German with data types
- Fields optional (for complex calculation formulas)

UX improvements:
- No need to guess table/column names
- Clear descriptions for each field
- Type-safe selection (no typos)
- Cascading dropdowns (column depends on table)

Closes user feedback: 'Admin weiß nicht welche Tabellen/Spalten verfügbar sind'
2026-03-27 08:05:45 +01:00
210671059a debug: comprehensive error handling and logging for list_goals
All checks were successful
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- try-catch around entire endpoint
- try-catch for each goal progress update
- Detailed error logging with traceback
- Continue processing other goals if one fails
- Clear error message to frontend

This will show exact error location in logs.
2026-03-27 07:58:56 +01:00
1f4ee5021e fix: robust error handling in goal value fetcher
All checks were successful
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Prevents crashes when:
- Goal types have NULL source_table/column (lean_mass, inactive placeholders)
- Old goals reference inactive goal types
- SQL queries fail for any reason

Changes:
- Guard clause checks table/column before SQL
- try-catch wraps all aggregation queries
- Returns None gracefully instead of crashing endpoint
- Logs warnings for debugging

Fixes: Goals page not loading due to /api/goals/list crash
2026-03-27 07:55:19 +01:00
1e758696fd feat: Migration 025 - automatic cleanup and seed for goal_type_definitions
All checks were successful
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Fixes cases where Migration 024 partially ran:
- Removes created_by/updated_by columns if they exist
- Re-inserts seed data with ON CONFLICT DO NOTHING
- Fully automated, no manual intervention needed
- Production-safe (idempotent)

This ensures clean deployment to production without manual DB changes.
2026-03-27 07:49:09 +01:00
a039a0fad3 fix: Migration 024 - remove problematic FK constraints created_by/updated_by
Some checks failed
Build Test / lint-backend (push) Waiting to run
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
Goal type definitions are global system entities, not user-specific.
System types seeded in migration cannot have created_by FK.

Changes:
- Remove created_by/updated_by columns from goal_type_definitions
- Update CREATE/UPDATE endpoints to not use these fields
- Migration now runs cleanly on container start
- No manual intervention needed for production deployment
2026-03-27 07:48:23 +01:00
b3cc588293 fix: make Migration 024 idempotent + add seed data fix script
All checks were successful
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 14s
2026-03-27 07:40:42 +01:00
c9e4b6aa02 debug: diagnostic script for Migration 024 state 2026-03-27 07:39:18 +01:00
8be87bfdfb fix: Remove broken table_exists check
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Removed faulty EXISTS check that was causing "0" error.
Added debug logging and better error messages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 07:34:29 +01:00
484c25575d feat: manual migration 024 runner script
All checks were successful
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Allows running Migration 024 manually if auto-migration failed.

Usage: python backend/run_migration_024.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 07:28:43 +01:00
bbee44ecdc fix: Better error handling for goal types loading
Some checks failed
Build Test / lint-backend (push) Waiting to run
Build Test / build-frontend (push) Waiting to run
Deploy Development / deploy (push) Has been cancelled
- Check if goal_type_definitions table exists
- Detailed error messages
- Fallback if goalTypes is empty
- Prevent form opening without types

Helps debugging Migration 024 issues.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 07:28:14 +01:00
65ee5f898f feat: Phase 1.5 - Flexible Goal System (DB-Registry) Part 1/2
All checks were successful
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
KRITISCHE ARCHITEKTUR-ÄNDERUNG vor Phase 0b:
Ermöglicht dynamische Goal Types ohne Code-Änderungen.

Backend:
- Migration 024: goal_type_definitions Tabelle
  → 8 existierende Typen als Seed-Data migriert
  → Flexible Schema: source_table, aggregation_method, calculation_formula
  → System vs. Custom Types (is_system flag)
- goal_utils.py: Universal Value Fetcher
  → get_current_value_for_goal() ersetzt hardcoded if/elif chain
  → Unterstützt: latest, avg_7d, avg_30d, sum_30d, count_7d, etc.
  → Komplexe Formeln (lean_mass) via calculation_formula JSON
- goals.py: CRUD API für Goal Type Definitions
  → GET /goals/goal-types (public)
  → POST/PUT/DELETE /goals/goal-types (admin-only)
  → Schutz für System-Types (nicht löschbar)
- goals.py: _get_current_value_for_goal_type() delegiert zu Universal Fetcher

Frontend:
- api.js: 4 neue Funktionen (listGoalTypeDefinitions, create, update, delete)

Dokumentation:
- TODO_GOAL_SYSTEM.md: Phase 1.5 hinzugefügt, Roadmap aktualisiert

Part 2/2 (nächster Commit):
- Frontend: Dynamic Goal Types Dropdown
- Admin UI: Goal Type Management Page
- Testing

Warum JETZT (vor Phase 0b)?
- Phase 0b Platzhalter (120+) nutzen Goals für Score-Berechnungen
- Flexible Goals → automatisch in Platzhaltern verfügbar
- Später umbauen = Doppelarbeit (alle Platzhalter anpassen)

Zukünftige Custom Goals möglich:
- 🧘 Meditation (min/Tag)
- 📅 Trainingshäufigkeit (x/Woche)
- 📊 Planabweichung (%)
- 🎯 Ritual-Adherence (%)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:45:05 +01:00
27a8af7008 debug: Add logging and warnings for Goal System issues
All checks were successful
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Based on test feedback - 3 issues addressed:

1. Primary Toggle (Frontend Debug):
   - Add console.log in handleSaveGoal
   - Shows what data is sent to backend
   - Helps debug if checkbox state is correct

2. Lean Mass Display (Backend Debug):
   - Add error handling in lean_mass calculation
   - Log why calculation fails (missing weight/bf data)
   - Try-catch for value conversion errors

3. BP/Strength/Flexibility Warning (UI):
   - Yellow warning box for incomplete goal types
   - BP: "benötigt 2 Werte (geplant für v2.0)"
   - Strength/Flexibility: "Keine Datenquelle"
   - Transparent about limitations

Next: User re-tests with debug output to identify root cause.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:24:40 +01:00
87464ff138 fix: Phase 1 - Goal System Quick Fixes + Abstraction Layer
All checks were successful
Deploy Development / deploy (push) Successful in 53s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Behebt 4 kritische Bugs in Phase 0a und schafft Basis für Phase 0b
ohne spätere Doppelarbeit.

Backend:
- NEW: goal_utils.py mit get_focus_weights() Abstraction Layer
  → V1: Mappt goal_mode zu Gewichten
  → V2 (später): Liest aus focus_areas Tabelle
  → Phase 0b Platzhalter (120+) müssen NICHT umgeschrieben werden
- FIX: Primary goal toggle in goals.py (is_primary im GoalUpdate Model)
  → Beim Update auf primary werden andere Goals korrekt auf false gesetzt
- FIX: lean_mass current_value Berechnung implementiert
  → weight - (weight * body_fat_pct / 100)
- FIX: VO2Max Spaltenname vo2_max (statt vo2max)
  → Internal Server Error behoben

CLAUDE.md:
- Version Update: Phase 1 Fixes (27.03.2026)

Keine Doppelarbeit:
- Alle zukünftigen Phase 0b Platzhalter nutzen get_focus_weights()
- v2.0 Redesign = nur eine Funktion ändern, nicht 120+ Platzhalter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 06:13:47 +01:00
906a3b7cdd fix: Migration 022 - remove invalid schema_migrations tracking
All checks were successful
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
The migration system tracks migrations via filename automatically.
Removed manual DO block that used wrong column name (version vs filename).

Also removed unused json import from goals.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 16:26:48 +01:00
337667fc07 feat: Phase 0a - Minimal Goal System (Strategic + Tactical)
All checks were successful
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Strategic Layer: Goal modes (weight_loss, strength, endurance, recomposition, health)
- Tactical Layer: Concrete goal targets with progress tracking
- Training phases (manual + auto-detection framework)
- Fitness tests (standardized performance tracking)

Backend:
- Migration 022: goal_mode in profiles, goals, training_phases, fitness_tests tables
- New router: routers/goals.py with full CRUD for goals, phases, tests
- API endpoints: /api/goals/* (mode, list, create, update, delete)

Frontend:
- GoalsPage: Goal mode selector + goal management UI
- Dashboard: Goals preview card with link
- API integration: goal mode, CRUD operations, progress calculation

Basis for 120+ placeholders and goal-aware analyses (Phase 0b)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 16:20:35 +01:00
6e651b5bb5 fix: include stage outputs in debug info for value table
All checks were successful
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- stage_debug now includes 'output' dict with all stage outputs
- Fixes empty values for stage_X_outputkey in expert mode
- Stage outputs are the actual AI responses passed to next stage
2026-03-26 14:33:00 +01:00
f37936c84d feat: show all stage outputs as collapsible JSON in expert mode
All checks were successful
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Backend:
- Add ALL stage outputs to metadata (not just referenced ones)
- Format JSON with indent for readability
- Description: 'Zwischenergebnis aus Stage X'

Frontend:
- Stage raw values shown in collapsible <details> element
- JSON formatted in <pre> tag with syntax highlighting
- 'JSON anzeigen ▼' summary for better UX

Fixes: Stage X - Rohdaten now shows intermediate results
2026-03-26 13:17:58 +01:00
159fcab17a feat: circ_summary with best-of-each strategy and age annotations
All checks were successful
Deploy Development / deploy (push) Successful in 42s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
- Each circumference point shows most recent value (even from different dates)
- Age annotations: heute, gestern, vor X Tagen/Wochen/Monaten
- Gives AI better context about measurement freshness
- Example: 'Brust 105cm (heute), Nacken 38cm (vor 2 Wochen)'
2026-03-26 13:09:38 +01:00
d06d3d84de fix: circ_summary now checks all 8 circumference points
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Previously only checked c_chest, c_waist, c_hip
- Now includes c_neck, c_belly, c_thigh, c_calf, c_arm
- Fixes 'keine Daten' when entries exist with only non-primary measurements
2026-03-26 13:06:37 +01:00
adb5dcea88 feat: category grouping in value table (Issue #47)
All checks were successful
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
FEATURE: Gruppierung nach Kategorien
- Wertetabelle jetzt nach Modulen/Kategorien gruppiert
- Bessere Übersicht und Zuordnung der Werte

BACKEND: Category Metadata
- Für normale Platzhalter: Kategorie aus Catalog (Profil, Körper, Ernährung, etc.)
- Für extrahierte Werte: "Stage X - [Output Name]"
- Für Rohdaten: "Stage X - Rohdaten"
- Fallback: "Sonstiges"

FRONTEND: Grouped Display
- sortedCategories: Sortierung (Normal → Stage Outputs → Rohdaten)
- Section Headers: Grauer Hintergrund mit Kategorie-Name
- React.Fragment für Gruppierung

SORTIERUNG:
1. Normale Kategorien (Profil, Körper, Ernährung, Training, etc.)
2. Stage Outputs (Stage 1 - Body, Stage 1 - Nutrition, etc.)
3. Rohdaten (Stage 1 - Rohdaten, Stage 2 - Rohdaten)
4. Innerhalb: Alphabetisch

BEISPIEL:
┌────────────────────────────────────────────┐
│ PROFIL                                     │
├────────────────────────────────────────────┤
│ name       │ Lars    │ Name des Nutzers   │
│ age        │ 55      │ Alter in Jahren    │
├────────────────────────────────────────────┤
│ KÖRPER                                     │
├────────────────────────────────────────────┤
│ weight_... │ 85.2 kg │ Aktuelles Gewicht  │
│ bmi        │ 26.6    │ Body Mass Index    │
├────────────────────────────────────────────┤
│ ERNÄHRUNG                                  │
├────────────────────────────────────────────┤
│ kcal_avg   │ 1427... │ Durchschn. Kalorien│
│ protein... │ 106g... │ Durchschn. Protein │
├────────────────────────────────────────────┤
│ STAGE 1 - BODY                             │
├────────────────────────────────────────────┤
│ ↳ bmi      │ 26.6    │ Aus Stage 1 (body) │
│ ↳ trend    │ sinkend │ Aus Stage 1 (body) │
├────────────────────────────────────────────┤
│ STAGE 1 - NUTRITION                        │
├────────────────────────────────────────────┤
│ ↳ kcal_... │ 1427    │ Aus Stage 1 (nutr.)│
└────────────────────────────────────────────┘

Experten-Modus zusätzlich:
├────────────────────────────────────────────┤
│ STAGE 1 - ROHDATEN                         │
├────────────────────────────────────────────┤
│ 🔬 stage...│ {"bmi"..│ Rohdaten Stage 1   │
└────────────────────────────────────────────┘

version: 9.10.0 (feature)
module: prompts 2.5.0, insights 1.8.0
2026-03-26 12:59:52 +01:00
da803da816 feat: extract individual values from stage outputs (Issue #47)
All checks were successful
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
FEATURE: Basis-Analysen Einzelwerte
Vorher: stage_1_body → {"bmi": 26.6, "weight": "85.2kg"} (1 Zeile)
Jetzt:  bmi → 26.6 (eigene Zeile)
        weight → 85.2kg (eigene Zeile)

BACKEND: JSON-Extraktion
- Stage outputs (JSON) → extract individual fields
- extracted_values dict sammelt alle Einzelwerte
- Deduplizierung: Gleiche Keys nur einmal
- Flags:
  - is_extracted: true → Wert aus Stage-Output extrahiert
  - is_stage_raw: true → Rohdaten (JSON) nur Experten-Modus

BEISPIEL Stage 1 Output:
{
  "stage_1_body": {
    "bmi": 26.6,
    "weight": "85.2 kg",
    "trend": "sinkend"
  }
}

→ Metadata:
{
  "bmi": {
    value: "26.6",
    description: "Aus Stage 1 (stage_1_body)",
    is_extracted: true
  },
  "weight": {
    value: "85.2 kg",
    description: "Aus Stage 1 (stage_1_body)",
    is_extracted: true
  },
  "stage_1_body": {
    value: "{\"bmi\": 26.6, ...}",
    description: "Rohdaten Stage 1 (Basis-Analyse JSON)",
    is_stage_raw: true
  }
}

FRONTEND: Smart Filtering
Normal-Modus:
- Zeigt: Einzelwerte (bmi, weight, trend)
- Versteckt: Rohdaten (stage_1_body JSON)
- Filter: is_stage_raw === false

Experten-Modus:
- Zeigt: Alles (Einzelwerte + Rohdaten)
- Rohdaten: Grauer Hintergrund + 🔬 Icon

VISUAL Indicators:
↳ bmi        → Extrahierter Wert (grün)
  weight     → Normaler Platzhalter (accent)
🔬 stage_1_* → Rohdaten JSON (grau, klein, nur Experten)

ERGEBNIS:
┌──────────────────────────────────────────┐
│ 📊 Verwendete Werte (8) (+2 ausgeblendet)│
│ ┌────────────────────────────────────────┐│
│ │ weight_aktuell │ 85.2 kg   │ Gewicht ││ ← Normal
│ │ ↳ bmi          │ 26.6      │ Aus St..││ ← Extrahiert
│ │ ↳ trend        │ sinkend   │ Aus St..││ ← Extrahiert
│ └────────────────────────────────────────┘│
└──────────────────────────────────────────┘

Experten-Modus zusätzlich:
│ 🔬 stage_1_body │ {"bmi":...│ Rohdaten││ ← JSON

version: 9.9.0 (feature)
module: prompts 2.4.0, insights 1.7.0
2026-03-26 12:55:53 +01:00
e799edbae4 feat: expert mode + stage outputs in value table (Issue #47)
All checks were successful
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
FEATURE: Experten-Modus 🔬
- Toggle-Button in Wertetabelle
- Normal: Nur gefüllte Werte anzeigen
- Experten: Alle Platzhalter inkl. leere/technische
- Anzeige: "(+X ausgeblendet)" wenn Werte gefiltert
- Button-Style: Accent wenn aktiv

FILTER: Leere Werte ausblenden (Normal-Modus)
- Filtert: '', 'nicht verfügbar', '[Nicht verfügbar]'
- Zeigt nur relevante Nutzer-Daten
- Experten-Modus zeigt alles

FEATURE: Stage-Outputs in Wertetabelle 
ROOT CAUSE: stage_N_key Platzhalter hatten keine Werte
- Stage-Outputs (z.B. stage_1_body) sind Basis-Analysen-Ergebnisse
- Wurden nicht in cleaned_values gefunden (nur statische Platzhalter)
FIX:
- Collect stage outputs aus result.debug.stages[].output
- Store als stage_N_key dict
- Lookup: erst stage_outputs, dann cleaned_values
- Description: "Output aus Stage X (Basis-Analyse)"
- JSON-Werte automatisch serialisiert

BEISPIEL Pipeline-Wertetabelle:
┌──────────────────────────────────────────────┐
│ 📊 Verwendete Werte (8) (+3 ausgeblendet) 🔬│
│ ┌──────────────────────────────────────────┐ │
│ │ weight_aktuell  │ 85.2 kg   │ Gewicht  │ │
│ │ stage_1_body    │ {"bmi":...│ Output...│ │ ← Stage output!
│ │ stage_1_nutr... │ {"kcal"...│ Output...│ │
│ └──────────────────────────────────────────┘ │
└──────────────────────────────────────────────┘

AKTIVIERUNG Experten-Modus:
1. Analyse öffnen
2. "📊 Verwendete Werte" aufklappen
3. Button "🔬 Experten-Modus" klicken
4. Zeigt alle Platzhalter (auch leere stage outputs)

version: 9.8.0 (feature)
module: prompts 2.3.0, insights 1.6.0
2026-03-26 12:44:28 +01:00
15bd6cddeb feat: untruncated values + smart base prompt display (Issue #47)
All checks were successful
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
FEATURE: Volle Werte (nicht abgeschnitten)
- Backend holt ungekürzten Werte direkt von placeholder_resolver
- get_placeholder_example_values() statt debug.resolved_placeholders
- Debug bleibt gekürzt (100 chars), Metadata ungekürzt

FEATURE: Smart Display für Basis-Prompts
- Basis-Prompts mit JSON-Output: Nur Wertetabelle anzeigen
- JSON-Output in Collapsible "Technische Daten" verschoben
- Wertetabelle auto-expanded bei Basis-Prompts
- Pipeline + Text-Prompts: Wie bisher (Content + Wertetabelle)

UI: Bessere Wertetabelle
- Werte: word-break + max-width (400px) → kein Overflow
- Alle Spalten: verticalAlign top für bessere Lesbarkeit
- Platzhalter: nowrap (keine Umbrüche)

BEISPIEL:
┌─────────────────────────────────────────┐
│ ℹ️ Basis-Prompt Rohdaten                │
│ [Technische Daten anzeigen ▼]           │
│                                          │
│ 📊 Verwendete Werte (8) ▼  ← expanded  │
│ ┌──────────────────────────────────────┐│
│ │ Platzhalter │ Vollständiger Wert... ││
│ │ kcal_avg    │ 1427 kcal/Tag (Ø 30...││ ← ungekürzt
│ └──────────────────────────────────────┘│
└─────────────────────────────────────────┘

version: 9.7.0 (feature)
module: prompts 2.2.0, insights 1.5.0
2026-03-26 12:37:52 +01:00
4a2bebe249 fix: value table metadata + |d modifier + cursor insertion (Issues #47, #48)
All checks were successful
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
BUG: Wertetabelle wurde nicht angezeigt
FIX: enable_debug=true wenn save=true (für metadata collection)
- metadata wird nur gespeichert wenn debug aktiv
- jetzt: debug or save → metadata immer verfügbar

BUG: {{placeholder|d}} Modifier funktionierte nicht
ROOT CAUSE: catalog wurde bei Exception nicht zu variables hinzugefügt
FIX:
- variables['_catalog'] = catalog (auch wenn None)
- Warning-Log wenn catalog nicht geladen werden kann
- Debug warning wenn |d ohne catalog verwendet

BUG: Platzhalter in Pipeline-Stages am Ende statt an Cursor
FIX:
- stageTemplateRefs Map für alle Stage-Textareas
- onClick + onKeyUp tracking für Cursor-Position
- Insert at cursor: template.slice(0, pos) + placeholder + template.slice(pos)
- Focus + Cursor restore nach Insert

TECHNICAL:
- prompt_executor.py: Besseres Exception Handling für catalog
- UnifiedPromptModal.jsx: Refs für alle Template-Felder
- prompts.py: enable_debug=debug or save

version: 9.6.1 (bugfix)
module: prompts 2.1.1
2026-03-26 12:04:20 +01:00
c0a50dedcd feat: value table + {{placeholder|d}} modifier (Issue #47)
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
FEATURE #47: Wertetabelle nach KI-Analysen
- Migration 021: metadata JSONB column in ai_insights
- Backend sammelt resolved placeholders mit descriptions beim Speichern
- Frontend: Collapsible value table in InsightCard
  - Zeigt: Platzhalter | Wert | Beschreibung
  - Sortiert tabellarisch
  - Funktioniert für base + pipeline prompts

FEATURE #48: {{placeholder|d}} Modifier
- Syntax: {{weight_aktuell|d}} → "85.2 kg (Aktuelles Gewicht in kg)"
- resolve_placeholders() erkennt |d modifier
- Hängt description aus catalog an Wert
- Fein-granulare Kontrolle pro Platzhalter (nicht global)
- Optional: nur wo sinnvoll einsetzen

TECHNICAL:
- prompt_executor.py: catalog parameter durchgereicht
- execute_prompt_with_data() lädt catalog via get_placeholder_catalog()
- Catalog als _catalog in variables übergeben, in execute_prompt() extrahiert
- Base + Pipeline Prompts unterstützen |d modifier

EXAMPLE:
Template: "Gewicht: {{weight_aktuell|d}}, Alter: {{age}}"
Output:   "Gewicht: 85.2 kg (Aktuelles Gewicht in kg), Alter: 55"

version: 9.6.0 (feature)
module: prompts 2.1.0, insights 1.4.0
2026-03-26 11:52:26 +01:00
7daa2e40c7 fix: sleep quality calculation using wrong key (stage vs phase)
All checks were successful
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
BUG: sleep_avg_quality showed 0% despite valid sleep data
ROOT CAUSE: sleep_segments use 'phase' key, not 'stage'
FIX: Changed s.get('stage') to s.get('phase') in get_sleep_avg_quality()

version: 9.5.1 (bugfix)
module: prompts 2.0.1
2026-03-26 10:31:39 +01:00
a43a9f129f fix: sleep_avg_quality uses lowercase stage names
All checks were successful
Deploy Development / deploy (push) Successful in 47s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Problem: Schlafphasen werden lowercase gespeichert (deep, rem, light, awake),
aber get_sleep_avg_quality() prüfte Titlecase (Deep, REM) → 0% Match

Fix: Ändere Prüfung zu lowercase: ['deep', 'rem']

Jetzt wird {{sleep_avg_quality}} korrekt berechnet aus JSONB segments.

Quelle: backend/routers/sleep.py → phase_map speichert lowercase

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:22:55 +01:00
3ad1a19dce fix: calculate_age now handles PostgreSQL date objects
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Problem: dob Spalte ist DATE (PostgreSQL) → Python bekommt datetime.date,
nicht String → strptime() schlägt fehl → age = "unbekannt"

Fix: Prüfe isinstance(dob, str) und handle beide Typen:
- String → strptime()
- date object → direkt verwenden

Jetzt funktioniert {{age}} Platzhalter korrekt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:19:36 +01:00
a9114bc40a feat: implement missing placeholder functions (sleep, vitals, rest)
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Implementiert 6 fehlende Platzhalter-Funktionen die im Katalog waren
aber keine Berechnung hatten.

Neue Funktionen:
- get_sleep_avg_duration(7d) → "7.5h"
- get_sleep_avg_quality(7d) → "65% (Deep+REM)"
- get_rest_days_count(30d) → "5 Ruhetage"
- get_vitals_avg_hr(7d) → "58 bpm"
- get_vitals_avg_hrv(7d) → "45 ms"
- get_vitals_vo2_max() → "42.5 ml/kg/min"

Datenquellen:
- sleep_log (JSONB segments mit Deep/REM/Light/Awake)
- rest_days (Kraft/Cardio/Entspannung)
- vitals_baseline (resting_hr, hrv, vo2_max)

Jetzt in PLACEHOLDER_MAP registriert → sofort nutzbar.

Fixes: Platzhalter-Export zeigt jetzt alle Werte (statt "nicht verfügbar")

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:14:17 +01:00
555ff62b56 feat: global placeholder export with values (Settings page)
All checks were successful
Deploy Development / deploy (push) Successful in 45s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Zentraler Export aller verfügbaren Platzhalter mit aktuellen Werten.

Backend:
- GET /api/prompts/placeholders/export-values
  - Returns all placeholders organized by category
  - Includes resolved values for current profile
  - Includes metadata (description, example)
  - Flat list + categorized structure

Frontend SettingsPage:
- Button "📊 Platzhalter exportieren"
- Downloads: placeholders-{profile}-{date}.json
- Shows all 38+ placeholders with current values
- Useful for:
  - Understanding available data
  - Debugging prompt templates
  - Verifying placeholder resolution

Frontend api.js:
- exportPlaceholderValues()

Export Format:
{
  "export_date": "2026-03-26T...",
  "profile_id": "...",
  "count": 38,
  "all_placeholders": { "name": "Lars", ... },
  "placeholders_by_category": {
    "Profil": [...],
    "Körper": [...],
    ...
  }
}

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 10:05:11 +01:00
7f94a41965 feat: batch import/export for prompts (Issue #28 Debug B)
All checks were successful
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Dev→Prod Sync in 2 Klicks: Export → Import

Backend:
- GET /api/prompts/export-all → JSON mit allen Prompts
- POST /api/prompts/import?overwrite=true/false → Import + Create/Update
  - Returns: created, updated, skipped counts
  - Validates JSON structure
  - Handles stages JSON conversion

Frontend AdminPromptsPage:
- Button "📦 Alle exportieren" → downloads all-prompts-{date}.json
- Button "📥 Importieren" → file upload dialog
  - User-Prompt: Überschreiben? Ja/Nein
  - Success-Message mit Statistik (created/updated/skipped)

Frontend api.js:
- exportAllPrompts()
- importPrompts(data, overwrite)

Use Cases:
1. Backup: Prompts als JSON sichern
2. Dev→Prod: Auf dev.mitai entwickeln → exportieren → auf mitai.jinkendo importieren
3. Versionierung: Prompts in Git speichern

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:44:08 +01:00
97e57481f9 fix: Analysis page now uses unified prompt executor (Issue #28)
All checks were successful
Deploy Development / deploy (push) Successful in 51s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
BREAKING: Analysis page switched from old /insights/run to new /prompts/execute

Changes:
- Backend: Added save=true parameter to /prompts/execute
  - When enabled, saves final output to ai_insights table
  - Extracts content from pipeline output (last stage)
- Frontend api.js: Added save parameter to executeUnifiedPrompt()
- Frontend Analysis.jsx: Switched from api.runInsight() to api.executeUnifiedPrompt()
  - Transforms new result format to match InsightCard expectations
  - Pipeline outputs properly extracted and displayed

Fixes: PIPELINE_MASTER responses (old template being sent to AI)
The old /insights/run endpoint used raw template field, which for the
legacy "pipeline" prompt was literally "PIPELINE_MASTER". The new
executor properly handles stages and data processing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:38:58 +01:00
811ba8b3dc fix: convert Decimal to float before multiplication in protein targets
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- get_protein_ziel_low: float(weight) * 1.6
- get_protein_ziel_high: float(weight) * 2.2

Fixes TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:23:50 +01:00
dfaf24d74c fix: correct SQL column names in placeholder_resolver
All checks were successful
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- caliper_summary: use body_fat_pct (not bf_jpl)
- circ_summary: use c_chest, c_waist, c_hip (not brust, taille, huefte)
- get_latest_bf: use body_fat_pct for consistency

Fixes SQL errors when running base prompts that feed pipeline prompts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:10:55 +01:00
0f2b85c6de fix: reconstruct missing placeholders + fix SQL column names
All checks were successful
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Added missing placeholders:
- caliper_summary, circ_summary (body measurements)
- goal_weight, goal_bf_pct (goals from profile)
- nutrition_days (count of nutrition entries)
- protein_ziel_low/high (calculated from weight)

Fixed SQL errors:
- protein → protein_g
- fat → fat_g
- carb → carbs_g

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 09:03:35 +01:00
f4d1fd4de1 feat: add activity_detail placeholder for detailed activity logs
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- New placeholder: {{activity_detail}} returns formatted activity log
- Shows last 20 activities with date, type, duration, kcal, HR
- Makes activity analysis prompts work properly

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:20:18 +01:00
ba92d66880 fix: remove {{ }} from placeholder keys before resolution
All checks were successful
Deploy Development / deploy (push) Successful in 46s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 12s
Placeholder resolver returns keys with {{ }} wrappers,
but resolve_placeholders expects clean keys.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:17:22 +01:00
afc70b5a95 fix: integrate placeholder resolver + JSON unwrapping (Issue #28)
All checks were successful
Deploy Development / deploy (push) Successful in 44s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Backend: integrate get_placeholder_example_values in execute_prompt_with_data
- Backend: now provides BOTH raw data AND processed placeholders
- Backend: unwrap Markdown-wrapped JSON (```json ... ```)
- Fixes old-style prompts that expect name, weight_trend, caliper_summary

Resolves unresolved placeholders issue.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:14:41 +01:00
84dad07e15 fix: show debug info on errors + prompt export function
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
- Frontend: debug viewer now shows even when test fails
- Frontend: export button to download complete prompt config as JSON
- Backend: attach debug info to JSON validation errors
- Backend: include raw output and length in error details

Users can now debug failed prompts and export configs for analysis.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:07:34 +01:00
7f2ba4fbad feat: debug system for prompt execution (Issue #28)
All checks were successful
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Backend: debug mode in prompt_executor with placeholder tracking
- Backend: show resolved/unresolved placeholders, final prompts, AI responses
- Frontend: test button in UnifiedPromptModal for saved prompts
- Frontend: debug output viewer with JSON preview
- Frontend: wider placeholder example fields in PlaceholderPicker

Resolves pipeline execution debugging issues.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 08:01:33 +01:00
7be7266477 feat: unified prompt executor - Phase 2 complete (Issue #28)
All checks were successful
Deploy Development / deploy (push) Successful in 52s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Backend:
- prompt_executor.py: Universal executor for base + pipeline prompts
  - Dynamic placeholder resolution
  - JSON output validation
  - Multi-stage parallel execution (sequential impl)
  - Reference and inline prompt support
  - Data loading per module (körper, ernährung, training, schlaf, vitalwerte)

Endpoints:
- POST /api/prompts/execute - Execute unified prompts
- POST /api/prompts/unified - Create unified prompts
- PUT /api/prompts/unified/{id} - Update unified prompts

Frontend:
- api.js: executeUnifiedPrompt, createUnifiedPrompt, updateUnifiedPrompt

Next: Phase 3 - Frontend UI consolidation
2026-03-25 14:52:24 +01:00
33653fdfd4 fix: migration 020 - make template column nullable
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 14s
Issue: template has NOT NULL constraint but pipeline-type prompts
don't use template (they use stages JSONB instead).

Solution: ALTER COLUMN template DROP NOT NULL before inserting
pipeline configs into ai_prompts.
2026-03-25 14:45:53 +01:00
95dcf080e5 fix: migration 020 SQL syntax - correlated subquery issue
All checks were successful
Deploy Development / deploy (push) Successful in 42s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Fixed Step 3 pipeline_configs migration:
- Simplified JSONB aggregation logic
- Properly scope pc alias in subqueries
- Use UNNEST with FROM clause for array expansion

Previous version had correlation issues with nested subqueries.
2026-03-25 12:58:02 +01:00
2e0838ca08 feat: unified prompt system migration schema (Issue #28 Phase 1)
All checks were successful
Deploy Development / deploy (push) Successful in 50s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
- Migration 020: Add type, stages, output_format columns to ai_prompts
- Migrate existing prompts to 1-stage pipeline format
- Migrate pipeline_configs into ai_prompts as multi-stage pipelines
- Add UnifiedPrompt Pydantic models for new API
- Backup pipeline_configs table (keep during transition)

Schema structure:
- type: 'base' (reusable) or 'pipeline' (multi-stage)
- stages: JSONB array [{stage:1, prompts:[{source, slug, template, output_key, output_format}]}]
- output_format: 'text' or 'json'
- output_schema: JSON validation schema (optional)

Next: Backend executor + Frontend UI consolidation
2026-03-25 10:43:10 +01:00
6627b5eee7 feat: Pipeline-System - Backend Infrastructure (Issue #28, Phase 1)
All checks were successful
Deploy Development / deploy (push) Successful in 43s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 13s
Implementiert konfigurierbare mehrstufige Analysen. Admins können
mehrere Pipeline-Konfigurationen erstellen mit unterschiedlichen
Modulen, Zeiträumen und Prompts.

**Backend:**
- Migration 019: pipeline_configs Tabelle + ai_prompts erweitert
- Pipeline-Config Models: PipelineConfigCreate, PipelineConfigUpdate
- Pipeline-Executor: refactored für config-basierte Ausführung
- CRUD-Endpoints: /api/prompts/pipeline-configs (list, create, update, delete, set-default)
- Reset-to-Default: /api/prompts/{id}/reset-to-default für System-Prompts

**Features:**
- 3 Seed-Configs: "Alltags-Check" (default), "Schlaf & Erholung", "Wettkampf-Analyse"
- Dynamische Platzhalter: {{stage1_<slug>}} für alle Stage-1-Ergebnisse
- Backward-compatible: /api/insights/pipeline ohne config_id nutzt default

**Dateien:**
- backend/migrations/019_pipeline_system.sql
- backend/models.py (PipelineConfigCreate, PipelineConfigUpdate)
- backend/routers/insights.py (analyze_pipeline refactored)
- backend/routers/prompts.py (Pipeline-Config CRUD + Reset-to-Default)

**Nächste Schritte:**
- Frontend: Pipeline-Config Dialog + Admin-UI
- Design: Mobile-Responsive + Icons

Issue #28 Progress: Backend 3/3  | Frontend 0/3 🔲 | Design 0/3 🔲

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 09:42:28 +01:00
5e7ef718e0 fix: placeholder picker improvements + insight display names (Issue #28)
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 13s
Backend:
- get_placeholder_catalog(): grouped placeholders with descriptions
- Returns {category: [{key, description, example}]} format
- Categories: Profil, Körper, Ernährung, Training, Schlaf, Vitalwerte, Zeitraum

Frontend - Placeholder Picker:
- Grouped by category with visual separation
- Search/filter across keys and descriptions
- Hover effects for better UX
- Insert at cursor position (not at end)
- Shows: key + description + example value
- 'Keine Platzhalter gefunden' message when filtered

Frontend - Insight Display Names:
- InsightCard receives prompts array
- Finds matching prompt by scope/slug
- Shows prompt.display_name instead of hardcoded SLUG_LABELS
- History tab also shows display_name in group headers
- Fallback chain: display_name → SLUG_LABELS → scope

User-facing improvements:
✓ Platzhalter zeigen echte Daten statt Zahlen
✓ Durchsuchbar + filterbar
✓ Einfügen an Cursor-Position
✓ Insights zeigen custom Namen (z.B. '🍽️ Meine Ernährung')

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 06:44:22 +01:00