Compare commits
99
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ff0cd43ee | ||
|
|
68ae82a5e5 | ||
|
|
b408e8fd7a | ||
|
|
ae0acf9ad2 | ||
|
|
1aeb7136df | ||
|
|
b59b7eae16 | ||
|
|
4ad62b6e38 | ||
|
|
4b33b17b2d | ||
|
|
b824115e9b | ||
|
|
c08c7c65b5 | ||
|
|
1527a430b9 | ||
|
|
fe3633ba8b | ||
|
|
b537750671 | ||
|
|
0431c9e160 | ||
|
|
f49de9c971 | ||
|
|
1bdb039a91 | ||
|
|
36d51d4c33 | ||
|
|
ad7c7ad4e5 | ||
|
|
5fc839afbc | ||
|
|
d4a193607f | ||
|
|
95d365d9fa | ||
|
|
f10c28e5cd | ||
|
|
5ea225ec6b | ||
|
|
2e22a7c8e0 | ||
|
|
32b28a93f3 | ||
|
|
6c7c24e887 | ||
|
|
3181cc126d | ||
|
|
35fe31774b | ||
|
|
90e8f51566 | ||
|
|
7e5ef4561a | ||
|
|
53f2b027cc | ||
|
|
9cee862c32 | ||
|
|
0b203489f7 | ||
|
|
1c67a50ce4 | ||
|
|
87d9fa9b65 | ||
|
|
4b9374765b | ||
|
|
b629f192ac | ||
|
|
313d613b7c | ||
|
|
7265cd5a01 | ||
|
|
5e5f4ca8d4 | ||
|
|
f0e581a9f5 | ||
|
|
cd457e3ea0 | ||
|
|
e9bf5bd1a5 | ||
|
|
3468b2066e | ||
|
|
a1e4ad66df | ||
|
|
85fccdd093 | ||
|
|
19bbcdaf50 | ||
|
|
cec96ae473 | ||
|
|
53f1c7161f | ||
|
|
89c6780294 | ||
|
|
3f130aa8ad | ||
|
|
69ce3f6975 | ||
|
|
dccb065181 | ||
|
|
e828a5da32 | ||
|
|
5bca5ef9eb | ||
|
|
5ed06002d9 | ||
|
|
b8f65e04c5 | ||
|
|
f3710ac0a1 | ||
|
|
6ab2f20f08 | ||
|
|
a4e73c830f | ||
|
|
63c99b0ec5 | ||
|
|
d448c3191f | ||
|
|
8a4be795f4 | ||
|
|
a49987408b | ||
|
|
f36a747efa | ||
|
|
de9fdf3ac0 | ||
|
|
df93da9a03 | ||
|
|
de939481ba | ||
|
|
6d130a7e09 | ||
|
|
b2fbf6b4af | ||
|
|
ca2adbd55e | ||
|
|
ad051c015f | ||
|
|
b464047c3a | ||
|
|
7203c871fc | ||
|
|
480890d0c6 | ||
|
|
8f1dad53ab | ||
|
|
044ce2ee60 | ||
|
|
f63b09fc9c | ||
|
|
713a344d17 | ||
|
|
1d94c2ebf1 | ||
|
|
a152218c45 | ||
|
|
4ef3f00e6b | ||
|
|
3c12363b8f | ||
|
|
07e147bc76 | ||
|
|
18547613ea | ||
|
|
48d51c07c5 | ||
|
|
3b483346de | ||
|
|
e0ddfa6ce5 | ||
|
|
ee22b22970 | ||
|
|
c1bf9279ad | ||
|
|
97efe66306 | ||
|
|
8d5f0b533c | ||
|
|
800189ff8f | ||
|
|
3be7606d90 | ||
|
|
ca3a9c6fa4 | ||
|
|
5692931d07 | ||
|
|
98b279fa89 | ||
|
|
1e7941f57b | ||
|
|
0adf20c9e1 |
No files matched your search
@@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
|
**Plattform-Rechtstexte (P-01, 0.8.95–0.8.96):** Admin-Editor mit **Abschnitts- und Vollvorschau** (Markdown); fortlaufende Abschnittsnummerierung in der Anzeige/PDF (Darstellung, nicht DB-persistent).
|
||||||
|
|
||||||
**Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**.
|
**Parallel weiter relevant:** **Trainingsplan Phasen & Streams** (Migration **063**, Coach + Planung **0.8.137–0.8.140**; Handover **`docs/HANDOVER.md`** §3); **Trainingsrahmenprogramm** (036–037), **Progressionsgraph** (032–034) — siehe **`TRAINING_FRAMEWORK_SPEC.md`**. **Planungs-KI Progressionsgraph** (Roadmap-first, Auto-Optimierung, Katalog-Kontext **0.8.233**, **F15** Match-Dialog + getrennte Pfad-QS lokal): Ist-Doku **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`**, Handover **`docs/HANDOVER.md`** §2.8.
|
||||||
|
|
||||||
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
|
**Referenz:** [`library/FEATURES_DELIVERED_2026-Q2.md`](library/FEATURES_DELIVERED_2026-Q2.md) Abschnitt 12 · Medien-Norm: [`technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md`](technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md) (inkl. **Abschnitt 11 Inline-Medien**, umgesetzt) · **Fachlicher Nutzerüberblick:** [`../../docs/FACHLICHE_NUTZERFUNKTIONEN.md`](../../docs/FACHLICHE_NUTZERFUNKTIONEN.md)
|
||||||
|
|
||||||
|
|||||||
@@ -465,6 +465,8 @@ skill_level_definitions (
|
|||||||
|
|
||||||
**Fachliche Grenze aktuell:** Mehrere gleichwertige „Pakete“ paralleler Alternativen sind **modellierbar** (mehrere ausgehende Kanten), aber noch **nicht** über eine dedizierte „Alternativgruppe“ in der UI trivial pflegbar; siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4.
|
**Fachliche Grenze aktuell:** Mehrere gleichwertige „Pakete“ paralleler Alternativen sind **modellierbar** (mehrere ausgehende Kanten), aber noch **nicht** über eine dedizierte „Alternativgruppe“ in der UI trivial pflegbar; siehe `technical/TRAINING_FRAMEWORK_SPEC.md` §4.
|
||||||
|
|
||||||
|
**KI-Planung (Workbench, Stand 0.8.233):** Am Graph können Trainer neben Kanten ein **`planning_roadmap`**-Artefakt (Curriculum-Stufen) und **`planning_catalog_context`** (Primärfokus, Stilrichtung, Trainingsstil, Zielgruppe aus den Katalog-Dimensionen §1) pflegen. Die Roadmap-first-Pipeline matcht Übungen pro Stufe; Didaktik und Reihenfolge kommen aus Roadmap + QS, nicht aus Technik-Hardcoding. **Geplant (H1):** Katalog-Dimensionen zusätzlich als **Prompt-Snippets** in LLM-Aufrufen (Priorität Primärfokus → Trainingsstil → Zielgruppe → Stilrichtung) — **`docs/architecture/PLANNING_CATALOG_PROMPT_SNIPPETS.md`**. Technische Details: **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`**. Für **Trainingsplanung** (Einheit, Abschnitt, Rahmen-Slot) gelten dieselben Katalog- und Retrieval-Bausteine mit anderen Scopes — Phase G, siehe Roadmap **`PLANNING_KI_ROADMAP.md`**.
|
||||||
|
|
||||||
### Trainingsrahmen‑Vorlage (Rahmenprogramm, CURR‑002 Stufe 2 / CURR‑009)
|
### Trainingsrahmen‑Vorlage (Rahmenprogramm, CURR‑002 Stufe 2 / CURR‑009)
|
||||||
|
|
||||||
**Abgrenzung:** Eine **einzeilige** Trainingsplan‑Mikrovorlage (`training_plan_template`) strukturiert **eine** Einheit; das **Rahmenprogramm** ist eine **eigene Bibliotheksentität** mit **sortierten Session‑Slots**, **mindestens einem** formulierten **Entwicklungsziel** (Zielliste, **CURR‑011**) und einem **vollständigen Ablauf** pro Slot (**`training_unit_sections` + `training_unit_section_items`** wie bei geplanten Einheiten — **CURR‑010** inhaltlich, technisch seit **037** identisch zur Planungsstruktur). Der persistierte **Progressionsgraph** zwischen Übungen bleibt **optional** (**CURR‑013**).
|
**Abgrenzung:** Eine **einzeilige** Trainingsplan‑Mikrovorlage (`training_plan_template`) strukturiert **eine** Einheit; das **Rahmenprogramm** ist eine **eigene Bibliotheksentität** mit **sortierten Session‑Slots**, **mindestens einem** formulierten **Entwicklungsziel** (Zielliste, **CURR‑011**) und einem **vollständigen Ablauf** pro Slot (**`training_unit_sections` + `training_unit_section_items`** wie bei geplanten Einheiten — **CURR‑010** inhaltlich, technisch seit **037** identisch zur Planungsstruktur). Der persistierte **Progressionsgraph** zwischen Übungen bleibt **optional** (**CURR‑013**).
|
||||||
|
|||||||
@@ -8,7 +8,10 @@
|
|||||||
|
|
||||||
**Ist-Stand API (Superadmin):**
|
**Ist-Stand API (Superadmin):**
|
||||||
- `GET /api/admin/ai-prompts`, `GET /api/admin/ai-prompts/{id}`, `PUT …`, `POST …/preview`, `POST …/reset-template`, `GET /api/admin/ai-prompts/catalog/placeholders`
|
- `GET /api/admin/ai-prompts`, `GET /api/admin/ai-prompts/{id}`, `PUT …`, `POST …/preview`, `POST …/reset-template`, `GET /api/admin/ai-prompts/catalog/placeholders`
|
||||||
- Spalte **`openrouter_model`** (Migration **070**): Optional pro Prompt-Zeile; OpenRouter **`model`**-Parameter; **`NULL`/leer ⇒ `OPENROUTER_MODEL`** aus der Umgebung.
|
- Spalte **`openrouter_model`** (Migration **070**): Optional pro Prompt-Zeile; OpenRouter **`model`**-Parameter. Leer ⇒ Plattform-Standard.
|
||||||
|
- **Plattform-Standard** (Migration **097**, `platform_ai_settings.openrouter_model`): Superadmin unter `/admin/openrouter`. `GET/PUT /api/admin/openrouter/settings`, Katalog `GET /api/admin/openrouter/models`. Leer ⇒ **`OPENROUTER_MODEL`** aus der Umgebung.
|
||||||
|
- Auflösung: Prompt-Override, sonst Aufgabengruppe (`ai_prompts.model_role`, Migration **098**: `reasoning` Denken, `drafting` Formulieren, `matching` Zuordnen), sonst Datenbank-Standard, sonst Umgebung.
|
||||||
|
- Gruppenmodelle: `GET/PUT /api/admin/openrouter/roles` und `PUT /api/admin/openrouter/prompts/{id}/role`.
|
||||||
|
|
||||||
**Autor:** Claude Code
|
**Autor:** Claude Code
|
||||||
**Vorbild:** Mitai Jinkendo Issue #53 + `backend/routers/prompts.py` + Placeholder-System
|
**Vorbild:** Mitai Jinkendo Issue #53 + `backend/routers/prompts.py` + Placeholder-System
|
||||||
|
|||||||
@@ -271,6 +271,7 @@ exercise_variants (id, exercise_id, name, description, ...)
|
|||||||
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
|
exercise_media (id, exercise_id, media_asset_id NULL FK, embed_url, file_path, …)
|
||||||
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
|
media_assets (id, sha256, visibility, club_id, lifecycle_state, copyright_notice, storage_key, …)
|
||||||
platform_media_storage (id, local_relative_root, …)
|
platform_media_storage (id, local_relative_root, …)
|
||||||
|
platform_ai_settings (id = 1, openrouter_model NULL = OPENROUTER_MODEL, …) -- Migration 097
|
||||||
```
|
```
|
||||||
|
|
||||||
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
|
### Trainingsrahmenprogramm Bibliothek (Migrationen **035–036**)
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Designprinzipien — verschoben
|
||||||
|
|
||||||
|
Die **Jinkendo-Produktfamilie Designprinzipien** (Index + Shinkan-Serie) liegen nicht mehr hier.
|
||||||
|
|
||||||
|
**Neuer Standort (Shinkan-Serie):** [docs/jinkendo-family/design-principles/DESIGN_PRINCIPLES_INDEX.md](../../../docs/jinkendo-family/design-principles/DESIGN_PRINCIPLES_INDEX.md)
|
||||||
|
|
||||||
|
**Mitai-Serie:** [mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md)
|
||||||
|
|
||||||
|
**Abgleich:** [docs/jinkendo-family/DESIGN_PRINCIPLES_ALIGNMENT.md](../../../docs/jinkendo-family/DESIGN_PRINCIPLES_ALIGNMENT.md)
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# Produktions-Deployments (Raspberry Pi + llm-node)
|
||||||
|
|
||||||
|
Stand: 2026-10-29
|
||||||
|
|
||||||
|
**Seit dem Cutover am 2026-10-29 ist llm-node die einzige Prod.** Der Reverse-Proxy für `shinkan.jinkendo.de` zeigt auf llm-node. Nur `deploy-prod-llm-node.yml` startet bei Push auf `main`; `deploy-prod.yml` (Pi) ist nur noch per „Run workflow“ startbar und dient als Rückfallweg (siehe „Rückfall auf den Pi“). Die Tabelle beschreibt beide Seiten.
|
||||||
|
|
||||||
|
Backup, Recovery und Erstbefüllung der llm-node-DB: `RECOVERY_CONTRACT.md`.
|
||||||
|
|
||||||
|
| | Raspberry Pi (alt) | llm-node (neu) |
|
||||||
|
|---|---|---|
|
||||||
|
| Workflow | `.gitea/workflows/deploy-prod.yml` | `.gitea/workflows/deploy-prod-llm-node.yml` |
|
||||||
|
| Workflow-Name | `Deploy Production` | `Deploy Production llm-node` |
|
||||||
|
| Host | 192.168.2.49, `raspberrypi5`, aarch64 | 192.168.2.144, `llm-node`, x86_64 |
|
||||||
|
| Runner | `Raspi5-Paperless`, Label `ubuntu-latest` (Host-Modus) | `llm-node-runner`, Label `linux_host` (Host-Modus) |
|
||||||
|
| Deploy-Verzeichnis | `/home/lars/docker/shinkan` | `/home/llmadmin/docker/shinkan-prod` |
|
||||||
|
| Compose | `docker-compose.yml`, Projekt `shinkan` (Verzeichnisname) | `docker-compose.yml` + `docker-compose.llm-node.yml`, Projekt `shinkan-prod` |
|
||||||
|
| Konfiguration | `/home/lars/docker/shinkan/.env` | `/etc/shinkan/prod.env` (Workflow-Variable `ENV_FILE`) |
|
||||||
|
| Datenbank | Volume `shinkan_shinkan-db-data` auf dem Pi | Volume `shinkan-prod_shinkan-db-data` auf llm-node |
|
||||||
|
| Medien (Host) | `SHINKAN_MEDIA_HOST` laut Pi-`.env` | `/srv/shinkan/prod/media` (NFSv4 von `192.168.2.63:/volume1/shinkan-media/prod`) |
|
||||||
|
| Medien (Container) | `/app/media` | `/app/media` |
|
||||||
|
| Medienbereinigung | `retention-cron` läuft bei jedem Lauf mit; nach Cutover gestoppt | an (`MEDIA_RETENTION: enabled`) |
|
||||||
|
| Ports | 3003, 127.0.0.1:8003, 127.0.0.1:5434 | 3003, 127.0.0.1:8003, 127.0.0.1:5434 |
|
||||||
|
| Auslösen | nur Gitea „Run workflow“ (`workflow_dispatch`) | Push auf `main` oder Gitea „Run workflow“ |
|
||||||
|
|
||||||
|
Die Runner-Labels sind am 2026-10-29 aus den `.runner`-Dateien beider Hosts abgelesen worden (act_runner v0.2.11). Jeder Workflow prüft im ersten Schritt Hostname und Architektur und bricht auf einem fremden Runner ab. Wer Labels an einem Runner ändert, muss beide Workflows mitprüfen; `ubuntu-latest` darf nicht auf llm-node, `linux_host` nicht auf dem Pi registriert werden.
|
||||||
|
|
||||||
|
Das llm-node-Deployment braucht vom Pi nichts: Code kommt aus dem Gitea auf llm-node selbst, DB und Konfiguration liegen lokal, Medien direkt auf dem NAS.
|
||||||
|
|
||||||
|
## Server-Voraussetzungen auf llm-node
|
||||||
|
|
||||||
|
Außerhalb des Repos eingerichtet und nicht Teil des Workflows:
|
||||||
|
|
||||||
|
- `/etc/shinkan/prod.env`, lesbar für `llmadmin` (Runner-User), Pflicht: `DB_PASSWORD`. `SHINKAN_MEDIA_HOST` und `MEDIA_ROOT` sind optional; wenn gesetzt, müssen sie `/srv/shinkan/prod/media` bzw. `/app/media` sein. `COMPOSE_PROFILES` darf dort nicht stehen.
|
||||||
|
- NFS-Mount `/srv/shinkan/prod/media`, dauerhaft und beim Boot abgesichert. Erreichbarkeit und Monitoring des NAS liegen beim Server, nicht im Deployment.
|
||||||
|
- `/home/llmadmin/docker/shinkan-prod`; das Git-Checkout legt der Workflow beim ersten Lauf selbst an.
|
||||||
|
|
||||||
|
## docker-compose.llm-node.yml
|
||||||
|
|
||||||
|
Override nur für llm-node; Pi und Dev nutzen ihn nicht. Alle Compose-Aufrufe im Workflow (build, up, rm, ps, logs) laufen als
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -p shinkan-prod -f docker-compose.yml -f docker-compose.llm-node.yml --env-file /etc/shinkan/prod.env ...
|
||||||
|
```
|
||||||
|
|
||||||
|
- Ersetzt den Medien-Mount von `backend` und `retention-cron` durch einen Bind-Mount `/srv/shinkan/prod/media` → `/app/media` mit `create_host_path: false`. Ist der Mount nicht da, startet der Container nicht, statt Medien auf die lokale Platte zu schreiben.
|
||||||
|
- Hängt `retention-cron` an das Profil `media-retention`. Ohne Profil wird der Dienst weder gebaut noch gestartet.
|
||||||
|
|
||||||
|
## Ablauf je Lauf (llm-node)
|
||||||
|
|
||||||
|
1. Runner-Guard (`llm-node`/`x86_64`)
|
||||||
|
2. `ENV_FILE` prüfen: lesbar, `DB_PASSWORD` gesetzt, kein `COMPOSE_PROFILES`, Medienwerte passend. Es werden keine Werte ausgegeben.
|
||||||
|
3. `git fetch origin main` + `git reset --hard origin/main` im Deploy-Verzeichnis
|
||||||
|
4. `build --no-cache` und `up -d --remove-orphans`. Bei `MEDIA_RETENTION: disabled` wird ein noch vorhandener `retention-cron` entfernt.
|
||||||
|
5. Healthchecks mit Wiederholung (bis ca. 3 min je Prüfung):
|
||||||
|
- `127.0.0.1:8003/api/version`
|
||||||
|
- `127.0.0.1:8003/api/health/ready` mit `status=ready`, `database=true`, `schema_complete=true` (HTTP 200 allein reicht nicht)
|
||||||
|
- `127.0.0.1:3003/api/version` und `127.0.0.1:3003/api/health/ready` (gleiche Bedingung, über Frontend-Nginx)
|
||||||
|
- `127.0.0.1:3003/`
|
||||||
|
|
||||||
|
Bei Fehler: `compose ps` und Backend-Logs, Lauf rot.
|
||||||
|
|
||||||
|
## Medienbereinigung
|
||||||
|
|
||||||
|
Pi und llm-node nutzen denselben Medienbestand, aber getrennte Datenbanken. Eine Bereinigung auf einer Seite kann Dateien löschen, die die andere Datenbank noch referenziert. Deshalb darf immer nur eine Seite bereinigen.
|
||||||
|
|
||||||
|
Seit 0.8.247 bereinigt llm-node (`MEDIA_RETENTION: enabled`): Der Lauf baut und startet `retention-cron` mit Profil `media-retention`. Voraussetzung: Der Pi-`retention-cron` ist gestoppt.
|
||||||
|
|
||||||
|
Abschalten: `MEDIA_RETENTION: disabled` setzen und über `develop` → `main` ausrollen; der Lauf entfernt den Container.
|
||||||
|
|
||||||
|
Die Bereinigungslogik (`backend/scripts/media_retention_scheduler.py`, täglich 03:00 Europe/Berlin, kein Löschen beim Start) ist auf beiden Seiten dieselbe.
|
||||||
|
|
||||||
|
## Pi-Deployment (abgeschaltet)
|
||||||
|
|
||||||
|
Seit 0.8.247 hat `deploy-prod.yml` nur noch `on: workflow_dispatch`; ein Push oder Merge auf `main` startet es nicht. Der Pi-Runner bleibt aktiv, er bedient `Deploy Development` und `Test Suite`.
|
||||||
|
|
||||||
|
Nach dem Cutover auf dem Pi stoppen (manuell, nicht Teil eines Workflows):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/lars/docker/shinkan && docker compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
Das DB-Volume `shinkan_shinkan-db-data` bleibt dabei erhalten.
|
||||||
|
|
||||||
|
`test.yml` läuft nur für `develop` gegen Dev und hängt an keinem Prod-Workflow. Prod prüfen allein die Healthchecks des Deploy-Workflows. (Bis 0.8.246 startete `test.yml` nach `Deploy Production` per `workflow_run`. Die Weiche über `workflow_run.name` griff in Gitea nicht, und repariert hätten die Integrationstests in die Prod-DB geschrieben.)
|
||||||
|
|
||||||
|
### Rückfall auf den Pi
|
||||||
|
|
||||||
|
1. In `deploy-prod-llm-node.yml` `MEDIA_RETENTION: disabled` setzen und ausrollen; nie beide Bereinigungen gleichzeitig.
|
||||||
|
2. Pi-DB auf den aktuellen Stand bringen: Sie ist seit dem Cutover veraltet.
|
||||||
|
3. Gitea → Actions → `Deploy Production` → „Run workflow“ (Branch `main`).
|
||||||
|
4. Reverse-Proxy zurück auf den Pi.
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
# Shinkan Backup & Recovery – Schnittstelle zum Backup-Orchestrator
|
||||||
|
|
||||||
|
Stand: 2026-10-29 · Status: **Entwurf zur Abstimmung, nichts umgesetzt**
|
||||||
|
|
||||||
|
Dieses Dokument legt fest, wie der Backup-Orchestrator (`pi-backup-orchestrator`, eigenes Projekt) und Shinkan bei Backup, Wiederherstellung und Restore-Test zusammenarbeiten. Es richtet sich an den Orchestrator-Agenten und an die Umsetzung der Shinkan-Skripte.
|
||||||
|
|
||||||
|
Grundsatz: **Der Orchestrator weiß, wann und wohin gesichert wird. Shinkan weiß, wie die eigene Datenbank sicher eingespielt und geprüft wird.** Der Orchestrator ruft Shinkan-Skripte auf und wertet Exit-Code und JSON aus. Shinkan-Interna (Migrationen, Sessions, Medienpfade, Healthchecks) stehen nicht im Orchestrator.
|
||||||
|
|
||||||
|
Verwandt: `PROD_DEPLOYMENTS.md` (Deployments Pi + llm-node), `MEDIA_ASSETS_AND_ARCHIVE_SPEC.md` (Medien-Lifecycle).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Ist-Stand (geprüft am 2026-10-29, nur lesend)
|
||||||
|
|
||||||
|
| Punkt | Stand |
|
||||||
|
|---|---|
|
||||||
|
| Orchestrator | `pi-backup-orchestrator` v0.3 auf dem Pi, Timer `backup-orchestrator-daily` täglich 05:30, Job `shinkan-prod-db` (Phase 10, kritisch), danach `nas-data` (Phase 20) |
|
||||||
|
| Dump | `pg_dump` im Container `shinkan-db-prod`, **Plain SQL**, PostgreSQL 16.12, ca. 1,2 MB, 94 Tabellen |
|
||||||
|
| Ablage | `/media/lars/paperless/db-backup/shinkan-prod.sql` auf der **lokalen NVMe** des Pi, fester Dateiname (bis 2026-10-28 mit Zeitstempel); auf das NAS über `nas-data` |
|
||||||
|
| Migrationen | Tabelle `schema_migrations(id, migration, executed_at)`; `migration` = Dateiname ohne `.sql`, z. B. `096_login_lockout_and_totp`. Maßgeblich ist `backend/run_migrations.py` (läuft beim Backend-Start). Die Variante in `db_init.py` (Spalte `filename`) wird beim Start nicht genutzt. |
|
||||||
|
| Medien | Gemeinsamer Bestand auf dem NAS (`192.168.2.63:/volume1/shinkan-media/prod`), im Container `/app/media`. `media_assets.storage_key` relativ (`library/…`) mit `sha256` und `byte_size`; ältere `exercise_media.file_path` als `/media/<storage_key>` |
|
||||||
|
| Ziel-Prod | llm-node, Compose-Projekt `shinkan-prod`, `docker-compose.yml` + `docker-compose.llm-node.yml`, Konfiguration `/etc/shinkan/prod.env`, Container `shinkan-db-prod` (Postgres nur `127.0.0.1:5434`) |
|
||||||
|
|
||||||
|
## 2. Begriffe
|
||||||
|
|
||||||
|
- **Backup-Satz:** Dump + Prüfsumme + Backup-Manifest + Medien-Manifest, alle mit demselben Zeitstempel. Nur ein vollständiger Satz gilt als Backup.
|
||||||
|
- **Ziel (target):** benannte, fest im Skript hinterlegte Umgebung. Kein freies Zusammenbauen von Pfaden über Parameter.
|
||||||
|
|
||||||
|
| target | Host | Zweck | Schreibt in DB |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `pi-prod` | raspberrypi5 | Manifest zum bestehenden Pi-Dump | nein (nur lesend) |
|
||||||
|
| `llm-prod` | llm-node | Manifest, Recovery, Erstbefüllung | ja, nur `restore` |
|
||||||
|
| `llm-restoretest` | llm-node | Restore-Test, wird danach entfernt | ja, nur eigene Wegwerf-DB |
|
||||||
|
|
||||||
|
Jedes Skript prüft wie die Workflows Hostname und Architektur und bricht auf einem fremden Host ab. Restore auf `pi-prod` gibt es nicht.
|
||||||
|
|
||||||
|
## 3. Schnittstelle
|
||||||
|
|
||||||
|
Alle Skripte liegen im Shinkan-Repo unter `scripts/ops/` und laufen auf dem Host der Zielumgebung, aus dem jeweiligen Deploy-Checkout. Die Code-Version, gegen die geprüft wird, ist damit immer die dort deployte.
|
||||||
|
|
||||||
|
Gemeinsam für alle Befehle:
|
||||||
|
|
||||||
|
- Ergebnis als JSON in die Datei `--result <pfad>` (Orchestrator legt den Pfad fest, z. B. im Run-Log-Verzeichnis). Auf stdout nur menschenlesbares Log.
|
||||||
|
- Keine Secrets, keine Dump-Inhalte, keine personenbezogenen Daten in Log oder JSON. Tabellennamen, Zeilenzahlen, Dateipfade im Medienbestand und Versionsangaben sind erlaubt.
|
||||||
|
- Exit-Codes:
|
||||||
|
|
||||||
|
| Code | Bedeutung |
|
||||||
|
|---|---|
|
||||||
|
| 0 | erfolgreich |
|
||||||
|
| 1 | Fehler während der Ausführung (Details im JSON) |
|
||||||
|
| 2 | Aufruf oder Vorbedingung falsch (falscher Host, fehlende Datei, fehlende Bestätigung) |
|
||||||
|
| 3 | Dump passt nicht zum Code (enthält Migrationen, die der Code nicht kennt) |
|
||||||
|
| 4 | Prüfsumme stimmt nicht |
|
||||||
|
| 5 | Wiederherstellung durchgeführt, Prüfung danach fehlgeschlagen (Rollback ausgeführt bzw. im JSON beschrieben) |
|
||||||
|
|
||||||
|
### 3.1 `shinkan-backup-manifest`
|
||||||
|
|
||||||
|
Aufruf direkt nach dem Dump, im selben Orchestrator-Job.
|
||||||
|
|
||||||
|
```
|
||||||
|
shinkan-backup-manifest --target pi-prod|llm-prod --dump <datei> --out-dir <verzeichnis> --result <json>
|
||||||
|
```
|
||||||
|
|
||||||
|
Schreibt neben den Dump:
|
||||||
|
|
||||||
|
- `<dump>.sha256`
|
||||||
|
- `<dump>.manifest.json`:
|
||||||
|
- `created_at`, `host`, `target`
|
||||||
|
- `app_version` (aus `/api/version`), `git_commit` (Deploy-Checkout)
|
||||||
|
- `migrations`: Liste aus `schema_migrations.migration`, `last_migration`
|
||||||
|
- `dump_format` (`plain` | `custom`), `dump_bytes`, `dump_sha256`
|
||||||
|
- `row_counts` je Tabelle, nur informativ (eigener Lesezugriff, nicht derselbe Snapshot wie der Dump)
|
||||||
|
- `media_manifest` (Dateiname + sha256)
|
||||||
|
- `<dump>.media.jsonl`, eine Zeile je Datei im Medienbestand: `path` (relativ zu `/app/media`), `size`, `mtime`. `sha256` nur für neue oder geänderte Dateien (Cache über `path`+`size`+`mtime`), damit der Lauf bei wachsendem Bestand kurz bleibt.
|
||||||
|
|
||||||
|
Der Manifest-Job liest nur; ein Fehler darin macht den Backup-Satz unvollständig, aber nicht den Dump ungültig. Empfehlung: Job unkritisch, Kuma-Meldung eigener Monitor.
|
||||||
|
|
||||||
|
### 3.2 `shinkan-restore`
|
||||||
|
|
||||||
|
```
|
||||||
|
shinkan-restore --target llm-prod|llm-restoretest --dump <datei> --result <json>
|
||||||
|
[--confirm <db>@<host>] [--allow-overwrite] [--sessions clear|keep]
|
||||||
|
```
|
||||||
|
|
||||||
|
- `--confirm shinkan@llm-node` ist bei `llm-prod` Pflicht.
|
||||||
|
- `--allow-overwrite` ist Pflicht, wenn die Ziel-DB echte Daten hat (mindestens ein Eintrag in `profiles`). Eine frisch migrierte DB ohne Profile gilt als leer.
|
||||||
|
- `--sessions`: Default `clear`. `keep` nur bei Recovery desselben Systems nach einem Crash, wenn angemeldete Nutzer angemeldet bleiben sollen.
|
||||||
|
|
||||||
|
Ablauf (verbindlich):
|
||||||
|
|
||||||
|
1. **Vorbedingungen:** Host-Guard, Dump lesbar, `<dump>.sha256` vorhanden und passend (sonst Exit 4), Zielkonfiguration vorhanden.
|
||||||
|
2. **In eine Staging-DB einspielen,** nicht direkt in die Live-DB: `shinkan_restore_<zeitstempel>` im laufenden Postgres-Container anlegen und den Dump in **einer Transaktion** einspielen, bei Fehler Abbruch ohne Teilstand.
|
||||||
|
- Plain SQL: `psql -v ON_ERROR_STOP=1 --single-transaction`
|
||||||
|
- Custom-Format (`PGDMP`-Kopf): `pg_restore --single-transaction --exit-on-error --no-owner --no-acl`
|
||||||
|
3. **Migrationsabgleich in der Staging-DB:** Jeder Eintrag in `schema_migrations.migration` muss als `backend/migrations/<eintrag>.sql` im deployten Code existieren. Sonst ist der Dump neuer als der Code → Staging-DB löschen, Exit 3. Fehlende Einträge (Dump älter als Code) sind normal; sie werden beim Backend-Start nachgezogen.
|
||||||
|
4. **Plausibilität in der Staging-DB:** Pflichttabellen wie im Ready-Check vorhanden; `profiles`, `skills` nicht leer. Abweichung der Zeilenzahlen zum Manifest nur als Hinweis im JSON.
|
||||||
|
5. **Sessions:** bei `clear` `TRUNCATE sessions` in der Staging-DB.
|
||||||
|
6. **Umschalten:**
|
||||||
|
- Backend, Frontend und `retention-cron` stoppen (Compose `stop`, Postgres läuft weiter).
|
||||||
|
- Live-DB umbenennen: `shinkan` → `shinkan_before_<zeitstempel>`.
|
||||||
|
- Staging-DB umbenennen: `shinkan_restore_<zeitstempel>` → `shinkan`.
|
||||||
|
- Backend und Frontend starten; `retention-cron` nur, wenn es im Deployment aktiviert ist (llm-node: `MEDIA_RETENTION`).
|
||||||
|
7. **Prüfen:** dieselben Healthchecks wie im Deploy-Workflow, insbesondere `/api/health/ready` mit `status=ready`, `database=true`, `schema_complete=true`.
|
||||||
|
8. **Bei Fehler in 6–7:** Dienste stoppen, Umbenennung rückgängig machen (`shinkan_before_<zeitstempel>` → `shinkan`), Dienste starten, erneut prüfen. Exit 5 mit beiden Ergebnissen im JSON.
|
||||||
|
9. **Aufräumen:** `shinkan_before_<zeitstempel>` bleibt stehen, bis jemand sie ausdrücklich löscht (eigener Befehl `--drop-previous <name>` oder manuell). Kein automatisches Löschen.
|
||||||
|
|
||||||
|
Ergebnis-JSON u. a.: `dump_sha256`, `dump_last_migration`, `code_last_migration`, `migrations_applied_on_start`, `sessions`, `previous_db`, `health`, `duration_seconds`.
|
||||||
|
|
||||||
|
### 3.3 `shinkan-restore-test`
|
||||||
|
|
||||||
|
```
|
||||||
|
shinkan-restore-test --dump <datei> --result <json> [--playwright] [--keep]
|
||||||
|
```
|
||||||
|
|
||||||
|
Baut eine Wegwerf-Umgebung auf llm-node, spielt den Dump mit `shinkan-restore --target llm-restoretest` ein, prüft und räumt auf.
|
||||||
|
|
||||||
|
- **Eigenes Compose-Projekt** `shinkan-restoretest` mit **eigener Compose-Datei ohne `container_name`**. Die Basisdatei setzt feste Namen (`shinkan-db-prod` …) und kollidiert sonst mit Prod auf demselben Host.
|
||||||
|
- **Ports:** Frontend und Backend nur auf `127.0.0.1`, Postgres ohne veröffentlichten Port. Konkrete Ports vor Umsetzung auf llm-node prüfen.
|
||||||
|
- **Medien nur lesend:** `/srv/shinkan/prod/media:/app/media:ro`. Der Medienbestand ist gemeinsam; ein Test darf dort nichts schreiben oder löschen.
|
||||||
|
- **Aus:** `retention-cron`, SMTP (Variablen leer), `AUTO_ADMIN_FIRST_USER`, `ADMIN_BOOTSTRAP_EMAILS`, OpenRouter.
|
||||||
|
- **Prüfungen:** Ready-Check, Plausibilität wie 3.2, Medien-Abgleich (3.4) gegen den aktuellen Bestand.
|
||||||
|
- **`--playwright`:** lesende Smoke-Tests gegen `PLAYWRIGHT_BASE_URL` der Testumgebung. Tests, die hochladen oder Medien ändern, müssen ausgeschlossen werden (schreibgeschützter Mount). Testzugang über einen eigens im Test angelegten Nutzer, nicht über echte Nutzerkonten.
|
||||||
|
- **Ende:** `docker compose -p shinkan-restoretest down -v`, außer bei `--keep` (zur Fehlersuche).
|
||||||
|
|
||||||
|
Empfohlener Takt: wöchentlich mit dem jüngsten Backup-Satz, zusätzlich nach Änderungen an Dump-Format oder Migrationsrunner.
|
||||||
|
|
||||||
|
### 3.4 `shinkan-media-diff`
|
||||||
|
|
||||||
|
```
|
||||||
|
shinkan-media-diff --target llm-prod|llm-restoretest --result <json> [--manifest <dump>.media.jsonl]
|
||||||
|
```
|
||||||
|
|
||||||
|
Vergleicht die Medienverweise der (wiederhergestellten) DB mit dem aktuellen Medienbestand. Löscht und ändert nichts.
|
||||||
|
|
||||||
|
Kategorien im Ergebnis:
|
||||||
|
|
||||||
|
| Kategorie | Bedeutung | Folge |
|
||||||
|
|---|---|---|
|
||||||
|
| `missing` | in `media_assets` / `exercise_media` referenziert, Datei fehlt | reparieren oder Eintrag bereinigen |
|
||||||
|
| `mismatch` | Datei vorhanden, `byte_size` oder `sha256` passt nicht | prüfen |
|
||||||
|
| `added_after_backup` | Datei vorhanden, nicht referenziert, nicht im Medien-Manifest des Backups | Upload nach dem Backup; DB-Eintrag ging mit dem Restore verloren → Kandidat für Nachpflege |
|
||||||
|
| `orphan` | Datei vorhanden, nicht referenziert, bereits im Manifest | Kandidat zum Aufräumen |
|
||||||
|
|
||||||
|
Solange Pi und llm-node denselben Bestand mit getrennten Datenbanken nutzen, gehören `orphan` und `added_after_backup` teilweise zur anderen Installation. **Keine automatische Bereinigung** auf Basis dieses Berichts.
|
||||||
|
|
||||||
|
Der Bericht enthält immer das Versions-Tripel: App-Version und Commit des Ziels, letzte Migration der DB, Medien-Manifest des Backups.
|
||||||
|
|
||||||
|
## 4. Zuständigkeiten
|
||||||
|
|
||||||
|
| Aufgabe | Orchestrator | Shinkan |
|
||||||
|
|---|---|---|
|
||||||
|
| Zeitplan (täglich, später 2-stündlich) | ✓ | |
|
||||||
|
| Dump erzeugen (`pg_dump` im Container) | ✓ | |
|
||||||
|
| Manifest erzeugen | ruft auf | `shinkan-backup-manifest` |
|
||||||
|
| Ablage, Generationen, Kopie auf NAS | ✓ | |
|
||||||
|
| Meldungen (Kuma, Webhooks) | ✓ | liefert Exit-Code + JSON |
|
||||||
|
| Restore-Test planen | ✓ | `shinkan-restore-test` |
|
||||||
|
| Recovery auslösen | manuell über Orchestrator-CLI | `shinkan-restore` |
|
||||||
|
| Medienabgleich | ruft nach Restore auf | `shinkan-media-diff` |
|
||||||
|
| Installation auf llm-node | ✓ | |
|
||||||
|
|
||||||
|
## 5. Anforderungen an den Orchestrator
|
||||||
|
|
||||||
|
1. **Generationen auf dem NAS.** Mit festem Dateinamen gibt es lokal nur einen Stand. Auf dem NAS müssen mehrere Backup-Sätze erhalten bleiben. Vorschlag: 2-stündliche Sätze 2 Tage, tägliche 30 Tage, monatliche 12 Monate. Ein Satz wird erst überschrieben bzw. rotiert, wenn der neue vollständig ist (Dump + `.sha256` + Manifest).
|
||||||
|
2. **Atomar schreiben:** Dump erst in eine temporäre Datei, nach Erfolg umbenennen. Ein abgebrochener Dump darf den letzten guten nicht ersetzen.
|
||||||
|
3. **Dump-Format:** Plain SQL funktioniert. Empfohlen für die Zukunft: `pg_dump -Fc` (kleiner, Inhaltsverzeichnis mit `pg_restore --list`, gezielte Teil-Restores). `shinkan-restore` erkennt beide Formate.
|
||||||
|
4. **llm-node:** Eigene Orchestrator-Instanz auf llm-node für `shinkan-prod` (`docker exec shinkan-db-prod pg_dump …`). Postgres ist dort nur lokal erreichbar; Fern-Dumps vom Pi sind nicht vorgesehen.
|
||||||
|
5. **Bis zum Cutover** laufen beide Sicherungen: Pi für das alte Prod, llm-node für das neue. Ablage getrennt (`shinkan-prod-pi/`, `shinkan-prod-llm/`), damit Sätze nicht verwechselt werden.
|
||||||
|
6. **Takt für externe Kunden:** Vollständige Dumps alle 2 Stunden sind bei der aktuellen Größe unproblematisch und jeder Satz ist eigenständig einspielbar. Ein „Diff zum ersten Dump des Tages“ ist mit `pg_dump` nicht möglich; ein Textvergleich von SQL-Dumps ist kein verlässliches Backup. Für Datenverlust im Minutenbereich ist der Weg WAL-Archivierung mit Basis-Backup (z. B. pgBackRest oder WAL-G, Point-in-Time-Recovery). Das ändert die Postgres-Konfiguration und ist ein eigenes Vorhaben.
|
||||||
|
|
||||||
|
## 6. Erstbefüllung llm-node (einmalig)
|
||||||
|
|
||||||
|
Nutzt bewusst denselben Weg wie die Recovery; die Erstbefüllung ist damit der erste echte Recovery-Test.
|
||||||
|
|
||||||
|
1. Deploy-Workflow `Deploy Production llm-node` ist mindestens einmal erfolgreich gelaufen (DB frisch migriert, keine Profile).
|
||||||
|
2. Jüngsten Pi-Backup-Satz (`shinkan-prod.sql` + `.sha256` + Manifest) nach llm-node kopieren, Ablage `/var/lib/shinkan/restore/` (Verzeichnis 700, Dateien 600, Eigentümer `llmadmin`).
|
||||||
|
3. Optional vorher `shinkan-restore-test` mit diesem Satz.
|
||||||
|
4. `shinkan-restore --target llm-prod --dump … --confirm shinkan@llm-node --sessions clear` (ohne `--allow-overwrite`, da die DB als leer gilt).
|
||||||
|
5. `shinkan-media-diff --target llm-prod` und Bericht ansehen.
|
||||||
|
6. Fachliche Stichprobe (Login, Übungen, Medien).
|
||||||
|
|
||||||
|
Vor Schritt 4 klären: SMTP in `/etc/shinkan/prod.env` für die Testphase aus oder bewusst an (echte Nutzerdaten → echte Mails möglich).
|
||||||
|
|
||||||
|
Für den Cutover wird Schritt 2–6 mit Schreibstopp auf dem Pi wiederholt (Pi-Backend stoppen, Dump, Restore mit `--allow-overwrite`).
|
||||||
|
|
||||||
|
## 7. Sicherheit und Datenschutz
|
||||||
|
|
||||||
|
- Dumps enthalten E-Mail-Adressen, Passwort-Hashes und TOTP-Geheimnisse. Ablage nur mit Rechten 600/640, Transport nur im LAN per SSH, nie ins Repo, nie in Webhooks, Logs oder Kuma-Nachrichten.
|
||||||
|
- Skripte geben keine Umgebungsvariablen aus und lesen Zugangsdaten nur aus der Zielkonfiguration bzw. dem Container.
|
||||||
|
- Auf dem Pi-Prod nur lesende Zugriffe (Manifest). Kein Restore auf dem Pi.
|
||||||
|
- Restore-Test nie mit beschreibbarem Medien-Mount, nie mit aktivem SMTP.
|
||||||
|
|
||||||
|
## 8. Offene Entscheidungen
|
||||||
|
|
||||||
|
1. Dump-Format künftig `-Fc` oder weiter Plain SQL?
|
||||||
|
2. Aufbewahrung der Generationen (Vorschlag in 5.1) und ob das NAS zusätzlich Snapshots führt.
|
||||||
|
3. Ports und Takt des Restore-Tests; welche Playwright-Tests als lesender Smoke-Satz gelten.
|
||||||
|
4. Default `--sessions` bei Crash-Recovery (`clear` sicherer, `keep` bequemer).
|
||||||
|
5. Zeitpunkt für WAL-Archivierung/PITR (spätestens mit dem ersten externen Kunden mit Zusage zur Verfügbarkeit).
|
||||||
|
6. Wiederherstellung einzelner Vereine bei mehreren Kunden: mit beiden Verfahren nicht direkt möglich; bei Bedarf eigenes Export/Import-Konzept je Mandant.
|
||||||
@@ -7,6 +7,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
|||||||
| profiles | `GET /api/profiles/me` | ja | `resolve_tenant_context` inline (`invalid_header_policy=ignore`) | teils | + `effective_club_id`; veralteter Header bricht Refresh nicht |
|
| profiles | `GET /api/profiles/me` | ja | `resolve_tenant_context` inline (`invalid_header_policy=ignore`) | teils | + `effective_club_id`; veralteter Header bricht Refresh nicht |
|
||||||
| profiles | `GET /api/profiles`, `GET /profiles/{pid}`, `POST /profiles`, `DELETE /profiles/{pid}` | ja/teils | `require_auth` | ja | Liste nur Plattform-Admin; GET nach ID eigenes Profil oder Admin; POST/DELETE nur Admin |
|
| profiles | `GET /api/profiles`, `GET /profiles/{pid}`, `POST /profiles`, `DELETE /profiles/{pid}` | ja/teils | `require_auth` | ja | Liste nur Plattform-Admin; GET nach ID eigenes Profil oder Admin; POST/DELETE nur Admin |
|
||||||
| profiles | `PUT /api/profiles/{id}`, `PUT /api/profile` | ja | `get_tenant_context` | `active_club_id` Mitgliedschaft | Validiert `X-Active-Club-Id` konsistent zu Mitgliedschaft |
|
| profiles | `PUT /api/profiles/{id}`, `PUT /api/profile` | ja | `get_tenant_context` | `active_club_id` Mitgliedschaft | Validiert `X-Active-Club-Id` konsistent zu Mitgliedschaft |
|
||||||
|
| profiles | `POST /api/profiles/{id}/totp-reset` | Plattform | `get_tenant_context` | nur `superadmin`, nicht das eigene Konto | Schaltet TOTP ab, löscht Wiederherstellungscodes, beendet Sitzungen |
|
||||||
| clubs | geschützte `/api/clubs*`, `/divisions*`, `/groups*` | ja | `get_tenant_context` | Mitgliedschaft / `can_manage_*` | Öffentlich: `/clubs/public-directory` ohne Auth |
|
| clubs | geschützte `/api/clubs*`, `/divisions*`, `/groups*` | ja | `get_tenant_context` | Mitgliedschaft / `can_manage_*` | Öffentlich: `/clubs/public-directory` ohne Auth |
|
||||||
| club_memberships | `/clubs/{id}/members*` | ja | `get_tenant_context` | ja | |
|
| club_memberships | `/clubs/{id}/members*` | ja | `get_tenant_context` | ja | |
|
||||||
| club_join_requests | `/me/club-join-requests`, `/clubs/{id}/join-requests*` | ja | `get_tenant_context` | ja | |
|
| club_join_requests | `/me/club-join-requests`, `/clubs/{id}/join-requests*` | ja | `get_tenant_context` | ja | |
|
||||||
@@ -28,6 +29,8 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
|||||||
| media_assets | `PATCH /api/media-assets/{id}` | ja | `get_tenant_context` | ja | Copyright, `original_filename`, optional `visibility`/`club_id`; Rechte pro Stufe |
|
| media_assets | `PATCH /api/media-assets/{id}` | ja | `get_tenant_context` | ja | Copyright, `original_filename`, optional `visibility`/`club_id`; Rechte pro Stufe |
|
||||||
| media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung |
|
| media_assets | `GET /api/media-assets/{id}/file` | ja | `get_tenant_context_flexible` | ja | aktiv: Bibliotheks-Sichtbarkeit; `trash_soft`/`trash_hidden`: wie Lifecycle-Verwaltung |
|
||||||
| exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv |
|
| exercises | `POST /api/exercises/{id}/media/from-asset` | ja | `get_tenant_context` | ja | Verknüpfung `exercise_media` → bestehendes `media_asset_id`; Bearbeitungsrecht Übung + Leserecht Archiv |
|
||||||
|
| distribution | `GET /api/distribution/v1/*` | Kanal aus Schlüssel | kein Trainer-Tenant | ja, Empfänger der Anbindung | ACCESS_LAYER exempt: Bearer-Distributions-Schlüssel, nicht `X-Auth-Token`. `GET …/exercises/{source_id}/availability` meldet Quelle und Paketstand dieses Kanals |
|
||||||
|
| distribution | `POST /api/exercises/{id}/distribution/*`, `/api/distribution/access/*`, `GET /api/distribution/release-updates`, `PATCH /api/exercises/api-offering` | ja | `get_tenant_context` | ja | API-Bereitstellung nutzt die Bearbeitungsrechte: global nur `superadmin`, sonst Ersteller, Plattform-Admin oder Planungsrecht im Verein. Katalogabruf `/api/distribution/v1/catalog` ist maschinell und vom Mandantenkontext ausgenommen |
|
||||||
| auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT |
|
| auth | `/api/auth/*` | nein | — | Login/Session | EXEMPT |
|
||||||
| catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen |
|
| catalogs | Katalog-CRUD | nein (global) | `require_auth` | Admin/Trainer je Endpoint | EXEMPT; bei späterem `club_id` nachziehen |
|
||||||
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
|
| skills | `/api/skills*` | nein (global) | `require_auth` | je Endpoint | EXEMPT |
|
||||||
@@ -37,6 +40,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
|||||||
| import_wiki / import_wiki_admin | Wiki-Import | Werkzeug | `require_auth`/Admin | Admin | EXEMPT |
|
| import_wiki / import_wiki_admin | Wiki-Import | Werkzeug | `require_auth`/Admin | Admin | EXEMPT |
|
||||||
| ai_skill_retrieval_admin | `/api/admin/ai-skill-retrieval-profiles*` (CRUD) | Plattform | `require_auth` | nur `superadmin`; JSON `config` | EXEMPT wie `admin_users`; kein Vereinsbezug |
|
| ai_skill_retrieval_admin | `/api/admin/ai-skill-retrieval-profiles*` (CRUD) | Plattform | `require_auth` | nur `superadmin`; JSON `config` | EXEMPT wie `admin_users`; kein Vereinsbezug |
|
||||||
| ai_prompts_admin | `/api/admin/ai-prompts*` (Liste, Detail, PUT, Preview, Reset) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; globale `ai_prompts` ohne Mandantenkontext |
|
| ai_prompts_admin | `/api/admin/ai-prompts*` (Liste, Detail, PUT, Preview, Reset) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; globale `ai_prompts` ohne Mandantenkontext |
|
||||||
|
| openrouter_admin | `GET/PUT /api/admin/openrouter/settings`, `GET /api/admin/openrouter/models`, `GET/PUT /api/admin/openrouter/roles`, `PUT /api/admin/openrouter/prompts/{id}/role` | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Plattform-Standard, Aufgabengruppen und OpenRouter-Katalog, kein Vereinsbezug, kein API-Key in der Antwort |
|
||||||
| exercise_enrichment_admin | `/api/admin/exercise-enrichment/*` (Kandidaten, Preview, Apply) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; plattformweite Übungsliste + Skill-Schreibung; kein TenantContext |
|
| exercise_enrichment_admin | `/api/admin/exercise-enrichment/*` (Kandidaten, Preview, Apply) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; plattformweite Übungsliste + Skill-Schreibung; kein TenantContext |
|
||||||
| admin_user_content | `/api/admin/user-content/*` (Meta, Nutzer-Summary, Items, PATCH, DELETE) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Moderation nutzerangelegter Inhalte inkl. privat; kein TenantContext |
|
| admin_user_content | `/api/admin/user-content/*` (Meta, Nutzer-Summary, Items, PATCH, DELETE) | Plattform | `require_auth` | nur `superadmin` | EXEMPT; Moderation nutzerangelegter Inhalte inkl. privat; kein TenantContext |
|
||||||
|
|
||||||
@@ -44,7 +48,7 @@ Fortlaufend gemäß `ACCESS_LAYER_AND_GOVERNANCE_PLAN.md` Stufe A–C.
|
|||||||
|
|
||||||
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
|
**Pflege / Drift:** Änderungen an Mandanten, Governance (`visibility`/`club_id`) oder neuen inhaltsbezogenen Endpoints → eine Zeile in dieser Tabelle anpassen und `PRODUCTION_READINESS_AUDIT_2026-05.md` prüfen.
|
||||||
|
|
||||||
Letzte Änderung: 2026-06-06 — Superadmin `/api/admin/user-content/*` (Nutzer-Inhalte Moderation).
|
Letzte Änderung: 2026-11-23 — Superadmin `/api/admin/openrouter/settings` und `/api/admin/openrouter/models`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -493,23 +493,37 @@ Nach Pfad-Bildung:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 24. Phase F — Roadmap-first Progressionsgraph (0.8.204+) 🔄
|
## 24. Phase F — Roadmap-first Progressionsgraph (0.8.204–217) ✅
|
||||||
|
|
||||||
**Entscheidung:** Progressionsgraph plant **vom Ziel rückwärts** (Roadmap → Stufenspezifikation → Bibliothek/KI). **Keine Gruppenanalyse** — die gehört zur Trainingsplanung.
|
**Entscheidung:** Progressionsgraph plant **vom Ziel rückwärts** (Roadmap → Stufenspezifikation → Bibliothek/KI). **Keine Gruppenanalyse** — die gehört zur Trainingsplanung.
|
||||||
|
|
||||||
|
**Ist-Stand (vollständig):** `docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`
|
||||||
**Spec:** `working/PLANNING_PROGRESSION_ROADMAP_SPEC.md` · **Roadmap:** `docs/architecture/PLANNING_KI_ROADMAP.md`
|
**Spec:** `working/PLANNING_PROGRESSION_ROADMAP_SPEC.md` · **Roadmap:** `docs/architecture/PLANNING_KI_ROADMAP.md`
|
||||||
|
|
||||||
| Teil | Modul / API |
|
| Teil | Modul / API |
|
||||||
|------|-------------|
|
|------|-------------|
|
||||||
| Pipeline | `planning_progression_roadmap.py` (Workflow-lite) |
|
| Pipeline | `planning_progression_roadmap.py` (Workflow-lite) |
|
||||||
| API | `include_roadmap_preview`, `include_llm_roadmap`, `roadmap_first` auf `progression-path-suggest` |
|
| Match | `planning_exercise_path_builder.py` — `roadmap_first`, `roadmap_override` |
|
||||||
| Prompts | Migration **078/079** — Slugs in `ai_prompts` (Admin), **kein** Template im Python-Code |
|
| Skills | `planning_skill_expectations.py` — pro Stufe + Pfad |
|
||||||
| UI | `ExerciseProgressionPathBuilder` — Roadmap-Box (Major Steps) |
|
| Gap-KI | `planning_exercise_form_context.py`, `planning_exercise_path_ai_fill.py` |
|
||||||
|
| Persistenz | `planning_roadmap` JSONB (Migration **088**) |
|
||||||
|
| API | `progression-path-suggest`, `PUT` Graph, `POST …/edges/sequence` |
|
||||||
|
| Prompts | **078/079/087** — Slugs nur in `ai_prompts` |
|
||||||
|
| UI | `ExerciseProgressionPathBuilder`, `ExerciseGapFillPrepModal` |
|
||||||
|
|
||||||
**F3 (0.8.206):** `roadmap_first=true` (Default im UI) — Retrieval pro `stage_spec`/Major Step; `roadmap_unfilled` Gap-Angebote. Ohne Flag: retrieval-first wie bisher, Roadmap nur Preview.
|
**Graph-Bias:** `progression_graph_id` bevorzugt **bestehende Nachfolger** ab Schritt 2 (Gewicht ~4–10 %), baut aber **keinen** Pfad aus vorhandenen Knoten — siehe Ist-Doku §5.
|
||||||
|
|
||||||
**Mitai Workflow-Engine:** bewusst **nicht** jetzt — Pipeline workflow-ready für spätere Anbindung.
|
**Mitai Workflow-Engine:** bewusst **nicht** jetzt — Pipeline workflow-ready für spätere Anbindung.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 25. Backlog (offen)
|
## 25. Backlog (offen)
|
||||||
|
|
||||||
|
Siehe priorisierte Liste in **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`** §10:
|
||||||
|
|
||||||
|
1. UI-Wizard (Progressionsgraph) — separater Chat
|
||||||
|
2. Graph-Erweiterungsmodus (Start ab Knoten)
|
||||||
|
3. Trainingsplanung Phase G (Gruppenkontext, `planning_skill_expectations`)
|
||||||
|
4. Kontext auf allen Pfad-Schritten in der UI
|
||||||
|
5. Enrichment / Prompt-Feintuning
|
||||||
|
6. Mitai Workflow-Engine (langfristig)
|
||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
**Version:** 0.1
|
**Version:** 0.1
|
||||||
**Datum:** 2026-06-07
|
**Datum:** 2026-06-07
|
||||||
**Status:** VERBINDLICHE ZIELARCHITEKTUR — Umsetzung gestartet (0.8.204+)
|
**Status:** VERBINDLICHE ZIELARCHITEKTUR — **F0–F9 umgesetzt** (0.8.217)
|
||||||
**Geltungsbereich:** **Progressionsgraph** (`exercise_progression_graphs`) — **ohne** Gruppenanalyse
|
**Geltungsbereich:** **Progressionsgraph** (`exercise_progression_graphs`) — **ohne** Gruppenanalyse
|
||||||
|
|
||||||
|
**Ist-Stand (Module, API, Graph-Verhalten, Persistenz):** `docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`
|
||||||
|
|
||||||
**Bezüge:**
|
**Bezüge:**
|
||||||
`working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md` · `working/AI_PLANNING_KI_MULTISTAGE_FORECAST.md` · `technical/AI_TRAINING_PLANNING_CONCEPT.md` · `technical/AI_PROMPT_TARGET_ARCHITECTURE.md` · `docs/architecture/PLANNING_KI_ROADMAP.md` · `docs/HANDOVER.md`
|
`working/PLANNING_EXERCISE_SUGGEST_CONTEXT.md` · `working/AI_PLANNING_KI_MULTISTAGE_FORECAST.md` · `technical/AI_TRAINING_PLANNING_CONCEPT.md` · `technical/AI_PROMPT_TARGET_ARCHITECTURE.md` · `docs/architecture/PLANNING_KI_ROADMAP.md` · `docs/HANDOVER.md`
|
||||||
|
|
||||||
@@ -152,6 +154,7 @@ Jede Phase: `(ctx) → ctx`, Zwischenergebnisse in API-Response für **Human-in-
|
|||||||
|
|
||||||
| Slug | Phase | Migration |
|
| Slug | Phase | Migration |
|
||||||
|------|-------|-----------|
|
|------|-------|-----------|
|
||||||
|
| `planning_progression_start_target` | Start/Ziel | **087** |
|
||||||
| `planning_progression_goal_analysis` | A | **078** |
|
| `planning_progression_goal_analysis` | A | **078** |
|
||||||
| `planning_progression_roadmap` | B | **078** |
|
| `planning_progression_roadmap` | B | **078** |
|
||||||
| `planning_progression_stage_spec` | C | **079** |
|
| `planning_progression_stage_spec` | C | **079** |
|
||||||
@@ -184,15 +187,23 @@ Jede Phase: `(ctx) → ctx`, Zwischenergebnisse in API-Response für **Human-in-
|
|||||||
|
|
||||||
| ID | Inhalt | Status |
|
| ID | Inhalt | Status |
|
||||||
|----|--------|--------|
|
|----|--------|--------|
|
||||||
| **F0** | Spec + Doku + `planning_progression_roadmap.py` Scaffold | 🔄 0.8.204 |
|
| **F0** | Spec + Doku + `planning_progression_roadmap.py` Scaffold | ✅ 0.8.204 |
|
||||||
| **F1** | `include_roadmap_preview` in API + deterministische A/B | 🔄 0.8.204 |
|
| **F1** | `include_roadmap_preview` in API + deterministische A/B | ✅ 0.8.204 |
|
||||||
| **F2** | LLM Phase A/B/C über `ai_prompts` (078/079), `include_llm_roadmap` | 🔄 0.8.205 |
|
| **F2** | LLM Phase A/B/C über `ai_prompts` (078/079), `include_llm_roadmap` | ✅ 0.8.205 |
|
||||||
| **F3** | Retrieval aus `stage_specs` (roadmap_first) | ✅ 0.8.206 |
|
| **F3** | Retrieval aus `stage_specs` (roadmap_first) | ✅ 0.8.206–209 |
|
||||||
| **F4** | UI Roadmap-Review | ✅ 0.8.207 |
|
| **F4** | UI Roadmap-Review + `roadmap_override` | ✅ 0.8.207 |
|
||||||
| **F5** | Trainingsplanung: eigene Pipeline + ggf. Workflow-Engine | 🔲 |
|
| **F5** | Start/Ziel strukturiert + Prompt **087** + Zwei-Schritt-UI | ✅ 0.8.210–214 |
|
||||||
|
| **F6** | Gap-Prep + `planning_context` an Übungs-KI | ✅ 0.8.212–214 |
|
||||||
|
| **F7** | `planning_skill_expectations` | ✅ 0.8.215–216 |
|
||||||
|
| **F8** | Editierbare `stage_specs` in UI | ✅ 0.8.216 |
|
||||||
|
| **F9** | `planning_roadmap` JSONB (Migration **088**) | ✅ 0.8.217 |
|
||||||
|
| **G** | Trainingsplanung: eigene Pipeline + Workflow-Engine | 🔲 |
|
||||||
|
|
||||||
|
Details: `docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Changelog
|
## 9. Changelog
|
||||||
|
|
||||||
|
- **2026-05-22:** Ist-Stand F5–F9 dokumentiert; Verweis auf `PLANNING_PROGRESSION_GRAPH_KI.md`.
|
||||||
- **2026-06-07:** Erstfassung — Roadmap-first Entscheidung, Abgrenzung Graphen vs. Planung, Workflow-lite.
|
- **2026-06-07:** Erstfassung — Roadmap-first Entscheidung, Abgrenzung Graphen vs. Planung, Workflow-lite.
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# Progressionsgraph — Slot-Editor (Phase B + F15)
|
||||||
|
|
||||||
|
**Stand:** 2026-05-22 · **Status:** Umgesetzt (F14 + F15 lokal nach 0.8.233)
|
||||||
|
|
||||||
|
## Ziel
|
||||||
|
|
||||||
|
Ein Progressionsgraph = **ein linearer Hauptpfad** (Roadmap = strukturgebend). Jeder **Major Step** ist ein **Slot** mit:
|
||||||
|
|
||||||
|
- **primary** — Hauptübung des Slots (Pfadknoten)
|
||||||
|
- **siblings** — 0..n Schwestern (gleiche Stufe, `edge_type: sibling`)
|
||||||
|
|
||||||
|
KI-Entwürfe und Bibliotheksübungen leben **im selben Slot-Modell**, ohne sofortige Übungsanlage.
|
||||||
|
|
||||||
|
## Slot-Zustände (`kind`)
|
||||||
|
|
||||||
|
| kind | Bedeutung |
|
||||||
|
|------|-----------|
|
||||||
|
| `empty` | Noch keine Übung |
|
||||||
|
| `library` | `exercise_id` (+ optional `variant_id`) |
|
||||||
|
| `proposal` | KI-Entwurf (`ai_suggestion`, kein `exercise_id`) |
|
||||||
|
|
||||||
|
## Kanten
|
||||||
|
|
||||||
|
- `primary(n) → primary(n+1)` — `next_exercise` (nur befüllte Primärkette, lückenlos verbunden)
|
||||||
|
- `primary ↔ sibling` — `sibling` (pro Slot)
|
||||||
|
|
||||||
|
Leere Slots in der Roadmap sind erlaubt; Kanten nur zwischen aufeinanderfolgenden befüllten Primär-Slots.
|
||||||
|
|
||||||
|
## Editor-Zustand (`ProgressionGraphDraft`)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
goalQuery, startSituation, targetState, roadmapNotes, maxSteps,
|
||||||
|
majorSteps: MajorStep[],
|
||||||
|
slots: Slot[], // index = major_step_index
|
||||||
|
pathSkillExpectations?,
|
||||||
|
lastFindings?, // path_qa-Snapshot
|
||||||
|
findingsStale?: boolean, // Bewertung veraltet (↔ Artefakt findings_stale)
|
||||||
|
dirty: boolean,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Hydration:** `planning_roadmap` + Kanten → Slots; `slot_contents[]` für Entwürfe; Primärkette aus `next_exercise`.
|
||||||
|
|
||||||
|
**Speichern:** Batch-Delete bestehender Pfad-/Schwester-Kanten → `edges/sequence` (Primärkette) → einzelne `sibling`-Kanten → `PUT`/`sequence` mit Artefakt inkl. `slot_contents`, `last_findings`, **`findings_stale`**.
|
||||||
|
|
||||||
|
## Findings-Panel
|
||||||
|
|
||||||
|
Nutzt `path_qa`:
|
||||||
|
|
||||||
|
| Feld | Bedeutung |
|
||||||
|
|------|-----------|
|
||||||
|
| `quality_score` | Gesamt = **min(`roadmap_qa`, `assignment_qa`)** |
|
||||||
|
| `roadmap_qa` | Stufen/Roadmap (LLM `topic_coverage`, …) |
|
||||||
|
| `assignment_qa` | Slot-Befüllung (`empty_slot_count`, …) |
|
||||||
|
| `overall_ok`, `issues`, `recommendations`, `gap_fill_offers`, … | wie bisher |
|
||||||
|
|
||||||
|
**API:** `POST /api/planning/progression-path-suggest` mit `evaluate_only: true` und `evaluate_steps[]` — QA ohne Re-Match.
|
||||||
|
|
||||||
|
**Bewertung veraltet:** Jede Graph-Änderung setzt `findingsStale: true` → Banner im Panel. Nach „Graph bewerten“ → `false`. Persistenz: `planning_roadmap.findings_stale`.
|
||||||
|
|
||||||
|
## Match-Flow („Übungen matchen“)
|
||||||
|
|
||||||
|
1. **Schritt 1:** `evaluate_only` + volle Pfad-QS (wie „Graph bewerten“)
|
||||||
|
2. **Schritt 2:** `unified_slot_review: true` → **`ProgressionOptimizeCompareModal`**
|
||||||
|
3. Pro Slot: aktuell vs. beste Bibliothek vs. optional KI-Vorschlag
|
||||||
|
4. **Vorauswahl:** Bibliothek nur wenn Stufen-Fit ≥ 50 % und besser als Baseline; sonst KI (bei leerem/schwachem Slot)
|
||||||
|
5. **Übernahme:** nur gewählte Slots speichern — **keine** automatische Nach-Bewertung
|
||||||
|
|
||||||
|
## Artefakt-Erweiterung (`GraphPlanningRoadmapArtifact`)
|
||||||
|
|
||||||
|
Optional:
|
||||||
|
|
||||||
|
- `slot_contents[]` — `{ major_step_index, primary, siblings[] }`
|
||||||
|
- `last_findings` — letzter `path_qa`-Snapshot
|
||||||
|
- **`findings_stale`** — bool, Bewertung bezieht sich nicht mehr auf aktuellen Graph-Stand
|
||||||
|
|
||||||
|
## UI (konsolidiert)
|
||||||
|
|
||||||
|
- **Eine Oberfläche:** `ExerciseProgressionGraphPanel` embeddet `ProgressionGraphEditor` (Slots + Findings)
|
||||||
|
- Kein separater Slot-Editor, kein 4-Schritt-KI-Wizard, kein `ProgressionChainEditor` im Panel
|
||||||
|
- Route `/progression-graphs/:id` → Redirect nach `/exercises` (Deep-Link wählt Graph)
|
||||||
|
- **Slot-Keys:** stabil `slot-{index}` (nicht Lernziel-Text) — sonst Fokusverlust beim Tippen
|
||||||
|
|
||||||
|
## Ersetzt (Legacy, nicht mehr im Panel)
|
||||||
|
|
||||||
|
- `ExerciseProgressionPathBuilder` · `ProgressionChainEditor` — Code bleibt vorerst, nicht eingebunden
|
||||||
|
|
||||||
|
## Implementierungsreihenfolge
|
||||||
|
|
||||||
|
| ID | Inhalt | Status |
|
||||||
|
|----|--------|--------|
|
||||||
|
| B.0 | Draft + Laden/Speichern Slots ↔ Kanten | ✅ |
|
||||||
|
| B.1 | Slot-Karten, Bibliothek + Entwurf | ✅ |
|
||||||
|
| B.2 | Findings-Panel + `evaluate_only` | ✅ |
|
||||||
|
| B.3 | Entwürfe im Artefakt + „Übung anlegen“ | ✅ |
|
||||||
|
| B.4 | Route + Panel vereinfachen | ✅ |
|
||||||
|
| B.5 | `last_findings` + Phase-C-Vorbereitung | ✅ |
|
||||||
|
| F15 | Unified Slot-Review, getrennte QS, `findings_stale` | ✅ |
|
||||||
|
|
||||||
|
**Ist-Doku:** `docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md` §8.1 · `docs/HANDOVER.md` §2.8 F15
|
||||||
+9
-3
@@ -38,8 +38,9 @@ OPENROUTER_MODEL=anthropic/claude-sonnet-4
|
|||||||
# Vereins-Kontingente hart blockieren (KI-Kosten!). Nur 1, true oder yes aktivieren.
|
# Vereins-Kontingente hart blockieren (KI-Kosten!). Nur 1, true oder yes aktivieren.
|
||||||
# Nach Änderung: docker compose -f docker-compose.dev-env.yml up -d backend
|
# Nach Änderung: docker compose -f docker-compose.dev-env.yml up -d backend
|
||||||
CLUB_FEATURE_ENFORCE=1
|
CLUB_FEATURE_ENFORCE=1
|
||||||
# Standard-OpenRouter-Modell (alle Aufrufe). Optional pro Prompt in ai_prompts.openrouter_model
|
# Fallback-OpenRouter-Modell, wenn kein Plattform-Standard gespeichert ist.
|
||||||
# ueberschreibbar (Migration 070, Superadmin unter „KI Prompts“).
|
# Superadmin: Administration → KI-Modell (platform_ai_settings, Migration 097).
|
||||||
|
# Optional pro Prompt in ai_prompts.openrouter_model (Migration 070, „KI Prompts“).
|
||||||
|
|
||||||
# Übungs-KI (Docker): ohne Eintrag im compose „environment:“ landet keine .env-Zeile im Container.
|
# Übungs-KI (Docker): ohne Eintrag im compose „environment:“ landet keine .env-Zeile im Container.
|
||||||
# Hier ist SHINKAN_AI_DEBUG in docker-compose*.yml angebunden — 1 = ausführliche WARN-Logs (exercise_ai, openrouter).
|
# Hier ist SHINKAN_AI_DEBUG in docker-compose*.yml angebunden — 1 = ausführliche WARN-Logs (exercise_ai, openrouter).
|
||||||
@@ -53,7 +54,12 @@ SMTP_FROM=noreply@jinkendo.de
|
|||||||
SMTP_SSL=
|
SMTP_SSL=
|
||||||
SMTP_STARTTLS=
|
SMTP_STARTTLS=
|
||||||
|
|
||||||
AUTO_ADMIN_FIRST_USER=true
|
# Produktion: false. true nur für eine bewusst leere Erstinstallation.
|
||||||
|
AUTO_ADMIN_FIRST_USER=false
|
||||||
|
# true erzwingt TOTP für Plattform-Admins beim Login. Standard ist freiwillig.
|
||||||
|
REQUIRE_ADMIN_TOTP=false
|
||||||
|
# Optional. Sonst wird das Medien-Token aus DB_PASSWORD abgeleitet.
|
||||||
|
# MEDIA_TOKEN_SECRET=
|
||||||
ADMIN_BOOTSTRAP_EMAILS=
|
ADMIN_BOOTSTRAP_EMAILS=
|
||||||
|
|
||||||
APP_URL=https://shinkan.jinkendo.de
|
APP_URL=https://shinkan.jinkendo.de
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
name: Deploy Production llm-node
|
||||||
|
|
||||||
|
# Prod-Deployment auf llm-node (192.168.2.144, AMD64), seit dem Cutover 2026-10-29 die einzige Prod.
|
||||||
|
# "Deploy Production" (Raspberry Pi) ist nur noch manuell startbar.
|
||||||
|
# Runner: llm-node-runner mit einzigem Label linux_host (Host-Modus).
|
||||||
|
# Der Pi-Runner (Raspi5-Paperless) hat nur ubuntu-latest und nimmt diesen Job nie an.
|
||||||
|
# Compose: docker-compose.yml + docker-compose.llm-node.yml, Konfiguration aus ENV_FILE.
|
||||||
|
# Doku: .claude/docs/technical/PROD_DEPLOYMENTS.md
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: linux_host
|
||||||
|
env:
|
||||||
|
APP_DIR: /home/llmadmin/docker/shinkan-prod
|
||||||
|
ENV_FILE: /etc/shinkan/prod.env
|
||||||
|
COMPOSE_PROJECT: shinkan-prod
|
||||||
|
REPO_URL: http://192.168.2.144:3000/Lars/shinkan-jinkendo.git
|
||||||
|
MEDIA_HOST: /srv/shinkan/prod/media
|
||||||
|
# Medienbereinigung (retention-cron): disabled | enabled.
|
||||||
|
# Seit dem Cutover führt nur llm-node den Medienbestand. Der Pi-retention-cron muss gestoppt sein:
|
||||||
|
# beide Seiten teilen den Bestand bei getrennten Datenbanken.
|
||||||
|
MEDIA_RETENTION: enabled
|
||||||
|
steps:
|
||||||
|
- name: Runner prüfen (nur llm-node)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ "$(hostname)" != "llm-node" ] || [ "$(uname -m)" != "x86_64" ]; then
|
||||||
|
echo "✗ Falscher Runner: $(hostname)/$(uname -m), erwartet llm-node/x86_64. Abbruch."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "✓ Runner $(hostname)/$(uname -m)"
|
||||||
|
|
||||||
|
- name: Konfiguration prüfen
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ ! -r "$ENV_FILE" ]; then
|
||||||
|
echo "✗ $ENV_FILE fehlt oder ist nicht lesbar."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
env_value() {
|
||||||
|
grep -E "^$1=" "$ENV_FILE" | tail -1 | cut -d= -f2- | tr -d "\"'" || true
|
||||||
|
}
|
||||||
|
if [ -z "$(env_value DB_PASSWORD)" ]; then
|
||||||
|
echo "✗ DB_PASSWORD ist in $ENV_FILE nicht gesetzt."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# Profile steuert allein MEDIA_RETENTION in diesem Workflow.
|
||||||
|
if grep -Eq "^COMPOSE_PROFILES=" "$ENV_FILE"; then
|
||||||
|
echo "✗ COMPOSE_PROFILES in $ENV_FILE entfernen; die Bereinigung schaltet MEDIA_RETENTION im Workflow."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# Override mountet fest $MEDIA_HOST -> /app/media; abweichende Werte ergäben einen zweiten Mount.
|
||||||
|
media_host="$(env_value SHINKAN_MEDIA_HOST)"
|
||||||
|
media_root="$(env_value MEDIA_ROOT)"
|
||||||
|
if [ -n "$media_host" ] && [ "$media_host" != "$MEDIA_HOST" ]; then
|
||||||
|
echo "✗ SHINKAN_MEDIA_HOST=$media_host, erwartet $MEDIA_HOST."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ -n "$media_root" ] && [ "$media_root" != "/app/media" ]; then
|
||||||
|
echo "✗ MEDIA_ROOT=$media_root, erwartet /app/media."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
case "$MEDIA_RETENTION" in
|
||||||
|
disabled|enabled) ;;
|
||||||
|
*) echo "✗ MEDIA_RETENTION=$MEDIA_RETENTION, erlaubt: disabled | enabled."; exit 1 ;;
|
||||||
|
esac
|
||||||
|
echo "✓ $ENV_FILE geprüft, Medien $MEDIA_HOST -> /app/media, Bereinigung $MEDIA_RETENTION"
|
||||||
|
|
||||||
|
- name: Code aktualisieren
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$APP_DIR"
|
||||||
|
if [ ! -d .git ]; then
|
||||||
|
git init -q
|
||||||
|
git remote add origin "$REPO_URL"
|
||||||
|
fi
|
||||||
|
git fetch origin main
|
||||||
|
git reset --hard origin/main
|
||||||
|
git log -1 --oneline
|
||||||
|
|
||||||
|
- name: Build und Start
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
echo "=== Deploying Shinkan to PRODUCTION (llm-node) ==="
|
||||||
|
cd "$APP_DIR"
|
||||||
|
dc() {
|
||||||
|
docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f docker-compose.llm-node.yml \
|
||||||
|
--env-file "$ENV_FILE" "$@"
|
||||||
|
}
|
||||||
|
if [ "$MEDIA_RETENTION" = enabled ]; then
|
||||||
|
dc --profile media-retention build --no-cache
|
||||||
|
dc --profile media-retention up -d --remove-orphans
|
||||||
|
else
|
||||||
|
dc build --no-cache
|
||||||
|
dc up -d --remove-orphans
|
||||||
|
# Ein früher gestarteter retention-cron läuft sonst weiter.
|
||||||
|
dc --profile media-retention rm -s -f retention-cron
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Healthchecks
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$APP_DIR"
|
||||||
|
dc() {
|
||||||
|
docker compose -p "$COMPOSE_PROJECT" -f docker-compose.yml -f docker-compose.llm-node.yml \
|
||||||
|
--env-file "$ENV_FILE" "$@"
|
||||||
|
}
|
||||||
|
wait_for() {
|
||||||
|
local url="$1" label="$2" i
|
||||||
|
for i in $(seq 1 60); do
|
||||||
|
if curl -sf -o /dev/null "$url"; then
|
||||||
|
echo "✓ $label healthy ($url)"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 3
|
||||||
|
done
|
||||||
|
echo "✗ $label nicht erreichbar ($url)"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
# HTTP 200 reicht nicht: status=ready, database=true und schema_complete=true.
|
||||||
|
wait_ready() {
|
||||||
|
local url="$1" label="$2" i body=""
|
||||||
|
for i in $(seq 1 60); do
|
||||||
|
body="$(curl -sf "$url" || true)"
|
||||||
|
if [ -n "$body" ] && printf '%s' "$body" \
|
||||||
|
| jq -e '.status == "ready" and .database == true and .schema_complete == true' >/dev/null 2>&1; then
|
||||||
|
echo "✓ $label ready ($url)"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 3
|
||||||
|
done
|
||||||
|
echo "✗ $label nicht ready ($url):"
|
||||||
|
printf '%s' "$body" | jq -c '{status, database, schema_complete}' 2>/dev/null || echo " keine gültige Antwort"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
ok=1
|
||||||
|
wait_for http://127.0.0.1:8003/api/version "PROD API (direkt)" || ok=0
|
||||||
|
if [ "$ok" = 1 ]; then
|
||||||
|
wait_ready http://127.0.0.1:8003/api/health/ready "PROD API (direkt)" || ok=0
|
||||||
|
fi
|
||||||
|
if [ "$ok" = 1 ]; then
|
||||||
|
wait_for http://127.0.0.1:3003/api/version "PROD API über Frontend-Nginx" || ok=0
|
||||||
|
fi
|
||||||
|
if [ "$ok" = 1 ]; then
|
||||||
|
wait_ready http://127.0.0.1:3003/api/health/ready "PROD API über Frontend-Nginx" || ok=0
|
||||||
|
fi
|
||||||
|
if [ "$ok" = 1 ]; then
|
||||||
|
wait_for http://127.0.0.1:3003/ "PROD Frontend" || ok=0
|
||||||
|
fi
|
||||||
|
if [ "$ok" != 1 ]; then
|
||||||
|
dc ps || true
|
||||||
|
dc logs backend --tail 120 || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "=== Shinkan PROD Deploy (llm-node) complete ==="
|
||||||
@@ -1,13 +1,28 @@
|
|||||||
name: Deploy Production
|
name: Deploy Production
|
||||||
|
|
||||||
|
# ABGESCHALTET seit dem Cutover auf llm-node (2026-10-29): kein Trigger auf main mehr.
|
||||||
|
# Prod läuft über deploy-prod-llm-node.yml. Nur noch manuell startbar, als Rückfallweg.
|
||||||
|
# Ein manueller Lauf startet auch den Pi-retention-cron auf dem gemeinsamen Medienbestand:
|
||||||
|
# vorher MEDIA_RETENTION auf llm-node abschalten. Details: .claude/docs/technical/PROD_DEPLOYMENTS.md
|
||||||
|
# Runner: Raspi5-Paperless mit einzigem Label ubuntu-latest (Host-Modus); der
|
||||||
|
# llm-node-Runner trägt dieses Label nicht. Der Guard bricht auf jedem anderen Host ab.
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
workflow_dispatch:
|
||||||
branches: [main]
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- name: Runner prüfen (nur Raspberry Pi)
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
if [ "$(hostname)" != "raspberrypi5" ] || [ "$(uname -m)" != "aarch64" ]; then
|
||||||
|
echo "✗ Falscher Runner: $(hostname)/$(uname -m), erwartet raspberrypi5/aarch64. Abbruch."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "✓ Runner $(hostname)/$(uname -m)"
|
||||||
|
|
||||||
- name: Deploy to Production
|
- name: Deploy to Production
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
|
|||||||
+27
-119
@@ -1,21 +1,18 @@
|
|||||||
name: Test Suite
|
name: Test Suite
|
||||||
|
|
||||||
# develop: push/PR → Tests gegen Dev (parallel oder vor Deploy Development).
|
# Eigener Workflow, getrennt von Deploy Development.
|
||||||
# main: kein push/PR-Trigger — vermeidet doppelten Dev-Lauf beim Merge develop→main;
|
# push/PR auf develop: Ziel ist ausschließlich das Testsystem.
|
||||||
# Prod-Tests nur via workflow_run nach erfolgreichem Deploy Production.
|
# Kein Lauf gegen Produktion: die Integrationstests schreiben in die Datenbank.
|
||||||
|
# Prod prüfen nur die Healthchecks der Deploy-Workflows.
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [develop]
|
branches: [develop]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [develop]
|
branches: [develop]
|
||||||
workflow_run:
|
|
||||||
workflows: ["Deploy Development", "Deploy Production"]
|
|
||||||
types: [completed]
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
|
# Pytest im laufenden backend-Container; ACCESS_LAYER + TRAINING_PLANNING Integration gegen dieselbe PostgreSQL wie Deploy (Schema via Container-Start migriert).
|
||||||
pytest-backend:
|
pytest-backend:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Backend pytest im deployten Container
|
- name: Backend pytest im deployten Container
|
||||||
@@ -24,19 +21,15 @@ jobs:
|
|||||||
EVENT_NAME="${{ github.event_name }}"
|
EVENT_NAME="${{ github.event_name }}"
|
||||||
REF_NAME="${{ github.ref_name }}"
|
REF_NAME="${{ github.ref_name }}"
|
||||||
BASE_REF="${{ github.base_ref }}"
|
BASE_REF="${{ github.base_ref }}"
|
||||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
|
||||||
APP_DIR="/home/lars/docker/shinkan"
|
|
||||||
COMPOSE_FILE="docker-compose.yml"
|
|
||||||
|
|
||||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
|
||||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
|
||||||
fi
|
|
||||||
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||||
|
else
|
||||||
|
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
echo "CI-Ziel: $APP_DIR ($COMPOSE_FILE)"
|
||||||
|
|
||||||
cd "$APP_DIR"
|
cd "$APP_DIR"
|
||||||
echo "Warte auf stabilen backend-Container …"
|
echo "Warte auf stabilen backend-Container …"
|
||||||
@@ -63,45 +56,41 @@ jobs:
|
|||||||
"
|
"
|
||||||
|
|
||||||
lint-backend:
|
lint-backend:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Check backend syntax
|
- name: Check backend syntax
|
||||||
run: |
|
run: |
|
||||||
EVENT_NAME="${{ github.event_name }}"
|
EVENT_NAME="${{ github.event_name }}"
|
||||||
REF_NAME="${{ github.ref_name }}"
|
REF_NAME="${{ github.ref_name }}"
|
||||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
BASE_REF="${{ github.base_ref }}"
|
||||||
APP_DIR="/home/lars/docker/shinkan"
|
|
||||||
|
|
||||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
|
||||||
fi
|
|
||||||
elif [ "$REF_NAME" = "develop" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||||
|
else
|
||||||
|
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
echo "CI-Ziel: $APP_DIR"
|
||||||
|
|
||||||
python3 -m py_compile "$APP_DIR/backend/main.py"
|
python3 -m py_compile "$APP_DIR/backend/main.py"
|
||||||
echo "✓ Backend syntax OK"
|
echo "✓ Backend syntax OK"
|
||||||
|
|
||||||
build-frontend:
|
build-frontend:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Build frontend
|
- name: Build frontend
|
||||||
run: |
|
run: |
|
||||||
EVENT_NAME="${{ github.event_name }}"
|
EVENT_NAME="${{ github.event_name }}"
|
||||||
REF_NAME="${{ github.ref_name }}"
|
REF_NAME="${{ github.ref_name }}"
|
||||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
BASE_REF="${{ github.base_ref }}"
|
||||||
APP_DIR="/home/lars/docker/shinkan"
|
|
||||||
|
|
||||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
if [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
|
||||||
fi
|
|
||||||
elif [ "$REF_NAME" = "develop" ]; then
|
|
||||||
APP_DIR="/home/lars/docker/shinkan-dev"
|
APP_DIR="/home/lars/docker/shinkan-dev"
|
||||||
|
else
|
||||||
|
echo "Kein Dev-Ziel (event=$EVENT_NAME ref=$REF_NAME base=$BASE_REF). Abbruch."
|
||||||
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
echo "CI-Ziel: $APP_DIR"
|
||||||
|
|
||||||
cd "$APP_DIR/frontend"
|
cd "$APP_DIR/frontend"
|
||||||
npm install
|
npm install
|
||||||
@@ -111,7 +100,6 @@ jobs:
|
|||||||
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
|
# Phase-0 Lastsmoke: nur k6 — eigener Job (kein Node/Playwright), klare CI-Zuordnung.
|
||||||
k6-health-baseline:
|
k6-health-baseline:
|
||||||
name: k6 /health Baseline
|
name: k6 /health Baseline
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
env:
|
env:
|
||||||
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||||
@@ -119,26 +107,9 @@ jobs:
|
|||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
|
||||||
id: e2e
|
|
||||||
run: |
|
|
||||||
EVENT="${{ github.event_name }}"
|
|
||||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
|
||||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
|
||||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
|
||||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
|
||||||
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
|
|
||||||
echo "→ k6 gegen Prod-Basis."
|
|
||||||
else
|
|
||||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
|
||||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
|
||||||
echo "→ k6 gegen Dev (${DEV_BASE})."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Dev /health abwarten
|
- name: Dev /health abwarten
|
||||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
|
||||||
run: |
|
run: |
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
BASE="${{ env.E2E_TARGET_URL }}"
|
||||||
echo "Warte auf $BASE/health …"
|
echo "Warte auf $BASE/health …"
|
||||||
for i in $(seq 1 90); do
|
for i in $(seq 1 90); do
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||||
@@ -151,22 +122,6 @@ jobs:
|
|||||||
curl -v "$BASE/health" || true
|
curl -v "$BASE/health" || true
|
||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
- name: Prod /health abwarten
|
|
||||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
|
||||||
run: |
|
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
|
||||||
echo "Warte auf $BASE/health …"
|
|
||||||
for i in $(seq 1 60); do
|
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
|
||||||
echo "Health OK (Versuch $i)"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 5
|
|
||||||
done
|
|
||||||
echo "Timeout: Prod /health nicht erreichbar"
|
|
||||||
curl -v "$BASE/health" || true
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Install k6
|
- name: Install k6
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
@@ -185,7 +140,7 @@ jobs:
|
|||||||
|
|
||||||
- name: k6 Health-Baseline (parallele /health)
|
- name: k6 Health-Baseline (parallele /health)
|
||||||
env:
|
env:
|
||||||
BASE_URL: ${{ steps.e2e.outputs.base_url }}
|
BASE_URL: ${{ env.E2E_TARGET_URL }}
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
echo "k6 gegen BASE_URL=$BASE_URL"
|
echo "k6 gegen BASE_URL=$BASE_URL"
|
||||||
@@ -193,10 +148,9 @@ jobs:
|
|||||||
echo "✓ k6 Health-Baseline passed"
|
echo "✓ k6 Health-Baseline passed"
|
||||||
|
|
||||||
playwright-tests:
|
playwright-tests:
|
||||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
# Kein zusätzlicher docker-compose im Job: keine zweiten Container/Host-Ports.
|
# Kein zusätzlicher docker-compose im Job: keine zweiten Container/Host-Ports.
|
||||||
# Dev: Tests gegen bereits deployte URL (HTTPS, Reverse-Proxy). Prod: gleicher Ablauf.
|
# Tests gegen die bereits deployte Dev-URL (HTTPS, Reverse-Proxy).
|
||||||
env:
|
env:
|
||||||
# Öffentliche Dev-Basis — muss ALLOWED_ORIGINS / Nginx entsprechen; bei anderer Domain Workflow anpassen.
|
# Öffentliche Dev-Basis — muss ALLOWED_ORIGINS / Nginx entsprechen; bei anderer Domain Workflow anpassen.
|
||||||
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
E2E_TARGET_URL: https://dev.shinkan.jinkendo.de
|
||||||
@@ -209,26 +163,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: '20'
|
node-version: '20'
|
||||||
|
|
||||||
- name: E2E-Ziel wählen (Dev über Proxy vs. Production)
|
|
||||||
id: e2e
|
|
||||||
run: |
|
|
||||||
EVENT="${{ github.event_name }}"
|
|
||||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
|
||||||
DEV_BASE="${{ env.E2E_TARGET_URL }}"
|
|
||||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
|
||||||
echo "mode=prod" >> $GITHUB_OUTPUT
|
|
||||||
echo "base_url=https://shinkan.jinkendo.de" >> $GITHUB_OUTPUT
|
|
||||||
echo "→ Prod. Secrets: E2E_PROD_TEST_EMAIL / E2E_PROD_TEST_PASSWORD."
|
|
||||||
else
|
|
||||||
echo "mode=dev" >> $GITHUB_OUTPUT
|
|
||||||
echo "base_url=${DEV_BASE}" >> $GITHUB_OUTPUT
|
|
||||||
echo "→ Deployte Dev-Umgebung (${DEV_BASE}). Secrets: E2E_DEV_TEST_EMAIL / E2E_DEV_TEST_PASSWORD."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Dev /health abwarten
|
- name: Dev /health abwarten
|
||||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
|
||||||
run: |
|
run: |
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
BASE="${{ env.E2E_TARGET_URL }}"
|
||||||
echo "Warte auf $BASE/health …"
|
echo "Warte auf $BASE/health …"
|
||||||
for i in $(seq 1 90); do
|
for i in $(seq 1 90); do
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
||||||
@@ -241,29 +178,12 @@ jobs:
|
|||||||
curl -v "$BASE/health" || true
|
curl -v "$BASE/health" || true
|
||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
- name: Prod /health abwarten
|
|
||||||
if: ${{ steps.e2e.outputs.mode == 'prod' }}
|
|
||||||
run: |
|
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
|
||||||
echo "Warte auf $BASE/health …"
|
|
||||||
for i in $(seq 1 60); do
|
|
||||||
if curl -sf "$BASE/health" >/dev/null 2>&1; then
|
|
||||||
echo "Health OK (Versuch $i)"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 5
|
|
||||||
done
|
|
||||||
echo "Timeout: Prod /health nicht erreichbar"
|
|
||||||
curl -v "$BASE/health" || true
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Testnutzer registrieren (Dev, nur wenn möglich)
|
- name: Testnutzer registrieren (Dev, nur wenn möglich)
|
||||||
if: ${{ steps.e2e.outputs.mode == 'dev' }}
|
|
||||||
env:
|
env:
|
||||||
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
|
E2E_DEV_TEST_EMAIL: ${{ secrets.E2E_DEV_TEST_EMAIL }}
|
||||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
BASE="${{ steps.e2e.outputs.base_url }}"
|
BASE="${{ env.E2E_TARGET_URL }}"
|
||||||
if [ -z "$E2E_DEV_TEST_EMAIL" ] || [ -z "$E2E_DEV_TEST_PASSWORD" ]; then
|
if [ -z "$E2E_DEV_TEST_EMAIL" ] || [ -z "$E2E_DEV_TEST_PASSWORD" ]; then
|
||||||
echo "(Registrierung übersprungen — Secrets E2E_DEV_* nicht gesetzt.)"
|
echo "(Registrierung übersprungen — Secrets E2E_DEV_* nicht gesetzt.)"
|
||||||
exit 0
|
exit 0
|
||||||
@@ -284,25 +204,13 @@ jobs:
|
|||||||
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
E2E_DEV_TEST_PASSWORD: ${{ secrets.E2E_DEV_TEST_PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
set -e
|
set -e
|
||||||
MODE="${{ steps.e2e.outputs.mode }}"
|
export PLAYWRIGHT_BASE_URL="${{ env.E2E_TARGET_URL }}"
|
||||||
BASE_URL="${{ steps.e2e.outputs.base_url }}"
|
|
||||||
export PLAYWRIGHT_BASE_URL="$BASE_URL"
|
|
||||||
|
|
||||||
if [ "$MODE" = "prod" ]; then
|
|
||||||
export TEST_EMAIL="${{ secrets.E2E_PROD_TEST_EMAIL }}"
|
|
||||||
export TEST_PASSWORD="${{ secrets.E2E_PROD_TEST_PASSWORD }}"
|
|
||||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
|
||||||
echo "Fehler: E2E_PROD_TEST_EMAIL und E2E_PROD_TEST_PASSWORD setzen."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
|
export TEST_EMAIL="$E2E_DEV_TEST_EMAIL"
|
||||||
export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
|
export TEST_PASSWORD="$E2E_DEV_TEST_PASSWORD"
|
||||||
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
if [ -z "$TEST_EMAIL" ] || [ -z "$TEST_PASSWORD" ]; then
|
||||||
echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
|
echo "Fehler: E2E_DEV_TEST_EMAIL und E2E_DEV_TEST_PASSWORD setzen (Playwright soll gegen Dev einloggen)."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
fi
|
|
||||||
|
|
||||||
mkdir -p screenshots
|
mkdir -p screenshots
|
||||||
npx playwright test
|
npx playwright test
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
> | Architektur-Zielbild, Refaktor-Roadmap, verbindliche Shinkan-Regeln | **`docs/architecture/README.md`** |
|
> | Architektur-Zielbild, Refaktor-Roadmap, verbindliche Shinkan-Regeln | **`docs/architecture/README.md`** |
|
||||||
> | Performance-Baseline (Phase 0) | **`docs/architecture/BASELINE_SNAPSHOT.md`** |
|
> | Performance-Baseline (Phase 0) | **`docs/architecture/BASELINE_SNAPSHOT.md`** |
|
||||||
> | KI-Prompt-System — Zielarchitektur | `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` |
|
> | KI-Prompt-System — Zielarchitektur | `.claude/docs/technical/AI_PROMPT_TARGET_ARCHITECTURE.md` |
|
||||||
> | Planungs-KI Progressions-Roadmap (Phase F) | **`.claude/docs/working/PLANNING_PROGRESSION_ROADMAP_SPEC.md`** · **`docs/architecture/PLANNING_KI_ROADMAP.md`** |
|
> | Planungs-KI Progressionsgraph (Ist-Stand) | **`docs/architecture/PLANNING_PROGRESSION_GRAPH_KI.md`** · Spec **`.claude/docs/working/PLANNING_PROGRESSION_ROADMAP_SPEC.md`** · Roadmap **`docs/architecture/PLANNING_KI_ROADMAP.md`** |
|
||||||
|
|
||||||
## Projekt-Übersicht
|
## Projekt-Übersicht
|
||||||
|
|
||||||
@@ -137,10 +137,15 @@ Internet → Fritz!Box (privat.stommer.com) → Synology NAS → Raspberry Pi 5
|
|||||||
|
|
||||||
Git Workflow:
|
Git Workflow:
|
||||||
develop → Auto-Deploy → dev.shinkan.jinkendo.de (shinkan-dev/, Port 3098/8098)
|
develop → Auto-Deploy → dev.shinkan.jinkendo.de (shinkan-dev/, Port 3098/8098)
|
||||||
main → Auto-Deploy → shinkan.jinkendo.de (shinkan/, Port 3003/8003)
|
main → Auto-Deploy → shinkan.jinkendo.de auf llm-node (192.168.2.144, /home/llmadmin/docker/shinkan-prod)
|
||||||
|
Workflow deploy-prod-llm-node.yml, Port 3003/8003
|
||||||
|
Compose-Override docker-compose.llm-node.yml, Config /etc/shinkan/prod.env
|
||||||
|
Pi-Prod (shinkan/, deploy-prod.yml) seit Cutover 2026-10-29 nur noch manuell
|
||||||
|
Details: .claude/docs/technical/PROD_DEPLOYMENTS.md
|
||||||
|
|
||||||
Gitea: http://192.168.2.144:3000/Lars/shinkan-jinkendo
|
Gitea: http://192.168.2.144:3000/Lars/shinkan-jinkendo
|
||||||
Runner: Raspberry Pi (/home/lars/gitea-runner/)
|
Runner: Raspberry Pi (/home/lars/gitea-runner/, Label ubuntu-latest)
|
||||||
|
llm-node (act_runner.service, Label linux_host)
|
||||||
|
|
||||||
Manuell:
|
Manuell:
|
||||||
cd /home/lars/docker/shinkan[-dev]
|
cd /home/lars/docker/shinkan[-dev]
|
||||||
|
|||||||
+4
-2
@@ -2,14 +2,16 @@ FROM python:3.12-slim
|
|||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Install system dependencies
|
# Install system dependencies (tzdata für zoneinfo/ZoneInfo unter Linux)
|
||||||
RUN apt-get update && apt-get install -y \
|
RUN apt-get update && apt-get install -y \
|
||||||
postgresql-client \
|
postgresql-client \
|
||||||
|
tzdata \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# Copy requirements and install dependencies
|
# Copy requirements and install dependencies
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
ENV PIP_DEFAULT_TIMEOUT=120
|
||||||
|
RUN pip install --no-cache-dir --retries 5 -r requirements.txt
|
||||||
|
|
||||||
# Copy application code
|
# Copy application code
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ AUTH_INFRA_PREFIXES = (
|
|||||||
"/api/auth/status",
|
"/api/auth/status",
|
||||||
"/api/auth/pin",
|
"/api/auth/pin",
|
||||||
"/api/auth/resend-verification",
|
"/api/auth/resend-verification",
|
||||||
|
"/api/auth/totp",
|
||||||
|
"/api/auth/media-grant",
|
||||||
"/api/profiles/me",
|
"/api/profiles/me",
|
||||||
"/api/me/entitlements",
|
"/api/me/entitlements",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Aufgabengruppen für OpenRouter-Modelle. Die Zuordnung der Prompts lebt in ai_prompts.model_role."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Optional, Tuple
|
||||||
|
|
||||||
|
ROLE_KEYS = frozenset({"reasoning", "drafting", "matching"})
|
||||||
|
|
||||||
|
_FALLBACK_MODEL = "anthropic/claude-sonnet-4"
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_prompt_openrouter_model(
|
||||||
|
*,
|
||||||
|
prompt_model: Optional[str],
|
||||||
|
role_model: Optional[str],
|
||||||
|
platform_model: Optional[str],
|
||||||
|
env_model: Optional[str],
|
||||||
|
) -> Tuple[str, str]:
|
||||||
|
"""
|
||||||
|
Auflösung und Quelle.
|
||||||
|
|
||||||
|
Quelle ist `prompt`, `role`, `database` oder `environment`.
|
||||||
|
Ungültige IDs werden übersprungen.
|
||||||
|
"""
|
||||||
|
from openrouter_chat import normalize_openrouter_model_id
|
||||||
|
|
||||||
|
for raw, source in (
|
||||||
|
(prompt_model, "prompt"),
|
||||||
|
(role_model, "role"),
|
||||||
|
(platform_model, "database"),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
model = normalize_openrouter_model_id(raw)
|
||||||
|
except ValueError:
|
||||||
|
model = None
|
||||||
|
if model:
|
||||||
|
return model, source
|
||||||
|
env = (str(env_model or "").strip() or _FALLBACK_MODEL)
|
||||||
|
return env, "environment"
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
"""
|
||||||
|
Admin-Vorschau: Platzhalter für Planungs-Prompts (Progressionsgraph, Pfad-QS, Suggest).
|
||||||
|
|
||||||
|
Nutzt repräsentative Beispieldaten + echte Katalog-Auszüge aus der DB.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from planning_exercise_semantics import brief_to_summary_dict, build_semantic_brief
|
||||||
|
from planning_intent_context import build_planning_intent_context
|
||||||
|
from planning_prompt_variables import merge_planning_prompt_variables
|
||||||
|
|
||||||
|
PLANNING_PROMPT_SLUGS = frozenset(
|
||||||
|
{
|
||||||
|
"planning_progression_start_target",
|
||||||
|
"planning_progression_goal_analysis",
|
||||||
|
"planning_progression_roadmap",
|
||||||
|
"planning_progression_stage_spec",
|
||||||
|
"planning_exercise_query_semantics",
|
||||||
|
"planning_exercise_path_qa",
|
||||||
|
"planning_exercise_search_intent",
|
||||||
|
"planning_exercise_search_rank",
|
||||||
|
"planning_exercise_expectation_profile",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PlanningPromptPreviewInput(BaseModel):
|
||||||
|
goal_query: str = Field(
|
||||||
|
default="Mae Geri vom Grundschritt bis zur kontrollierten Kumite-Nähe",
|
||||||
|
max_length=2000,
|
||||||
|
)
|
||||||
|
user_notes: str = Field(default="Fokus Breitensport, ohne Wettkampfdruck.", max_length=2000)
|
||||||
|
max_steps: int = Field(default=5, ge=2, le=10)
|
||||||
|
search_query: Optional[str] = Field(default=None, max_length=2000)
|
||||||
|
planning_catalog_context: Optional[Dict[str, Any]] = Field(default=None)
|
||||||
|
|
||||||
|
|
||||||
|
def is_planning_prompt_slug(slug: str) -> bool:
|
||||||
|
return (slug or "").strip().lower() in PLANNING_PROMPT_SLUGS
|
||||||
|
|
||||||
|
|
||||||
|
def _compact_json(obj: Any) -> str:
|
||||||
|
return json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_goal_analysis() -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"primary_topic": "Mae Geri",
|
||||||
|
"start_assumption": "Grundstellung und einfache Frontkick-Bewegung bekannt",
|
||||||
|
"target_state": "Kontrollierter Mae Geri in Kumite-Nähe mit Hüftöffnung",
|
||||||
|
"success_criteria": [
|
||||||
|
"Hüfte öffnet vor dem Kick",
|
||||||
|
"Ballen trifft Zielzone",
|
||||||
|
"Rückzug ohne Balanceverlust",
|
||||||
|
],
|
||||||
|
"constraints": {
|
||||||
|
"partner_required": False,
|
||||||
|
"excluded_themes": ["reine Kraft ohne Technikbezug"],
|
||||||
|
"trainer_notes": "Breitensport, kein Wettkampf",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_major_steps(max_steps: int) -> List[Dict[str, Any]]:
|
||||||
|
phases = ["einstieg", "grundlage", "vertiefung", "anwendung", "perfektion"]
|
||||||
|
titles = [
|
||||||
|
"Grundstellung und Mae Geri Einstieg",
|
||||||
|
"Hüftöffnung und Ballen-Fokus",
|
||||||
|
"Koordination und Rückzug",
|
||||||
|
"Anwendung in Partnerübung",
|
||||||
|
"Qualität unter leichtem Druck",
|
||||||
|
]
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
for i in range(max_steps):
|
||||||
|
out.append(
|
||||||
|
{
|
||||||
|
"index": i,
|
||||||
|
"phase": phases[min(i, len(phases) - 1)],
|
||||||
|
"title": titles[min(i, len(titles) - 1)],
|
||||||
|
"learning_goal": titles[min(i, len(titles) - 1)],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_path_steps() -> List[Dict[str, Any]]:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"index": 1,
|
||||||
|
"exercise_id": 101,
|
||||||
|
"title": "Mae Geri — Stand und Hüftöffnung",
|
||||||
|
"goal": "Frontkick mit geöffneter Hüfte aus Grundstellung",
|
||||||
|
"is_bridge": False,
|
||||||
|
"is_ai_proposal": False,
|
||||||
|
"reasons": ["Stufen-Gate: Grundlagen"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"index": 2,
|
||||||
|
"exercise_id": 102,
|
||||||
|
"title": "Mae Geri — Ballen und Rückzug",
|
||||||
|
"goal": "Präziser Ballentreffer mit kontrolliertem Rückzug",
|
||||||
|
"is_bridge": False,
|
||||||
|
"is_ai_proposal": False,
|
||||||
|
"reasons": ["Nachfolger im Graph"],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_planning_context() -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"scope": "progression_path",
|
||||||
|
"goal_query": "Mae Geri vom Grundschritt bis zur Kumite-Nähe",
|
||||||
|
"stage_index": 1,
|
||||||
|
"learning_goal": "Hüftöffnung und Ballen-Fokus",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_target_profile() -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"primary_focus": "Kihon",
|
||||||
|
"training_type": "Breitensport",
|
||||||
|
"skill_expectations": ["Geri Waza", "Koordination"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_candidates() -> List[Dict[str, Any]]:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"exercise_id": 101,
|
||||||
|
"title": "Mae Geri — Stand und Hüftöffnung",
|
||||||
|
"summary": "Frontkick mit Hüftöffnung",
|
||||||
|
"skill_names": ["Geri Waza"],
|
||||||
|
"score_hint": 0.82,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"exercise_id": 102,
|
||||||
|
"title": "Mae Geri — Ballen und Rückzug",
|
||||||
|
"summary": "Ballentreffer mit Rückzug",
|
||||||
|
"skill_names": ["Geri Waza", "Koordination"],
|
||||||
|
"score_hint": 0.76,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_catalog_variables(cur) -> Dict[str, str]:
|
||||||
|
from planning_exercise_intent import (
|
||||||
|
_load_compact_catalog,
|
||||||
|
_load_skills_catalog_compact,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"skills_catalog_json": _compact_json(_load_skills_catalog_compact(cur)),
|
||||||
|
"focus_areas_catalog_json": _compact_json(_load_compact_catalog(cur, "focus_areas", "id")),
|
||||||
|
"training_types_catalog_json": _compact_json(_load_compact_catalog(cur, "training_types", "id")),
|
||||||
|
"style_directions_catalog_json": _compact_json(_load_compact_catalog(cur, "style_directions", "id")),
|
||||||
|
"target_groups_catalog_json": _compact_json(_load_compact_catalog(cur, "target_groups", "id")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _preview_catalog_context(body: PlanningPromptPreviewInput):
|
||||||
|
from planning_catalog_context import catalog_context_from_mapping
|
||||||
|
|
||||||
|
raw = body.planning_catalog_context
|
||||||
|
if raw:
|
||||||
|
return catalog_context_from_mapping(raw)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_catalog_preview(cur, slug: str, base: Dict[str, str], body: PlanningPromptPreviewInput) -> Dict[str, str]:
|
||||||
|
return merge_planning_prompt_variables(
|
||||||
|
cur,
|
||||||
|
base,
|
||||||
|
catalog=_preview_catalog_context(body),
|
||||||
|
slug=slug,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_planning_prompt_preview_variables(
|
||||||
|
cur,
|
||||||
|
slug: str,
|
||||||
|
body: PlanningPromptPreviewInput,
|
||||||
|
) -> Dict[str, str]:
|
||||||
|
"""Mustache-Variablen für Planungs-Prompt-Vorschau im Admin."""
|
||||||
|
s = (slug or "").strip().lower()
|
||||||
|
if s not in PLANNING_PROMPT_SLUGS:
|
||||||
|
raise ValueError(f"Kein Planungs-Prompt-Slug: {slug!r}")
|
||||||
|
|
||||||
|
goal_query = (body.goal_query or "").strip() or "Mae Geri Progression"
|
||||||
|
search_query = (body.search_query or "").strip() or goal_query
|
||||||
|
max_steps = int(body.max_steps)
|
||||||
|
brief = build_semantic_brief(goal_query)
|
||||||
|
brief_json = _compact_json(brief_to_summary_dict(brief))
|
||||||
|
goal_analysis = _sample_goal_analysis()
|
||||||
|
major_steps = _sample_major_steps(max_steps)
|
||||||
|
intent_ctx = build_planning_intent_context(
|
||||||
|
goal_query=goal_query,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
semantic_brief=brief,
|
||||||
|
extra_context=(body.user_notes or "").strip() or None,
|
||||||
|
)
|
||||||
|
intent_ctx_json = _compact_json(intent_ctx.to_api_dict())
|
||||||
|
ctx = _sample_planning_context()
|
||||||
|
target = _sample_target_profile()
|
||||||
|
catalogs = _load_catalog_variables(cur)
|
||||||
|
|
||||||
|
if s == "planning_progression_start_target":
|
||||||
|
return _merge_catalog_preview(
|
||||||
|
cur,
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"goal_query": goal_query,
|
||||||
|
"semantic_brief_json": brief_json,
|
||||||
|
"user_notes": (body.user_notes or "").strip(),
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
|
||||||
|
if s == "planning_progression_goal_analysis":
|
||||||
|
return _merge_catalog_preview(
|
||||||
|
cur,
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"goal_query": goal_query,
|
||||||
|
"semantic_brief_json": brief_json,
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
|
||||||
|
if s == "planning_progression_roadmap":
|
||||||
|
return _merge_catalog_preview(
|
||||||
|
cur,
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"goal_query": goal_query,
|
||||||
|
"goal_analysis_json": _compact_json(goal_analysis),
|
||||||
|
"semantic_brief_json": brief_json,
|
||||||
|
"max_steps": str(max_steps),
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
|
||||||
|
if s == "planning_progression_stage_spec":
|
||||||
|
return _merge_catalog_preview(
|
||||||
|
cur,
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"goal_query": goal_query,
|
||||||
|
"goal_analysis_json": _compact_json(goal_analysis),
|
||||||
|
"major_steps_json": _compact_json(major_steps),
|
||||||
|
"intent_context_json": intent_ctx_json,
|
||||||
|
"semantic_brief_json": brief_json,
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
|
||||||
|
if s == "planning_exercise_query_semantics":
|
||||||
|
return {
|
||||||
|
"search_query": search_query,
|
||||||
|
"semantic_brief_json": brief_json,
|
||||||
|
}
|
||||||
|
|
||||||
|
if s == "planning_exercise_path_qa":
|
||||||
|
return _merge_catalog_preview(
|
||||||
|
cur,
|
||||||
|
s,
|
||||||
|
{
|
||||||
|
"goal_query": goal_query,
|
||||||
|
"semantic_brief_json": brief_json,
|
||||||
|
"steps_json": _compact_json(_sample_path_steps()),
|
||||||
|
"gaps_json": _compact_json([]),
|
||||||
|
"bridge_inserts_json": _compact_json([]),
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
|
||||||
|
if s == "planning_exercise_search_intent":
|
||||||
|
return {
|
||||||
|
"search_query": search_query,
|
||||||
|
"heuristic_intent": "progression_next",
|
||||||
|
"scenario_hint": "preset_next",
|
||||||
|
"planning_context_json": _compact_json(ctx),
|
||||||
|
"target_profile_json": _compact_json(target),
|
||||||
|
**catalogs,
|
||||||
|
}
|
||||||
|
|
||||||
|
if s == "planning_exercise_search_rank":
|
||||||
|
return {
|
||||||
|
"search_query": search_query,
|
||||||
|
"intent": "progression_next",
|
||||||
|
"planning_context_json": _compact_json(ctx),
|
||||||
|
"target_profile_json": _compact_json(target),
|
||||||
|
"candidates_json": _compact_json(_sample_candidates()),
|
||||||
|
"result_limit": "5",
|
||||||
|
}
|
||||||
|
|
||||||
|
if s == "planning_exercise_expectation_profile":
|
||||||
|
return {
|
||||||
|
"heuristic_intent": "suggest_next",
|
||||||
|
"planning_context_json": _compact_json(ctx),
|
||||||
|
"target_profile_json": _compact_json(target),
|
||||||
|
**{k: v for k, v in catalogs.items() if k != "style_directions_catalog_json"},
|
||||||
|
}
|
||||||
|
|
||||||
|
raise ValueError(f"Planungs-Prompt-Slug nicht implementiert: {slug!r}")
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"PLANNING_PROMPT_SLUGS",
|
||||||
|
"PlanningPromptPreviewInput",
|
||||||
|
"is_planning_prompt_slug",
|
||||||
|
"resolve_planning_prompt_preview_variables",
|
||||||
|
]
|
||||||
@@ -57,7 +57,7 @@ def load_ai_prompt_row(cur, slug: str, *, active_only: bool = True) -> Optional[
|
|||||||
if active_only:
|
if active_only:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
SELECT slug, display_name, template, output_format, active, openrouter_model
|
SELECT slug, display_name, template, output_format, active, openrouter_model, model_role
|
||||||
FROM ai_prompts
|
FROM ai_prompts
|
||||||
WHERE slug = %s AND active = true
|
WHERE slug = %s AND active = true
|
||||||
""",
|
""",
|
||||||
@@ -66,7 +66,7 @@ def load_ai_prompt_row(cur, slug: str, *, active_only: bool = True) -> Optional[
|
|||||||
else:
|
else:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
SELECT slug, display_name, template, output_format, active, openrouter_model
|
SELECT slug, display_name, template, output_format, active, openrouter_model, model_role
|
||||||
FROM ai_prompts
|
FROM ai_prompts
|
||||||
WHERE slug = %s
|
WHERE slug = %s
|
||||||
""",
|
""",
|
||||||
|
|||||||
+70
-4
@@ -12,6 +12,11 @@ from fastapi import Header, Query, HTTPException
|
|||||||
import bcrypt
|
import bcrypt
|
||||||
|
|
||||||
from db import get_db, get_cursor
|
from db import get_db, get_cursor
|
||||||
|
from media_grant import profile_id_from_media_grant
|
||||||
|
|
||||||
|
# Fester bcrypt-Hash, damit ein unbekannter Login dieselbe Rechenzeit hat wie ein Treffer.
|
||||||
|
_LOGIN_TIMING_HASH = "$2b$12$GYdnAmeiqaZg/.5J9E4f4.xhz70piViqXIpqKCY/FY609qj65sc9i"
|
||||||
|
MAX_SESSION_DAYS = 30
|
||||||
|
|
||||||
|
|
||||||
def hash_pin(pin: str) -> str:
|
def hash_pin(pin: str) -> str:
|
||||||
@@ -33,6 +38,34 @@ def verify_pin(pin: str, stored_hash: str) -> bool:
|
|||||||
return stored_hash == hashlib.sha256(pin.encode()).hexdigest()
|
return stored_hash == hashlib.sha256(pin.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def verify_pin_for_login(pin: str, stored_hash: Optional[str]) -> bool:
|
||||||
|
"""Immer ein bcrypt-Vergleich, auch wenn das Konto fehlt (kein Zeit-Orakel)."""
|
||||||
|
if stored_hash and str(stored_hash).startswith("$2"):
|
||||||
|
return verify_pin(pin, stored_hash)
|
||||||
|
verify_pin(pin or "x", _LOGIN_TIMING_HASH)
|
||||||
|
if not stored_hash:
|
||||||
|
return False
|
||||||
|
return verify_pin(pin, stored_hash)
|
||||||
|
|
||||||
|
|
||||||
|
def session_lifetime_days(profile: Optional[dict]) -> int:
|
||||||
|
raw = profile.get("session_days") if profile else None
|
||||||
|
try:
|
||||||
|
days = int(raw) if raw is not None else MAX_SESSION_DAYS
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
days = MAX_SESSION_DAYS
|
||||||
|
if days < 1:
|
||||||
|
days = 1
|
||||||
|
if days > MAX_SESSION_DAYS:
|
||||||
|
days = MAX_SESSION_DAYS
|
||||||
|
return days
|
||||||
|
|
||||||
|
|
||||||
|
def revoke_profile_sessions(cur, profile_id: int) -> None:
|
||||||
|
"""Alle Sitzungen eines Profils entfernen, inklusive Reset- und 2FA-Zwischentokens."""
|
||||||
|
cur.execute("DELETE FROM sessions WHERE profile_id = %s", (profile_id,))
|
||||||
|
|
||||||
|
|
||||||
def make_token() -> str:
|
def make_token() -> str:
|
||||||
"""Generate a secure random token for sessions."""
|
"""Generate a secure random token for sessions."""
|
||||||
return secrets.token_urlsafe(32)
|
return secrets.token_urlsafe(32)
|
||||||
@@ -51,12 +84,39 @@ def get_session(token: str):
|
|||||||
cur.execute(
|
cur.execute(
|
||||||
"SELECT s.*, p.role, p.name "
|
"SELECT s.*, p.role, p.name "
|
||||||
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
||||||
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP",
|
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP "
|
||||||
|
"AND COALESCE(s.purpose, 'full') = 'full'",
|
||||||
(token,)
|
(token,)
|
||||||
)
|
)
|
||||||
return cur.fetchone()
|
return cur.fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def get_limited_session(token: str, purpose: str):
|
||||||
|
"""Sitzung mit festem Zweck (totp_enroll, totp_challenge). Kein Fach-API-Zugriff."""
|
||||||
|
if not token or purpose not in ("totp_enroll", "totp_challenge"):
|
||||||
|
return None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT s.*, p.role, p.name, p.email "
|
||||||
|
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
||||||
|
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP "
|
||||||
|
"AND s.purpose = %s",
|
||||||
|
(token, purpose),
|
||||||
|
)
|
||||||
|
return cur.fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def _profile_session_from_id(profile_id: int) -> Optional[dict]:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id AS profile_id, role, name FROM profiles WHERE id = %s",
|
||||||
|
(profile_id,),
|
||||||
|
)
|
||||||
|
return cur.fetchone()
|
||||||
|
|
||||||
|
|
||||||
def require_auth(x_auth_token: Optional[str] = Header(default=None)):
|
def require_auth(x_auth_token: Optional[str] = Header(default=None)):
|
||||||
"""
|
"""
|
||||||
FastAPI dependency - requires valid authentication.
|
FastAPI dependency - requires valid authentication.
|
||||||
@@ -80,8 +140,8 @@ def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), ss
|
|||||||
"""
|
"""
|
||||||
FastAPI dependency - auth via header OR query parameter.
|
FastAPI dependency - auth via header OR query parameter.
|
||||||
|
|
||||||
Used for endpoints accessed by <img> tags and SSE connections that can't send headers.
|
Dateiabruf für <img>/<video>: Header-Sitzung oder kurzlebiges Medien-Token (?ssetoken).
|
||||||
Query parameter is 'ssetoken' to avoid conflicts with endpoint 'token' parameters.
|
Ein Sitzungstoken in der Query-Zeichenfolge wird nicht akzeptiert.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
@app.get("/api/photos/{id}")
|
@app.get("/api/photos/{id}")
|
||||||
@@ -93,7 +153,13 @@ def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), ss
|
|||||||
Raises:
|
Raises:
|
||||||
HTTPException 401 if not authenticated
|
HTTPException 401 if not authenticated
|
||||||
"""
|
"""
|
||||||
session = get_session(x_auth_token or ssetoken)
|
session = get_session(x_auth_token) if x_auth_token else None
|
||||||
|
if session:
|
||||||
|
return session
|
||||||
|
profile_id = profile_id_from_media_grant(ssetoken)
|
||||||
|
if profile_id is None:
|
||||||
|
raise HTTPException(401, "Nicht eingeloggt")
|
||||||
|
session = _profile_session_from_id(profile_id)
|
||||||
if not session:
|
if not session:
|
||||||
raise HTTPException(401, "Nicht eingeloggt")
|
raise HTTPException(401, "Nicht eingeloggt")
|
||||||
return session
|
return session
|
||||||
|
|||||||
@@ -0,0 +1,432 @@
|
|||||||
|
"""
|
||||||
|
Katalog-Prompt-Slots — Slot-Typ-Vokabular + Werte pro Stammdaten-Zeile (H2).
|
||||||
|
|
||||||
|
Prompts in ai_prompts referenzieren Platzhalter wie {{focus_area_hints_on_progression}}.
|
||||||
|
Inhalte liegen in catalog_prompt_slots (Admin-editierbar), nicht im Code pro Eintrag.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
||||||
|
|
||||||
|
from planning_catalog_context import (
|
||||||
|
ProgressionPlanningCatalogContext,
|
||||||
|
PlanningCatalogContextItem,
|
||||||
|
catalog_context_has_items,
|
||||||
|
)
|
||||||
|
from catalog_slot_fallbacks import merge_stored_slots_with_fallbacks
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Dimensionen (Prioritätsreihenfolge)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CatalogKindConfig:
|
||||||
|
kind: str
|
||||||
|
table: str
|
||||||
|
context_attr: str
|
||||||
|
label_de: str
|
||||||
|
|
||||||
|
|
||||||
|
CATALOG_KINDS: Tuple[CatalogKindConfig, ...] = (
|
||||||
|
CatalogKindConfig("focus_area", "focus_areas", "focus_areas", "Primärfokus"),
|
||||||
|
CatalogKindConfig("training_type", "training_types", "training_types", "Trainingsstil"),
|
||||||
|
CatalogKindConfig("target_group", "target_groups", "target_groups", "Zielgruppe"),
|
||||||
|
CatalogKindConfig("style_direction", "style_directions", "style_directions", "Stilrichtung"),
|
||||||
|
)
|
||||||
|
|
||||||
|
_KIND_BY_NAME = {c.kind: c for c in CATALOG_KINDS}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Slot-Typen (Vokabular — erweiterbar via catalog_prompt_slot_types)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
SLOT_KEYS: Tuple[str, ...] = (
|
||||||
|
"description",
|
||||||
|
"hints_on_progression",
|
||||||
|
"hints_on_exercise",
|
||||||
|
"hints_on_path_qa",
|
||||||
|
"anti_patterns",
|
||||||
|
"rematch_guard",
|
||||||
|
)
|
||||||
|
|
||||||
|
LLM_SLOT_KEYS: Tuple[str, ...] = tuple(k for k in SLOT_KEYS if k != "rematch_guard")
|
||||||
|
|
||||||
|
GUIDANCE_BLOCK_SLOTS: Tuple[str, ...] = (
|
||||||
|
"description",
|
||||||
|
"hints_on_progression",
|
||||||
|
"hints_on_path_qa",
|
||||||
|
"anti_patterns",
|
||||||
|
)
|
||||||
|
|
||||||
|
GUIDANCE_PROFILE_BY_SLUG: Dict[str, Tuple[str, ...]] = {
|
||||||
|
"planning_exercise_path_qa": ("description", "hints_on_path_qa", "anti_patterns"),
|
||||||
|
"planning_progression_roadmap": ("description", "hints_on_progression", "anti_patterns"),
|
||||||
|
"planning_progression_stage_spec": ("hints_on_progression", "anti_patterns", "description"),
|
||||||
|
"planning_progression_goal_analysis": ("description", "hints_on_progression"),
|
||||||
|
"planning_progression_start_target": ("description",),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def placeholder_key(catalog_kind: str, slot_key: str) -> str:
|
||||||
|
return f"{catalog_kind}_{slot_key}"
|
||||||
|
|
||||||
|
|
||||||
|
def all_placeholder_keys() -> List[str]:
|
||||||
|
keys: List[str] = []
|
||||||
|
for cfg in CATALOG_KINDS:
|
||||||
|
for slot in SLOT_KEYS:
|
||||||
|
keys.append(placeholder_key(cfg.kind, slot))
|
||||||
|
keys.extend(["catalog_guidance_block", "catalog_context_json", "has_catalog_guidance"])
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def empty_catalog_variables() -> Dict[str, str]:
|
||||||
|
out = {k: "" for k in all_placeholder_keys()}
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Katalog-Kontext → aktiver Eintrag
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def pick_active_catalog_item(
|
||||||
|
items: Sequence[PlanningCatalogContextItem],
|
||||||
|
) -> Optional[PlanningCatalogContextItem]:
|
||||||
|
if not items:
|
||||||
|
return None
|
||||||
|
primaries = [i for i in items if i.is_primary]
|
||||||
|
if primaries:
|
||||||
|
return primaries[0]
|
||||||
|
if len(items) == 1:
|
||||||
|
return items[0]
|
||||||
|
return max(items, key=lambda i: (float(i.weight), -int(i.id)))
|
||||||
|
|
||||||
|
|
||||||
|
def _load_catalog_row(cur, table: str, item_id: int) -> Optional[Dict[str, Any]]:
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, name, description
|
||||||
|
FROM {table}
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(int(item_id),),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": int(row["id"]),
|
||||||
|
"name": str(row.get("name") or "").strip(),
|
||||||
|
"description": str(row.get("description") or "").strip(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _load_slots_for_entry(cur, catalog_kind: str, catalog_id: int) -> Dict[str, str]:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT slot_key, content
|
||||||
|
FROM catalog_prompt_slots
|
||||||
|
WHERE catalog_kind = %s AND catalog_id = %s
|
||||||
|
""",
|
||||||
|
(catalog_kind, int(catalog_id)),
|
||||||
|
)
|
||||||
|
out: Dict[str, str] = {}
|
||||||
|
for row in cur.fetchall():
|
||||||
|
key = str(row.get("slot_key") or "").strip()
|
||||||
|
if key:
|
||||||
|
out[key] = str(row.get("content") or "").strip()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _slot_types_table_ready(cur) -> bool:
|
||||||
|
cur.execute("SELECT to_regclass(%s)::text AS t", ("public.catalog_prompt_slot_types",))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return False
|
||||||
|
val = row.get("t") if isinstance(row, dict) else row[0]
|
||||||
|
return val is not None and str(val).strip() != ""
|
||||||
|
|
||||||
|
|
||||||
|
def list_slot_type_definitions(cur) -> List[Dict[str, Any]]:
|
||||||
|
if not _slot_types_table_ready(cur):
|
||||||
|
return _fallback_slot_type_rows()
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT slot_key, display_name, description, applicable_kinds, sort_order, for_llm, for_code
|
||||||
|
FROM catalog_prompt_slot_types
|
||||||
|
ORDER BY sort_order ASC NULLS LAST, slot_key ASC
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
rows = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
d = dict(row)
|
||||||
|
kinds = d.get("applicable_kinds")
|
||||||
|
if isinstance(kinds, str):
|
||||||
|
kinds = [k.strip() for k in kinds.strip("{}").split(",") if k.strip()]
|
||||||
|
d["applicable_kinds"] = list(kinds or [])
|
||||||
|
rows.append(d)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _fallback_slot_type_rows() -> List[Dict[str, Any]]:
|
||||||
|
labels = {
|
||||||
|
"description": "Allgemeine Beschreibung",
|
||||||
|
"hints_on_progression": "Hinweise Progressionsgraph",
|
||||||
|
"hints_on_exercise": "Hinweise Übungsanlage",
|
||||||
|
"hints_on_path_qa": "Hinweise Pfad-QS",
|
||||||
|
"anti_patterns": "Anti-Patterns (Fehlbewertung vermeiden)",
|
||||||
|
"rematch_guard": "Rematch-Guard (Code)",
|
||||||
|
}
|
||||||
|
kinds = [c.kind for c in CATALOG_KINDS]
|
||||||
|
rows = []
|
||||||
|
for i, key in enumerate(SLOT_KEYS):
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"slot_key": key,
|
||||||
|
"display_name": labels.get(key, key),
|
||||||
|
"description": "",
|
||||||
|
"applicable_kinds": kinds,
|
||||||
|
"sort_order": (i + 1) * 10,
|
||||||
|
"for_llm": key != "rematch_guard",
|
||||||
|
"for_code": key == "rematch_guard",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_entry_slot_values(
|
||||||
|
stored: Mapping[str, str],
|
||||||
|
row: Mapping[str, Any],
|
||||||
|
catalog_kind: str,
|
||||||
|
) -> Dict[str, str]:
|
||||||
|
"""DB → Namens-Fallback → Stammdaten-Beschreibung (nur description)."""
|
||||||
|
return merge_stored_slots_with_fallbacks(
|
||||||
|
stored,
|
||||||
|
catalog_kind=catalog_kind,
|
||||||
|
name=str(row.get("name") or ""),
|
||||||
|
stammdaten_description=str(row.get("description") or ""),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_catalog_entry_slots(cur, catalog_kind: str, catalog_id: int) -> Dict[str, Any]:
|
||||||
|
cfg = _KIND_BY_NAME.get((catalog_kind or "").strip())
|
||||||
|
if not cfg:
|
||||||
|
raise ValueError(f"Unbekannter catalog_kind: {catalog_kind!r}")
|
||||||
|
row = _load_catalog_row(cur, cfg.table, catalog_id)
|
||||||
|
if not row:
|
||||||
|
raise LookupError("Katalog-Eintrag nicht gefunden")
|
||||||
|
stored = _load_slots_for_entry(cur, cfg.kind, catalog_id)
|
||||||
|
merged = _resolve_entry_slot_values(stored, row, cfg.kind)
|
||||||
|
return {
|
||||||
|
"catalog_kind": cfg.kind,
|
||||||
|
"catalog_id": int(catalog_id),
|
||||||
|
"name": row["name"],
|
||||||
|
"slots": merged,
|
||||||
|
"stored_slots": {k: stored.get(k, "") for k in SLOT_KEYS},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_catalog_entry_slots(
|
||||||
|
cur,
|
||||||
|
catalog_kind: str,
|
||||||
|
catalog_id: int,
|
||||||
|
slots: Mapping[str, Any],
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
cfg = _KIND_BY_NAME.get((catalog_kind or "").strip())
|
||||||
|
if not cfg:
|
||||||
|
raise ValueError(f"Unbekannter catalog_kind: {catalog_kind!r}")
|
||||||
|
row = _load_catalog_row(cur, cfg.table, catalog_id)
|
||||||
|
if not row:
|
||||||
|
raise LookupError("Katalog-Eintrag nicht gefunden")
|
||||||
|
for slot_key, raw in (slots or {}).items():
|
||||||
|
sk = str(slot_key or "").strip()
|
||||||
|
if sk not in SLOT_KEYS:
|
||||||
|
continue
|
||||||
|
content = str(raw or "").strip()
|
||||||
|
if not content:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
DELETE FROM catalog_prompt_slots
|
||||||
|
WHERE catalog_kind = %s AND catalog_id = %s AND slot_key = %s
|
||||||
|
""",
|
||||||
|
(cfg.kind, int(catalog_id), sk),
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO catalog_prompt_slots (catalog_kind, catalog_id, slot_key, content, updated_at)
|
||||||
|
VALUES (%s, %s, %s, %s, NOW())
|
||||||
|
ON CONFLICT (catalog_kind, catalog_id, slot_key)
|
||||||
|
DO UPDATE SET content = EXCLUDED.content, updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(cfg.kind, int(catalog_id), sk, content),
|
||||||
|
)
|
||||||
|
return get_catalog_entry_slots(cur, cfg.kind, catalog_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _render_dimension_section(
|
||||||
|
label_de: str,
|
||||||
|
name: str,
|
||||||
|
slot_values: Mapping[str, str],
|
||||||
|
*,
|
||||||
|
slot_keys: Sequence[str],
|
||||||
|
) -> Optional[str]:
|
||||||
|
parts: List[str] = [f"### {label_de} — {name}"]
|
||||||
|
labels = {
|
||||||
|
"description": "Beschreibung",
|
||||||
|
"hints_on_progression": "Progressions-Hinweise",
|
||||||
|
"hints_on_path_qa": "QS-Hinweise",
|
||||||
|
"hints_on_exercise": "Übungsanlage",
|
||||||
|
"anti_patterns": "Vermeiden",
|
||||||
|
}
|
||||||
|
added = False
|
||||||
|
for sk in slot_keys:
|
||||||
|
text = str(slot_values.get(sk) or "").strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
added = True
|
||||||
|
if sk == "description":
|
||||||
|
parts.append(text)
|
||||||
|
else:
|
||||||
|
parts.append(f"{labels.get(sk, sk)}: {text}")
|
||||||
|
if not added:
|
||||||
|
return None
|
||||||
|
return "\n".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_guidance_block(
|
||||||
|
sections: List[str],
|
||||||
|
) -> str:
|
||||||
|
if not sections:
|
||||||
|
return ""
|
||||||
|
return "## Katalog-Kontext (Didaktik & Bewertung)\n\n" + "\n\n".join(sections)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_catalog_prompt_variables(
|
||||||
|
cur,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext],
|
||||||
|
*,
|
||||||
|
slug: Optional[str] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Liefert Mustache-Strings + Metadaten.
|
||||||
|
|
||||||
|
Returns dict mit allen {{kind_slot}} Keys, catalog_guidance_block, catalog_context_json,
|
||||||
|
has_catalog_guidance (bool), active_slots (list).
|
||||||
|
"""
|
||||||
|
variables = empty_catalog_variables()
|
||||||
|
meta: Dict[str, Any] = {
|
||||||
|
"active_slots": [],
|
||||||
|
"audit": {},
|
||||||
|
}
|
||||||
|
if cur is None or not catalog_context_has_items(catalog):
|
||||||
|
variables["catalog_context_json"] = ""
|
||||||
|
return {**variables, **meta}
|
||||||
|
|
||||||
|
profile = GUIDANCE_PROFILE_BY_SLUG.get((slug or "").strip().lower(), GUIDANCE_BLOCK_SLOTS)
|
||||||
|
sections: List[str] = []
|
||||||
|
audit: Dict[str, Any] = {}
|
||||||
|
has_any = False
|
||||||
|
active_slots: List[str] = []
|
||||||
|
|
||||||
|
for cfg in CATALOG_KINDS:
|
||||||
|
items = getattr(catalog, cfg.context_attr, None) or []
|
||||||
|
active = pick_active_catalog_item(items)
|
||||||
|
if not active:
|
||||||
|
continue
|
||||||
|
row = _load_catalog_row(cur, cfg.table, active.id)
|
||||||
|
if not row:
|
||||||
|
continue
|
||||||
|
stored = _load_slots_for_entry(cur, cfg.kind, row["id"]) if _slot_types_table_ready(cur) else {}
|
||||||
|
slot_values = _resolve_entry_slot_values(stored, row, cfg.kind)
|
||||||
|
for sk in SLOT_KEYS:
|
||||||
|
pk = placeholder_key(cfg.kind, sk)
|
||||||
|
text = slot_values.get(sk, "")
|
||||||
|
variables[pk] = text
|
||||||
|
if text.strip() and sk in LLM_SLOT_KEYS:
|
||||||
|
has_any = True
|
||||||
|
active_slots.append(pk)
|
||||||
|
|
||||||
|
audit[cfg.context_attr] = {
|
||||||
|
"catalog_kind": cfg.kind,
|
||||||
|
"id": row["id"],
|
||||||
|
"name": row["name"],
|
||||||
|
"is_primary": bool(active.is_primary),
|
||||||
|
"weight": float(active.weight),
|
||||||
|
"filled_slots": [k for k in LLM_SLOT_KEYS if slot_values.get(k, "").strip()],
|
||||||
|
"stored_slots": [k for k in SLOT_KEYS if (stored.get(k) or "").strip()],
|
||||||
|
}
|
||||||
|
|
||||||
|
section = _render_dimension_section(cfg.label_de, row["name"], slot_values, slot_keys=profile)
|
||||||
|
if section:
|
||||||
|
sections.append(section)
|
||||||
|
|
||||||
|
variables["catalog_guidance_block"] = _compose_guidance_block(sections)
|
||||||
|
ctx_json = json.dumps(audit, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
variables["catalog_context_json"] = f"Katalog-Audit: {ctx_json}" if audit else ""
|
||||||
|
variables["has_catalog_guidance"] = "true" if has_any else ""
|
||||||
|
return {
|
||||||
|
**variables,
|
||||||
|
"active_slots": active_slots,
|
||||||
|
"audit": audit,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_rematch_guard_for_catalog(
|
||||||
|
cur,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext],
|
||||||
|
) -> Optional[str]:
|
||||||
|
"""Erste passende rematch_guard entlang der Dimensions-Priorität."""
|
||||||
|
if cur is None or not catalog_context_has_items(catalog):
|
||||||
|
return None
|
||||||
|
for cfg in CATALOG_KINDS:
|
||||||
|
items = getattr(catalog, cfg.context_attr, None) or []
|
||||||
|
active = pick_active_catalog_item(items)
|
||||||
|
if not active:
|
||||||
|
continue
|
||||||
|
stored = _load_slots_for_entry(cur, cfg.kind, active.id)
|
||||||
|
row = _load_catalog_row(cur, cfg.table, active.id)
|
||||||
|
if not row:
|
||||||
|
continue
|
||||||
|
slot_values = _resolve_entry_slot_values(stored, row, cfg.kind)
|
||||||
|
guard = (slot_values.get("rematch_guard") or "").strip()
|
||||||
|
if guard:
|
||||||
|
return guard
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# Abwärtskompatibilität H1-API
|
||||||
|
def build_catalog_guidance_for_prompt(
|
||||||
|
cur,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext],
|
||||||
|
*,
|
||||||
|
slug: Optional[str] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
resolved = resolve_catalog_prompt_variables(cur, catalog, slug=slug)
|
||||||
|
return {
|
||||||
|
"catalog_guidance_block": resolved.get("catalog_guidance_block", ""),
|
||||||
|
"catalog_context_json": resolved.get("catalog_context_json", ""),
|
||||||
|
"has_catalog_guidance": resolved.get("has_catalog_guidance") == "true",
|
||||||
|
"snippet_keys": list(resolved.get("active_slots") or []),
|
||||||
|
"variables": {k: str(resolved.get(k) or "") for k in all_placeholder_keys()},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"CATALOG_KINDS",
|
||||||
|
"GUIDANCE_PROFILE_BY_SLUG",
|
||||||
|
"SLOT_KEYS",
|
||||||
|
"build_catalog_guidance_for_prompt",
|
||||||
|
"empty_catalog_variables",
|
||||||
|
"get_catalog_entry_slots",
|
||||||
|
"get_rematch_guard_for_catalog",
|
||||||
|
"list_slot_type_definitions",
|
||||||
|
"pick_active_catalog_item",
|
||||||
|
"placeholder_key",
|
||||||
|
"all_placeholder_keys",
|
||||||
|
"resolve_catalog_prompt_variables",
|
||||||
|
"upsert_catalog_entry_slots",
|
||||||
|
]
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
"""
|
||||||
|
Namensbasierte Fallback-Slots — bis Admin/DB befüllt sind (H1-Registry-Inhalt).
|
||||||
|
|
||||||
|
DB-Werte in catalog_prompt_slots haben immer Vorrang. Fallbacks füllen nur leere Slot-Keys.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from typing import Dict, Mapping, Optional, Sequence, Tuple
|
||||||
|
|
||||||
|
_UMLAUT_MAP = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "ß": "ss", "Ä": "ae", "Ö": "oe", "Ü": "ue"})
|
||||||
|
|
||||||
|
SlotPack = Dict[str, str]
|
||||||
|
|
||||||
|
# (catalog_kind, name_pattern_lower) — erste passende Regel gewinnt; * = Default pro Kind
|
||||||
|
_FALLBACK_RULES: Tuple[Tuple[str, str, SlotPack], ...] = (
|
||||||
|
# --- focus_area ---
|
||||||
|
(
|
||||||
|
"focus_area",
|
||||||
|
"gewaltschutz",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Planung zielt auf Prävention, Deeskalation, Grenzen und sichere Übungsformen — "
|
||||||
|
"nicht auf Wettkampf-Perfektion oder Technik-Show."
|
||||||
|
),
|
||||||
|
"hints_on_progression": (
|
||||||
|
"Phasen: Wahrnehmung → Grenzen → Deeskalation → sichere Übungsformen; "
|
||||||
|
"keine Kumite-Perfektionsstufen erzwingen."
|
||||||
|
),
|
||||||
|
"hints_on_exercise": (
|
||||||
|
"Übungen mit Rollen, Kommunikation, Ausweichen; keine rein technischen Kick-Fokus-Inseln ohne Bezug."
|
||||||
|
),
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Gute Pfade bauen Sicherheit, Kommunikation und Alternativen auf; "
|
||||||
|
"„Lücken“ sind fehlende Deeskalations- oder Rollenspiel-Stufen, nicht fehlende Kick-Varianten."
|
||||||
|
),
|
||||||
|
"anti_patterns": "Nicht nach Kumite-Tiefe, Explosivität oder Wettkampf-Belastung bewerten.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"focus_area",
|
||||||
|
"selbstverteidigung",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Praktische Selbstverteidigung: realistische Szenarien, Sicherheit und "
|
||||||
|
"anwendungsnahe Progression — nicht Show-Technik oder Wettkampf-Kata."
|
||||||
|
),
|
||||||
|
"hints_on_progression": (
|
||||||
|
"Von Wahrnehmung und Distanz zu einfachen Abwehrmustern und kontrollierter Anwendung."
|
||||||
|
),
|
||||||
|
"hints_on_exercise": "Partnerübungen mit klaren Sicherheitsregeln; Szenario-Bezug wichtiger als Stil-Show.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Lücken bei Szenario- oder Sicherheitsstufen sind relevant; "
|
||||||
|
"fehlende Kick-Varianten oder Wettkampftiefe sind kein Mangel."
|
||||||
|
),
|
||||||
|
"anti_patterns": "Keine Wettkampf- oder Kata-Perfektion als QS-Maßstab.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"focus_area",
|
||||||
|
"fitness",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Fitness- und Konditionsorientierung mit sicherer Belastungssteuerung; "
|
||||||
|
"Technikbezug nur wo fachlich sinnvoll."
|
||||||
|
),
|
||||||
|
"hints_on_progression": "Progression von niedriger zu moderater Belastung; klare Pausen und Technikhygiene.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Keine Wettkampf-Spezialisierung als Pflicht-Kriterium; "
|
||||||
|
"Belastungssteigerung ohne Technikbezug abwerten."
|
||||||
|
),
|
||||||
|
"anti_patterns": "Keine Kumite-Perfektion oder Wettkampf-Kombinationen als QS-Maßstab verlangen.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"focus_area",
|
||||||
|
"karate",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Technik-Curriculum im Karate-Kontext: aufeinander aufbauende Kihon-Progression "
|
||||||
|
"mit klaren Qualitätsankern (Stand, Hüfte, Kime)."
|
||||||
|
),
|
||||||
|
"hints_on_progression": (
|
||||||
|
"Typische Phasen: Einstieg → Grundlagen → Koordination/Kraft → Anwendung → optional Vertiefung; "
|
||||||
|
"Grundlagen vor Perfektion."
|
||||||
|
),
|
||||||
|
"hints_on_exercise": (
|
||||||
|
"Kihon und Partnerübungen mit Technikbezug; reine Kraft-/Ausdauer-Inseln nur mit klarer Begründung."
|
||||||
|
),
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Kohärente Progression Grundlagen → Anwendung → Vertiefung; "
|
||||||
|
"Übergänge ohne Sprünge; themenfremde Kraft-/Ausdauer-Inseln abwerten."
|
||||||
|
),
|
||||||
|
"anti_patterns": "Keine pauschale Perfektions-Stufe verlangen, wenn Kontext Breitensport ist.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"focus_area",
|
||||||
|
"*",
|
||||||
|
{
|
||||||
|
"description": "Technik- oder Themen-Curriculum mit didaktisch aufeinander aufbauenden Stufen.",
|
||||||
|
"hints_on_progression": "Grundlagen vor Anwendung; moderate Sprünge zwischen Stufen vermeiden.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Kohärente Progression zum Anfrage-Thema; "
|
||||||
|
"Lücken sind fehlende Zwischenstufen im Lernpfad, nicht fehlende Nebenthemen."
|
||||||
|
),
|
||||||
|
"hints_on_exercise": "Übungen mit klarem Bezug zum Pfad-Thema und zur Stufe.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
# --- training_type ---
|
||||||
|
(
|
||||||
|
"training_type",
|
||||||
|
"breitensport",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Partizipation, Verständlichkeit, Freude am Bewegen; weniger maximale Spezialisierung."
|
||||||
|
),
|
||||||
|
"hints_on_progression": "Moderater Schwierigkeitsanstieg; Perfektionsphasen optional.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Hohe OK-Rate bei moderatem Schwierigkeitsanstieg; "
|
||||||
|
"„Perfektion“-Stufen nur optional, nicht als Pflicht-Lücke."
|
||||||
|
),
|
||||||
|
"rematch_guard": "Keine leeren Slots erzwingen, nur um eine Leistungs-Perfektionsstufe zu füllen.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"training_type",
|
||||||
|
"leistungssport",
|
||||||
|
{
|
||||||
|
"description": "Leistungsorientiertes Training mit höherer Anspruchskurve und Spezialisierung.",
|
||||||
|
"hints_on_progression": "Belastungs- und Kombinationsprogressionen sind erwünscht.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Höhere Anspruchskurven sind passend; Lücken in Spezialisierung können echte Hinweise sein."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"training_type",
|
||||||
|
"wettkampf",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Wettkampforientiertes Training mit höherer Anspruchskurve und belastungsnahen Phasen."
|
||||||
|
),
|
||||||
|
"hints_on_progression": "Anwendungs- und Druckphasen zeitig einplanen.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Spezialisierung, Kombination und Belastung unter Druck sind relevant; "
|
||||||
|
"Lücken in Anwendungs- oder Perfektionsphasen können echte Hinweise sein."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"training_type",
|
||||||
|
"*",
|
||||||
|
{
|
||||||
|
"hints_on_path_qa": "Didaktische Kohärenz wichtiger als maximale Spezialisierung — Kontext beachten.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
# --- target_group ---
|
||||||
|
(
|
||||||
|
"target_group",
|
||||||
|
"kinder",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Kinder: kurze Einheiten, spielerische Einstiege, Sicherheit und altersgerechte Komplexität."
|
||||||
|
),
|
||||||
|
"hints_on_progression": "Spielerische Einstiege; kurze Abschnitte; Sicherheit vor Perfektion.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Didaktik ohne Überforderung; klare Regeln und Sicherheit vor Perfektion; "
|
||||||
|
"Lücken bei Spiel-/Rollenelementen wichtiger als Wettkampftiefe."
|
||||||
|
),
|
||||||
|
"anti_patterns": "Keine Erwachsenen-Wettkampf-Perfektion als QS-Maßstab.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"target_group",
|
||||||
|
"leistungssportler",
|
||||||
|
{
|
||||||
|
"description": "Leistungsgruppe: höhere Anspruchskurven und Spezialisierung sind fachlich passend.",
|
||||||
|
"hints_on_progression": "Anspruchskurve und Spezialisierung dürfen steiler sein.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Höhere Anspruchskurven, Belastungs- und Kombinationsprogressionen sind relevant; "
|
||||||
|
"Lücken in Spezialisierung können echte Hinweise sein."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"target_group",
|
||||||
|
"breitensportler",
|
||||||
|
{
|
||||||
|
"description": "Breitensport: Partizipation und Verständlichkeit vor maximaler Spezialisierung.",
|
||||||
|
"hints_on_path_qa": (
|
||||||
|
"Moderate Progression; Perfektions-Lücken sind selten echte Mängel."
|
||||||
|
),
|
||||||
|
"anti_patterns": "Keine Leistungssport-Perfektion als Pflicht-Kriterium.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"target_group",
|
||||||
|
"*",
|
||||||
|
{
|
||||||
|
"hints_on_path_qa": "Zielgruppe im Tempo und in der Komplexität berücksichtigen.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
# --- style_direction ---
|
||||||
|
(
|
||||||
|
"style_direction",
|
||||||
|
"shotokan",
|
||||||
|
{
|
||||||
|
"description": (
|
||||||
|
"Shotokan-Linie: klare Kihon-Struktur, Hüft- und Standarbeit als wiederkehrende Qualitätsanker."
|
||||||
|
),
|
||||||
|
"hints_on_progression": "Nuancen in Stellung und Hüfttechnik; kein neuer Planungstyp.",
|
||||||
|
"hints_on_path_qa": "Konsistenz von Stand, Hüfte und Kime entlang des Pfads bewerten.",
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"style_direction",
|
||||||
|
"*",
|
||||||
|
{
|
||||||
|
"hints_on_progression": (
|
||||||
|
"Stil-spezifische Nuancen (Stand, Hüfte, Rhythmus) einbeziehen — ohne Stilwechsel zu erzwingen."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_catalog_name_key(name: str) -> str:
|
||||||
|
s = unicodedata.normalize("NFKD", (name or "").translate(_UMLAUT_MAP))
|
||||||
|
s = s.encode("ascii", "ignore").decode("ascii").lower()
|
||||||
|
s = re.sub(r"[^a-z0-9]+", "_", s).strip("_")
|
||||||
|
return s or "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def get_fallback_slots_for_entry(catalog_kind: str, name: str) -> SlotPack:
|
||||||
|
kind = (catalog_kind or "").strip().lower()
|
||||||
|
norm = normalize_catalog_name_key(name)
|
||||||
|
default: SlotPack = {}
|
||||||
|
for rule_kind, pattern, pack in _FALLBACK_RULES:
|
||||||
|
if rule_kind != kind:
|
||||||
|
continue
|
||||||
|
if pattern == "*":
|
||||||
|
default = dict(pack)
|
||||||
|
continue
|
||||||
|
if pattern in norm or norm.startswith(pattern) or pattern in (name or "").lower():
|
||||||
|
return dict(pack)
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def merge_stored_slots_with_fallbacks(
|
||||||
|
stored: Mapping[str, str],
|
||||||
|
*,
|
||||||
|
catalog_kind: str,
|
||||||
|
name: str,
|
||||||
|
stammdaten_description: str = "",
|
||||||
|
) -> Dict[str, str]:
|
||||||
|
"""DB + Stammdaten-Beschreibung + Namens-Fallback."""
|
||||||
|
fallbacks = get_fallback_slots_for_entry(catalog_kind, name)
|
||||||
|
out: Dict[str, str] = {}
|
||||||
|
for key in (
|
||||||
|
"description",
|
||||||
|
"hints_on_progression",
|
||||||
|
"hints_on_exercise",
|
||||||
|
"hints_on_path_qa",
|
||||||
|
"anti_patterns",
|
||||||
|
"rematch_guard",
|
||||||
|
):
|
||||||
|
if key == "description":
|
||||||
|
out[key] = (
|
||||||
|
(stored.get(key) or "").strip()
|
||||||
|
or (fallbacks.get(key) or "").strip()
|
||||||
|
or (stammdaten_description or "").strip()
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
out[key] = (stored.get(key) or "").strip() or (fallbacks.get(key) or "").strip()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"get_fallback_slots_for_entry",
|
||||||
|
"merge_stored_slots_with_fallbacks",
|
||||||
|
"normalize_catalog_name_key",
|
||||||
|
]
|
||||||
@@ -0,0 +1,833 @@
|
|||||||
|
"""Vertrag v1: kanonisches Manifest, Ereignisse, Freigaberegeln, Cursor.
|
||||||
|
|
||||||
|
Reine Funktionen. Die Datenbankschicht ruft sie auf, die Tests prüfen sie ohne Postgres.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from html import unescape
|
||||||
|
from typing import Any, Iterable, Optional
|
||||||
|
|
||||||
|
from exercise_rich_text import normalize_inline_exercise_media_markup
|
||||||
|
|
||||||
|
PART_ROLES = (
|
||||||
|
"goal",
|
||||||
|
"prerequisites",
|
||||||
|
"preparation",
|
||||||
|
"instructions",
|
||||||
|
"trainer_notes",
|
||||||
|
"equipment",
|
||||||
|
"duration_note",
|
||||||
|
)
|
||||||
|
ASSET_ROLES = ("demonstration", "worksheet", "illustration")
|
||||||
|
ACTIONS = (
|
||||||
|
"store",
|
||||||
|
"render",
|
||||||
|
"stream",
|
||||||
|
"download",
|
||||||
|
"print",
|
||||||
|
"course_display",
|
||||||
|
"commercial_course_use",
|
||||||
|
"adapt",
|
||||||
|
"public_preview",
|
||||||
|
"grant_customer_use",
|
||||||
|
)
|
||||||
|
REASON_CODES = ("rights", "safety", "privacy", "expired", "editorial_error")
|
||||||
|
WITHDRAW_TYPES = ("release.withdrawn", "variant.withdrawn", "asset.withdrawn")
|
||||||
|
EVENT_TYPES = ("release.published", "release.retired", *WITHDRAW_TYPES)
|
||||||
|
|
||||||
|
_TAG = re.compile(r"<[^>]+>")
|
||||||
|
_MEDIA_TOKEN = re.compile(r"\{\{exerciseMedia:(\d+)\}\}")
|
||||||
|
_DATA_MEDIA = re.compile(r'data-exercise-media-id=["\'](\d+)["\']', re.I)
|
||||||
|
|
||||||
|
LEGAL_HOLD_REASON = {
|
||||||
|
"rights_dispute": "rights",
|
||||||
|
"copyright_complaint": "rights",
|
||||||
|
"consent_withdrawn": "privacy",
|
||||||
|
"privacy_complaint": "privacy",
|
||||||
|
"youth_protection": "safety",
|
||||||
|
"illegal_content": "safety",
|
||||||
|
"other": "safety",
|
||||||
|
}
|
||||||
|
|
||||||
|
OFFICIAL_WRITE_DENIED = "Globale Übungen dürfen nur von Superadmins bearbeitet werden."
|
||||||
|
RATE_LIMIT_PER_MINUTE = 60
|
||||||
|
|
||||||
|
|
||||||
|
def distribution_enabled() -> bool:
|
||||||
|
return os.getenv("DISTRIBUTION_ENABLED", "").strip().lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
def cursor_secret() -> str:
|
||||||
|
secret = os.getenv("DISTRIBUTION_CURSOR_SECRET", "").strip()
|
||||||
|
if secret:
|
||||||
|
return secret
|
||||||
|
if os.getenv("ENVIRONMENT", "development").strip().lower() in ("production", "prod"):
|
||||||
|
material = os.getenv("DB_PASSWORD", "").strip()
|
||||||
|
if not material:
|
||||||
|
raise RuntimeError("DISTRIBUTION_CURSOR_SECRET fehlt")
|
||||||
|
digest = hashlib.sha256(f"shinkan-distribution-cursor:{material}".encode()).hexdigest()
|
||||||
|
return digest
|
||||||
|
return "shinkan-distribution-dev-cursor"
|
||||||
|
|
||||||
|
|
||||||
|
def format_utc(dt: datetime) -> str:
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
dt = dt.replace(tzinfo=timezone.utc)
|
||||||
|
return dt.astimezone(timezone.utc).replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_utc(value: str) -> datetime:
|
||||||
|
raw = value.strip()
|
||||||
|
if raw.endswith("Z"):
|
||||||
|
raw = raw[:-1] + "+00:00"
|
||||||
|
parsed = datetime.fromisoformat(raw)
|
||||||
|
if parsed.tzinfo is None:
|
||||||
|
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||||
|
return parsed.astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_json(value: Any) -> bytes:
|
||||||
|
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def sha256_bytes(data: bytes) -> str:
|
||||||
|
return hashlib.sha256(data).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _copy_if(source: dict, key: str, required: bool = False, keep_null: bool = False) -> Any:
|
||||||
|
if key not in source:
|
||||||
|
if required:
|
||||||
|
raise ValueError(f"Feld fehlt: {key}")
|
||||||
|
return None
|
||||||
|
value = source[key]
|
||||||
|
if value is None and not keep_null:
|
||||||
|
return None
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def order_manifest(source: dict) -> dict:
|
||||||
|
"""Feldreihenfolge des Übergabevertrags. Optionale leere Felder entfallen, null bleibt bei Fristen."""
|
||||||
|
exercise = source["exercise"]
|
||||||
|
ordered_exercise: dict[str, Any] = {"title": exercise["title"]}
|
||||||
|
if exercise.get("summary") is not None:
|
||||||
|
ordered_exercise["summary"] = exercise["summary"]
|
||||||
|
if exercise.get("audience") is not None:
|
||||||
|
ordered_exercise["audience"] = exercise["audience"]
|
||||||
|
ordered_exercise["rights_id"] = exercise["rights_id"]
|
||||||
|
ordered_exercise["parts"] = [
|
||||||
|
{
|
||||||
|
"id": part["id"],
|
||||||
|
"role": part["role"],
|
||||||
|
"text": part["text"],
|
||||||
|
"rights_id": part["rights_id"],
|
||||||
|
}
|
||||||
|
for part in exercise["parts"]
|
||||||
|
]
|
||||||
|
assets = []
|
||||||
|
for asset in exercise["assets"]:
|
||||||
|
item = {
|
||||||
|
"id": asset["id"],
|
||||||
|
"role": asset["role"],
|
||||||
|
"media_type": asset["media_type"],
|
||||||
|
"size_bytes": asset["size_bytes"],
|
||||||
|
"sha256": asset["sha256"],
|
||||||
|
"rights_id": asset["rights_id"],
|
||||||
|
}
|
||||||
|
if asset.get("label") is not None:
|
||||||
|
item["label"] = asset["label"]
|
||||||
|
assets.append(item)
|
||||||
|
ordered_exercise["assets"] = assets
|
||||||
|
ordered_exercise["common_part_ids"] = list(exercise["common_part_ids"])
|
||||||
|
ordered_exercise["common_asset_ids"] = list(exercise["common_asset_ids"])
|
||||||
|
ordered_exercise["variants"] = [
|
||||||
|
{
|
||||||
|
"id": variant["id"],
|
||||||
|
"label": variant["label"],
|
||||||
|
"part_ids": list(variant["part_ids"]),
|
||||||
|
"asset_ids": list(variant["asset_ids"]),
|
||||||
|
}
|
||||||
|
for variant in exercise["variants"]
|
||||||
|
]
|
||||||
|
rights = []
|
||||||
|
for right in source["rights"]:
|
||||||
|
item = {
|
||||||
|
"id": right["id"],
|
||||||
|
"evidence_ref": right["evidence_ref"],
|
||||||
|
"actions": list(right["actions"]),
|
||||||
|
"territories": right["territories"],
|
||||||
|
"valid_from": right["valid_from"],
|
||||||
|
"valid_until": right["valid_until"],
|
||||||
|
}
|
||||||
|
if right.get("attribution") is not None:
|
||||||
|
item["attribution"] = right["attribution"]
|
||||||
|
rights.append(item)
|
||||||
|
return {
|
||||||
|
"schema_version": source["schema_version"],
|
||||||
|
"resource_type": source["resource_type"],
|
||||||
|
"release_id": source["release_id"],
|
||||||
|
"source_id": source["source_id"],
|
||||||
|
"revision": source["revision"],
|
||||||
|
"publisher_id": source["publisher_id"],
|
||||||
|
"published_at": source["published_at"],
|
||||||
|
"exercise": ordered_exercise,
|
||||||
|
"rights": rights,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def manifest_bytes(source: dict) -> bytes:
|
||||||
|
return canonical_json(order_manifest(source))
|
||||||
|
|
||||||
|
|
||||||
|
def order_event(event: dict) -> dict:
|
||||||
|
ordered = {
|
||||||
|
"event_id": event["event_id"],
|
||||||
|
"type": event["type"],
|
||||||
|
"release_id": event["release_id"],
|
||||||
|
"occurred_at": event["occurred_at"],
|
||||||
|
}
|
||||||
|
if event["type"] == "release.published":
|
||||||
|
ordered["source_id"] = event["source_id"]
|
||||||
|
ordered["revision"] = event["revision"]
|
||||||
|
ordered["manifest_sha256"] = event["manifest_sha256"]
|
||||||
|
elif event["type"] in WITHDRAW_TYPES:
|
||||||
|
if event["type"] != "release.withdrawn":
|
||||||
|
ordered["target_id"] = event["target_id"]
|
||||||
|
ordered["reason_code"] = event["reason_code"]
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
|
def encode_cursor(secret: str, recipient_id: str, seq: int) -> str:
|
||||||
|
payload = f"{recipient_id}:{int(seq)}".encode("utf-8")
|
||||||
|
sig = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
|
||||||
|
raw = payload + b"." + sig.encode("ascii")
|
||||||
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def decode_cursor(secret: str, recipient_id: str, token: Optional[str]) -> int:
|
||||||
|
if token is None or token == "":
|
||||||
|
return 0
|
||||||
|
pad = "=" * (-len(token) % 4)
|
||||||
|
try:
|
||||||
|
raw = base64.urlsafe_b64decode(token + pad)
|
||||||
|
payload, sig = raw.rsplit(b".", 1)
|
||||||
|
expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest().encode("ascii")
|
||||||
|
if not hmac.compare_digest(sig, expected):
|
||||||
|
raise ValueError("sig")
|
||||||
|
rec, seq_raw = payload.decode("utf-8").split(":", 1)
|
||||||
|
if rec != recipient_id:
|
||||||
|
raise ValueError("channel")
|
||||||
|
seq = int(seq_raw)
|
||||||
|
if seq < 0:
|
||||||
|
raise ValueError("seq")
|
||||||
|
return seq
|
||||||
|
except Exception as exc:
|
||||||
|
raise InvalidCursor() from exc
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_available(offered: bool, in_scope: bool) -> bool:
|
||||||
|
"""Der aktuelle Abruf liefert eine Übung nur bei ausdrücklicher Auswahl und passendem Schlüsselumfang."""
|
||||||
|
return bool(offered) and bool(in_scope)
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_html(value: Optional[str]) -> str:
|
||||||
|
"""Gespeichertes Übungs-HTML. Absätze, Umbrüche, Listen und Hervorhebungen bleiben erhalten."""
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
normalized = normalize_inline_exercise_media_markup(str(value))
|
||||||
|
return normalized or ""
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_document(exercise: dict, variants: list[dict], media: list[dict]) -> dict:
|
||||||
|
"""Aktueller Übungsstand. Die Reihenfolge der Varianten und Medien gehört zum Inhalt.
|
||||||
|
|
||||||
|
text_format html gilt für summary, goal, execution, preparation, trainer_notes
|
||||||
|
und variants.execution_changes. Titel, Variantenbeschreibung und Material bleiben Text.
|
||||||
|
"""
|
||||||
|
ordered_variants = sorted(
|
||||||
|
variants,
|
||||||
|
key=lambda item: (item.get("sequence_order") is None, item.get("sequence_order") or 0, int(item.get("id") or 0)),
|
||||||
|
)
|
||||||
|
ordered_media = sorted(
|
||||||
|
media,
|
||||||
|
key=lambda item: (item.get("sort_order") is None, item.get("sort_order") or 0, int(item.get("id") or 0)),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"source_id": str(exercise.get("public_id")),
|
||||||
|
"text_format": "html",
|
||||||
|
"title": exercise.get("title") or "",
|
||||||
|
"summary": catalog_html(exercise.get("summary")),
|
||||||
|
"goal": catalog_html(exercise.get("goal")),
|
||||||
|
"execution": catalog_html(exercise.get("execution")),
|
||||||
|
"preparation": catalog_html(exercise.get("preparation")),
|
||||||
|
"trainer_notes": catalog_html(exercise.get("trainer_notes")),
|
||||||
|
"equipment": _equipment_text(exercise) or "",
|
||||||
|
"duration_min": exercise.get("duration_min"),
|
||||||
|
"duration_max": exercise.get("duration_max"),
|
||||||
|
"variants": [
|
||||||
|
{
|
||||||
|
"id": str(item.get("public_id")),
|
||||||
|
"name": item.get("variant_name") or "",
|
||||||
|
"description": (item.get("description") or "").strip(),
|
||||||
|
"execution_changes": catalog_html(item.get("execution_changes")),
|
||||||
|
"sequence_order": item.get("sequence_order"),
|
||||||
|
}
|
||||||
|
for item in ordered_variants
|
||||||
|
],
|
||||||
|
"media": [
|
||||||
|
{
|
||||||
|
"id": str(item.get("public_id")),
|
||||||
|
"media_type": item.get("media_type") or "",
|
||||||
|
"title": item.get("title") or "",
|
||||||
|
"sort_order": item.get("sort_order"),
|
||||||
|
}
|
||||||
|
for item in ordered_media
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_hash(document: dict) -> str:
|
||||||
|
return sha256_bytes(canonical_json(document))
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_changes(previous: dict, current: dict) -> list[dict]:
|
||||||
|
"""Differenz seit dem letzten erfolgreichen Abruf. Gleiche Prüfsumme gilt als unverändert."""
|
||||||
|
changes = []
|
||||||
|
for source_id in sorted(current):
|
||||||
|
digest = current[source_id]
|
||||||
|
if source_id not in previous:
|
||||||
|
changes.append({"source_id": source_id, "change": "added", "content_hash": digest})
|
||||||
|
elif previous[source_id] != digest:
|
||||||
|
changes.append({"source_id": source_id, "change": "updated", "content_hash": digest})
|
||||||
|
for source_id in sorted(previous):
|
||||||
|
if source_id not in current:
|
||||||
|
changes.append({"source_id": source_id, "change": "removed"})
|
||||||
|
return changes
|
||||||
|
|
||||||
|
|
||||||
|
def encode_catalog_cursor(secret: str, binding_id: str, snapshot_id: str) -> str:
|
||||||
|
payload = f"{binding_id}:{snapshot_id}".encode("utf-8")
|
||||||
|
sig = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
|
||||||
|
raw = payload + b"." + sig.encode("ascii")
|
||||||
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
def decode_catalog_cursor(secret: str, binding_id: str, token: Optional[str]) -> str:
|
||||||
|
pad = "=" * (-len(token) % 4)
|
||||||
|
try:
|
||||||
|
raw = base64.urlsafe_b64decode(token + pad)
|
||||||
|
payload, sig = raw.rsplit(b".", 1)
|
||||||
|
expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest().encode("ascii")
|
||||||
|
if not hmac.compare_digest(sig, expected):
|
||||||
|
raise ValueError("sig")
|
||||||
|
bound, snapshot_id = payload.decode("utf-8").split(":", 1)
|
||||||
|
if bound != str(binding_id):
|
||||||
|
raise ValueError("channel")
|
||||||
|
return snapshot_id
|
||||||
|
except Exception as exc:
|
||||||
|
raise InvalidCursor() from exc
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidCursor(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def official_write_allowed(visibility: Optional[str], role: Optional[str]) -> bool:
|
||||||
|
if (visibility or "").strip().lower() != "official":
|
||||||
|
return True
|
||||||
|
return (role or "").strip().lower() == "superadmin"
|
||||||
|
|
||||||
|
|
||||||
|
def _same_club(left: Any, right: Any) -> bool:
|
||||||
|
try:
|
||||||
|
return left is not None and right is not None and int(left) == int(right)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def release_denial(
|
||||||
|
*,
|
||||||
|
visibility: Optional[str],
|
||||||
|
role: Optional[str],
|
||||||
|
publisher_kind: str,
|
||||||
|
is_owner: bool,
|
||||||
|
is_club_admin: bool,
|
||||||
|
publisher_club_id: Any = None,
|
||||||
|
exercise_club_id: Any = None,
|
||||||
|
) -> Optional[str]:
|
||||||
|
"""Freigabe folgt der Zugehörigkeit der Übung, nicht einer gesonderten Zuordnungsliste."""
|
||||||
|
vis = (visibility or "").strip().lower()
|
||||||
|
role_l = (role or "").strip().lower()
|
||||||
|
kind = (publisher_kind or "").strip().lower()
|
||||||
|
if vis == "official":
|
||||||
|
if role_l != "superadmin":
|
||||||
|
return "Globale Übungen dürfen nur von Superadmins freigegeben werden."
|
||||||
|
if kind != "platform":
|
||||||
|
return "Globale Übungen werden nur über den Plattformbestand freigegeben."
|
||||||
|
return None
|
||||||
|
if kind == "platform":
|
||||||
|
return "Der Plattformbestand gibt nur globale Übungen frei."
|
||||||
|
if vis == "private":
|
||||||
|
if not is_owner:
|
||||||
|
return "Private Übungen gibt nur die Person frei, der sie gehören."
|
||||||
|
if kind != "own":
|
||||||
|
return "Private Übungen werden über den eigenen Bestand freigegeben."
|
||||||
|
return None
|
||||||
|
if vis == "club":
|
||||||
|
if not is_club_admin:
|
||||||
|
return "Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei."
|
||||||
|
if kind != "club" or not _same_club(publisher_club_id, exercise_club_id):
|
||||||
|
return "Vereinsübungen werden über den Bestand dieses Vereins freigegeben."
|
||||||
|
return None
|
||||||
|
return "Diese Übung kann so nicht freigegeben werden."
|
||||||
|
|
||||||
|
|
||||||
|
def can_withdraw(*, role: Optional[str], denial: Optional[str]) -> bool:
|
||||||
|
if (role or "").strip().lower() == "superadmin":
|
||||||
|
return True
|
||||||
|
return denial is None
|
||||||
|
|
||||||
|
|
||||||
|
OBJECT_SCOPES = ("exercise", "training_plan", "framework", "training_module")
|
||||||
|
CONTEXT_VISIBILITIES = {
|
||||||
|
"platform": ("official", "private"),
|
||||||
|
"club": ("club", "private"),
|
||||||
|
"personal": ("private",),
|
||||||
|
"user": ("official", "club", "private"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def scope_denial(context_kind: str, objects: Iterable[str], visibilities: Iterable[str]) -> Optional[str]:
|
||||||
|
allowed = CONTEXT_VISIBILITIES.get(context_kind)
|
||||||
|
if allowed is None:
|
||||||
|
return "Unbekannter Schlüsselkontext."
|
||||||
|
chosen_objects = [str(item) for item in objects]
|
||||||
|
chosen_visibilities = [str(item) for item in visibilities]
|
||||||
|
if not chosen_objects:
|
||||||
|
return "Der Schlüssel braucht mindestens eine Objektart."
|
||||||
|
if any(item not in OBJECT_SCOPES for item in chosen_objects):
|
||||||
|
return "Unbekannte Objektart."
|
||||||
|
if not chosen_visibilities:
|
||||||
|
return "Der Schlüssel braucht mindestens eine Sichtbarkeit."
|
||||||
|
if any(item not in allowed for item in chosen_visibilities):
|
||||||
|
return "Diese Sichtbarkeit ist in diesem Kontext nicht erlaubt."
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def key_covers(objects: Optional[Iterable[str]], visibilities: Optional[Iterable[str]], *, resource: str, visibility: str) -> bool:
|
||||||
|
chosen_objects = list(objects) if objects else ["exercise"]
|
||||||
|
chosen_visibilities = list(visibilities) if visibilities else ["official", "club", "private"]
|
||||||
|
return resource in chosen_objects and visibility in chosen_visibilities
|
||||||
|
|
||||||
|
|
||||||
|
def package_state(*, fetch_blocked: bool, retired: bool) -> str:
|
||||||
|
if fetch_blocked:
|
||||||
|
return "withdrawn"
|
||||||
|
if retired:
|
||||||
|
return "retired"
|
||||||
|
return "available"
|
||||||
|
|
||||||
|
|
||||||
|
def exercise_offerable(source_status: Optional[str], package_states: Iterable[str]) -> tuple[str, bool]:
|
||||||
|
"""Die eingefrorene Kopie bleibt abrufbar. Neu anbieten darf der Empfänger sie nur, solange die Quelle approved und ein Paket verfügbar ist."""
|
||||||
|
status = "deleted" if not (source_status or "").strip() else str(source_status).strip().lower()
|
||||||
|
states = list(package_states)
|
||||||
|
return status, status == "approved" and any(item == "available" for item in states)
|
||||||
|
|
||||||
|
|
||||||
|
def decide_confirm(stored_release_id: Optional[str], new_release_id: str) -> tuple[str, bool]:
|
||||||
|
"""Technische Wiederholung liefert die gespeicherte Paket-ID. Eine neue Bestätigung legt ein Paket an."""
|
||||||
|
if stored_release_id:
|
||||||
|
return stored_release_id, False
|
||||||
|
return new_release_id, True
|
||||||
|
|
||||||
|
|
||||||
|
def rate_decision(hits: int, window_age_seconds: float, limit: int = RATE_LIMIT_PER_MINUTE) -> tuple[int, bool]:
|
||||||
|
if window_age_seconds >= 60:
|
||||||
|
return 1, False
|
||||||
|
if hits >= limit:
|
||||||
|
return hits, True
|
||||||
|
return hits + 1, False
|
||||||
|
|
||||||
|
|
||||||
|
def plaintext(value: Optional[str]) -> str:
|
||||||
|
text = value or ""
|
||||||
|
text = _MEDIA_TOKEN.sub("", text)
|
||||||
|
text = _DATA_MEDIA.sub("", text)
|
||||||
|
text = _TAG.sub("", text)
|
||||||
|
return unescape(text).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def inline_media_ids(value: Optional[str]) -> set[int]:
|
||||||
|
if not value:
|
||||||
|
return set()
|
||||||
|
ids = {int(item) for item in _MEDIA_TOKEN.findall(value)}
|
||||||
|
ids.update(int(item) for item in _DATA_MEDIA.findall(value))
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot_hash(exercise: dict, variants: list[dict], media: list[dict]) -> str:
|
||||||
|
body = {
|
||||||
|
"title": exercise.get("title") or "",
|
||||||
|
"summary": exercise.get("summary") or "",
|
||||||
|
"goal": exercise.get("goal") or "",
|
||||||
|
"execution": exercise.get("execution") or "",
|
||||||
|
"preparation": exercise.get("preparation") or "",
|
||||||
|
"trainer_notes": exercise.get("trainer_notes") or "",
|
||||||
|
"equipment": exercise.get("equipment"),
|
||||||
|
"duration_min": exercise.get("duration_min"),
|
||||||
|
"duration_max": exercise.get("duration_max"),
|
||||||
|
"status": exercise.get("status"),
|
||||||
|
"exercise_kind": exercise.get("exercise_kind") or "simple",
|
||||||
|
"variants": [
|
||||||
|
{
|
||||||
|
"id": str(item.get("public_id")),
|
||||||
|
"name": item.get("variant_name") or "",
|
||||||
|
"description": item.get("description") or "",
|
||||||
|
"execution_changes": item.get("execution_changes") or "",
|
||||||
|
"duration_min": item.get("duration_min"),
|
||||||
|
"duration_max": item.get("duration_max"),
|
||||||
|
}
|
||||||
|
for item in variants
|
||||||
|
],
|
||||||
|
"media": [
|
||||||
|
{
|
||||||
|
"id": str(item.get("public_id")),
|
||||||
|
"sha256": item.get("sha256") or "",
|
||||||
|
"media_type": item.get("media_type") or "",
|
||||||
|
}
|
||||||
|
for item in media
|
||||||
|
],
|
||||||
|
}
|
||||||
|
return sha256_bytes(canonical_json(body))
|
||||||
|
|
||||||
|
|
||||||
|
def _duration_note(exercise: dict) -> Optional[str]:
|
||||||
|
low = exercise.get("duration_min")
|
||||||
|
high = exercise.get("duration_max")
|
||||||
|
if low and high:
|
||||||
|
return f"{low}–{high} Minuten"
|
||||||
|
if low or high:
|
||||||
|
return f"{low or high} Minuten"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _manifest_part_text(manifest: dict, role: str) -> str:
|
||||||
|
parts = ((manifest.get("exercise") or {}).get("parts") or [])
|
||||||
|
return "\n".join((part.get("text") or "").strip() for part in parts if part.get("role") == role).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _instruction_texts(exercise: dict, variants: list[dict]) -> list[str]:
|
||||||
|
texts = []
|
||||||
|
base = plaintext(exercise.get("execution"))
|
||||||
|
if variants:
|
||||||
|
for variant in variants:
|
||||||
|
extra = plaintext(variant.get("execution_changes"))
|
||||||
|
combined = "\n".join(piece for piece in (base, extra) if piece)
|
||||||
|
if combined:
|
||||||
|
texts.append(combined)
|
||||||
|
elif base:
|
||||||
|
texts.append(base)
|
||||||
|
return texts
|
||||||
|
|
||||||
|
|
||||||
|
def changed_areas(exercise: dict, variants: list[dict], media: list[dict], manifest: dict) -> list[str]:
|
||||||
|
"""Benannte Abweichungen der Arbeitsfassung vom gespeicherten Release-Manifest."""
|
||||||
|
body = manifest.get("exercise") or {}
|
||||||
|
areas: list[str] = []
|
||||||
|
if (exercise.get("title") or "") != (body.get("title") or ""):
|
||||||
|
areas.append("Titel")
|
||||||
|
if (plaintext(exercise.get("summary")) or "") != (body.get("summary") or ""):
|
||||||
|
areas.append("Kurztext")
|
||||||
|
for role, label, current in (
|
||||||
|
("goal", "Ziel", plaintext(exercise.get("goal"))),
|
||||||
|
("preparation", "Vorbereitung", plaintext(exercise.get("preparation"))),
|
||||||
|
("trainer_notes", "Trainerhinweise", plaintext(exercise.get("trainer_notes"))),
|
||||||
|
("equipment", "Material", plaintext(_equipment_text(exercise))),
|
||||||
|
("duration_note", "Dauer", plaintext(_duration_note(exercise))),
|
||||||
|
):
|
||||||
|
if (current or "") != _manifest_part_text(manifest, role):
|
||||||
|
areas.append(label)
|
||||||
|
released_instructions = sorted(
|
||||||
|
(part.get("text") or "").strip()
|
||||||
|
for part in (body.get("parts") or [])
|
||||||
|
if part.get("role") == "instructions" and (part.get("text") or "").strip()
|
||||||
|
)
|
||||||
|
if sorted(_instruction_texts(exercise, variants)) != released_instructions:
|
||||||
|
areas.append("Durchführung")
|
||||||
|
released_variants = list(body.get("variants") or [])
|
||||||
|
if variants:
|
||||||
|
current_variants = sorted((str(item.get("public_id")), item.get("variant_name") or "") for item in variants)
|
||||||
|
released_pairs = sorted((str(item.get("id")), item.get("label") or "") for item in released_variants)
|
||||||
|
if current_variants != released_pairs:
|
||||||
|
areas.append("Varianten")
|
||||||
|
elif len(released_variants) != 1:
|
||||||
|
areas.append("Varianten")
|
||||||
|
current_by_id = {str(item.get("public_id")): item.get("sha256") or "" for item in media}
|
||||||
|
released_by_id = {str(item.get("id")): item.get("sha256") or "" for item in (body.get("assets") or [])}
|
||||||
|
media_changed = set(current_by_id) != set(released_by_id)
|
||||||
|
if not media_changed:
|
||||||
|
for key, digest in current_by_id.items():
|
||||||
|
released_digest = released_by_id.get(key) or ""
|
||||||
|
if digest and released_digest and digest != released_digest:
|
||||||
|
media_changed = True
|
||||||
|
break
|
||||||
|
if media_changed:
|
||||||
|
areas.append("Medien")
|
||||||
|
return areas
|
||||||
|
|
||||||
|
|
||||||
|
def _equipment_text(exercise: dict) -> Optional[str]:
|
||||||
|
raw = exercise.get("equipment")
|
||||||
|
if isinstance(raw, str):
|
||||||
|
try:
|
||||||
|
raw = json.loads(raw)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
raw = [raw] if raw.strip() else []
|
||||||
|
if isinstance(raw, list):
|
||||||
|
parts = [str(item).strip() for item in raw if str(item).strip()]
|
||||||
|
return ", ".join(parts) or None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def default_cut(exercise: dict, variants: list[dict], media: list[dict]) -> dict:
|
||||||
|
parts: list[dict] = []
|
||||||
|
|
||||||
|
def add(key: str, role: str, text: Optional[str]) -> None:
|
||||||
|
cleaned = plaintext(text)
|
||||||
|
if cleaned:
|
||||||
|
parts.append({"key": key, "role": role, "text": cleaned})
|
||||||
|
|
||||||
|
add("field:goal", "goal", exercise.get("goal"))
|
||||||
|
add("field:preparation", "preparation", exercise.get("preparation"))
|
||||||
|
add("field:trainer_notes", "trainer_notes", exercise.get("trainer_notes"))
|
||||||
|
add("field:equipment", "equipment", _equipment_text(exercise))
|
||||||
|
add("field:duration", "duration_note", _duration_note(exercise))
|
||||||
|
common_keys = [part["key"] for part in parts]
|
||||||
|
variant_rows = []
|
||||||
|
if variants:
|
||||||
|
for variant in variants:
|
||||||
|
key = f"variant:{variant['public_id']}:instructions"
|
||||||
|
text = plaintext(exercise.get("execution"))
|
||||||
|
extra = plaintext(variant.get("execution_changes"))
|
||||||
|
combined = "\n".join(piece for piece in (text, extra) if piece)
|
||||||
|
if combined:
|
||||||
|
parts.append({"key": key, "role": "instructions", "text": combined})
|
||||||
|
variant_rows.append(
|
||||||
|
{
|
||||||
|
"key": str(variant["public_id"]),
|
||||||
|
"label": variant.get("variant_name") or "Variante",
|
||||||
|
"part_keys": [key] if combined else [],
|
||||||
|
"media_ids": [],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
key = "variant:default:instructions"
|
||||||
|
text = plaintext(exercise.get("execution"))
|
||||||
|
if text:
|
||||||
|
parts.append({"key": key, "role": "instructions", "text": text})
|
||||||
|
variant_rows.append(
|
||||||
|
{
|
||||||
|
"key": "default",
|
||||||
|
"label": "Standard",
|
||||||
|
"part_keys": [key] if text else [],
|
||||||
|
"media_ids": [],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
assets = []
|
||||||
|
for item in media:
|
||||||
|
kind = (item.get("media_type") or "").lower()
|
||||||
|
if kind == "video":
|
||||||
|
role = "demonstration"
|
||||||
|
elif kind in ("document", "pdf"):
|
||||||
|
role = "worksheet"
|
||||||
|
else:
|
||||||
|
role = "illustration"
|
||||||
|
assets.append(
|
||||||
|
{
|
||||||
|
"media_id": str(item["public_id"]),
|
||||||
|
"role": role,
|
||||||
|
"label": item.get("title") or None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"title": exercise.get("title") or "",
|
||||||
|
"summary": plaintext(exercise.get("summary")) or None,
|
||||||
|
"audience": None,
|
||||||
|
"rights": [],
|
||||||
|
"parts": parts,
|
||||||
|
"assets": assets,
|
||||||
|
"common_part_keys": common_keys,
|
||||||
|
"common_media_ids": [],
|
||||||
|
"variants": variant_rows,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def cut_hash(cut: dict) -> str:
|
||||||
|
return sha256_bytes(canonical_json(cut))
|
||||||
|
|
||||||
|
|
||||||
|
def collect_blockers(exercise: dict, variants: list[dict], media: list[dict], cut: dict, now: datetime) -> list[str]:
|
||||||
|
blockers: list[str] = []
|
||||||
|
if (exercise.get("exercise_kind") or "simple") != "simple":
|
||||||
|
blockers.append("Kombinationsübungen können in dieser Fassung nicht herausgegeben werden.")
|
||||||
|
if (exercise.get("status") or "") != "approved":
|
||||||
|
blockers.append("Nur Übungen mit Status approved können freigegeben werden.")
|
||||||
|
texts = " ".join(
|
||||||
|
str(exercise.get(field) or "")
|
||||||
|
for field in ("goal", "execution", "preparation", "trainer_notes", "summary")
|
||||||
|
)
|
||||||
|
selected_media = {str(item.get("media_id")) for item in cut.get("assets") or []}
|
||||||
|
known_media = {str(item.get("public_id")): item for item in media}
|
||||||
|
referenced = inline_media_ids(texts)
|
||||||
|
for media_id in referenced:
|
||||||
|
match = next((item for item in media if int(item.get("id") or 0) == media_id), None)
|
||||||
|
if match is None or str(match.get("public_id")) not in selected_media:
|
||||||
|
blockers.append("Ein Medienanker im Text ist nicht als Medium im Paket enthalten.")
|
||||||
|
break
|
||||||
|
part_keys = [part.get("key") for part in cut.get("parts") or []]
|
||||||
|
if len(part_keys) != len(set(part_keys)):
|
||||||
|
blockers.append("Teilschlüssel sind nicht eindeutig.")
|
||||||
|
if not any(part.get("role") == "goal" and str(part.get("text") or "").strip() for part in cut.get("parts") or []):
|
||||||
|
blockers.append("Das Paket braucht ein Lernziel.")
|
||||||
|
rights = {item.get("id"): item for item in cut.get("rights") or []}
|
||||||
|
if None in rights or "" in rights:
|
||||||
|
blockers.append("Jeder Rechtevermerk braucht eine Kennung.")
|
||||||
|
for right in cut.get("rights") or []:
|
||||||
|
actions = set(right.get("actions") or [])
|
||||||
|
unknown = actions - set(ACTIONS)
|
||||||
|
if unknown:
|
||||||
|
blockers.append("Unbekannte Nutzungsaktion im Rechtevermerk.")
|
||||||
|
if "store" not in actions:
|
||||||
|
blockers.append("Jeder Rechtevermerk muss die Übernahme erlauben.")
|
||||||
|
if not str(right.get("evidence_ref") or "").strip():
|
||||||
|
blockers.append("Jeder Rechtevermerk braucht eine Nachweisreferenz.")
|
||||||
|
try:
|
||||||
|
start = parse_utc(right["valid_from"])
|
||||||
|
except Exception:
|
||||||
|
blockers.append("valid_from ist kein UTC-Zeitpunkt.")
|
||||||
|
continue
|
||||||
|
until_raw = right.get("valid_until")
|
||||||
|
until = None
|
||||||
|
if until_raw is not None:
|
||||||
|
try:
|
||||||
|
until = parse_utc(until_raw)
|
||||||
|
except Exception:
|
||||||
|
blockers.append("valid_until ist kein UTC-Zeitpunkt.")
|
||||||
|
continue
|
||||||
|
if start > now or (until is not None and not (start <= now < until)):
|
||||||
|
blockers.append("Ein Rechtevermerk ist zum Freigabezeitpunkt nicht wirksam.")
|
||||||
|
territories = right.get("territories")
|
||||||
|
if territories is not None:
|
||||||
|
if not isinstance(territories, list) or any(not re.fullmatch(r"[A-Z]{2}", str(code)) for code in territories):
|
||||||
|
blockers.append("territories sind ISO-Ländercodes oder null.")
|
||||||
|
editorial = cut.get("editorial_rights_id")
|
||||||
|
if editorial not in rights:
|
||||||
|
blockers.append("Die redaktionellen Angaben brauchen einen Rechtevermerk.")
|
||||||
|
used_parts: set[str] = set(cut.get("common_part_keys") or [])
|
||||||
|
used_media: set[str] = set(str(item) for item in (cut.get("common_media_ids") or []))
|
||||||
|
variant_keys = []
|
||||||
|
for variant in cut.get("variants") or []:
|
||||||
|
variant_keys.append(variant.get("key"))
|
||||||
|
used_parts.update(variant.get("part_keys") or [])
|
||||||
|
used_media.update(str(item) for item in (variant.get("media_ids") or []))
|
||||||
|
for key in variant.get("part_keys") or []:
|
||||||
|
if key not in part_keys:
|
||||||
|
blockers.append("Eine Variante verweist auf einen unbekannten Teil.")
|
||||||
|
for media_id in variant.get("media_ids") or []:
|
||||||
|
if str(media_id) not in selected_media:
|
||||||
|
blockers.append("Eine Variante verweist auf ein unbekanntes Medium.")
|
||||||
|
for key in cut.get("common_part_keys") or []:
|
||||||
|
if key not in part_keys:
|
||||||
|
blockers.append("Ein gemeinsamer Teil ist unbekannt.")
|
||||||
|
for media_id in cut.get("common_media_ids") or []:
|
||||||
|
if str(media_id) not in selected_media:
|
||||||
|
blockers.append("Ein gemeinsames Medium ist unbekannt.")
|
||||||
|
if len(variant_keys) != len(set(variant_keys)) or not variant_keys:
|
||||||
|
blockers.append("Das Paket braucht mindestens eine Variante.")
|
||||||
|
for part in cut.get("parts") or []:
|
||||||
|
if part.get("role") not in PART_ROLES:
|
||||||
|
blockers.append("Unbekannte Textrolle.")
|
||||||
|
if part.get("key") not in used_parts:
|
||||||
|
blockers.append("Ein Textteil hängt an keiner Variante.")
|
||||||
|
if part.get("rights_id") not in rights:
|
||||||
|
blockers.append("Ein Textteil hat keinen wirksamen Rechtevermerk.")
|
||||||
|
for asset in cut.get("assets") or []:
|
||||||
|
media_id = str(asset.get("media_id"))
|
||||||
|
if media_id not in used_media:
|
||||||
|
blockers.append("Ein Medium hängt an keiner Variante.")
|
||||||
|
if asset.get("role") not in ASSET_ROLES:
|
||||||
|
blockers.append("Unbekannte Medienrolle.")
|
||||||
|
if asset.get("rights_id") not in rights:
|
||||||
|
blockers.append("Ein Medium hat keinen wirksamen Rechtevermerk.")
|
||||||
|
stored = known_media.get(media_id)
|
||||||
|
if stored is None:
|
||||||
|
blockers.append("Ein ausgewähltes Medium gehört nicht zu dieser Übung.")
|
||||||
|
continue
|
||||||
|
if stored.get("legal_hold_active"):
|
||||||
|
blockers.append("Ein ausgewähltes Medium ist gesperrt.")
|
||||||
|
if not stored.get("file_path"):
|
||||||
|
blockers.append("Ein ausgewähltes Medium hat keine gespeicherten Bytes.")
|
||||||
|
if (stored.get("rights_status") or "legacy_unreviewed") in ("legacy_unreviewed", "blocked", ""):
|
||||||
|
blockers.append("Die Upload-Erklärung eines Mediums trägt die Herausgabe nicht.")
|
||||||
|
if variants:
|
||||||
|
known_variant_ids = {str(item.get("public_id")) for item in variants}
|
||||||
|
for variant in cut.get("variants") or []:
|
||||||
|
if variant.get("key") not in known_variant_ids and variant.get("key") != "default":
|
||||||
|
blockers.append("Eine Variante gehört nicht zur Übung.")
|
||||||
|
return list(dict.fromkeys(blockers))
|
||||||
|
|
||||||
|
|
||||||
|
def resolved_asset_ids(manifest: dict, variant_id: str) -> set[str]:
|
||||||
|
exercise = manifest["exercise"]
|
||||||
|
variant = next(item for item in exercise["variants"] if item["id"] == variant_id)
|
||||||
|
return set(exercise["common_asset_ids"]) | set(variant["asset_ids"])
|
||||||
|
|
||||||
|
|
||||||
|
def package_fetch_blocked(events: Iterable[dict], release_id: str) -> bool:
|
||||||
|
return any(
|
||||||
|
event.get("type") in WITHDRAW_TYPES and event.get("release_id") == release_id
|
||||||
|
for event in events
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def retrievable_release_ids(events: Iterable[dict]) -> set[str]:
|
||||||
|
published: set[str] = set()
|
||||||
|
blocked: set[str] = set()
|
||||||
|
for event in events:
|
||||||
|
if event.get("type") == "release.published":
|
||||||
|
published.add(event["release_id"])
|
||||||
|
elif event.get("type") in WITHDRAW_TYPES:
|
||||||
|
blocked.add(event["release_id"])
|
||||||
|
return published - blocked
|
||||||
|
|
||||||
|
|
||||||
|
def plan_available(plan: dict, manifest: dict, events: Iterable[dict]) -> bool:
|
||||||
|
release_id = plan["release_id"]
|
||||||
|
variant_id = plan["variant_id"]
|
||||||
|
relevant = [event for event in events if event.get("release_id") == release_id]
|
||||||
|
if any(event.get("type") == "release.withdrawn" for event in relevant):
|
||||||
|
return False
|
||||||
|
if any(event.get("type") == "variant.withdrawn" and event.get("target_id") == variant_id for event in relevant):
|
||||||
|
return False
|
||||||
|
withdrawn_assets = {
|
||||||
|
event["target_id"] for event in relevant if event.get("type") == "asset.withdrawn"
|
||||||
|
}
|
||||||
|
if withdrawn_assets & resolved_asset_ids(manifest, variant_id):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def actions_cover(actions: Iterable[str], required: Iterable[str]) -> bool:
|
||||||
|
return set(required).issubset(set(actions))
|
||||||
|
|
||||||
|
|
||||||
|
def new_id() -> str:
|
||||||
|
return str(uuid.uuid4())
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -8,7 +8,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
from html.parser import HTMLParser
|
||||||
from typing import FrozenSet, Optional, Set
|
from typing import FrozenSet, Optional, Set
|
||||||
|
from html import escape as html_escape
|
||||||
|
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
@@ -40,7 +42,126 @@ def normalize_inline_exercise_media_markup(html: Optional[str]) -> Optional[str]
|
|||||||
f'class="shinkan-inline-media"></span>'
|
f'class="shinkan-inline-media"></span>'
|
||||||
)
|
)
|
||||||
|
|
||||||
return _BRACE_PATTERN.sub(_repl, html)
|
return sanitize_exercise_rich_html(_BRACE_PATTERN.sub(_repl, html))
|
||||||
|
|
||||||
|
|
||||||
|
_ALLOWED_RICH_TAGS = frozenset(
|
||||||
|
{"p", "div", "br", "ul", "ol", "li", "h3", "b", "strong", "i", "em", "u", "span", "a"}
|
||||||
|
)
|
||||||
|
_DROP_WITH_CHILDREN = frozenset(
|
||||||
|
{"script", "iframe", "object", "embed", "style", "link", "meta", "svg", "math"}
|
||||||
|
)
|
||||||
|
_VOID_TAGS = frozenset({"br"})
|
||||||
|
_MEDIA_SIZES = frozenset({"small", "medium", "full"})
|
||||||
|
_CAPTION_MAX = 120
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_caption(raw: str) -> str:
|
||||||
|
text = re.sub(r"[\u0000-\u001f\u007f]", " ", raw or "")
|
||||||
|
text = re.sub(r"[\"'`<>]", " ", text)
|
||||||
|
text = re.sub(r"\s+", " ", text).strip()
|
||||||
|
return text[:_CAPTION_MAX]
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_rich_attrs(tag: str, attrs: list[tuple[str, Optional[str]]]) -> list[tuple[str, str]]:
|
||||||
|
values = {}
|
||||||
|
for name, value in attrs:
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
values[name.lower()] = "" if value is None else str(value)
|
||||||
|
if tag == "a":
|
||||||
|
href = values.get("href", "").strip()
|
||||||
|
if href.lower().startswith(("http://", "https://")) and not re.search(r"[\u0000-\u001f\u007f]", href):
|
||||||
|
return [("href", href)]
|
||||||
|
return []
|
||||||
|
if tag != "span":
|
||||||
|
return []
|
||||||
|
media_id = values.get("data-shinkan-exercise-media", "").strip()
|
||||||
|
if not re.fullmatch(r"\d+", media_id):
|
||||||
|
return []
|
||||||
|
out = [("data-shinkan-exercise-media", media_id)]
|
||||||
|
size = values.get("data-shinkan-exercise-media-size", "").strip().lower()
|
||||||
|
if size in _MEDIA_SIZES:
|
||||||
|
out.append(("data-shinkan-exercise-media-size", size))
|
||||||
|
caption = _clean_caption(values.get("data-shinkan-exercise-media-caption", ""))
|
||||||
|
if caption:
|
||||||
|
out.append(("data-shinkan-exercise-media-caption", caption))
|
||||||
|
classes = [c for c in values.get("class", "").split() if c == "shinkan-inline-media"]
|
||||||
|
if classes:
|
||||||
|
out.append(("class", "shinkan-inline-media"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class _RichHtmlSanitizer(HTMLParser):
|
||||||
|
"""Baut erlaubtes Übungs-HTML neu auf. Unbekannte Tags fallen weg, ihr Text bleibt."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts: list[str] = []
|
||||||
|
self._drop_depth = 0
|
||||||
|
self._stack: list[str] = []
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
|
||||||
|
self._start(tag.lower(), attrs, void=False)
|
||||||
|
|
||||||
|
def handle_startendtag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
|
||||||
|
self._start(tag.lower(), attrs, void=True)
|
||||||
|
|
||||||
|
def _start(self, tag: str, attrs: list[tuple[str, Optional[str]]], *, void: bool) -> None:
|
||||||
|
if self._drop_depth:
|
||||||
|
if not void and tag not in _VOID_TAGS:
|
||||||
|
self._drop_depth += 1
|
||||||
|
return
|
||||||
|
if tag in _DROP_WITH_CHILDREN:
|
||||||
|
if not void:
|
||||||
|
self._drop_depth = 1
|
||||||
|
return
|
||||||
|
if tag not in _ALLOWED_RICH_TAGS:
|
||||||
|
return
|
||||||
|
safe = _safe_rich_attrs(tag, attrs)
|
||||||
|
rendered = tag
|
||||||
|
if safe:
|
||||||
|
rendered += "".join(f' {name}="{html_escape(value, quote=True)}"' for name, value in safe)
|
||||||
|
if void or tag in _VOID_TAGS:
|
||||||
|
self.parts.append(f"<{rendered}>")
|
||||||
|
return
|
||||||
|
self._stack.append(tag)
|
||||||
|
self.parts.append(f"<{rendered}>")
|
||||||
|
|
||||||
|
def handle_endtag(self, tag: str) -> None:
|
||||||
|
tag = tag.lower()
|
||||||
|
if self._drop_depth:
|
||||||
|
if tag in _DROP_WITH_CHILDREN or self._drop_depth > 1:
|
||||||
|
self._drop_depth = max(0, self._drop_depth - 1)
|
||||||
|
return
|
||||||
|
if self._stack and self._stack[-1] == tag:
|
||||||
|
self._stack.pop()
|
||||||
|
self.parts.append(f"</{tag}>")
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
if self._drop_depth or not data:
|
||||||
|
return
|
||||||
|
self.parts.append(html_escape(data))
|
||||||
|
|
||||||
|
def handle_entityref(self, name: str) -> None:
|
||||||
|
self.handle_data(f"&{name};")
|
||||||
|
|
||||||
|
def handle_charref(self, name: str) -> None:
|
||||||
|
self.handle_data(f"&#{name};")
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_exercise_rich_html(html: Optional[str]) -> Optional[str]:
|
||||||
|
"""Allowlist für gespeichertes Übungs-HTML. Skripte, Handler und fremde Attribute fallen weg."""
|
||||||
|
if html is None:
|
||||||
|
return None
|
||||||
|
if not isinstance(html, str):
|
||||||
|
html = str(html)
|
||||||
|
if not html.strip():
|
||||||
|
return html
|
||||||
|
parser = _RichHtmlSanitizer()
|
||||||
|
parser.feed(html)
|
||||||
|
parser.close()
|
||||||
|
return "".join(parser.parts)
|
||||||
|
|
||||||
|
|
||||||
def collect_inline_exercise_media_ids(html: Optional[str]) -> Set[int]:
|
def collect_inline_exercise_media_ids(html: Optional[str]) -> Set[int]:
|
||||||
|
|||||||
+6
-2
@@ -243,7 +243,7 @@ def read_root():
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
# Register routers
|
# Register routers
|
||||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin
|
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin, distribution
|
||||||
|
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
app.include_router(profiles.router)
|
app.include_router(profiles.router)
|
||||||
@@ -269,6 +269,7 @@ app.include_router(dashboard.router)
|
|||||||
app.include_router(training_modules.router)
|
app.include_router(training_modules.router)
|
||||||
app.include_router(training_framework_programs.router)
|
app.include_router(training_framework_programs.router)
|
||||||
app.include_router(catalogs.router)
|
app.include_router(catalogs.router)
|
||||||
|
app.include_router(catalog_prompt_slots.router)
|
||||||
app.include_router(maturity_models.router)
|
app.include_router(maturity_models.router)
|
||||||
app.include_router(matrix_stack_bundle.router)
|
app.include_router(matrix_stack_bundle.router)
|
||||||
app.include_router(matrix_editor.router)
|
app.include_router(matrix_editor.router)
|
||||||
@@ -277,11 +278,14 @@ app.include_router(import_wiki_admin.router)
|
|||||||
app.include_router(legal_documents.router)
|
app.include_router(legal_documents.router)
|
||||||
app.include_router(content_reports.router)
|
app.include_router(content_reports.router)
|
||||||
app.include_router(ai_prompts_admin.router)
|
app.include_router(ai_prompts_admin.router)
|
||||||
|
app.include_router(openrouter_admin.router)
|
||||||
app.include_router(ai_skill_retrieval_admin.router)
|
app.include_router(ai_skill_retrieval_admin.router)
|
||||||
app.include_router(exercise_enrichment_admin.router)
|
app.include_router(exercise_enrichment_admin.router)
|
||||||
|
app.include_router(distribution.router)
|
||||||
|
app.include_router(distribution.editorial)
|
||||||
|
|
||||||
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
|
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
|
||||||
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken für <img>/<video>).
|
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken = kurzlebiges Medien-Token, kein Sitzungstoken).
|
||||||
# Notfall/Legacy: ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder öffentlich unter /media/
|
# Notfall/Legacy: ALLOW_PUBLIC_MEDIA_STATIC=1 → wieder öffentlich unter /media/
|
||||||
_media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
|
_media_dir = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
|
||||||
Path(_media_dir).mkdir(parents=True, exist_ok=True)
|
Path(_media_dir).mkdir(parents=True, exist_ok=True)
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Kurzlebige Medien-Tokens. Kein Sitzungstoken — nur für Dateiabruf per Query."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
MEDIA_GRANT_TTL_SECONDS = 600
|
||||||
|
_PREFIX = "mg1"
|
||||||
|
|
||||||
|
|
||||||
|
def _key() -> bytes:
|
||||||
|
dedicated = (os.getenv("MEDIA_TOKEN_SECRET") or "").strip()
|
||||||
|
if dedicated:
|
||||||
|
return hashlib.sha256(dedicated.encode("utf-8")).digest()
|
||||||
|
material = (os.getenv("DB_PASSWORD") or "shinkan-dev-media").encode("utf-8")
|
||||||
|
return hashlib.sha256(b"shinkan-media-grant-v1|" + material).digest()
|
||||||
|
|
||||||
|
|
||||||
|
def issue_media_grant(profile_id: int, *, ttl_seconds: int = MEDIA_GRANT_TTL_SECONDS) -> tuple[str, int]:
|
||||||
|
exp = int(time.time()) + int(ttl_seconds)
|
||||||
|
payload = f"{int(profile_id)}.{exp}"
|
||||||
|
sig = hmac.new(_key(), payload.encode("ascii"), hashlib.sha256).hexdigest()
|
||||||
|
return f"{_PREFIX}.{payload}.{sig}", exp
|
||||||
|
|
||||||
|
|
||||||
|
def profile_id_from_media_grant(token: Optional[str], *, now: Optional[int] = None) -> Optional[int]:
|
||||||
|
if not token or not token.startswith(f"{_PREFIX}."):
|
||||||
|
return None
|
||||||
|
parts = token.split(".")
|
||||||
|
if len(parts) != 4:
|
||||||
|
return None
|
||||||
|
_, pid_s, exp_s, sig = parts
|
||||||
|
if not pid_s.isdigit() or not exp_s.isdigit():
|
||||||
|
return None
|
||||||
|
payload = f"{pid_s}.{exp_s}"
|
||||||
|
expected = hmac.new(_key(), payload.encode("ascii"), hashlib.sha256).hexdigest()
|
||||||
|
if not hmac.compare_digest(expected, sig):
|
||||||
|
return None
|
||||||
|
exp = int(exp_s)
|
||||||
|
moment = int(time.time() if now is None else now)
|
||||||
|
if exp < moment:
|
||||||
|
return None
|
||||||
|
pid = int(pid_s)
|
||||||
|
if pid < 1:
|
||||||
|
return None
|
||||||
|
return pid
|
||||||
@@ -134,6 +134,10 @@ def set_legal_hold(
|
|||||||
updated_row = cur.fetchone()
|
updated_row = cur.fetchone()
|
||||||
updated = r2d(updated_row)
|
updated = r2d(updated_row)
|
||||||
|
|
||||||
|
from distribution_service import withdraw_assets_for_media_asset
|
||||||
|
|
||||||
|
withdraw_assets_for_media_asset(cur, asset_id, reason_code)
|
||||||
|
|
||||||
write_audit_log_entry(
|
write_audit_log_entry(
|
||||||
cur,
|
cur,
|
||||||
asset_id=asset_id,
|
asset_id=asset_id,
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Migration 088: Planungs-Roadmap-Artefakt am Progressionsgraph (JSONB, optional).
|
||||||
|
-- Speichert Ziel, Start/Ziel, progression_roadmap + stage_specs für Wiederaufnahme der KI-Planung.
|
||||||
|
|
||||||
|
ALTER TABLE exercise_progression_graphs
|
||||||
|
ADD COLUMN IF NOT EXISTS planning_roadmap JSONB;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN exercise_progression_graphs.planning_roadmap IS
|
||||||
|
'Optionales Planungs-Artefakt (goal_query, resolved_structured, progression_roadmap, stage_specs) — Schema v1 im App-Code.';
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
-- Migration 089: Planungs-Intent — Zielanalyse + Stufenspecs (anti_patterns, success_criteria)
|
||||||
|
|
||||||
|
UPDATE ai_prompts SET
|
||||||
|
description = 'Phase A: Ist-/Soll, Erfolgskriterien und explizite Ausschlüsse (ohne Gruppenkontext).',
|
||||||
|
template = $t$Du bist Assistent für Kampfsport-Trainer und analysierst eine Anfrage für einen Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
|
||||||
|
Wichtig:
|
||||||
|
- Keine Gruppenanalyse — nur didaktischer Pfad für die Technik/das Thema.
|
||||||
|
- Explizite Negationen aus der Anfrage (ohne/kein/nicht …) in constraints.excluded_themes übernehmen — nicht raten.
|
||||||
|
- success_criteria: messbar, für späteres Übungs-Matching (Titel + Kurzbeschreibung + Übungsziel).
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"primary_topic": "Hauptthema",
|
||||||
|
"start_assumption": "Voraussetzungen für den Einstieg",
|
||||||
|
"target_state": "Konkreter Zielzustand der Progression",
|
||||||
|
"success_criteria": ["messbare Kriterien entlang des Pfads"],
|
||||||
|
"constraints": {
|
||||||
|
"partner_required": false,
|
||||||
|
"excluded_themes": ["wörtliche Negationen, z. B. keine Kumite-Anwendung"],
|
||||||
|
"trainer_notes": "optional: Fokus aus Ergänzungen"
|
||||||
|
}
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_goal_analysis';
|
||||||
|
|
||||||
|
UPDATE ai_prompts SET
|
||||||
|
description = 'Phase C: Belastung, Übungstyp, Erfolgskriterien und anti_patterns je Major Step — für Retrieval-Matching.',
|
||||||
|
template = $t$Du bist Assistent für Kampfsport-Trainer und spezifizierst didaktische Stufen eines Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Zielanalyse: {{goal_analysis_json}}
|
||||||
|
Major Steps: {{major_steps_json}}
|
||||||
|
Planungs-Intent (Pfadweite Regeln): {{intent_context_json}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
|
||||||
|
Aufgabe je Major Step — Felder für automatisches Übungs-Matching (nicht nur Titel):
|
||||||
|
- learning_goal: messbares Stufen-Lernziel (was die Übung bringen soll)
|
||||||
|
- load_profile: z. B. koordination, präzision, kraft, athletik
|
||||||
|
- exercise_type: kihon_einzel | partner_drill | kombination | kraft_auxiliary
|
||||||
|
- success_criteria: 2–4 prüfbare Kriterien an Kurzbeschreibung + Übungsziel (nicht nur Technikname im Titel)
|
||||||
|
- anti_patterns: 2–5 Dinge, die für diese Stufe unpassend sind
|
||||||
|
|
||||||
|
Regeln:
|
||||||
|
1. Jede explicit_exclusions / excluded_themes aus intent_context und Zielanalyse MUSS in anti_patterns jeder Stufe vorkommen (umformuliert ok).
|
||||||
|
2. Keine neuen Ausschlüsse erfinden, die nicht in Anfrage/Intent/Zielanalyse stehen.
|
||||||
|
3. success_criteria Pfad-weit + stufenspezifisch kombinieren.
|
||||||
|
4. partner_drill nur wenn Partner/Kumite nicht ausgeschlossen ist.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"stage_specs": [
|
||||||
|
{
|
||||||
|
"major_step_index": 0,
|
||||||
|
"learning_goal": "…",
|
||||||
|
"load_profile": ["koordination"],
|
||||||
|
"exercise_type": "kihon_einzel",
|
||||||
|
"success_criteria": ["…"],
|
||||||
|
"anti_patterns": ["…"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_stage_spec';
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
-- Migration 090: Stufenspecs — start_state / target_state pro Major Step (Soll-Verkettung)
|
||||||
|
|
||||||
|
UPDATE ai_prompts SET
|
||||||
|
description = 'Phase C: Stufenspezifikation inkl. Soll-Start und Stufen-Ziel je Major Step.',
|
||||||
|
template = $t$Du bist Assistent für Kampfsport-Trainer und spezifizierst didaktische Stufen eines Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Zielanalyse: {{goal_analysis_json}}
|
||||||
|
Major Steps: {{major_steps_json}}
|
||||||
|
Planungs-Intent (Pfadweite Regeln): {{intent_context_json}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
|
||||||
|
Jede Stufe ist ein Übergang im Gesamtpfad:
|
||||||
|
- start_state: Soll-Zustand zu Beginn (= Ziel der vorherigen Stufe; Stufe 0 = Pfad-Start)
|
||||||
|
- target_state: Zielzustand nach dieser Stufe (= Soll für die nächste Stufe)
|
||||||
|
- learning_goal: messbares Lernziel der Übungssuche (was die Übung bringen soll)
|
||||||
|
|
||||||
|
Felder je Major Step:
|
||||||
|
- load_profile, exercise_type, success_criteria, anti_patterns (wie bisher)
|
||||||
|
|
||||||
|
Regeln:
|
||||||
|
1. start_state/target_state aus Zielanalyse und Major Steps ableiten — konsistente Kette.
|
||||||
|
2. explicit_exclusions aus intent_context in anti_patterns jeder Stufe.
|
||||||
|
3. success_criteria: prüfbar an Kurzbeschreibung + Übungsziel.
|
||||||
|
4. Keine erfundenen Ausschlüsse.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"stage_specs": [
|
||||||
|
{
|
||||||
|
"major_step_index": 0,
|
||||||
|
"start_state": "…",
|
||||||
|
"target_state": "…",
|
||||||
|
"learning_goal": "…",
|
||||||
|
"load_profile": ["koordination"],
|
||||||
|
"exercise_type": "kihon_einzel",
|
||||||
|
"success_criteria": ["…"],
|
||||||
|
"anti_patterns": ["…"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_stage_spec';
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
-- Migration 091: Planungs-KI H1 — Katalog-Guidance-Platzhalter in Progressions-Prompts
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und prüfst einen vorgeschlagenen Übungspfad.
|
||||||
|
|
||||||
|
Ziel-Anfrage: {{goal_query}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
Schritte (JSON): {{steps_json}}
|
||||||
|
Erkannte Lücken: {{gaps_json}}
|
||||||
|
Eingefügte Brücken: {{bridge_inserts_json}}
|
||||||
|
|
||||||
|
{{catalog_guidance_block}}
|
||||||
|
{{catalog_context_json}}
|
||||||
|
|
||||||
|
Wichtig: Wenn Katalog-Kontext gesetzt ist, haben dessen QS-Kriterien Vorrang vor allgemeinen Technik-/Wettkampf-Maßstäben.
|
||||||
|
|
||||||
|
Prüfe:
|
||||||
|
1. Deckt der Pfad das Hauptthema der Anfrage ab (nicht nur Oberbegriffe)?
|
||||||
|
2. Ist die Reihenfolge didaktisch sinnvoll (Einstieg → Vertiefung → Ziel)?
|
||||||
|
3. Sind Sprünge zwischen benachbarten Schritten zu groß?
|
||||||
|
4. Sind Brücken-Übungen sinnvoll oder überflüssig?
|
||||||
|
5. Fehlen wichtige Zwischenschritte (Kraft, Geschwindigkeit, Anwendung, Perfektion)?
|
||||||
|
6. Gibt es Schritte ohne Bezug zum Hauptthema (z. B. reine Kraftübungen bei einer Technik)?
|
||||||
|
|
||||||
|
Wenn die Reihenfolge verbessert werden sollte: ordered_step_indices = Permutation der aktuellen 0-basierten Schritt-Indizes (beste didaktische Reihenfolge).
|
||||||
|
Nur Indizes aus dem steps_json verwenden — Länge muss exakt der Schrittzahl entsprechen.
|
||||||
|
|
||||||
|
Wenn wichtige Zwischenschritte fehlen oder Schritte themenfremd sind: suggested_new_exercises mit konkreten Übungs-Ideen (Titel + Kurzskizze), jeweils mit insert_after_step_index (0-basiert: nach welchem Schritt einfügen).
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"overall_ok": true,
|
||||||
|
"quality_score": 0.85,
|
||||||
|
"topic_coverage": "Kurz: wie gut das Hauptthema abgedeckt ist",
|
||||||
|
"ordered_step_indices": [0, 1, 2, 3],
|
||||||
|
"issues": ["…"],
|
||||||
|
"sequence_notes": ["…"],
|
||||||
|
"recommendations": ["…"],
|
||||||
|
"suggested_new_exercises": [
|
||||||
|
{
|
||||||
|
"title_hint": "Mae Geri Kraftentwicklung am Sandsack",
|
||||||
|
"sketch": "Gezielte Kraft- und Schnelligkeitsentwicklung für Mae Geri …",
|
||||||
|
"phase": "vertiefung",
|
||||||
|
"insert_after_step_index": 2,
|
||||||
|
"rationale": "Schließt Lücke zwischen Grundlagen und Gleichgewichtstritt"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}$t$,
|
||||||
|
default_template = $t$Du bist Assistent für Kampfsport-Trainer und prüfst einen vorgeschlagenen Übungspfad.
|
||||||
|
|
||||||
|
Ziel-Anfrage: {{goal_query}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
Schritte (JSON): {{steps_json}}
|
||||||
|
Erkannte Lücken: {{gaps_json}}
|
||||||
|
Eingefügte Brücken: {{bridge_inserts_json}}
|
||||||
|
|
||||||
|
{{catalog_guidance_block}}
|
||||||
|
{{catalog_context_json}}
|
||||||
|
|
||||||
|
Wichtig: Wenn Katalog-Kontext gesetzt ist, haben dessen QS-Kriterien Vorrang vor allgemeinen Technik-/Wettkampf-Maßstäben.
|
||||||
|
|
||||||
|
Prüfe:
|
||||||
|
1. Deckt der Pfad das Hauptthema der Anfrage ab (nicht nur Oberbegriffe)?
|
||||||
|
2. Ist die Reihenfolge didaktisch sinnvoll (Einstieg → Vertiefung → Ziel)?
|
||||||
|
3. Sind Sprünge zwischen benachbarten Schritten zu groß?
|
||||||
|
4. Sind Brücken-Übungen sinnvoll oder überflüssig?
|
||||||
|
5. Fehlen wichtige Zwischenschritte (Kraft, Geschwindigkeit, Anwendung, Perfektion)?
|
||||||
|
6. Gibt es Schritte ohne Bezug zum Hauptthema (z. B. reine Kraftübungen bei einer Technik)?
|
||||||
|
|
||||||
|
Wenn die Reihenfolge verbessert werden sollte: ordered_step_indices = Permutation der aktuellen 0-basierten Schritt-Indizes (beste didaktische Reihenfolge).
|
||||||
|
Nur Indizes aus dem steps_json verwenden — Länge muss exakt der Schrittzahl entsprechen.
|
||||||
|
|
||||||
|
Wenn wichtige Zwischenschritte fehlen oder Schritte themenfremd sind: suggested_new_exercises mit konkreten Übungs-Ideen (Titel + Kurzskizze), jeweils mit insert_after_step_index (0-basiert: nach welchem Schritt einfügen).
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"overall_ok": true,
|
||||||
|
"quality_score": 0.85,
|
||||||
|
"topic_coverage": "Kurz: wie gut das Hauptthema abgedeckt ist",
|
||||||
|
"ordered_step_indices": [0, 1, 2, 3],
|
||||||
|
"issues": ["…"],
|
||||||
|
"sequence_notes": ["…"],
|
||||||
|
"recommendations": ["…"],
|
||||||
|
"suggested_new_exercises": [
|
||||||
|
{
|
||||||
|
"title_hint": "Mae Geri Kraftentwicklung am Sandsack",
|
||||||
|
"sketch": "Gezielte Kraft- und Schnelligkeitsentwicklung für Mae Geri …",
|
||||||
|
"phase": "vertiefung",
|
||||||
|
"insert_after_step_index": 2,
|
||||||
|
"rationale": "Schließt Lücke zwischen Grundlagen und Gleichgewichtstritt"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}$t$
|
||||||
|
WHERE slug = 'planning_exercise_path_qa';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und analysierst eine Anfrage für einen Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
|
||||||
|
{{catalog_guidance_block}}
|
||||||
|
|
||||||
|
Wichtig: Keine Gruppenanalyse — nur didaktischer Pfad für die Technik/das Thema.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"primary_topic": "Mae Geri",
|
||||||
|
"start_assumption": "Welche Voraussetzungen werden für den Einstieg angenommen",
|
||||||
|
"target_state": "Konkreter Zielzustand der Progression",
|
||||||
|
"success_criteria": ["messbare Kriterien"],
|
||||||
|
"constraints": { "partner_required": false }
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_goal_analysis';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und erstellst eine didaktische Roadmap für einen Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Zielanalyse: {{goal_analysis_json}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
Anzahl Major Steps (N): {{max_steps}}
|
||||||
|
|
||||||
|
{{catalog_guidance_block}}
|
||||||
|
{{catalog_context_json}}
|
||||||
|
|
||||||
|
Erzeuge zuerst 8–12 micro_objectives (phase, title, weight, depends_on), dann konsolidiere auf genau N major_steps.
|
||||||
|
Phasen: einstieg, grundlage, vertiefung, anwendung, perfektion — in sinnvoller Reihenfolge (Grundlagen vor Perfektion).
|
||||||
|
Beachte Katalog-Roadmap-Hinweise, falls gesetzt.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"micro_objectives": [
|
||||||
|
{ "id": "m1", "phase": "grundlage", "title": "…", "weight": 0.9, "depends_on": [] }
|
||||||
|
],
|
||||||
|
"major_steps": [
|
||||||
|
{ "index": 0, "phase": "grundlage", "learning_goal": "…", "consolidates": ["m1","m2"], "rationale": "…" }
|
||||||
|
],
|
||||||
|
"consolidation_notes": ["…"]
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_roadmap';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und spezifizierst didaktische Stufen eines Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Zielanalyse: {{goal_analysis_json}}
|
||||||
|
Major Steps: {{major_steps_json}}
|
||||||
|
|
||||||
|
{{catalog_guidance_block}}
|
||||||
|
{{catalog_context_json}}
|
||||||
|
|
||||||
|
Für jeden Major Step: messbares Lernziel, load_profile (z. B. koordination, präzision, kraft), exercise_type (kihon_einzel, partner_drill, kombination, kraft_auxiliary), success_criteria, anti_patterns (z. B. reine Kraft ohne Technikbezug).
|
||||||
|
Beachte Katalog-QS-Kriterien und Anti-Patterns, falls gesetzt.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"stage_specs": [
|
||||||
|
{
|
||||||
|
"major_step_index": 0,
|
||||||
|
"learning_goal": "…",
|
||||||
|
"load_profile": ["koordination", "gleichgewicht"],
|
||||||
|
"exercise_type": "kihon_einzel",
|
||||||
|
"success_criteria": ["…"],
|
||||||
|
"anti_patterns": ["…"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_stage_spec';
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
-- Migration 092: Katalog-Prompt-Slots (H2) — Slot-Typ-Vokabular + leere Wertetabelle
|
||||||
|
-- Keine Inhalts-Seeds: Stammdaten (Primärfokus etc.) sind mandantenspezifisch.
|
||||||
|
-- Slot-Inhalte: Admin-UI oder catalog_slot_fallbacks.py (Namens-Match zur Laufzeit).
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS catalog_prompt_slot_types (
|
||||||
|
slot_key VARCHAR(64) PRIMARY KEY,
|
||||||
|
display_name VARCHAR(200) NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
applicable_kinds TEXT[] NOT NULL DEFAULT '{}',
|
||||||
|
sort_order INT DEFAULT 99,
|
||||||
|
for_llm BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
for_code BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
created_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS catalog_prompt_slots (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
catalog_kind VARCHAR(32) NOT NULL,
|
||||||
|
catalog_id INT NOT NULL,
|
||||||
|
slot_key VARCHAR(64) NOT NULL REFERENCES catalog_prompt_slot_types(slot_key) ON DELETE CASCADE,
|
||||||
|
content TEXT NOT NULL DEFAULT '',
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW(),
|
||||||
|
UNIQUE (catalog_kind, catalog_id, slot_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_catalog_prompt_slots_kind_id
|
||||||
|
ON catalog_prompt_slots (catalog_kind, catalog_id);
|
||||||
|
|
||||||
|
INSERT INTO catalog_prompt_slot_types (slot_key, display_name, description, applicable_kinds, sort_order, for_llm, for_code)
|
||||||
|
VALUES
|
||||||
|
(
|
||||||
|
'description',
|
||||||
|
'Allgemeine Beschreibung',
|
||||||
|
'Fachliche Einordnung des Katalog-Eintrags für Planungs-KI.',
|
||||||
|
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
|
||||||
|
10,
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'hints_on_progression',
|
||||||
|
'Hinweise Progressionsgraph',
|
||||||
|
'Didaktik für Roadmap, Major Steps und Stufenspezifikation.',
|
||||||
|
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
|
||||||
|
20,
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'hints_on_exercise',
|
||||||
|
'Hinweise Übungsanlage',
|
||||||
|
'Kontext für Gap-Fill, Übungs-KI und Schnellanlage.',
|
||||||
|
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
|
||||||
|
30,
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'hints_on_path_qa',
|
||||||
|
'Hinweise Pfad-QS',
|
||||||
|
'Bewertungsmaßstäbe für Pfad-Qualitätssicherung.',
|
||||||
|
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
|
||||||
|
40,
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'anti_patterns',
|
||||||
|
'Anti-Patterns',
|
||||||
|
'Explizite Fehlbewertungen vermeiden.',
|
||||||
|
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
|
||||||
|
50,
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'rematch_guard',
|
||||||
|
'Rematch-Guard',
|
||||||
|
'Wann kein Auto-Rematch sinnvoll ist (primär Code-Logik).',
|
||||||
|
ARRAY['focus_area', 'training_type', 'target_group', 'style_direction'],
|
||||||
|
60,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
)
|
||||||
|
ON CONFLICT (slot_key) DO NOTHING;
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
-- Migration 093: Planungs-KI — granulare Katalog-Slot-Platzhalter in Prompt-Templates
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und prüfst einen vorgeschlagenen Übungspfad.
|
||||||
|
|
||||||
|
Ziel-Anfrage: {{goal_query}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
Schritte (JSON): {{steps_json}}
|
||||||
|
Erkannte Lücken: {{gaps_json}}
|
||||||
|
Eingefügte Brücken: {{bridge_inserts_json}}
|
||||||
|
|
||||||
|
Katalog-Kontext für Bewertung (Trainer-Auswahl — leere Zeilen ignorieren):
|
||||||
|
|
||||||
|
Primärfokus:
|
||||||
|
{{focus_area_description}}
|
||||||
|
QS: {{focus_area_hints_on_path_qa}}
|
||||||
|
Vermeiden: {{focus_area_anti_patterns}}
|
||||||
|
|
||||||
|
Trainingsstil:
|
||||||
|
{{training_type_description}}
|
||||||
|
QS: {{training_type_hints_on_path_qa}}
|
||||||
|
|
||||||
|
Zielgruppe:
|
||||||
|
{{target_group_description}}
|
||||||
|
QS: {{target_group_hints_on_path_qa}}
|
||||||
|
|
||||||
|
Stilrichtung:
|
||||||
|
{{style_direction_description}}
|
||||||
|
QS: {{style_direction_hints_on_path_qa}}
|
||||||
|
|
||||||
|
{{catalog_context_json}}
|
||||||
|
|
||||||
|
Wichtig: Wenn Katalog-Slots gesetzt sind, haben diese Vorrang vor allgemeinen Technik-/Wettkampf-Maßstäben.
|
||||||
|
|
||||||
|
Prüfe:
|
||||||
|
1. Deckt der Pfad das Hauptthema der Anfrage ab (nicht nur Oberbegriffe)?
|
||||||
|
2. Ist die Reihenfolge didaktisch sinnvoll (Einstieg → Vertiefung → Ziel)?
|
||||||
|
3. Sind Sprünge zwischen benachbarten Schritten zu groß?
|
||||||
|
4. Sind Brücken-Übungen sinnvoll oder überflüssig?
|
||||||
|
5. Fehlen wichtige Zwischenschritte — gemäß Katalog-QS-Hinweisen, nicht pauschal „Perfektion“?
|
||||||
|
6. Gibt es Schritte ohne Bezug zum Hauptthema?
|
||||||
|
|
||||||
|
Wenn die Reihenfolge verbessert werden sollte: ordered_step_indices = Permutation der aktuellen 0-basierten Schritt-Indizes.
|
||||||
|
Wenn wichtige Zwischenschritte fehlen: suggested_new_exercises mit Titel + Kurzskizze und insert_after_step_index.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"overall_ok": true,
|
||||||
|
"quality_score": 0.85,
|
||||||
|
"topic_coverage": "Kurz: wie gut das Hauptthema abgedeckt ist",
|
||||||
|
"ordered_step_indices": [0, 1, 2, 3],
|
||||||
|
"issues": ["…"],
|
||||||
|
"sequence_notes": ["…"],
|
||||||
|
"recommendations": ["…"],
|
||||||
|
"suggested_new_exercises": []
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_exercise_path_qa';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und analysierst eine Anfrage für einen Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
|
||||||
|
Katalog-Kontext (Primärfokus / Trainingsstil / Zielgruppe / Stil — leere Zeilen ignorieren):
|
||||||
|
|
||||||
|
Primärfokus: {{focus_area_description}}
|
||||||
|
Progression: {{focus_area_hints_on_progression}}
|
||||||
|
|
||||||
|
Trainingsstil: {{training_type_description}}
|
||||||
|
Progression: {{training_type_hints_on_progression}}
|
||||||
|
|
||||||
|
Zielgruppe: {{target_group_description}}
|
||||||
|
|
||||||
|
Stilrichtung: {{style_direction_description}}
|
||||||
|
|
||||||
|
Wichtig: Keine Gruppenanalyse — nur didaktischer Pfad. Katalog-Hinweise beachten.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"primary_topic": "Mae Geri",
|
||||||
|
"start_assumption": "Welche Voraussetzungen werden für den Einstieg angenommen",
|
||||||
|
"target_state": "Konkreter Zielzustand der Progression",
|
||||||
|
"success_criteria": ["messbare Kriterien"],
|
||||||
|
"constraints": { "partner_required": false }
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_goal_analysis';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und erstellst eine didaktische Roadmap für einen Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Zielanalyse: {{goal_analysis_json}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
Anzahl Major Steps (N): {{max_steps}}
|
||||||
|
|
||||||
|
Katalog-Kontext für Stufenlogik:
|
||||||
|
|
||||||
|
Primärfokus:
|
||||||
|
{{focus_area_description}}
|
||||||
|
Roadmap: {{focus_area_hints_on_progression}}
|
||||||
|
Vermeiden: {{focus_area_anti_patterns}}
|
||||||
|
|
||||||
|
Trainingsstil:
|
||||||
|
{{training_type_description}}
|
||||||
|
Roadmap: {{training_type_hints_on_progression}}
|
||||||
|
|
||||||
|
Zielgruppe:
|
||||||
|
{{target_group_description}}
|
||||||
|
Roadmap: {{target_group_hints_on_progression}}
|
||||||
|
|
||||||
|
Stilrichtung:
|
||||||
|
{{style_direction_description}}
|
||||||
|
Roadmap: {{style_direction_hints_on_progression}}
|
||||||
|
|
||||||
|
{{catalog_context_json}}
|
||||||
|
|
||||||
|
Erzeuge zuerst 8–12 micro_objectives, dann konsolidiere auf genau N major_steps.
|
||||||
|
Phasen: einstieg, grundlage, vertiefung, anwendung, perfektion — Katalog-Roadmap-Hinweise beachten.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"micro_objectives": [
|
||||||
|
{ "id": "m1", "phase": "grundlage", "title": "…", "weight": 0.9, "depends_on": [] }
|
||||||
|
],
|
||||||
|
"major_steps": [
|
||||||
|
{ "index": 0, "phase": "grundlage", "learning_goal": "…", "consolidates": ["m1","m2"], "rationale": "…" }
|
||||||
|
],
|
||||||
|
"consolidation_notes": ["…"]
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_roadmap';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und spezifizierst didaktische Stufen eines Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Zielanalyse: {{goal_analysis_json}}
|
||||||
|
Major Steps: {{major_steps_json}}
|
||||||
|
Intent-Kontext: {{intent_context_json}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
|
||||||
|
Katalog-Kontext je Stufe:
|
||||||
|
|
||||||
|
Primärfokus — Progression: {{focus_area_hints_on_progression}}
|
||||||
|
Primärfokus — Vermeiden: {{focus_area_anti_patterns}}
|
||||||
|
|
||||||
|
Trainingsstil — Progression: {{training_type_hints_on_progression}}
|
||||||
|
Trainingsstil — Vermeiden: {{training_type_anti_patterns}}
|
||||||
|
|
||||||
|
Zielgruppe — Progression: {{target_group_hints_on_progression}}
|
||||||
|
Zielgruppe — Vermeiden: {{target_group_anti_patterns}}
|
||||||
|
|
||||||
|
Stilrichtung — Progression: {{style_direction_hints_on_progression}}
|
||||||
|
|
||||||
|
{{catalog_context_json}}
|
||||||
|
|
||||||
|
Für jeden Major Step: messbares Lernziel, load_profile, exercise_type, success_criteria, anti_patterns — Katalog-Slots beachten.
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"stage_specs": [
|
||||||
|
{
|
||||||
|
"major_step_index": 0,
|
||||||
|
"learning_goal": "…",
|
||||||
|
"load_profile": ["koordination", "gleichgewicht"],
|
||||||
|
"exercise_type": "kihon_einzel",
|
||||||
|
"success_criteria": ["…"],
|
||||||
|
"anti_patterns": ["…"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_stage_spec';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET template = $t$Du bist Assistent für Kampfsport-Trainer und extrahierst Start, Ziel und Ergänzungen für einen Progressionsgraphen.
|
||||||
|
|
||||||
|
Anfrage: {{goal_query}}
|
||||||
|
Semantic Brief: {{semantic_brief_json}}
|
||||||
|
Trainer-Notizen: {{user_notes}}
|
||||||
|
|
||||||
|
Katalog-Einordnung:
|
||||||
|
Primärfokus: {{focus_area_description}}
|
||||||
|
Trainingsstil: {{training_type_description}}
|
||||||
|
Zielgruppe: {{target_group_description}}
|
||||||
|
|
||||||
|
Antworte NUR mit JSON:
|
||||||
|
{
|
||||||
|
"primary_topic": "…",
|
||||||
|
"start_situation": "…",
|
||||||
|
"target_state": "…",
|
||||||
|
"roadmap_notes": "…",
|
||||||
|
"extraction_notes": "…"
|
||||||
|
}$t$,
|
||||||
|
default_template = template
|
||||||
|
WHERE slug = 'planning_progression_start_target';
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- Migration 094: bewusst ohne Daten-Seed (ersetzt frühere Voll-Befüllung)
|
||||||
|
--
|
||||||
|
-- Katalog-Stammdaten (Primärfokus, Trainingsstile, …) sind pro Umgebung unterschiedlich.
|
||||||
|
-- Migrationen dürfen keine Dev-Standardtexte an Prod-Kataloge hängen.
|
||||||
|
--
|
||||||
|
-- Slot-Inhalte stattdessen:
|
||||||
|
-- • Admin-UI (catalog_prompt_slots pro Eintrag)
|
||||||
|
-- • Laufzeit-Fallback catalog_slot_fallbacks.py (Namens-Match, kein DB-Schreiben)
|
||||||
|
-- • optional: backend/scripts/seed_catalog_prompt_slots_dev.py (nur lokale Dev-DB)
|
||||||
|
|
||||||
|
SELECT 1;
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Migration 095: Entfernt per 092/094 (alte Version) eingespielte Standard-Slot-Texte
|
||||||
|
--
|
||||||
|
-- Betrifft Dev-Umgebungen, die die frühen Seed-Migrationen bereits erhalten haben.
|
||||||
|
-- Prod mit eigener Katalogstruktur: Tabelle bleibt leer bis Admin-Inhalte gepflegt werden.
|
||||||
|
-- Manuell in der Admin-UI gesetzte Texte nach 095 bitte erneut prüfen (waren ggf. identisch mit Seeds).
|
||||||
|
|
||||||
|
DELETE FROM catalog_prompt_slots;
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
-- Login-Sperre, Sitzungszweck (Vollzugriff / 2FA-Einrichtung / 2FA-Challenge), TOTP.
|
||||||
|
|
||||||
|
ALTER TABLE profiles
|
||||||
|
ADD COLUMN IF NOT EXISTS failed_login_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN IF NOT EXISTS locked_until TIMESTAMP,
|
||||||
|
ADD COLUMN IF NOT EXISTS totp_secret TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS totp_pending_secret TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
|
||||||
|
ALTER TABLE sessions
|
||||||
|
ADD COLUMN IF NOT EXISTS purpose VARCHAR(32) NOT NULL DEFAULT 'full',
|
||||||
|
ADD COLUMN IF NOT EXISTS failed_attempts INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
UPDATE sessions
|
||||||
|
SET purpose = 'password_reset'
|
||||||
|
WHERE token LIKE 'reset_%' AND purpose = 'full';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sessions_profile_purpose ON sessions (profile_id, purpose);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS profile_recovery_codes (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
profile_id INTEGER NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||||
|
code_hash VARCHAR(64) NOT NULL,
|
||||||
|
used_at TIMESTAMP,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_profile_recovery_codes_profile
|
||||||
|
ON profile_recovery_codes (profile_id);
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- Migration 097: Plattform-Standard für das OpenRouter-Modell (Superadmin).
|
||||||
|
-- NULL = Umgebungsvariable OPENROUTER_MODEL.
|
||||||
|
-- Ein Prompt-Override in ai_prompts.openrouter_model hat weiter Vorrang.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS platform_ai_settings (
|
||||||
|
id SMALLINT PRIMARY KEY DEFAULT 1,
|
||||||
|
CONSTRAINT platform_ai_settings_singleton CHECK (id = 1),
|
||||||
|
openrouter_model VARCHAR(200),
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO platform_ai_settings (id, openrouter_model)
|
||||||
|
VALUES (1, NULL)
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN platform_ai_settings.openrouter_model IS
|
||||||
|
'Plattform-Standard OpenRouter model id; NULL = OPENROUTER_MODEL aus der Umgebung';
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
-- Migration 098: Aufgabengruppen für OpenRouter-Modelle.
|
||||||
|
-- Ein Prompt nutzt: eigenes openrouter_model, sonst das Modell seiner Gruppe,
|
||||||
|
-- sonst platform_ai_settings.openrouter_model, sonst OPENROUTER_MODEL.
|
||||||
|
-- model_role IS NULL wird nur beim ersten Setzen gefüllt, damit spätere
|
||||||
|
-- Umgruppierungen im Admin bei einem erneuten Lauf erhalten bleiben.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS platform_ai_model_roles (
|
||||||
|
role_key VARCHAR(40) PRIMARY KEY,
|
||||||
|
display_name VARCHAR(120) NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
openrouter_model VARCHAR(200),
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO platform_ai_model_roles (role_key, display_name, description, sort_order)
|
||||||
|
VALUES
|
||||||
|
(
|
||||||
|
'reasoning',
|
||||||
|
'Denken',
|
||||||
|
'Didaktische Entwürfe und Qualitätsurteile: Start und Ziel, Zielanalyse, Roadmap, Stufen und die Prüfung eines Übungspfads.',
|
||||||
|
10
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'drafting',
|
||||||
|
'Formulieren',
|
||||||
|
'Texte und eng gefasste Profile: Zusammenfassung, Anleitung, Suchabsicht, Semantik und Erwartungsprofil.',
|
||||||
|
20
|
||||||
|
),
|
||||||
|
(
|
||||||
|
'matching',
|
||||||
|
'Zuordnen',
|
||||||
|
'Auswahl aus einer vorgegebenen Menge: Fähigkeiten vorschlagen und Suchtreffer neu ordnen.',
|
||||||
|
30
|
||||||
|
)
|
||||||
|
ON CONFLICT (role_key) DO UPDATE
|
||||||
|
SET display_name = EXCLUDED.display_name,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
sort_order = EXCLUDED.sort_order;
|
||||||
|
|
||||||
|
ALTER TABLE ai_prompts ADD COLUMN IF NOT EXISTS model_role VARCHAR(40);
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_constraint WHERE conname = 'ai_prompts_model_role_fkey'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE ai_prompts
|
||||||
|
ADD CONSTRAINT ai_prompts_model_role_fkey
|
||||||
|
FOREIGN KEY (model_role) REFERENCES platform_ai_model_roles(role_key);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN ai_prompts.model_role IS
|
||||||
|
'Aufgabengruppe für das Standardmodell; NULL = Plattformstandard. openrouter_model am Prompt hat Vorrang.';
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET model_role = 'reasoning'
|
||||||
|
WHERE model_role IS NULL
|
||||||
|
AND slug IN (
|
||||||
|
'planning_progression_start_target',
|
||||||
|
'planning_progression_goal_analysis',
|
||||||
|
'planning_progression_roadmap',
|
||||||
|
'planning_progression_stage_spec',
|
||||||
|
'planning_exercise_path_qa'
|
||||||
|
);
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET model_role = 'drafting'
|
||||||
|
WHERE model_role IS NULL
|
||||||
|
AND slug IN (
|
||||||
|
'exercise_summary',
|
||||||
|
'exercise_instruction_rewrite',
|
||||||
|
'planning_exercise_search_intent',
|
||||||
|
'planning_exercise_query_semantics',
|
||||||
|
'planning_exercise_expectation_profile'
|
||||||
|
);
|
||||||
|
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET model_role = 'matching'
|
||||||
|
WHERE model_role IS NULL
|
||||||
|
AND slug IN (
|
||||||
|
'exercise_skill_suggestions',
|
||||||
|
'planning_exercise_search_rank'
|
||||||
|
);
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
-- Distribution v1: eingefrorene Übungspakete für Empfängerkanäle.
|
||||||
|
-- Produktiver Abruf bleibt über DISTRIBUTION_ENABLED aus, bis die Testinstanz ihn einschaltet.
|
||||||
|
|
||||||
|
ALTER TABLE exercises
|
||||||
|
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||||
|
|
||||||
|
UPDATE exercises SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||||
|
|
||||||
|
ALTER TABLE exercises
|
||||||
|
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||||
|
|
||||||
|
ALTER TABLE exercises
|
||||||
|
ALTER COLUMN public_id SET NOT NULL;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercises_public_id ON exercises (public_id);
|
||||||
|
|
||||||
|
ALTER TABLE exercise_variants
|
||||||
|
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||||
|
|
||||||
|
UPDATE exercise_variants SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||||
|
|
||||||
|
ALTER TABLE exercise_variants
|
||||||
|
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||||
|
|
||||||
|
ALTER TABLE exercise_variants
|
||||||
|
ALTER COLUMN public_id SET NOT NULL;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_variants_public_id ON exercise_variants (public_id);
|
||||||
|
|
||||||
|
ALTER TABLE exercise_media
|
||||||
|
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||||
|
|
||||||
|
UPDATE exercise_media SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||||
|
|
||||||
|
ALTER TABLE exercise_media
|
||||||
|
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||||
|
|
||||||
|
ALTER TABLE exercise_media
|
||||||
|
ALTER COLUMN public_id SET NOT NULL;
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_media_public_id ON exercise_media (public_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_publishers (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
kind TEXT NOT NULL CHECK (kind IN ('platform', 'own', 'club')),
|
||||||
|
club_id INT REFERENCES clubs (id),
|
||||||
|
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CONSTRAINT distribution_publishers_kind_club CHECK (
|
||||||
|
(kind = 'club' AND club_id IS NOT NULL)
|
||||||
|
OR (kind <> 'club' AND club_id IS NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_distribution_platform_publisher
|
||||||
|
ON distribution_publishers (kind)
|
||||||
|
WHERE kind = 'platform';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_recipients (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_relationships (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||||
|
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||||
|
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||||
|
UNIQUE (publisher_id, recipient_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_bindings (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_keys (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
binding_id UUID NOT NULL REFERENCES distribution_bindings (id),
|
||||||
|
key_prefix TEXT NOT NULL UNIQUE,
|
||||||
|
secret_hash TEXT NOT NULL,
|
||||||
|
expires_at TIMESTAMPTZ,
|
||||||
|
revoked_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_releasers (
|
||||||
|
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||||
|
profile_id INT NOT NULL REFERENCES profiles (id),
|
||||||
|
PRIMARY KEY (publisher_id, profile_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_publisher_exercises (
|
||||||
|
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||||
|
exercise_id INT NOT NULL REFERENCES exercises (id),
|
||||||
|
PRIMARY KEY (publisher_id, exercise_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_part_identities (
|
||||||
|
source_id UUID NOT NULL,
|
||||||
|
part_key TEXT NOT NULL,
|
||||||
|
part_id UUID NOT NULL,
|
||||||
|
PRIMARY KEY (source_id, part_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_source_revisions (
|
||||||
|
source_id UUID NOT NULL,
|
||||||
|
revision INT NOT NULL CHECK (revision > 0),
|
||||||
|
snapshot_hash TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (source_id, revision),
|
||||||
|
UNIQUE (source_id, snapshot_hash)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_drafts (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
exercise_id INT NOT NULL REFERENCES exercises (id),
|
||||||
|
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||||
|
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||||
|
prepared_by INT NOT NULL REFERENCES profiles (id),
|
||||||
|
cut JSONB NOT NULL,
|
||||||
|
preview_hash TEXT NOT NULL,
|
||||||
|
release_id UUID,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
confirmed_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_releases (
|
||||||
|
release_id UUID PRIMARY KEY,
|
||||||
|
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||||
|
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||||
|
source_id UUID NOT NULL,
|
||||||
|
revision INT NOT NULL,
|
||||||
|
cut_hash TEXT NOT NULL,
|
||||||
|
manifest_text TEXT NOT NULL,
|
||||||
|
manifest_sha256 TEXT NOT NULL,
|
||||||
|
published_at TIMESTAMPTZ NOT NULL,
|
||||||
|
fetch_blocked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
confirmed_by INT REFERENCES profiles (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_distribution_releases_source ON distribution_releases (source_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_distribution_releases_recipient ON distribution_releases (recipient_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_release_assets (
|
||||||
|
release_id UUID NOT NULL REFERENCES distribution_releases (release_id),
|
||||||
|
asset_id UUID NOT NULL,
|
||||||
|
sha256 TEXT NOT NULL,
|
||||||
|
size_bytes INT NOT NULL,
|
||||||
|
media_type TEXT NOT NULL,
|
||||||
|
storage_path TEXT NOT NULL,
|
||||||
|
source_media_public_id UUID,
|
||||||
|
source_asset_id INT,
|
||||||
|
PRIMARY KEY (release_id, asset_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_distribution_release_assets_source
|
||||||
|
ON distribution_release_assets (source_asset_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_events (
|
||||||
|
event_id UUID PRIMARY KEY,
|
||||||
|
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||||
|
seq BIGINT NOT NULL,
|
||||||
|
event_type TEXT NOT NULL,
|
||||||
|
release_id UUID NOT NULL,
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL,
|
||||||
|
body JSONB NOT NULL,
|
||||||
|
UNIQUE (recipient_id, seq)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_distribution_events_feed
|
||||||
|
ON distribution_events (recipient_id, seq);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_evidence (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||||
|
note TEXT NOT NULL,
|
||||||
|
created_by INT NOT NULL REFERENCES profiles (id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_rate_windows (
|
||||||
|
binding_id UUID PRIMARY KEY REFERENCES distribution_bindings (id),
|
||||||
|
window_start TIMESTAMPTZ NOT NULL,
|
||||||
|
hits INT NOT NULL
|
||||||
|
);
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- API-Schnittstelle je Verein und benannte Schlüssel mit Objekt- und Sichtbarkeitsrechten.
|
||||||
|
-- Bestehende Schlüssel behalten den Abruf von Übungen über alle Sichtbarkeiten, damit die Testschlüssel weiter gelten.
|
||||||
|
|
||||||
|
ALTER TABLE clubs
|
||||||
|
ADD COLUMN IF NOT EXISTS distribution_api_enabled BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS label TEXT;
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS objects TEXT[] NOT NULL DEFAULT ARRAY['exercise']::text[];
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS visibilities TEXT[] NOT NULL DEFAULT ARRAY['official', 'club', 'private']::text[];
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS context_kind TEXT NOT NULL DEFAULT 'platform';
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS context_club_id INT REFERENCES clubs (id);
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS context_profile_id INT REFERENCES profiles (id);
|
||||||
|
|
||||||
|
UPDATE distribution_keys SET label = key_prefix WHERE label IS NULL OR btrim(label) = '';
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Ein Schlüssel kann mehrere Vereine und Sichtbarkeiten tragen. Der Wert bleibt für den Inhaber kopierbar.
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS token_value TEXT;
|
||||||
|
|
||||||
|
ALTER TABLE distribution_keys
|
||||||
|
ADD COLUMN IF NOT EXISTS club_ids INT[] NOT NULL DEFAULT ARRAY[]::int[];
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- Auswahl, welche Übungen der aktuelle Abruf ausliefert. Frühere Lieferpakete schalten das nicht mit ein.
|
||||||
|
|
||||||
|
ALTER TABLE exercises
|
||||||
|
ADD COLUMN IF NOT EXISTS api_offered BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_exercises_api_offered
|
||||||
|
ON exercises (id)
|
||||||
|
WHERE api_offered = TRUE;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS distribution_catalog_snapshots (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
binding_id UUID NOT NULL REFERENCES distribution_bindings (id),
|
||||||
|
snapshot JSONB NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_distribution_catalog_snapshots_binding
|
||||||
|
ON distribution_catalog_snapshots (binding_id, created_at DESC);
|
||||||
+25
-3
@@ -13,16 +13,38 @@ from datetime import date, time, datetime
|
|||||||
|
|
||||||
class LoginRequest(BaseModel):
|
class LoginRequest(BaseModel):
|
||||||
email: EmailStr
|
email: EmailStr
|
||||||
password: str
|
password: str = Field(min_length=1, max_length=128)
|
||||||
|
|
||||||
|
|
||||||
|
class LoginTotpRequest(BaseModel):
|
||||||
|
challenge_token: str = Field(min_length=8, max_length=200)
|
||||||
|
code: str = Field(min_length=6, max_length=32)
|
||||||
|
|
||||||
|
|
||||||
|
class ChangePasswordRequest(BaseModel):
|
||||||
|
current_password: str = Field(min_length=1, max_length=128)
|
||||||
|
new_password: str = Field(min_length=8, max_length=128)
|
||||||
|
|
||||||
|
|
||||||
|
class TotpCodeRequest(BaseModel):
|
||||||
|
code: str = Field(min_length=6, max_length=12)
|
||||||
|
|
||||||
|
|
||||||
|
class TotpDisableRequest(BaseModel):
|
||||||
|
current_password: str = Field(min_length=1, max_length=128)
|
||||||
|
code: str = Field(min_length=6, max_length=32)
|
||||||
|
|
||||||
class RegisterRequest(BaseModel):
|
class RegisterRequest(BaseModel):
|
||||||
email: EmailStr
|
email: EmailStr
|
||||||
password: str
|
password: str = Field(min_length=1, max_length=128)
|
||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
requested_club_id: Optional[int] = Field(default=None, ge=1)
|
requested_club_id: Optional[int] = Field(default=None, ge=1)
|
||||||
|
|
||||||
class PasswordResetRequest(BaseModel):
|
class PasswordResetRequest(BaseModel):
|
||||||
email: str
|
email: EmailStr
|
||||||
|
|
||||||
|
class ResendVerificationRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
|
||||||
class PasswordResetConfirm(BaseModel):
|
class PasswordResetConfirm(BaseModel):
|
||||||
token: str
|
token: str
|
||||||
|
|||||||
+306
-13
@@ -1,12 +1,19 @@
|
|||||||
"""
|
"""
|
||||||
Minimal OpenRouter REST client (sync). Reads OPENROUTER_API_KEY / OPENROUTER_MODEL / OPENROUTER_BASE_URL from env.
|
Minimal OpenRouter REST client (sync).
|
||||||
|
|
||||||
|
API-Key und Basis-URL aus der Umgebung. Das wirksame Standardmodell kommt aus
|
||||||
|
platform_ai_settings (Superadmin), sonst aus OPENROUTER_MODEL.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from typing import Any, Dict, List, Mapping, Optional
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Tuple
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
@@ -196,29 +203,315 @@ def openrouter_chat_completion(
|
|||||||
cc,
|
cc,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from planning_llm_usage import record_planning_llm_call
|
||||||
|
|
||||||
|
record_planning_llm_call(1)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
return joined
|
return joined
|
||||||
|
|
||||||
|
|
||||||
|
_MODEL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:@+/-]{0,198}$")
|
||||||
|
_CATALOG_TTL_SEC = 600
|
||||||
|
_catalog_lock = threading.Lock()
|
||||||
|
_catalog_cache: Dict[str, Any] = {"fetched_at": 0.0, "fetched_at_iso": None, "models": None}
|
||||||
|
_settings_read_failed = False
|
||||||
|
|
||||||
|
_FALLBACK_MODEL = "anthropic/claude-sonnet-4"
|
||||||
|
|
||||||
|
|
||||||
|
def openrouter_base_url() -> str:
|
||||||
|
return (os.getenv("OPENROUTER_BASE_URL") or "").strip().rstrip("/") or "https://openrouter.ai/api/v1"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_openrouter_model_id(raw: Optional[str]) -> Optional[str]:
|
||||||
|
"""Leer wird None. Ungültige IDs werfen ValueError."""
|
||||||
|
if raw is None:
|
||||||
|
return None
|
||||||
|
text = str(raw).strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
if any(ch.isspace() for ch in text):
|
||||||
|
raise ValueError("OpenRouter-Modell-ID darf keine Leer- oder Steuerzeichen enthalten.")
|
||||||
|
if (
|
||||||
|
not _MODEL_ID_RE.match(text)
|
||||||
|
or "/" not in text
|
||||||
|
or text.startswith("/")
|
||||||
|
or text.endswith("/")
|
||||||
|
or "//" in text
|
||||||
|
):
|
||||||
|
raise ValueError("OpenRouter-Modell-ID muss wie anbieter/modell aussehen.")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def env_openrouter_model_id() -> str:
|
||||||
|
model = (os.getenv("OPENROUTER_MODEL") or _FALLBACK_MODEL).strip()
|
||||||
|
return model or _FALLBACK_MODEL
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_default_openrouter_model_id(
|
||||||
|
stored: Optional[str],
|
||||||
|
env_model: Optional[str] = None,
|
||||||
|
) -> Tuple[str, str]:
|
||||||
|
"""Wirksame ID und Quelle (`database` oder `environment`)."""
|
||||||
|
custom: Optional[str] = None
|
||||||
|
try:
|
||||||
|
custom = normalize_openrouter_model_id(stored)
|
||||||
|
except ValueError:
|
||||||
|
custom = None
|
||||||
|
if custom:
|
||||||
|
return custom, "database"
|
||||||
|
env = env_openrouter_model_id() if env_model is None else (str(env_model).strip() or _FALLBACK_MODEL)
|
||||||
|
return env or _FALLBACK_MODEL, "environment"
|
||||||
|
|
||||||
|
|
||||||
|
def read_stored_platform_openrouter_model() -> Optional[str]:
|
||||||
|
"""Gespeichertes Plattformmodell. Bei fehlender Tabelle oder DB-Fehler: None."""
|
||||||
|
global _settings_read_failed
|
||||||
|
try:
|
||||||
|
from db import get_cursor, get_db
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT openrouter_model FROM platform_ai_settings WHERE id = 1")
|
||||||
|
row = cur.fetchone()
|
||||||
|
_settings_read_failed = False
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
raw = row.get("openrouter_model") if isinstance(row, dict) else row[0]
|
||||||
|
text = str(raw or "").strip()
|
||||||
|
return text or None
|
||||||
|
except Exception as exc:
|
||||||
|
if not _settings_read_failed:
|
||||||
|
_logger.warning(
|
||||||
|
"Plattform-OpenRouter-Modell nicht lesbar, nutze OPENROUTER_MODEL: %s",
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
_settings_read_failed = True
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def normalize_openrouter_env() -> tuple[str, str]:
|
def normalize_openrouter_env() -> tuple[str, str]:
|
||||||
|
"""API-Key und Env-Modell. Das wirksame Modell liefert default_openrouter_model_id()."""
|
||||||
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
|
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
|
||||||
model = (os.getenv("OPENROUTER_MODEL") or "anthropic/claude-sonnet-4").strip()
|
return key, env_openrouter_model_id()
|
||||||
return key, model
|
|
||||||
|
|
||||||
|
|
||||||
def default_openrouter_model_id() -> str:
|
def default_openrouter_model_id() -> str:
|
||||||
"""Standard-Modell aus OPENROUTER_MODEL (ohne API-Key zu pruefen)."""
|
"""Plattform-Standard aus der Datenbank, sonst OPENROUTER_MODEL."""
|
||||||
_, model = normalize_openrouter_env()
|
effective, _source = resolve_default_openrouter_model_id(read_stored_platform_openrouter_model())
|
||||||
return model
|
return effective
|
||||||
|
|
||||||
|
|
||||||
|
def read_platform_role_models() -> Dict[str, str]:
|
||||||
|
"""Gespeicherte Gruppenmodelle. Fehlende Tabelle oder DB-Fehler: leeres Dict."""
|
||||||
|
try:
|
||||||
|
from db import get_cursor, get_db
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT role_key, openrouter_model FROM platform_ai_model_roles"
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
except Exception as exc:
|
||||||
|
_logger.warning("Aufgabengruppen-Modelle nicht lesbar: %s", exc)
|
||||||
|
return {}
|
||||||
|
out: Dict[str, str] = {}
|
||||||
|
for row in rows or []:
|
||||||
|
key = str((row.get("role_key") if isinstance(row, dict) else row[0]) or "").strip()
|
||||||
|
raw = row.get("openrouter_model") if isinstance(row, dict) else row[1]
|
||||||
|
text = str(raw or "").strip()
|
||||||
|
if key and text:
|
||||||
|
out[key] = text
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]]) -> str:
|
def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]]) -> str:
|
||||||
"""
|
"""
|
||||||
Pro-Prompt-Override in ai_prompts.openrouter_model, sonst Env-Default.
|
Prompt-Ausnahme, sonst Aufgabengruppe, sonst Plattform-Standard, sonst Umgebung.
|
||||||
|
|
||||||
`row` kann eine partial Row aus load_ai_prompt_row sein (Felder slug, openrouter_model, …).
|
`row` kann eine partial Row aus load_ai_prompt_row sein
|
||||||
|
(Felder slug, openrouter_model, model_role, …).
|
||||||
"""
|
"""
|
||||||
|
from ai_model_roles import resolve_prompt_openrouter_model
|
||||||
|
|
||||||
|
prompt_model = None
|
||||||
|
role_key = ""
|
||||||
if row:
|
if row:
|
||||||
custom = str(row.get("openrouter_model") or "").strip()
|
prompt_model = row.get("openrouter_model")
|
||||||
if custom:
|
role_key = str(row.get("model_role") or "").strip()
|
||||||
return custom
|
role_model = read_platform_role_models().get(role_key) if role_key else None
|
||||||
return default_openrouter_model_id()
|
effective, _source = resolve_prompt_openrouter_model(
|
||||||
|
prompt_model=None if prompt_model is None else str(prompt_model),
|
||||||
|
role_model=role_model,
|
||||||
|
platform_model=read_stored_platform_openrouter_model(),
|
||||||
|
env_model=env_openrouter_model_id(),
|
||||||
|
)
|
||||||
|
return effective
|
||||||
|
|
||||||
|
|
||||||
|
def _price_str(pricing: Any, key: str) -> Optional[str]:
|
||||||
|
if not isinstance(pricing, dict):
|
||||||
|
return None
|
||||||
|
raw = pricing.get(key)
|
||||||
|
if raw is None or raw == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
float(str(raw))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
return str(raw)
|
||||||
|
|
||||||
|
|
||||||
|
def _modalities(item: Mapping[str, Any], side: str) -> List[str]:
|
||||||
|
arch = item.get("architecture") if isinstance(item.get("architecture"), dict) else {}
|
||||||
|
key = "input_modalities" if side == "input" else "output_modalities"
|
||||||
|
raw = arch.get(key)
|
||||||
|
if isinstance(raw, list):
|
||||||
|
out = [str(x).strip().lower() for x in raw if str(x).strip()]
|
||||||
|
if out:
|
||||||
|
return out
|
||||||
|
modality = str(arch.get("modality") or "")
|
||||||
|
parts = modality.split("->")
|
||||||
|
chunk = parts[0] if side == "input" else (parts[1] if len(parts) > 1 else "")
|
||||||
|
return [p.strip().lower() for p in chunk.split("+") if p.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def _context_length(item: Mapping[str, Any]) -> Optional[int]:
|
||||||
|
candidates = [item.get("context_length")]
|
||||||
|
top = item.get("top_provider")
|
||||||
|
if isinstance(top, dict):
|
||||||
|
candidates.append(top.get("context_length"))
|
||||||
|
for raw in candidates:
|
||||||
|
try:
|
||||||
|
value = int(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if value > 0:
|
||||||
|
return value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_openrouter_models_payload(data: Any) -> List[Dict[str, Any]]:
|
||||||
|
"""OpenRouter `/models` auf eine schlanke, stabile Liste bringen."""
|
||||||
|
rows = data.get("data") if isinstance(data, dict) else None
|
||||||
|
if not isinstance(rows, list):
|
||||||
|
raise OpenRouterError("OpenRouter: Modellliste ohne data-Array")
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
seen = set()
|
||||||
|
for item in rows:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
model_id = str(item.get("id") or "").strip()
|
||||||
|
if not model_id or model_id in seen:
|
||||||
|
continue
|
||||||
|
seen.add(model_id)
|
||||||
|
provider = model_id.split("/", 1)[0]
|
||||||
|
description = str(item.get("description") or "").replace("\r", " ").replace("\n", " ").strip()
|
||||||
|
if len(description) > 400:
|
||||||
|
description = description[:397].rstrip() + "…"
|
||||||
|
prompt_price = _price_str(item.get("pricing"), "prompt")
|
||||||
|
completion_price = _price_str(item.get("pricing"), "completion")
|
||||||
|
try:
|
||||||
|
prompt_num = float(prompt_price) if prompt_price is not None else None
|
||||||
|
completion_num = float(completion_price) if completion_price is not None else None
|
||||||
|
except ValueError:
|
||||||
|
prompt_num = None
|
||||||
|
completion_num = None
|
||||||
|
is_free = model_id.endswith(":free") or (
|
||||||
|
prompt_num == 0 and completion_num == 0 and (prompt_num is not None or completion_num is not None)
|
||||||
|
)
|
||||||
|
out.append(
|
||||||
|
{
|
||||||
|
"id": model_id,
|
||||||
|
"name": str(item.get("name") or model_id).strip() or model_id,
|
||||||
|
"description": description,
|
||||||
|
"context_length": _context_length(item),
|
||||||
|
"prompt_usd_per_token": prompt_price,
|
||||||
|
"completion_usd_per_token": completion_price,
|
||||||
|
"input_modalities": _modalities(item, "input"),
|
||||||
|
"output_modalities": _modalities(item, "output"),
|
||||||
|
"provider": provider,
|
||||||
|
"is_free": bool(is_free),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
out.sort(key=lambda row: (row["name"].lower(), row["id"].lower()))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def clear_openrouter_model_catalog_cache() -> None:
|
||||||
|
with _catalog_lock:
|
||||||
|
_catalog_cache["fetched_at"] = 0.0
|
||||||
|
_catalog_cache["fetched_at_iso"] = None
|
||||||
|
_catalog_cache["models"] = None
|
||||||
|
|
||||||
|
|
||||||
|
def _download_openrouter_models() -> List[Dict[str, Any]]:
|
||||||
|
url = f"{openrouter_base_url()}/models"
|
||||||
|
headers: Dict[str, str] = {"Accept": "application/json"}
|
||||||
|
key = (os.getenv("OPENROUTER_API_KEY") or "").strip()
|
||||||
|
if key:
|
||||||
|
headers["Authorization"] = f"Bearer {key}"
|
||||||
|
referer = (os.getenv("APP_URL") or "").strip()
|
||||||
|
if referer:
|
||||||
|
headers["HTTP-Referer"] = referer
|
||||||
|
title = (os.getenv("OPENROUTER_APP_TITLE") or "Shinkan Jinkendo").strip()
|
||||||
|
if title:
|
||||||
|
headers["X-Title"] = title
|
||||||
|
try:
|
||||||
|
with httpx.Client(timeout=25.0) as client:
|
||||||
|
resp = client.get(url, headers=headers)
|
||||||
|
except httpx.RequestError as exc:
|
||||||
|
raise OpenRouterError("Verbindung zu OpenRouter fehlgeschlagen") from exc
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
raise OpenRouterError(f"OpenRouter antwortet mit HTTP {resp.status_code}")
|
||||||
|
try:
|
||||||
|
payload = resp.json()
|
||||||
|
except json.JSONDecodeError as exc:
|
||||||
|
raise OpenRouterError("OpenRouter hat kein gültiges JSON geliefert") from exc
|
||||||
|
return parse_openrouter_models_payload(payload)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_openrouter_model_catalog(*, force: bool = False) -> Dict[str, Any]:
|
||||||
|
"""Modellkatalog, zehn Minuten im Prozess zwischengespeichert."""
|
||||||
|
now = time.monotonic()
|
||||||
|
with _catalog_lock:
|
||||||
|
cached = _catalog_cache.get("models")
|
||||||
|
age = now - float(_catalog_cache.get("fetched_at") or 0)
|
||||||
|
if isinstance(cached, list) and not force and age < _CATALOG_TTL_SEC:
|
||||||
|
return {
|
||||||
|
"models": cached,
|
||||||
|
"count": len(cached),
|
||||||
|
"cached": True,
|
||||||
|
"stale": False,
|
||||||
|
"fetched_at": _catalog_cache.get("fetched_at_iso"),
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
models = _download_openrouter_models()
|
||||||
|
except OpenRouterError:
|
||||||
|
with _catalog_lock:
|
||||||
|
cached = _catalog_cache.get("models")
|
||||||
|
if isinstance(cached, list):
|
||||||
|
return {
|
||||||
|
"models": cached,
|
||||||
|
"count": len(cached),
|
||||||
|
"cached": True,
|
||||||
|
"stale": True,
|
||||||
|
"fetched_at": _catalog_cache.get("fetched_at_iso"),
|
||||||
|
}
|
||||||
|
raise
|
||||||
|
fetched_iso = datetime.now(timezone.utc).isoformat()
|
||||||
|
with _catalog_lock:
|
||||||
|
_catalog_cache["models"] = models
|
||||||
|
_catalog_cache["fetched_at"] = time.monotonic()
|
||||||
|
_catalog_cache["fetched_at_iso"] = fetched_iso
|
||||||
|
return {
|
||||||
|
"models": models,
|
||||||
|
"count": len(models),
|
||||||
|
"cached": False,
|
||||||
|
"stale": False,
|
||||||
|
"fetched_at": fetched_iso,
|
||||||
|
}
|
||||||
@@ -33,8 +33,8 @@ def insert_password_reset_session(cur: Any, profile_id: int, *, hours_valid: int
|
|||||||
expires = datetime.now() + timedelta(hours=hours_valid)
|
expires = datetime.now() + timedelta(hours=hours_valid)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO sessions (token, profile_id, expires_at, created_at)
|
INSERT INTO sessions (token, profile_id, expires_at, created_at, purpose)
|
||||||
VALUES (%s, %s, %s, CURRENT_TIMESTAMP)
|
VALUES (%s, %s, %s, CURRENT_TIMESTAMP, 'password_reset')
|
||||||
""",
|
""",
|
||||||
(f"{RESET_TOKEN_PREFIX}{raw}", profile_id, expires.isoformat()),
|
(f"{RESET_TOKEN_PREFIX}{raw}", profile_id, expires.isoformat()),
|
||||||
)
|
)
|
||||||
@@ -53,6 +53,7 @@ Neues Passwort setzen:
|
|||||||
|
|
||||||
Der Link ist 1 Stunde gültig. Erst wenn du ihn nutzt und ein neues Passwort wählst, wird dein bestehendes
|
Der Link ist 1 Stunde gültig. Erst wenn du ihn nutzt und ein neues Passwort wählst, wird dein bestehendes
|
||||||
Passwort ersetzt — bis dahin kannst du dich wie gewohnt anmelden.
|
Passwort ersetzt — bis dahin kannst du dich wie gewohnt anmelden.
|
||||||
|
Der Link meldet dich nicht an und schaltet die Zwei-Faktor-Anmeldung nicht ab.
|
||||||
|
|
||||||
Falls du diese Anfrage nicht erwartest, ignoriere diese E-Mail; dein Zugang bleibt unverändert.
|
Falls du diese Anfrage nicht erwartest, ignoriere diese E-Mail; dein Zugang bleibt unverändert.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""
|
||||||
|
Katalog-Kontext für Progressionsgraph-Planung — Fokusbereich, Stil, Trainingsstil, Zielgruppe.
|
||||||
|
|
||||||
|
Explizite Trainer-Auswahl ergänzt Freitext/LLM; ersetzt kein Roadmap-Didaktik-Modell.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from planning_exercise_profiles import PlanningTargetProfile, _normalize_weight_map
|
||||||
|
from planning_exercise_target_pipeline import (
|
||||||
|
SCENARIO_FREE_SEARCH,
|
||||||
|
merge_query_overlay_into_target,
|
||||||
|
)
|
||||||
|
from planning_exercise_text_signals import resolve_planning_text_to_catalog_weights
|
||||||
|
|
||||||
|
|
||||||
|
class PlanningCatalogContextItem(BaseModel):
|
||||||
|
id: int = Field(..., ge=1)
|
||||||
|
is_primary: bool = False
|
||||||
|
weight: float = Field(default=1.0, ge=0.1, le=1.0)
|
||||||
|
|
||||||
|
|
||||||
|
class ProgressionPlanningCatalogContext(BaseModel):
|
||||||
|
focus_areas: List[PlanningCatalogContextItem] = Field(default_factory=list)
|
||||||
|
style_directions: List[PlanningCatalogContextItem] = Field(default_factory=list)
|
||||||
|
training_types: List[PlanningCatalogContextItem] = Field(default_factory=list)
|
||||||
|
target_groups: List[PlanningCatalogContextItem] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_context_has_items(catalog: Optional[ProgressionPlanningCatalogContext]) -> bool:
|
||||||
|
if catalog is None:
|
||||||
|
return False
|
||||||
|
return bool(
|
||||||
|
catalog.focus_areas
|
||||||
|
or catalog.style_directions
|
||||||
|
or catalog.training_types
|
||||||
|
or catalog.target_groups
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_items_to_weight_map(
|
||||||
|
items: Sequence[PlanningCatalogContextItem],
|
||||||
|
*,
|
||||||
|
primary_weight: float = 0.95,
|
||||||
|
secondary_weight: float = 0.78,
|
||||||
|
) -> Dict[int, float]:
|
||||||
|
out: Dict[int, float] = {}
|
||||||
|
for item in items or []:
|
||||||
|
base = primary_weight if item.is_primary else secondary_weight
|
||||||
|
w = base * float(item.weight)
|
||||||
|
iid = int(item.id)
|
||||||
|
out[iid] = max(out.get(iid, 0.0), w)
|
||||||
|
return _normalize_weight_map(out) if out else out
|
||||||
|
|
||||||
|
|
||||||
|
def merge_catalog_context_into_target(
|
||||||
|
target: PlanningTargetProfile,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext],
|
||||||
|
*,
|
||||||
|
emphasis: str = "replace",
|
||||||
|
) -> PlanningTargetProfile:
|
||||||
|
"""Trainer-Katalog-Kontext ins Erwartungsprofil — beeinflusst Retrieval-Scoring."""
|
||||||
|
if not catalog_context_has_items(catalog):
|
||||||
|
return target
|
||||||
|
|
||||||
|
focus = catalog_items_to_weight_map(catalog.focus_areas)
|
||||||
|
style = catalog_items_to_weight_map(catalog.style_directions, primary_weight=0.9, secondary_weight=0.72)
|
||||||
|
tt = catalog_items_to_weight_map(catalog.training_types, primary_weight=0.9, secondary_weight=0.72)
|
||||||
|
tg = catalog_items_to_weight_map(catalog.target_groups, primary_weight=0.88, secondary_weight=0.7)
|
||||||
|
|
||||||
|
merged = merge_query_overlay_into_target(
|
||||||
|
target,
|
||||||
|
focus=focus,
|
||||||
|
style=style,
|
||||||
|
tt=tt,
|
||||||
|
tg=tg,
|
||||||
|
skills={},
|
||||||
|
emphasis=emphasis,
|
||||||
|
scenario=SCENARIO_FREE_SEARCH,
|
||||||
|
)
|
||||||
|
sources = list(merged.sources or [])
|
||||||
|
if "catalog_context" not in sources:
|
||||||
|
sources.append("catalog_context")
|
||||||
|
merged.sources = sources
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
|
def enrich_target_from_planning_text_blobs(
|
||||||
|
cur,
|
||||||
|
target: PlanningTargetProfile,
|
||||||
|
*text_blobs: Optional[str],
|
||||||
|
) -> PlanningTargetProfile:
|
||||||
|
"""Additive Katalog-Signale aus Freitext (Anfrage, Start/Ziel, Notizen)."""
|
||||||
|
combined = " ".join(str(t or "").strip() for t in text_blobs if (t or "").strip())
|
||||||
|
if len(combined) < 4:
|
||||||
|
return target
|
||||||
|
focus, style, tt, tg, skills = resolve_planning_text_to_catalog_weights(cur, combined)
|
||||||
|
if not (focus or style or tt or tg or skills):
|
||||||
|
return target
|
||||||
|
merged = merge_query_overlay_into_target(
|
||||||
|
target,
|
||||||
|
focus=focus,
|
||||||
|
style=style,
|
||||||
|
tt=tt,
|
||||||
|
tg=tg,
|
||||||
|
skills=skills,
|
||||||
|
emphasis="additive",
|
||||||
|
scenario=SCENARIO_FREE_SEARCH,
|
||||||
|
)
|
||||||
|
sources = list(merged.sources or [])
|
||||||
|
if "text_catalog_signals" not in sources:
|
||||||
|
sources.append("text_catalog_signals")
|
||||||
|
merged.sources = sources
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_context_from_mapping(raw: Any) -> Optional[ProgressionPlanningCatalogContext]:
|
||||||
|
if not raw or not isinstance(raw, Mapping):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
ctx = ProgressionPlanningCatalogContext.model_validate(dict(raw))
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
return ctx if catalog_context_has_items(ctx) else None
|
||||||
|
|
||||||
|
|
||||||
|
def load_catalog_context_from_graph_row(
|
||||||
|
planning_roadmap: Any,
|
||||||
|
) -> Optional[ProgressionPlanningCatalogContext]:
|
||||||
|
if not isinstance(planning_roadmap, dict):
|
||||||
|
return None
|
||||||
|
return catalog_context_from_mapping(planning_roadmap.get("planning_catalog_context"))
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"PlanningCatalogContextItem",
|
||||||
|
"ProgressionPlanningCatalogContext",
|
||||||
|
"catalog_context_from_mapping",
|
||||||
|
"catalog_context_has_items",
|
||||||
|
"catalog_items_to_weight_map",
|
||||||
|
"enrich_target_from_planning_text_blobs",
|
||||||
|
"load_catalog_context_from_graph_row",
|
||||||
|
"merge_catalog_context_into_target",
|
||||||
|
]
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""
|
||||||
|
Katalog-Prompt-Snippets — Abwärtskompatibilität (H1-Importpfade).
|
||||||
|
|
||||||
|
Implementierung: catalog_prompt_slots.py (H2).
|
||||||
|
"""
|
||||||
|
from catalog_prompt_slots import (
|
||||||
|
build_catalog_guidance_for_prompt,
|
||||||
|
get_rematch_guard_for_catalog,
|
||||||
|
pick_active_catalog_item,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"build_catalog_guidance_for_prompt",
|
||||||
|
"get_rematch_guard_for_catalog",
|
||||||
|
"pick_active_catalog_item",
|
||||||
|
]
|
||||||
@@ -6,7 +6,7 @@ Wird als ``planning_context_json`` in Übungs-Prompts (summary, skills, instruct
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from typing import Any, Dict, List, Mapping, Optional
|
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
||||||
|
|
||||||
_MAX_JSON_CHARS = 6000
|
_MAX_JSON_CHARS = 6000
|
||||||
_MAX_STRING = 800
|
_MAX_STRING = 800
|
||||||
@@ -85,6 +85,163 @@ def planning_context_prompt_variables(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _major_index_from_step(step: Mapping[str, Any]) -> Optional[int]:
|
||||||
|
for key in ("roadmap_major_step_index", "major_step_index"):
|
||||||
|
raw = step.get(key)
|
||||||
|
if raw is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
return int(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def prior_path_steps_before_major(
|
||||||
|
steps: Sequence[Mapping[str, Any]],
|
||||||
|
major_idx: int,
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Pfadschritte mit kleinerem roadmap_major_step_index, sortiert."""
|
||||||
|
prior: List[Dict[str, Any]] = []
|
||||||
|
for step in steps:
|
||||||
|
mi = _major_index_from_step(step)
|
||||||
|
if mi is not None and mi < major_idx:
|
||||||
|
prior.append(dict(step))
|
||||||
|
prior.sort(key=lambda s: _major_index_from_step(s) or 0)
|
||||||
|
return prior
|
||||||
|
|
||||||
|
|
||||||
|
def _step_display_fields(step: Mapping[str, Any]) -> Dict[str, Any]:
|
||||||
|
title = _trim_str(
|
||||||
|
step.get("title") or step.get("exercise_title"),
|
||||||
|
limit=200,
|
||||||
|
)
|
||||||
|
learning_goal = _trim_str(
|
||||||
|
step.get("roadmap_learning_goal") or step.get("learning_goal"),
|
||||||
|
limit=500,
|
||||||
|
)
|
||||||
|
summary = _trim_str(step.get("summary"), limit=400)
|
||||||
|
start_state = _trim_str(step.get("roadmap_start_state") or step.get("start_state"))
|
||||||
|
target_state = _trim_str(step.get("roadmap_target_state") or step.get("target_state"))
|
||||||
|
phase = _trim_str(step.get("roadmap_phase") or step.get("phase"))
|
||||||
|
criteria_raw = step.get("stage_success_criteria") or step.get("success_criteria") or []
|
||||||
|
criteria = [
|
||||||
|
t
|
||||||
|
for x in criteria_raw
|
||||||
|
if (t := _trim_str(x, limit=200))
|
||||||
|
][:4]
|
||||||
|
out: Dict[str, Any] = {
|
||||||
|
"title": title,
|
||||||
|
"learning_goal": learning_goal,
|
||||||
|
"summary": summary,
|
||||||
|
"start_state": start_state,
|
||||||
|
"target_state": target_state,
|
||||||
|
"phase": phase,
|
||||||
|
"success_criteria": criteria or None,
|
||||||
|
"major_step_index": _major_index_from_step(step),
|
||||||
|
}
|
||||||
|
return {k: v for k, v in out.items() if v is not None and v != "" and v != []}
|
||||||
|
|
||||||
|
|
||||||
|
def build_progression_entry_state(
|
||||||
|
*,
|
||||||
|
major_step_index: Optional[int] = None,
|
||||||
|
prior_steps: Sequence[Mapping[str, Any]] = (),
|
||||||
|
start_situation: Optional[str] = None,
|
||||||
|
current_stage_start: Optional[str] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Eingangszustand für eine Roadmap-Stufe: erreichte Voraussetzungen aus Vorstufen.
|
||||||
|
"""
|
||||||
|
prior_compact = [_step_display_fields(s) for s in prior_steps]
|
||||||
|
prior_compact = [
|
||||||
|
p
|
||||||
|
for p in prior_compact
|
||||||
|
if any(p.get(k) for k in ("title", "learning_goal", "summary", "success_criteria"))
|
||||||
|
]
|
||||||
|
|
||||||
|
achievements: List[str] = []
|
||||||
|
detail_lines: List[str] = []
|
||||||
|
for p in prior_compact:
|
||||||
|
if p.get("success_criteria"):
|
||||||
|
achievements.extend(p["success_criteria"])
|
||||||
|
elif p.get("learning_goal"):
|
||||||
|
achievements.append(p["learning_goal"])
|
||||||
|
|
||||||
|
label_parts: List[str] = []
|
||||||
|
if p.get("major_step_index") is not None:
|
||||||
|
label_parts.append(f"Stufe {int(p['major_step_index']) + 1}")
|
||||||
|
if p.get("phase"):
|
||||||
|
label_parts.append(f"({p['phase']})")
|
||||||
|
if p.get("title"):
|
||||||
|
label_parts.append(f"„{p['title']}\"")
|
||||||
|
prefix = " ".join(label_parts) if label_parts else "Vorstufe"
|
||||||
|
achieved = ""
|
||||||
|
if p.get("target_state"):
|
||||||
|
achieved = p["target_state"]
|
||||||
|
elif p.get("success_criteria"):
|
||||||
|
achieved = "; ".join(p["success_criteria"])
|
||||||
|
elif p.get("learning_goal"):
|
||||||
|
achieved = p["learning_goal"]
|
||||||
|
elif p.get("summary"):
|
||||||
|
achieved = p["summary"]
|
||||||
|
if achieved:
|
||||||
|
detail_lines.append(f"{prefix}: erreicht — {achieved}")
|
||||||
|
|
||||||
|
immediate_entry: Optional[str] = _trim_str(current_stage_start)
|
||||||
|
if not immediate_entry and prior_compact:
|
||||||
|
immediate = prior_compact[-1]
|
||||||
|
if immediate.get("target_state"):
|
||||||
|
immediate_entry = immediate["target_state"]
|
||||||
|
elif immediate.get("success_criteria"):
|
||||||
|
immediate_entry = "; ".join(immediate["success_criteria"])
|
||||||
|
elif immediate.get("learning_goal"):
|
||||||
|
immediate_entry = immediate["learning_goal"]
|
||||||
|
elif immediate.get("summary"):
|
||||||
|
immediate_entry = immediate["summary"]
|
||||||
|
elif not immediate_entry and start_situation:
|
||||||
|
immediate_entry = start_situation
|
||||||
|
|
||||||
|
entry_state = immediate_entry or start_situation
|
||||||
|
if prior_compact and start_situation and not immediate_entry:
|
||||||
|
detail_lines.insert(0, f"Ausgangsbasis Pfad: {start_situation}")
|
||||||
|
|
||||||
|
out: Dict[str, Any] = {}
|
||||||
|
if entry_state:
|
||||||
|
out["entry_state"] = _trim_str(entry_state, limit=1200)
|
||||||
|
if detail_lines:
|
||||||
|
out["entry_state_detail"] = _trim_str("\n".join(detail_lines), limit=2000)
|
||||||
|
if prior_compact:
|
||||||
|
out["prior_steps"] = prior_compact[:6]
|
||||||
|
if achievements:
|
||||||
|
out["prior_achievements"] = list(dict.fromkeys(achievements))[:8]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def enrich_gap_snapshot_with_entry_state(
|
||||||
|
snapshot: Mapping[str, Any],
|
||||||
|
*,
|
||||||
|
steps: Sequence[Mapping[str, Any]],
|
||||||
|
major_step_index: Optional[int],
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
snap = dict(snapshot)
|
||||||
|
if major_step_index is None:
|
||||||
|
return snap
|
||||||
|
try:
|
||||||
|
mi = int(major_step_index)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return snap
|
||||||
|
prior = prior_path_steps_before_major(steps, mi)
|
||||||
|
entry = build_progression_entry_state(
|
||||||
|
major_step_index=mi,
|
||||||
|
prior_steps=prior,
|
||||||
|
start_situation=snap.get("start_situation"),
|
||||||
|
current_stage_start=snap.get("stage_start_state"),
|
||||||
|
)
|
||||||
|
snap.update(entry)
|
||||||
|
return snap
|
||||||
|
|
||||||
|
|
||||||
def build_progression_gap_snapshot(
|
def build_progression_gap_snapshot(
|
||||||
*,
|
*,
|
||||||
goal_analysis: Optional[Mapping[str, Any]] = None,
|
goal_analysis: Optional[Mapping[str, Any]] = None,
|
||||||
@@ -141,6 +298,8 @@ def build_progression_gap_snapshot(
|
|||||||
"stage_learning_goal": _trim_str(
|
"stage_learning_goal": _trim_str(
|
||||||
spec.get("learning_goal"), limit=1200
|
spec.get("learning_goal"), limit=1200
|
||||||
),
|
),
|
||||||
|
"stage_start_state": _trim_str(spec.get("start_state")),
|
||||||
|
"stage_target_state": _trim_str(spec.get("target_state")),
|
||||||
"stage_phase": _trim_str(spec.get("phase")),
|
"stage_phase": _trim_str(spec.get("phase")),
|
||||||
"stage_exercise_type": _trim_str(spec.get("exercise_type")),
|
"stage_exercise_type": _trim_str(spec.get("exercise_type")),
|
||||||
"stage_load_profile": load_profile or None,
|
"stage_load_profile": load_profile or None,
|
||||||
@@ -160,6 +319,7 @@ def build_progression_path_gap_planning_context(
|
|||||||
offer: Optional[Mapping[str, Any]] = None,
|
offer: Optional[Mapping[str, Any]] = None,
|
||||||
neighbor_before: Optional[Mapping[str, Any]] = None,
|
neighbor_before: Optional[Mapping[str, Any]] = None,
|
||||||
neighbor_after: Optional[Mapping[str, Any]] = None,
|
neighbor_after: Optional[Mapping[str, Any]] = None,
|
||||||
|
prior_path_steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
path_step_count: int = 0,
|
path_step_count: int = 0,
|
||||||
major_step_count: Optional[int] = None,
|
major_step_count: Optional[int] = None,
|
||||||
roadmap_phase: Optional[str] = None,
|
roadmap_phase: Optional[str] = None,
|
||||||
@@ -168,6 +328,8 @@ def build_progression_path_gap_planning_context(
|
|||||||
resolved_structured: Optional[Mapping[str, Any]] = None,
|
resolved_structured: Optional[Mapping[str, Any]] = None,
|
||||||
stage_spec: Optional[Mapping[str, Any]] = None,
|
stage_spec: Optional[Mapping[str, Any]] = None,
|
||||||
semantic_brief: Optional[Mapping[str, Any]] = None,
|
semantic_brief: Optional[Mapping[str, Any]] = None,
|
||||||
|
stage_learning_goal_override: Optional[str] = None,
|
||||||
|
gap_trainer_supplements: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Kontext für KI-Neuanlage aus Progressionsgraph-Pfad-Lücke."""
|
"""Kontext für KI-Neuanlage aus Progressionsgraph-Pfad-Lücke."""
|
||||||
offer = offer or {}
|
offer = offer or {}
|
||||||
@@ -205,12 +367,28 @@ def build_progression_path_gap_planning_context(
|
|||||||
semantic_brief=semantic_brief,
|
semantic_brief=semantic_brief,
|
||||||
)
|
)
|
||||||
ctx.update(snap)
|
ctx.update(snap)
|
||||||
|
if major_idx is not None and prior_path_steps:
|
||||||
|
ctx.update(
|
||||||
|
build_progression_entry_state(
|
||||||
|
major_step_index=major_idx,
|
||||||
|
prior_steps=list(prior_path_steps),
|
||||||
|
start_situation=ctx.get("start_situation"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if stage_learning_goal_override and stage_learning_goal_override.strip():
|
||||||
|
ctx["stage_learning_goal"] = _trim_str(stage_learning_goal_override, limit=1200)
|
||||||
|
ctx["roadmap_learning_goal"] = ctx["stage_learning_goal"]
|
||||||
|
if gap_trainer_supplements and gap_trainer_supplements.strip():
|
||||||
|
ctx["gap_trainer_supplements"] = _trim_str(gap_trainer_supplements, limit=2000)
|
||||||
return sanitize_planning_context_for_ai(ctx)
|
return sanitize_planning_context_for_ai(ctx)
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
"build_progression_entry_state",
|
||||||
"build_progression_gap_snapshot",
|
"build_progression_gap_snapshot",
|
||||||
"build_progression_path_gap_planning_context",
|
"build_progression_path_gap_planning_context",
|
||||||
|
"enrich_gap_snapshot_with_entry_state",
|
||||||
|
"prior_path_steps_before_major",
|
||||||
"compact_planning_context_json",
|
"compact_planning_context_json",
|
||||||
"planning_context_prompt_variables",
|
"planning_context_prompt_variables",
|
||||||
"sanitize_planning_context_for_ai",
|
"sanitize_planning_context_for_ai",
|
||||||
|
|||||||
@@ -12,12 +12,184 @@ from ai_prompt_job import run_exercise_form_ai_suggestion
|
|||||||
from exercise_ai import strip_html_to_plain
|
from exercise_ai import strip_html_to_plain
|
||||||
|
|
||||||
from planning_exercise_path_qa import find_step_pair_index
|
from planning_exercise_path_qa import find_step_pair_index
|
||||||
from planning_exercise_form_context import build_progression_gap_snapshot
|
from planning_exercise_form_context import (
|
||||||
|
build_progression_entry_state,
|
||||||
|
build_progression_gap_snapshot,
|
||||||
|
enrich_gap_snapshot_with_entry_state,
|
||||||
|
prior_path_steps_before_major,
|
||||||
|
)
|
||||||
from planning_exercise_semantics import PlanningSemanticBrief, brief_to_summary_dict
|
from planning_exercise_semantics import PlanningSemanticBrief, brief_to_summary_dict
|
||||||
|
from planning_catalog_context import ProgressionPlanningCatalogContext
|
||||||
|
from planning_prompt_variables import catalog_exercise_hints_block
|
||||||
|
|
||||||
_logger = logging.getLogger("shinkan.planning_exercise_path_ai_fill")
|
_logger = logging.getLogger("shinkan.planning_exercise_path_ai_fill")
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_neighbor_steps_by_major_index(
|
||||||
|
steps: Sequence[Mapping[str, Any]],
|
||||||
|
major_idx: int,
|
||||||
|
) -> Tuple[Optional[Mapping[str, Any]], Optional[Mapping[str, Any]]]:
|
||||||
|
"""Nachbarn im Pfad anhand roadmap_major_step_index (nicht Array-Position)."""
|
||||||
|
step_before: Optional[Mapping[str, Any]] = None
|
||||||
|
step_after: Optional[Mapping[str, Any]] = None
|
||||||
|
for step in steps:
|
||||||
|
raw = step.get("roadmap_major_step_index")
|
||||||
|
if raw is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
mi = int(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if mi < major_idx:
|
||||||
|
step_before = step
|
||||||
|
elif mi > major_idx and step_after is None:
|
||||||
|
step_after = step
|
||||||
|
return step_before, step_after
|
||||||
|
|
||||||
|
|
||||||
|
def _build_stage_ai_context(
|
||||||
|
*,
|
||||||
|
goal_query: str,
|
||||||
|
brief: PlanningSemanticBrief,
|
||||||
|
spec: Mapping[str, Any],
|
||||||
|
step_before: Optional[Mapping[str, Any]] = None,
|
||||||
|
step_after: Optional[Mapping[str, Any]] = None,
|
||||||
|
prior_steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
start_situation: Optional[str] = None,
|
||||||
|
catalog_exercise_hints: Optional[str] = None,
|
||||||
|
) -> ExerciseFormAiPromptContext:
|
||||||
|
"""KI-Kontext für unbesetzte Roadmap-Stufe (keine Brücke zwischen falschen Array-Indizes)."""
|
||||||
|
gap = dict(spec.get("gap") or {})
|
||||||
|
phase = spec.get("phase") or gap.get("expected_phase") or "vertiefung"
|
||||||
|
topic = (brief.primary_topic or "Technik").strip()
|
||||||
|
learning_goal = (
|
||||||
|
gap.get("learning_goal")
|
||||||
|
or spec.get("title_hint")
|
||||||
|
or spec.get("sketch")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
title = (spec.get("title_hint") or f"{topic} — {phase}").strip()[:280]
|
||||||
|
major_idx = spec.get("roadmap_major_step_index")
|
||||||
|
entry: Dict[str, Any] = {}
|
||||||
|
if prior_steps is not None and major_idx is not None:
|
||||||
|
entry = build_progression_entry_state(
|
||||||
|
major_step_index=major_idx,
|
||||||
|
prior_steps=prior_steps,
|
||||||
|
start_situation=start_situation,
|
||||||
|
)
|
||||||
|
|
||||||
|
goal_parts = [
|
||||||
|
f"Planungsziel: {goal_query}",
|
||||||
|
f"Roadmap-Stufe ({phase}): {learning_goal}",
|
||||||
|
"Erstelle eine Übung, die dieses Stufen-Lernziel erfüllt — keine generische Brücken-Übung.",
|
||||||
|
]
|
||||||
|
if entry.get("entry_state"):
|
||||||
|
goal_parts.append(
|
||||||
|
f"Eingangszustand (erreichte Voraussetzungen): {entry['entry_state']}"
|
||||||
|
)
|
||||||
|
if entry.get("entry_state_detail") and entry.get("entry_state_detail") != entry.get("entry_state"):
|
||||||
|
goal_parts.append(f"Bisheriger Pfad:\n{entry['entry_state_detail']}")
|
||||||
|
if step_before:
|
||||||
|
goal_parts.append(
|
||||||
|
f"Vorherige Stufe im Pfad: „{(step_before.get('title') or '').strip()}“"
|
||||||
|
)
|
||||||
|
if step_after:
|
||||||
|
goal_parts.append(
|
||||||
|
f"Nächste Stufe im Pfad: „{(step_after.get('title') or '').strip()}“"
|
||||||
|
)
|
||||||
|
sketch = (spec.get("sketch") or "").strip()
|
||||||
|
if sketch and sketch != learning_goal:
|
||||||
|
goal_parts.extend(["", f"Kontext: {sketch}"])
|
||||||
|
hints = (catalog_exercise_hints or "").strip()
|
||||||
|
if hints:
|
||||||
|
goal_parts.extend(["", "Katalog-Hinweise Übungsanlage:", hints])
|
||||||
|
goal = "\n".join(goal_parts)
|
||||||
|
|
||||||
|
focus_hint = topic if brief.topic_type == "technique" else None
|
||||||
|
if brief.must_phrases:
|
||||||
|
focus_hint = ", ".join(brief.must_phrases[:2])
|
||||||
|
|
||||||
|
return ExerciseFormAiPromptContext(
|
||||||
|
title=title[:280],
|
||||||
|
goal=goal[:8000],
|
||||||
|
execution=None,
|
||||||
|
focus_hint=focus_hint,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def try_suggest_ai_stage_step(
|
||||||
|
cur,
|
||||||
|
*,
|
||||||
|
goal_query: str,
|
||||||
|
brief: PlanningSemanticBrief,
|
||||||
|
spec: Mapping[str, Any],
|
||||||
|
steps: Sequence[Mapping[str, Any]],
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
|
) -> Optional[Dict[str, Any]]:
|
||||||
|
"""KI-Vorschlag für leere Roadmap-Stufe."""
|
||||||
|
major_idx = spec.get("roadmap_major_step_index")
|
||||||
|
if major_idx is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
mi = int(major_idx)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
step_before, step_after = _resolve_neighbor_steps_by_major_index(steps, mi)
|
||||||
|
prior_steps = prior_path_steps_before_major(steps, mi)
|
||||||
|
gap = dict(spec.get("gap") or {})
|
||||||
|
if not gap.get("expected_phase"):
|
||||||
|
gap["expected_phase"] = spec.get("phase") or "vertiefung"
|
||||||
|
gap["roadmap_major_step_index"] = mi
|
||||||
|
if not gap.get("learning_goal"):
|
||||||
|
gap["learning_goal"] = spec.get("title_hint") or spec.get("sketch")
|
||||||
|
|
||||||
|
exercise_hints = catalog_exercise_hints_block(cur, catalog) if catalog else ""
|
||||||
|
|
||||||
|
ctx = _build_stage_ai_context(
|
||||||
|
goal_query=goal_query,
|
||||||
|
brief=brief,
|
||||||
|
spec=spec,
|
||||||
|
step_before=step_before,
|
||||||
|
step_after=step_after,
|
||||||
|
prior_steps=prior_steps,
|
||||||
|
catalog_exercise_hints=exercise_hints or None,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
ai_payload = run_exercise_form_ai_suggestion(cur, ctx=ctx)
|
||||||
|
except Exception:
|
||||||
|
_logger.exception("roadmap_unfilled AI suggest failed")
|
||||||
|
return None
|
||||||
|
if not ai_payload:
|
||||||
|
return None
|
||||||
|
|
||||||
|
summary_text = ""
|
||||||
|
summary_obj = ai_payload.get("summary")
|
||||||
|
if isinstance(summary_obj, dict):
|
||||||
|
summary_text = str(summary_obj.get("text") or "").strip()
|
||||||
|
elif isinstance(summary_obj, str):
|
||||||
|
summary_text = summary_obj.strip()
|
||||||
|
|
||||||
|
proposal_key = f"ai-{uuid.uuid4().hex[:10]}"
|
||||||
|
title = (ctx.title or spec.get("title_hint") or "KI-Vorschlag").strip()
|
||||||
|
return {
|
||||||
|
"exercise_id": None,
|
||||||
|
"proposal_key": proposal_key,
|
||||||
|
"variant_id": None,
|
||||||
|
"title": title,
|
||||||
|
"summary": summary_text or None,
|
||||||
|
"score": None,
|
||||||
|
"semantic_score": None,
|
||||||
|
"reasons": ["KI-Neuanlage für Roadmap-Stufe ohne Bibliothekstreffer"],
|
||||||
|
"variants": [],
|
||||||
|
"is_bridge": False,
|
||||||
|
"is_ai_proposal": True,
|
||||||
|
"ai_suggestion": dict(ai_payload),
|
||||||
|
"roadmap_major_step_index": mi,
|
||||||
|
"roadmap_phase": gap.get("expected_phase"),
|
||||||
|
"roadmap_learning_goal": gap.get("learning_goal"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def _build_gap_ai_context(
|
def _build_gap_ai_context(
|
||||||
*,
|
*,
|
||||||
goal_query: str,
|
goal_query: str,
|
||||||
@@ -27,6 +199,7 @@ def _build_gap_ai_context(
|
|||||||
gap: Mapping[str, Any],
|
gap: Mapping[str, Any],
|
||||||
title_hint: Optional[str] = None,
|
title_hint: Optional[str] = None,
|
||||||
sketch_hint: Optional[str] = None,
|
sketch_hint: Optional[str] = None,
|
||||||
|
catalog_exercise_hints: Optional[str] = None,
|
||||||
) -> ExerciseFormAiPromptContext:
|
) -> ExerciseFormAiPromptContext:
|
||||||
topic = (brief.primary_topic or "Technik").strip()
|
topic = (brief.primary_topic or "Technik").strip()
|
||||||
phase = gap.get("expected_phase") or "vertiefung"
|
phase = gap.get("expected_phase") or "vertiefung"
|
||||||
@@ -44,6 +217,9 @@ def _build_gap_ai_context(
|
|||||||
]
|
]
|
||||||
if sketch:
|
if sketch:
|
||||||
goal_parts.extend(["", f"Hinweis: {sketch}"])
|
goal_parts.extend(["", f"Hinweis: {sketch}"])
|
||||||
|
hints = (catalog_exercise_hints or "").strip()
|
||||||
|
if hints:
|
||||||
|
goal_parts.extend(["", "Katalog-Hinweise Übungsanlage:", hints])
|
||||||
goal = "\n".join(goal_parts)
|
goal = "\n".join(goal_parts)
|
||||||
|
|
||||||
focus_hint = topic if brief.topic_type == "technique" else None
|
focus_hint = topic if brief.topic_type == "technique" else None
|
||||||
@@ -109,8 +285,10 @@ def try_suggest_ai_bridge_step(
|
|||||||
gap: Mapping[str, Any],
|
gap: Mapping[str, Any],
|
||||||
title_hint: Optional[str] = None,
|
title_hint: Optional[str] = None,
|
||||||
sketch_hint: Optional[str] = None,
|
sketch_hint: Optional[str] = None,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Optional[Dict[str, Any]]:
|
) -> Optional[Dict[str, Any]]:
|
||||||
"""Ruft exercise AI suggest auf — kein Speichern in DB."""
|
"""Ruft exercise AI suggest auf — kein Speichern in DB."""
|
||||||
|
exercise_hints = catalog_exercise_hints_block(cur, catalog) if catalog else ""
|
||||||
ctx = _build_gap_ai_context(
|
ctx = _build_gap_ai_context(
|
||||||
goal_query=goal_query,
|
goal_query=goal_query,
|
||||||
brief=brief,
|
brief=brief,
|
||||||
@@ -119,6 +297,7 @@ def try_suggest_ai_bridge_step(
|
|||||||
gap=gap,
|
gap=gap,
|
||||||
title_hint=title_hint,
|
title_hint=title_hint,
|
||||||
sketch_hint=sketch_hint,
|
sketch_hint=sketch_hint,
|
||||||
|
catalog_exercise_hints=exercise_hints or None,
|
||||||
)
|
)
|
||||||
g_plain = strip_html_to_plain(ctx.goal)
|
g_plain = strip_html_to_plain(ctx.goal)
|
||||||
if not g_plain.strip() and not (ctx.title or "").strip():
|
if not g_plain.strip() and not (ctx.title or "").strip():
|
||||||
@@ -175,6 +354,18 @@ def _spec_dedupe_key(spec: Mapping[str, Any]) -> Tuple[Any, ...]:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _step_neighbors_at_index(
|
||||||
|
steps: Sequence[Mapping[str, Any]],
|
||||||
|
idx: int,
|
||||||
|
) -> Tuple[Optional[Mapping[str, Any]], Optional[Mapping[str, Any]]]:
|
||||||
|
"""Vorheriger/nächster Pfadschritt ohne IndexError (Rand-Slots, leere Stufen)."""
|
||||||
|
if idx < 0 or idx >= len(steps):
|
||||||
|
return None, None
|
||||||
|
step_a = steps[idx - 1] if idx > 0 else None
|
||||||
|
step_b = steps[idx + 1] if idx + 1 < len(steps) else None
|
||||||
|
return step_a, step_b
|
||||||
|
|
||||||
|
|
||||||
def collect_gap_fill_specs(
|
def collect_gap_fill_specs(
|
||||||
*,
|
*,
|
||||||
steps: Sequence[Mapping[str, Any]],
|
steps: Sequence[Mapping[str, Any]],
|
||||||
@@ -202,8 +393,10 @@ def collect_gap_fill_specs(
|
|||||||
int(gap["from_exercise_id"]),
|
int(gap["from_exercise_id"]),
|
||||||
int(gap["to_exercise_id"]),
|
int(gap["to_exercise_id"]),
|
||||||
)
|
)
|
||||||
if idx is None:
|
if idx is None or idx + 1 >= len(steps):
|
||||||
continue
|
continue
|
||||||
|
step_a = steps[idx]
|
||||||
|
step_b = steps[idx + 1]
|
||||||
phase = gap.get("expected_phase") or "vertiefung"
|
phase = gap.get("expected_phase") or "vertiefung"
|
||||||
add(
|
add(
|
||||||
{
|
{
|
||||||
@@ -215,41 +408,76 @@ def collect_gap_fill_specs(
|
|||||||
"sketch": _default_sketch(
|
"sketch": _default_sketch(
|
||||||
goal_query=goal_query,
|
goal_query=goal_query,
|
||||||
brief=brief,
|
brief=brief,
|
||||||
step_a=steps[idx],
|
step_a=step_a,
|
||||||
step_b=steps[idx + 1],
|
step_b=step_b,
|
||||||
phase=str(phase),
|
phase=str(phase),
|
||||||
rationale="Bibliothek enthält keine passende Brücke.",
|
rationale="Bibliothek enthält keine passende Brücke.",
|
||||||
),
|
),
|
||||||
"rationale": "Lücke zwischen benachbarten Schritten — keine passende Bibliotheks-Übung.",
|
"rationale": "Lücke zwischen benachbaren Schritten — keine passende Bibliotheks-Übung.",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
for ot in off_topic_steps:
|
for ot in off_topic_steps:
|
||||||
|
major_idx = ot.get("roadmap_major_step_index")
|
||||||
|
idx: Optional[int] = None
|
||||||
|
if major_idx is not None:
|
||||||
|
try:
|
||||||
|
mi = int(major_idx)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
mi = None
|
||||||
|
if mi is not None:
|
||||||
|
idx = next(
|
||||||
|
(
|
||||||
|
i
|
||||||
|
for i, s in enumerate(steps)
|
||||||
|
if s.get("roadmap_major_step_index") is not None
|
||||||
|
and int(s["roadmap_major_step_index"]) == mi
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if idx is None:
|
||||||
idx = int(ot.get("step_index") or 0)
|
idx = int(ot.get("step_index") or 0)
|
||||||
if idx <= 0 or idx >= len(steps) - 1:
|
if idx < 0 or idx >= len(steps):
|
||||||
continue
|
continue
|
||||||
|
step_a, step_b = _step_neighbors_at_index(steps, idx)
|
||||||
phase = ot.get("expected_phase") or "vertiefung"
|
phase = ot.get("expected_phase") or "vertiefung"
|
||||||
|
insert_after = max(idx - 1, -1)
|
||||||
|
stage_goal = str(ot.get("roadmap_learning_goal") or "").strip()
|
||||||
|
if str(ot.get("issue") or "") == "stage_mismatch" and stage_goal:
|
||||||
|
title_hint = stage_goal[:120]
|
||||||
|
rationale = (
|
||||||
|
f"Keine passende Bibliotheks-Übung für Stufen-Lernziel „{stage_goal[:100]}“."
|
||||||
|
)
|
||||||
|
sketch_rationale = (
|
||||||
|
f"Slot braucht Übung passend zu: {stage_goal[:200]}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
title_hint = f"{topic} — {phase} (Ersatz für themenfremden Schritt)"
|
||||||
|
rationale = f"Schritt „{ot.get('title')}“ passt nicht zum Pfad-Thema."
|
||||||
|
sketch_rationale = f"Ersetzt themenfremden Schritt „{ot.get('title')}“."
|
||||||
add(
|
add(
|
||||||
{
|
{
|
||||||
"source": "off_topic",
|
"source": "off_topic" if ot.get("issue") != "stage_mismatch" else "stage_mismatch",
|
||||||
"insert_after_index": idx - 1,
|
"insert_after_index": insert_after,
|
||||||
"replace_step_index": idx,
|
"replace_step_index": idx,
|
||||||
|
"roadmap_major_step_index": major_idx,
|
||||||
"gap": {
|
"gap": {
|
||||||
"expected_phase": phase,
|
"expected_phase": phase,
|
||||||
"off_topic_title": ot.get("title"),
|
"off_topic_title": ot.get("title"),
|
||||||
"off_topic_exercise_id": ot.get("exercise_id"),
|
"off_topic_exercise_id": ot.get("exercise_id"),
|
||||||
|
"roadmap_learning_goal": stage_goal or None,
|
||||||
},
|
},
|
||||||
"phase": phase,
|
"phase": phase,
|
||||||
"title_hint": f"{topic} — {phase} (Ersatz für themenfremden Schritt)",
|
"title_hint": title_hint,
|
||||||
"sketch": _default_sketch(
|
"sketch": _default_sketch(
|
||||||
goal_query=goal_query,
|
goal_query=goal_query,
|
||||||
brief=brief,
|
brief=brief,
|
||||||
step_a=steps[idx - 1],
|
step_a=step_a,
|
||||||
step_b=steps[idx + 1],
|
step_b=step_b,
|
||||||
phase=str(phase),
|
phase=str(phase),
|
||||||
rationale=f"Ersetzt themenfremden Schritt „{ot.get('title')}“.",
|
rationale=sketch_rationale,
|
||||||
),
|
),
|
||||||
"rationale": f"Schritt „{ot.get('title')}“ passt nicht zum Pfad-Thema.",
|
"rationale": rationale,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -267,6 +495,7 @@ def build_gap_fill_goal_text(
|
|||||||
step_a: Optional[Mapping[str, Any]] = None,
|
step_a: Optional[Mapping[str, Any]] = None,
|
||||||
step_b: Optional[Mapping[str, Any]] = None,
|
step_b: Optional[Mapping[str, Any]] = None,
|
||||||
roadmap_snapshot: Optional[Mapping[str, Any]] = None,
|
roadmap_snapshot: Optional[Mapping[str, Any]] = None,
|
||||||
|
catalog_exercise_hints: Optional[str] = None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Ausführlicher Zieltext für KI-Neuanlage aus Pfad-, Roadmap- und Stufen-Kontext."""
|
"""Ausführlicher Zieltext für KI-Neuanlage aus Pfad-, Roadmap- und Stufen-Kontext."""
|
||||||
topic = (brief.primary_topic or "Technik").strip()
|
topic = (brief.primary_topic or "Technik").strip()
|
||||||
@@ -282,8 +511,16 @@ def build_gap_fill_goal_text(
|
|||||||
f"Planungsziel (gesamter Pfad): {goal_query}",
|
f"Planungsziel (gesamter Pfad): {goal_query}",
|
||||||
f"Hauptthema: {snap.get('primary_topic') or topic}",
|
f"Hauptthema: {snap.get('primary_topic') or topic}",
|
||||||
]
|
]
|
||||||
if snap.get("start_situation"):
|
if snap.get("entry_state"):
|
||||||
|
parts.append(
|
||||||
|
f"Eingangszustand (erreichte Voraussetzungen aus Vorstufen): {snap['entry_state']}"
|
||||||
|
)
|
||||||
|
if snap.get("entry_state_detail") and snap.get("entry_state_detail") != snap.get("entry_state"):
|
||||||
|
parts.append(f"Bisheriger Pfad:\n{snap['entry_state_detail']}")
|
||||||
|
if snap.get("start_situation") and not snap.get("entry_state"):
|
||||||
parts.append(f"Voraussetzung / Ausgangslage (Progression): {snap['start_situation']}")
|
parts.append(f"Voraussetzung / Ausgangslage (Progression): {snap['start_situation']}")
|
||||||
|
elif snap.get("start_situation") and snap.get("prior_steps"):
|
||||||
|
parts.append(f"Ausgangsbasis des gesamten Pfads: {snap['start_situation']}")
|
||||||
if snap.get("target_state"):
|
if snap.get("target_state"):
|
||||||
parts.append(f"Gesamtziel der Progression: {snap['target_state']}")
|
parts.append(f"Gesamtziel der Progression: {snap['target_state']}")
|
||||||
if snap.get("roadmap_notes"):
|
if snap.get("roadmap_notes"):
|
||||||
@@ -291,12 +528,19 @@ def build_gap_fill_goal_text(
|
|||||||
stage_goal = snap.get("stage_learning_goal") or spec.get("title_hint")
|
stage_goal = snap.get("stage_learning_goal") or spec.get("title_hint")
|
||||||
if stage_goal:
|
if stage_goal:
|
||||||
parts.append(f"Lernziel dieser Roadmap-Stufe: {stage_goal}")
|
parts.append(f"Lernziel dieser Roadmap-Stufe: {stage_goal}")
|
||||||
parts.extend(
|
parts.append(f"Entwicklungsphase dieser Übung: {snap.get('stage_phase') or phase}")
|
||||||
[
|
parts.append(f"Erwarteter Entwicklungsbogen: {arc}")
|
||||||
f"Entwicklungsphase dieser Übung: {snap.get('stage_phase') or phase}",
|
if spec.get("source") == "roadmap_unfilled":
|
||||||
f"Erwarteter Entwicklungsbogen: {arc}",
|
parts.append(
|
||||||
f"Einordnung: didaktische Zwischenstufe zwischen „{from_title}“ und „{to_title}“.",
|
"Einordnung: Übung für diese Roadmap-Stufe — das Stufen-Lernziel steht im Vordergrund."
|
||||||
]
|
)
|
||||||
|
if step_a:
|
||||||
|
parts.append(f"Vorherige Stufe: „{from_title}“")
|
||||||
|
if step_b:
|
||||||
|
parts.append(f"Nächste Stufe: „{to_title}“")
|
||||||
|
else:
|
||||||
|
parts.append(
|
||||||
|
f"Einordnung: didaktische Zwischenstufe zwischen „{from_title}“ und „{to_title}“."
|
||||||
)
|
)
|
||||||
if snap.get("stage_load_profile"):
|
if snap.get("stage_load_profile"):
|
||||||
parts.append(f"Belastungsschwerpunkte: {', '.join(snap['stage_load_profile'])}")
|
parts.append(f"Belastungsschwerpunkte: {', '.join(snap['stage_load_profile'])}")
|
||||||
@@ -314,10 +558,24 @@ def build_gap_fill_goal_text(
|
|||||||
"Fähigkeiten-/Fokus-Hinweise: "
|
"Fähigkeiten-/Fokus-Hinweise: "
|
||||||
+ "; ".join(str(x) for x in snap["skill_hints"][:4])
|
+ "; ".join(str(x) for x in snap["skill_hints"][:4])
|
||||||
)
|
)
|
||||||
|
expected = snap.get("expected_skills") or []
|
||||||
|
if expected:
|
||||||
|
names = [
|
||||||
|
str(s.get("skill_name") or "").strip()
|
||||||
|
for s in expected[:5]
|
||||||
|
if str(s.get("skill_name") or "").strip()
|
||||||
|
]
|
||||||
|
if names:
|
||||||
|
parts.append(
|
||||||
|
"Erwartete Fähigkeiten (Scoring): " + ", ".join(names)
|
||||||
|
)
|
||||||
if spec.get("rationale"):
|
if spec.get("rationale"):
|
||||||
parts.append(f"Qualitätsprüfung: {spec['rationale']}")
|
parts.append(f"Qualitätsprüfung: {spec['rationale']}")
|
||||||
if spec.get("sketch"):
|
if spec.get("sketch"):
|
||||||
parts.append(f"Skizze: {spec['sketch']}")
|
parts.append(f"Skizze: {spec['sketch']}")
|
||||||
|
hints = (catalog_exercise_hints or "").strip()
|
||||||
|
if hints:
|
||||||
|
parts.append(f"Katalog-Hinweise Übungsanlage:\n{hints}")
|
||||||
parts.append(
|
parts.append(
|
||||||
"Die Übung muss die Stufe didaktisch erfüllen: klare Voraussetzungen, messbares Stufenziel, "
|
"Die Übung muss die Stufe didaktisch erfüllen: klare Voraussetzungen, messbares Stufenziel, "
|
||||||
"Bezug zum Gesamtpfad — keine generische Kraftübung ohne Technikbezug. "
|
"Bezug zum Gesamtpfad — keine generische Kraftübung ohne Technikbezug. "
|
||||||
@@ -334,11 +592,30 @@ def build_gap_fill_offer(
|
|||||||
brief: Optional[PlanningSemanticBrief] = None,
|
brief: Optional[PlanningSemanticBrief] = None,
|
||||||
proposal: Optional[Mapping[str, Any]] = None,
|
proposal: Optional[Mapping[str, Any]] = None,
|
||||||
roadmap_snapshot: Optional[Mapping[str, Any]] = None,
|
roadmap_snapshot: Optional[Mapping[str, Any]] = None,
|
||||||
|
catalog_exercise_hints: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
|
source = spec.get("source")
|
||||||
idx = int(spec.get("insert_after_index") or 0)
|
idx = int(spec.get("insert_after_index") or 0)
|
||||||
offer_id = f"{spec.get('source')}-{idx}-{uuid.uuid4().hex[:8]}"
|
major_idx = spec.get("roadmap_major_step_index")
|
||||||
|
if source == "roadmap_unfilled" and major_idx is not None:
|
||||||
|
try:
|
||||||
|
mi = int(major_idx)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
mi = idx
|
||||||
|
step_a, step_b = _resolve_neighbor_steps_by_major_index(steps, mi)
|
||||||
|
idx = mi
|
||||||
|
else:
|
||||||
step_a = steps[idx] if idx < len(steps) else None
|
step_a = steps[idx] if idx < len(steps) else None
|
||||||
step_b = steps[idx + 1] if idx + 1 < len(steps) else None
|
step_b = steps[idx + 1] if idx + 1 < len(steps) else None
|
||||||
|
offer_id = f"{spec.get('source')}-{idx}-{uuid.uuid4().hex[:8]}"
|
||||||
|
enriched_snapshot = dict(roadmap_snapshot) if roadmap_snapshot else {}
|
||||||
|
major_raw = spec.get("roadmap_major_step_index")
|
||||||
|
if major_raw is not None:
|
||||||
|
enriched_snapshot = enrich_gap_snapshot_with_entry_state(
|
||||||
|
enriched_snapshot,
|
||||||
|
steps=steps,
|
||||||
|
major_step_index=major_raw,
|
||||||
|
)
|
||||||
goal_for_ai = ""
|
goal_for_ai = ""
|
||||||
if brief and goal_query:
|
if brief and goal_query:
|
||||||
goal_for_ai = build_gap_fill_goal_text(
|
goal_for_ai = build_gap_fill_goal_text(
|
||||||
@@ -347,9 +624,10 @@ def build_gap_fill_offer(
|
|||||||
spec=spec,
|
spec=spec,
|
||||||
step_a=step_a,
|
step_a=step_a,
|
||||||
step_b=step_b,
|
step_b=step_b,
|
||||||
roadmap_snapshot=roadmap_snapshot,
|
roadmap_snapshot=enriched_snapshot or None,
|
||||||
|
catalog_exercise_hints=catalog_exercise_hints,
|
||||||
)
|
)
|
||||||
ctx_preview = dict(roadmap_snapshot) if roadmap_snapshot else None
|
ctx_preview = enriched_snapshot or None
|
||||||
offer: Dict[str, Any] = {
|
offer: Dict[str, Any] = {
|
||||||
"offer_id": offer_id,
|
"offer_id": offer_id,
|
||||||
"source": spec.get("source"),
|
"source": spec.get("source"),
|
||||||
@@ -387,6 +665,7 @@ def apply_gap_fill_after_qa(
|
|||||||
max_ai_proposals: int = 3,
|
max_ai_proposals: int = 3,
|
||||||
auto_insert_proposals: bool = False,
|
auto_insert_proposals: bool = False,
|
||||||
roadmap_snapshot: Optional[Mapping[str, Any]] = None,
|
roadmap_snapshot: Optional[Mapping[str, Any]] = None,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
|
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]:
|
||||||
"""
|
"""
|
||||||
Erzeugt gap_fill_offers für die UI; optional KI-Vorschläge einfügen.
|
Erzeugt gap_fill_offers für die UI; optional KI-Vorschläge einfügen.
|
||||||
@@ -398,8 +677,43 @@ def apply_gap_fill_after_qa(
|
|||||||
out = list(steps)
|
out = list(steps)
|
||||||
proposals: List[Dict[str, Any]] = []
|
proposals: List[Dict[str, Any]] = []
|
||||||
offers: List[Dict[str, Any]] = []
|
offers: List[Dict[str, Any]] = []
|
||||||
|
exercise_hints = catalog_exercise_hints_block(cur, catalog) if catalog else ""
|
||||||
|
|
||||||
for spec in specs:
|
for spec in specs:
|
||||||
|
source = spec.get("source")
|
||||||
|
|
||||||
|
if source == "roadmap_unfilled":
|
||||||
|
proposal: Optional[Dict[str, Any]] = None
|
||||||
|
if include_ai_calls and len(proposals) < max_ai_proposals:
|
||||||
|
proposal = try_suggest_ai_stage_step(
|
||||||
|
cur,
|
||||||
|
goal_query=goal_query,
|
||||||
|
brief=brief,
|
||||||
|
spec=spec,
|
||||||
|
steps=out,
|
||||||
|
catalog=catalog,
|
||||||
|
)
|
||||||
|
offer = build_gap_fill_offer(
|
||||||
|
spec=spec,
|
||||||
|
steps=out,
|
||||||
|
goal_query=goal_query,
|
||||||
|
brief=brief,
|
||||||
|
proposal=proposal,
|
||||||
|
roadmap_snapshot=roadmap_snapshot,
|
||||||
|
catalog_exercise_hints=exercise_hints or None,
|
||||||
|
)
|
||||||
|
offers.append(offer)
|
||||||
|
if proposal and auto_insert_proposals:
|
||||||
|
proposals.append(
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": spec.get("roadmap_major_step_index"),
|
||||||
|
"proposal_key": proposal.get("proposal_key"),
|
||||||
|
"proposal_title": proposal.get("title"),
|
||||||
|
"offer_id": offer.get("offer_id"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
idx = int(spec.get("insert_after_index") or 0)
|
idx = int(spec.get("insert_after_index") or 0)
|
||||||
if idx < 0 or idx >= len(out) - 1:
|
if idx < 0 or idx >= len(out) - 1:
|
||||||
continue
|
continue
|
||||||
@@ -413,6 +727,7 @@ def apply_gap_fill_after_qa(
|
|||||||
brief=brief,
|
brief=brief,
|
||||||
proposal=None,
|
proposal=None,
|
||||||
roadmap_snapshot=roadmap_snapshot,
|
roadmap_snapshot=roadmap_snapshot,
|
||||||
|
catalog_exercise_hints=exercise_hints or None,
|
||||||
)
|
)
|
||||||
offers.append(offer)
|
offers.append(offer)
|
||||||
continue
|
continue
|
||||||
@@ -421,7 +736,7 @@ def apply_gap_fill_after_qa(
|
|||||||
if not gap.get("expected_phase"):
|
if not gap.get("expected_phase"):
|
||||||
gap["expected_phase"] = spec.get("phase") or "vertiefung"
|
gap["expected_phase"] = spec.get("phase") or "vertiefung"
|
||||||
|
|
||||||
proposal: Optional[Dict[str, Any]] = None
|
proposal = None
|
||||||
if include_ai_calls and len(proposals) < max_ai_proposals:
|
if include_ai_calls and len(proposals) < max_ai_proposals:
|
||||||
proposal = try_suggest_ai_bridge_step(
|
proposal = try_suggest_ai_bridge_step(
|
||||||
cur,
|
cur,
|
||||||
@@ -432,6 +747,7 @@ def apply_gap_fill_after_qa(
|
|||||||
gap=gap,
|
gap=gap,
|
||||||
title_hint=str(spec.get("title_hint") or ""),
|
title_hint=str(spec.get("title_hint") or ""),
|
||||||
sketch_hint=str(spec.get("sketch") or ""),
|
sketch_hint=str(spec.get("sketch") or ""),
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
|
|
||||||
offer = build_gap_fill_offer(
|
offer = build_gap_fill_offer(
|
||||||
@@ -441,6 +757,7 @@ def apply_gap_fill_after_qa(
|
|||||||
brief=brief,
|
brief=brief,
|
||||||
proposal=proposal,
|
proposal=proposal,
|
||||||
roadmap_snapshot=roadmap_snapshot,
|
roadmap_snapshot=roadmap_snapshot,
|
||||||
|
catalog_exercise_hints=exercise_hints or None,
|
||||||
)
|
)
|
||||||
offers.append(offer)
|
offers.append(offer)
|
||||||
|
|
||||||
@@ -497,4 +814,5 @@ __all__ = [
|
|||||||
"collect_gap_fill_specs",
|
"collect_gap_fill_specs",
|
||||||
"insert_ai_proposals_for_gaps",
|
"insert_ai_proposals_for_gaps",
|
||||||
"try_suggest_ai_bridge_step",
|
"try_suggest_ai_bridge_step",
|
||||||
|
"try_suggest_ai_stage_step",
|
||||||
]
|
]
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -9,6 +9,8 @@ import re
|
|||||||
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||||
|
|
||||||
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
|
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
|
||||||
|
from planning_catalog_context import ProgressionPlanningCatalogContext
|
||||||
|
from planning_prompt_variables import merge_planning_prompt_variables
|
||||||
from exercise_ai import strip_html_to_plain
|
from exercise_ai import strip_html_to_plain
|
||||||
from openrouter_chat import (
|
from openrouter_chat import (
|
||||||
effective_openrouter_model_for_prompt_row,
|
effective_openrouter_model_for_prompt_row,
|
||||||
@@ -18,10 +20,21 @@ from openrouter_chat import (
|
|||||||
|
|
||||||
from planning_exercise_semantics import (
|
from planning_exercise_semantics import (
|
||||||
PlanningSemanticBrief,
|
PlanningSemanticBrief,
|
||||||
|
_blob_from_fields,
|
||||||
|
_blob_matches_stage_excludes,
|
||||||
brief_to_summary_dict,
|
brief_to_summary_dict,
|
||||||
|
build_stage_match_brief,
|
||||||
exercise_passes_path_semantic_gate,
|
exercise_passes_path_semantic_gate,
|
||||||
|
exercise_passes_stage_learning_goal_gate,
|
||||||
|
exercise_passes_technique_path_scope,
|
||||||
|
merge_stage_exclude_phrases,
|
||||||
|
resolve_path_anti_patterns,
|
||||||
|
resolve_path_primary_topic,
|
||||||
score_exercise_semantic_relevance,
|
score_exercise_semantic_relevance,
|
||||||
|
score_exercise_stage_fit,
|
||||||
|
semantic_brief_for_stage,
|
||||||
step_phase_for_index,
|
step_phase_for_index,
|
||||||
|
technique_sibling_excludes,
|
||||||
)
|
)
|
||||||
|
|
||||||
_logger = logging.getLogger("shinkan.planning_exercise_path_qa")
|
_logger = logging.getLogger("shinkan.planning_exercise_path_qa")
|
||||||
@@ -174,6 +187,8 @@ def detect_path_gaps(
|
|||||||
for i in range(total_segments):
|
for i in range(total_segments):
|
||||||
step_a = steps[i]
|
step_a = steps[i]
|
||||||
step_b = steps[i + 1]
|
step_b = steps[i + 1]
|
||||||
|
if step_a.get("exercise_id") is None or step_b.get("exercise_id") is None:
|
||||||
|
continue
|
||||||
if roadmap_first and is_roadmap_planned_neighbor_pair(step_a, step_b):
|
if roadmap_first and is_roadmap_planned_neighbor_pair(step_a, step_b):
|
||||||
continue
|
continue
|
||||||
gap = measure_step_transition_gap(
|
gap = measure_step_transition_gap(
|
||||||
@@ -307,6 +322,7 @@ def try_llm_qa_progression_path(
|
|||||||
steps: Sequence[Mapping[str, Any]],
|
steps: Sequence[Mapping[str, Any]],
|
||||||
gaps: Sequence[Mapping[str, Any]],
|
gaps: Sequence[Mapping[str, Any]],
|
||||||
bridge_inserts: Sequence[Mapping[str, Any]],
|
bridge_inserts: Sequence[Mapping[str, Any]],
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Tuple[Optional[Dict[str, Any]], bool]:
|
) -> Tuple[Optional[Dict[str, Any]], bool]:
|
||||||
api_key, _ = normalize_openrouter_env()
|
api_key, _ = normalize_openrouter_env()
|
||||||
if not api_key or len(steps) < 2:
|
if not api_key or len(steps) < 2:
|
||||||
@@ -341,13 +357,18 @@ def try_llm_qa_progression_path(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
variables = {
|
variables = merge_planning_prompt_variables(
|
||||||
|
cur,
|
||||||
|
{
|
||||||
"goal_query": goal_query or "",
|
"goal_query": goal_query or "",
|
||||||
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
|
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
|
||||||
"steps_json": json.dumps(step_payload, ensure_ascii=False),
|
"steps_json": json.dumps(step_payload, ensure_ascii=False),
|
||||||
"gaps_json": json.dumps(list(gaps), ensure_ascii=False),
|
"gaps_json": json.dumps(list(gaps), ensure_ascii=False),
|
||||||
"bridge_inserts_json": json.dumps(list(bridge_inserts), ensure_ascii=False),
|
"bridge_inserts_json": json.dumps(list(bridge_inserts), ensure_ascii=False),
|
||||||
}
|
},
|
||||||
|
catalog=catalog,
|
||||||
|
slug="planning_exercise_path_qa",
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
prow, rendered = load_and_render_ai_prompt(cur, "planning_exercise_path_qa", variables)
|
prow, rendered = load_and_render_ai_prompt(cur, "planning_exercise_path_qa", variables)
|
||||||
@@ -391,43 +412,188 @@ def apply_llm_path_reorder(
|
|||||||
_OFF_TOPIC_SEMANTIC_MAX = 0.10
|
_OFF_TOPIC_SEMANTIC_MAX = 0.10
|
||||||
|
|
||||||
|
|
||||||
|
def _with_roadmap_major_index(
|
||||||
|
step: Mapping[str, Any],
|
||||||
|
entry: Dict[str, Any],
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
midx = step.get("roadmap_major_step_index")
|
||||||
|
if midx is not None:
|
||||||
|
entry["roadmap_major_step_index"] = int(midx)
|
||||||
|
return entry
|
||||||
|
|
||||||
|
|
||||||
def detect_off_topic_steps(
|
def detect_off_topic_steps(
|
||||||
cur,
|
cur,
|
||||||
steps: Sequence[Mapping[str, Any]],
|
steps: Sequence[Mapping[str, Any]],
|
||||||
*,
|
*,
|
||||||
brief: PlanningSemanticBrief,
|
brief: PlanningSemanticBrief,
|
||||||
|
goal_query: Optional[str] = None,
|
||||||
) -> List[Dict[str, Any]]:
|
) -> List[Dict[str, Any]]:
|
||||||
"""Schritte ohne Bezug zum Pfad-Thema (z. B. reine Kraftübungen bei Mae Geri)."""
|
"""Schritte ohne Bezug zum Pfad-Thema (z. B. reine Kraftübungen bei Mae Geri)."""
|
||||||
if brief.semantic_strength < 0.55 or len(steps) < 2:
|
if len(steps) < 2:
|
||||||
|
return []
|
||||||
|
roadmap_stage_steps = any(
|
||||||
|
(step.get("roadmap_match_source") == "stage_spec")
|
||||||
|
or (step.get("roadmap_learning_goal") or "").strip()
|
||||||
|
for step in steps
|
||||||
|
)
|
||||||
|
if brief.semantic_strength < 0.55 and not roadmap_stage_steps:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
path_anti = resolve_path_anti_patterns(goal_query or "", semantic_brief=brief)
|
||||||
off_topic: List[Dict[str, Any]] = []
|
off_topic: List[Dict[str, Any]] = []
|
||||||
total = len(steps)
|
total = len(steps)
|
||||||
for idx, step in enumerate(steps):
|
for idx, step in enumerate(steps):
|
||||||
if step.get("is_ai_proposal") or step.get("exercise_id") is None:
|
if step.get("is_ai_proposal") or step.get("exercise_id") is None:
|
||||||
continue
|
continue
|
||||||
bundle = _load_exercise_text_bundle(cur, int(step["exercise_id"]))
|
bundle = _load_exercise_text_bundle(cur, int(step["exercise_id"]))
|
||||||
phase = step_phase_for_index(brief, idx, total)
|
blob = _blob_from_fields(
|
||||||
|
bundle["title"],
|
||||||
|
bundle["summary"],
|
||||||
|
bundle["goal"],
|
||||||
|
bundle["variant_names"],
|
||||||
|
)
|
||||||
|
step_anti_raw = list(step.get("roadmap_anti_patterns") or [])
|
||||||
|
stage_goal_pre = (step.get("roadmap_learning_goal") or "").strip()
|
||||||
|
exclude_phrases = merge_stage_exclude_phrases(
|
||||||
|
stage_goal_pre,
|
||||||
|
[*step_anti_raw, *path_anti],
|
||||||
|
)
|
||||||
|
if exclude_phrases and _blob_matches_stage_excludes(blob, exclude_phrases):
|
||||||
|
off_topic.append(
|
||||||
|
_with_roadmap_major_index(
|
||||||
|
step,
|
||||||
|
{
|
||||||
|
"step_index": idx,
|
||||||
|
"exercise_id": int(step["exercise_id"]),
|
||||||
|
"title": step.get("title") or bundle["title"],
|
||||||
|
"semantic_score": 0.0,
|
||||||
|
"expected_phase": (step.get("roadmap_phase") or "").strip().lower() or None,
|
||||||
|
"issue": "path_exclude",
|
||||||
|
"reasons": ["Widerspricht Pfad-Ausschlüssen (z. B. Kumite)"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
primary = (
|
||||||
|
resolve_path_primary_topic(
|
||||||
|
goal_query or "",
|
||||||
|
brief,
|
||||||
|
stage_learning_goal=None,
|
||||||
|
)
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
if primary and brief.topic_type == "technique":
|
||||||
|
siblings = technique_sibling_excludes(primary)
|
||||||
|
if not exercise_passes_technique_path_scope(
|
||||||
|
primary_topic=primary,
|
||||||
|
title=bundle["title"],
|
||||||
|
summary=bundle["summary"],
|
||||||
|
goal=bundle["goal"],
|
||||||
|
learning_goal=stage_goal_pre,
|
||||||
|
sibling_excludes=siblings,
|
||||||
|
relaxed=False,
|
||||||
|
):
|
||||||
|
off_topic.append(
|
||||||
|
_with_roadmap_major_index(
|
||||||
|
step,
|
||||||
|
{
|
||||||
|
"step_index": idx,
|
||||||
|
"exercise_id": int(step["exercise_id"]),
|
||||||
|
"title": step.get("title") or bundle["title"],
|
||||||
|
"semantic_score": 0.0,
|
||||||
|
"expected_phase": (step.get("roadmap_phase") or "").strip().lower() or None,
|
||||||
|
"issue": "technique_scope",
|
||||||
|
"reasons": [f"Passt nicht zur Haupttechnik „{primary}“"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
stage_goal = (step.get("roadmap_learning_goal") or "").strip()
|
||||||
|
phase = (step.get("roadmap_phase") or "").strip().lower() or step_phase_for_index(
|
||||||
|
brief, idx, total
|
||||||
|
)
|
||||||
|
step_brief = (
|
||||||
|
semantic_brief_for_stage(brief, learning_goal=stage_goal, phase=phase or None)
|
||||||
|
if stage_goal
|
||||||
|
else brief
|
||||||
|
)
|
||||||
sem, sem_reasons = score_exercise_semantic_relevance(
|
sem, sem_reasons = score_exercise_semantic_relevance(
|
||||||
title=bundle["title"],
|
title=bundle["title"],
|
||||||
summary=bundle["summary"],
|
summary=bundle["summary"],
|
||||||
goal=bundle["goal"],
|
goal=bundle["goal"],
|
||||||
variant_names=bundle["variant_names"],
|
variant_names=bundle["variant_names"],
|
||||||
brief=brief,
|
brief=step_brief,
|
||||||
step_phase=phase,
|
step_phase=phase,
|
||||||
)
|
)
|
||||||
|
stage_anti = list(step.get("roadmap_anti_patterns") or [])
|
||||||
|
stage_match_brief = (
|
||||||
|
build_stage_match_brief(
|
||||||
|
learning_goal=stage_goal,
|
||||||
|
anti_patterns=stage_anti or None,
|
||||||
|
phase=phase or None,
|
||||||
|
)
|
||||||
|
if stage_goal
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
stage_sem = 0.0
|
||||||
|
stage_reasons: List[str] = []
|
||||||
|
if stage_match_brief:
|
||||||
|
stage_sem, stage_reasons = score_exercise_stage_fit(
|
||||||
|
title=bundle["title"],
|
||||||
|
summary=bundle["summary"],
|
||||||
|
goal=bundle["goal"],
|
||||||
|
variant_names=bundle["variant_names"],
|
||||||
|
stage_brief=stage_match_brief,
|
||||||
|
step_phase=phase,
|
||||||
|
)
|
||||||
|
if stage_goal and not exercise_passes_stage_learning_goal_gate(
|
||||||
|
learning_goal=stage_goal,
|
||||||
|
title=bundle["title"],
|
||||||
|
summary=bundle["summary"],
|
||||||
|
goal=bundle["goal"],
|
||||||
|
semantic_score=sem,
|
||||||
|
anti_patterns=stage_anti or None,
|
||||||
|
):
|
||||||
|
reasons = [
|
||||||
|
r
|
||||||
|
for r in stage_reasons
|
||||||
|
if r and r != "Kern-Thema der Anfrage im Übungstext"
|
||||||
|
]
|
||||||
|
if not reasons:
|
||||||
|
reasons = [
|
||||||
|
f"Stufen-Fit zu schwach ({stage_sem:.2f}) für „{stage_goal[:80]}“"
|
||||||
|
]
|
||||||
|
off_topic.append(
|
||||||
|
_with_roadmap_major_index(
|
||||||
|
step,
|
||||||
|
{
|
||||||
|
"step_index": idx,
|
||||||
|
"exercise_id": int(step["exercise_id"]),
|
||||||
|
"title": step.get("title") or bundle["title"],
|
||||||
|
"semantic_score": round(stage_sem, 4),
|
||||||
|
"expected_phase": phase,
|
||||||
|
"issue": "stage_mismatch",
|
||||||
|
"roadmap_learning_goal": stage_goal,
|
||||||
|
"reasons": reasons[:3],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
continue
|
||||||
if exercise_passes_path_semantic_gate(
|
if exercise_passes_path_semantic_gate(
|
||||||
semantic_score=sem,
|
semantic_score=sem,
|
||||||
title=bundle["title"],
|
title=bundle["title"],
|
||||||
summary=bundle["summary"],
|
summary=bundle["summary"],
|
||||||
goal=bundle["goal"],
|
goal=bundle["goal"],
|
||||||
brief=brief,
|
brief=step_brief,
|
||||||
strict=True,
|
strict=True,
|
||||||
):
|
):
|
||||||
continue
|
continue
|
||||||
if sem > _OFF_TOPIC_SEMANTIC_MAX:
|
if sem > _OFF_TOPIC_SEMANTIC_MAX:
|
||||||
continue
|
continue
|
||||||
off_topic.append(
|
off_topic.append(
|
||||||
|
_with_roadmap_major_index(
|
||||||
|
step,
|
||||||
{
|
{
|
||||||
"step_index": idx,
|
"step_index": idx,
|
||||||
"exercise_id": int(step["exercise_id"]),
|
"exercise_id": int(step["exercise_id"]),
|
||||||
@@ -436,7 +602,8 @@ def detect_off_topic_steps(
|
|||||||
"expected_phase": phase,
|
"expected_phase": phase,
|
||||||
"issue": "off_topic",
|
"issue": "off_topic",
|
||||||
"reasons": sem_reasons[:3],
|
"reasons": sem_reasons[:3],
|
||||||
}
|
},
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return off_topic
|
return off_topic
|
||||||
|
|
||||||
@@ -497,9 +664,10 @@ def strip_off_topic_steps_from_path(
|
|||||||
return steps, []
|
return steps, []
|
||||||
|
|
||||||
by_index = {int(o["step_index"]): dict(o) for o in off_topic_steps if o.get("step_index") is not None}
|
by_index = {int(o["step_index"]): dict(o) for o in off_topic_steps if o.get("step_index") is not None}
|
||||||
indices = sorted(by_index.keys(), reverse=True)
|
max_remove = max(0, len(steps) - min_remaining)
|
||||||
if len(steps) - len(indices) < min_remaining:
|
if max_remove <= 0:
|
||||||
return steps, []
|
return steps, []
|
||||||
|
indices = sorted(by_index.keys(), reverse=True)[:max_remove]
|
||||||
|
|
||||||
out = list(steps)
|
out = list(steps)
|
||||||
removed: List[Dict[str, Any]] = []
|
removed: List[Dict[str, Any]] = []
|
||||||
@@ -528,6 +696,160 @@ def find_step_pair_index(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def count_step_assignment_stats(steps: Optional[Sequence[Mapping[str, Any]]]) -> Dict[str, int]:
|
||||||
|
stats = {"total": 0, "empty": 0, "library_filled": 0, "ai_proposal": 0}
|
||||||
|
for raw in steps or []:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
stats["total"] += 1
|
||||||
|
if raw.get("exercise_id") is not None and not raw.get("is_ai_proposal"):
|
||||||
|
stats["library_filled"] += 1
|
||||||
|
elif raw.get("is_ai_proposal"):
|
||||||
|
stats["ai_proposal"] += 1
|
||||||
|
else:
|
||||||
|
stats["empty"] += 1
|
||||||
|
return stats
|
||||||
|
|
||||||
|
|
||||||
|
def compute_assignment_quality_score(
|
||||||
|
*,
|
||||||
|
steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
off_topic_steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
) -> float:
|
||||||
|
"""QS der Übungsbesetzung — leere Slots stark abwerten."""
|
||||||
|
stats = count_step_assignment_stats(steps)
|
||||||
|
total = stats["total"]
|
||||||
|
if total <= 0:
|
||||||
|
return 0.45
|
||||||
|
empty = stats["empty"]
|
||||||
|
library = stats["library_filled"]
|
||||||
|
ai = stats["ai_proposal"]
|
||||||
|
fill_credit = (library + 0.55 * ai) / total
|
||||||
|
score = 0.1 + 0.84 * fill_credit
|
||||||
|
if empty > 0:
|
||||||
|
score -= 0.22 * (empty / total)
|
||||||
|
score -= 0.08 * len(off_topic_steps or [])
|
||||||
|
score -= 0.03 * len(gaps or [])
|
||||||
|
return max(0.08, min(0.98, round(score, 4)))
|
||||||
|
|
||||||
|
|
||||||
|
def compute_roadmap_quality_score(
|
||||||
|
*,
|
||||||
|
llm_qa: Optional[Mapping[str, Any]] = None,
|
||||||
|
llm_applied: bool = False,
|
||||||
|
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
multistage_qa: Optional[Mapping[str, Any]] = None,
|
||||||
|
) -> float:
|
||||||
|
"""QS der Roadmap-/Stufenlogik — unabhängig von Slot-Befüllung."""
|
||||||
|
if llm_applied and llm_qa and llm_qa.get("quality_score") is not None:
|
||||||
|
try:
|
||||||
|
return max(0.08, min(0.98, round(float(llm_qa["quality_score"]), 4)))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
score = 0.9
|
||||||
|
score -= 0.05 * len(gaps or [])
|
||||||
|
hint_count = int((multistage_qa or {}).get("optimization_hint_count") or 0)
|
||||||
|
score -= min(0.12, 0.015 * hint_count)
|
||||||
|
return max(0.35, min(0.98, round(score, 4)))
|
||||||
|
|
||||||
|
|
||||||
|
def build_assignment_qa_snapshot(
|
||||||
|
*,
|
||||||
|
steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
off_topic_steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
off_topic = list(off_topic_steps or [])
|
||||||
|
stats = count_step_assignment_stats(steps)
|
||||||
|
score = compute_assignment_quality_score(
|
||||||
|
steps=steps,
|
||||||
|
off_topic_steps=off_topic,
|
||||||
|
gaps=gaps,
|
||||||
|
)
|
||||||
|
issues: List[str] = []
|
||||||
|
if stats["empty"] > 0:
|
||||||
|
issues.append(
|
||||||
|
f"{stats['empty']} von {stats['total']} Slot(s) ohne Übung — bitte Bibliothek oder KI-Vorschlag zuweisen",
|
||||||
|
)
|
||||||
|
if stats["ai_proposal"] > 0 and stats["library_filled"] == 0 and stats["empty"] > 0:
|
||||||
|
issues.append(
|
||||||
|
f"{stats['ai_proposal']} KI-Entwurf(e), aber noch {stats['empty']} leere Slot(s)",
|
||||||
|
)
|
||||||
|
for item in off_topic[:5]:
|
||||||
|
title = (item.get("title") or "Schritt").strip()
|
||||||
|
issues.append(f"„{title}“ passt nicht zum Stufen-Ziel")
|
||||||
|
overall_ok = stats["empty"] == 0 and len(off_topic) == 0
|
||||||
|
return {
|
||||||
|
"overall_ok": overall_ok,
|
||||||
|
"quality_score": score,
|
||||||
|
"slot_count": stats["total"],
|
||||||
|
"empty_slot_count": stats["empty"],
|
||||||
|
"library_filled_count": stats["library_filled"],
|
||||||
|
"ai_proposal_count": stats["ai_proposal"],
|
||||||
|
"issues": issues,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_roadmap_qa_snapshot(
|
||||||
|
*,
|
||||||
|
llm_qa: Optional[Mapping[str, Any]] = None,
|
||||||
|
llm_applied: bool = False,
|
||||||
|
gaps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
multistage_qa: Optional[Mapping[str, Any]] = None,
|
||||||
|
roadmap_qa_mode: Optional[str] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
score = compute_roadmap_quality_score(
|
||||||
|
llm_qa=llm_qa,
|
||||||
|
llm_applied=llm_applied,
|
||||||
|
gaps=gaps,
|
||||||
|
multistage_qa=multistage_qa,
|
||||||
|
)
|
||||||
|
issues: List[str] = []
|
||||||
|
if not llm_applied:
|
||||||
|
for gap in gaps or []:
|
||||||
|
issues.append(
|
||||||
|
f"Übergang „{gap.get('from_title')}“ → „{gap.get('to_title')}“ schwach (Score {gap.get('gap_score')})",
|
||||||
|
)
|
||||||
|
if llm_applied and llm_qa:
|
||||||
|
issues.extend(str(x).strip() for x in (llm_qa.get("issues") or []) if str(x).strip())
|
||||||
|
overall_ok = bool(llm_qa.get("overall_ok", True)) if llm_applied and llm_qa else len(gaps or []) == 0
|
||||||
|
snapshot: Dict[str, Any] = {
|
||||||
|
"overall_ok": overall_ok,
|
||||||
|
"quality_score": score,
|
||||||
|
"issues": issues[:8],
|
||||||
|
"llm_applied": bool(llm_applied),
|
||||||
|
"roadmap_qa_mode": roadmap_qa_mode,
|
||||||
|
}
|
||||||
|
if llm_applied and llm_qa:
|
||||||
|
snapshot["topic_coverage"] = llm_qa.get("topic_coverage")
|
||||||
|
snapshot["recommendations"] = list(llm_qa.get("recommendations") or [])
|
||||||
|
snapshot["sequence_notes"] = list(llm_qa.get("sequence_notes") or [])
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
|
||||||
|
def merge_path_quality_scores(
|
||||||
|
roadmap_qa: Mapping[str, Any],
|
||||||
|
assignment_qa: Mapping[str, Any],
|
||||||
|
) -> float:
|
||||||
|
"""Gesamt-QS: schwächere Dimension begrenzt — leere Slots senken den Pfad deutlich."""
|
||||||
|
try:
|
||||||
|
roadmap_score = float(roadmap_qa.get("quality_score"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
roadmap_score = None
|
||||||
|
try:
|
||||||
|
assignment_score = float(assignment_qa.get("quality_score"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
assignment_score = None
|
||||||
|
if roadmap_score is not None and assignment_score is not None:
|
||||||
|
return round(min(roadmap_score, assignment_score), 4)
|
||||||
|
if assignment_score is not None:
|
||||||
|
return assignment_score
|
||||||
|
if roadmap_score is not None:
|
||||||
|
return roadmap_score
|
||||||
|
return 0.5
|
||||||
|
|
||||||
|
|
||||||
def build_path_qa_summary(
|
def build_path_qa_summary(
|
||||||
*,
|
*,
|
||||||
gaps: Sequence[Mapping[str, Any]],
|
gaps: Sequence[Mapping[str, Any]],
|
||||||
@@ -541,6 +863,8 @@ def build_path_qa_summary(
|
|||||||
reorder_applied: bool = False,
|
reorder_applied: bool = False,
|
||||||
reorder_notes: Optional[Sequence[str]] = None,
|
reorder_notes: Optional[Sequence[str]] = None,
|
||||||
roadmap_qa_mode: Optional[str] = None,
|
roadmap_qa_mode: Optional[str] = None,
|
||||||
|
multistage_qa: Optional[Mapping[str, Any]] = None,
|
||||||
|
steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
offers = list(gap_fill_offers or [])
|
offers = list(gap_fill_offers or [])
|
||||||
off_topic = list(off_topic_steps or [])
|
off_topic = list(off_topic_steps or [])
|
||||||
@@ -561,34 +885,74 @@ def build_path_qa_summary(
|
|||||||
"reorder_notes": list(reorder_notes or []),
|
"reorder_notes": list(reorder_notes or []),
|
||||||
"roadmap_qa_mode": roadmap_qa_mode,
|
"roadmap_qa_mode": roadmap_qa_mode,
|
||||||
}
|
}
|
||||||
|
if multistage_qa:
|
||||||
|
summary["qa_tiers"] = list(multistage_qa.get("qa_tiers") or [])
|
||||||
|
summary["optimization_hints"] = list(multistage_qa.get("optimization_hints") or [])
|
||||||
|
summary["optimization_hint_count"] = int(multistage_qa.get("optimization_hint_count") or 0)
|
||||||
|
|
||||||
|
assignment_qa = build_assignment_qa_snapshot(
|
||||||
|
steps=steps,
|
||||||
|
off_topic_steps=off_topic,
|
||||||
|
gaps=gaps,
|
||||||
|
)
|
||||||
|
roadmap_qa = build_roadmap_qa_snapshot(
|
||||||
|
llm_qa=llm_qa,
|
||||||
|
llm_applied=llm_applied,
|
||||||
|
gaps=gaps,
|
||||||
|
multistage_qa=multistage_qa,
|
||||||
|
roadmap_qa_mode=roadmap_qa_mode,
|
||||||
|
)
|
||||||
|
summary["assignment_qa"] = assignment_qa
|
||||||
|
summary["roadmap_qa"] = roadmap_qa
|
||||||
|
summary["quality_score"] = merge_path_quality_scores(roadmap_qa, assignment_qa)
|
||||||
|
summary["overall_ok"] = bool(
|
||||||
|
assignment_qa.get("overall_ok")
|
||||||
|
and roadmap_qa.get("overall_ok", True),
|
||||||
|
)
|
||||||
|
summary["topic_coverage"] = roadmap_qa.get("topic_coverage")
|
||||||
|
summary["recommendations"] = list(roadmap_qa.get("recommendations") or [])
|
||||||
|
summary["sequence_notes"] = list(roadmap_qa.get("sequence_notes") or [])
|
||||||
|
summary["issues"] = list(assignment_qa.get("issues") or []) + list(roadmap_qa.get("issues") or [])[:6]
|
||||||
if llm_qa:
|
if llm_qa:
|
||||||
summary["overall_ok"] = bool(llm_qa.get("overall_ok", True))
|
|
||||||
summary["quality_score"] = llm_qa.get("quality_score")
|
|
||||||
summary["issues"] = list(llm_qa.get("issues") or [])
|
|
||||||
summary["sequence_notes"] = list(llm_qa.get("sequence_notes") or [])
|
|
||||||
summary["topic_coverage"] = llm_qa.get("topic_coverage")
|
|
||||||
summary["recommendations"] = list(llm_qa.get("recommendations") or [])
|
|
||||||
summary["suggested_new_exercises"] = list(llm_qa.get("suggested_new_exercises") or [])
|
summary["suggested_new_exercises"] = list(llm_qa.get("suggested_new_exercises") or [])
|
||||||
else:
|
|
||||||
summary["overall_ok"] = len(gaps) == 0 and len(off_topic) == 0
|
|
||||||
summary["issues"] = [
|
|
||||||
f"Lücke zwischen „{g.get('from_title')}“ und „{g.get('to_title')}“ (Score {g.get('gap_score')})"
|
|
||||||
for g in gaps
|
|
||||||
] if gaps else []
|
|
||||||
if off_topic:
|
|
||||||
summary["issues"] = list(summary["issues"]) + [
|
|
||||||
f"Schritt „{o.get('title')}“ passt nicht zum Pfad-Thema"
|
|
||||||
for o in off_topic
|
|
||||||
]
|
|
||||||
return summary
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
def compute_deterministic_path_quality_score(
|
||||||
|
*,
|
||||||
|
gaps: Sequence[Mapping[str, Any]],
|
||||||
|
off_topic_steps: Sequence[Mapping[str, Any]],
|
||||||
|
steps: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
multistage_qa: Optional[Mapping[str, Any]] = None,
|
||||||
|
) -> float:
|
||||||
|
"""Heuristische Pfad-QS ohne LLM — Roadmap + Besetzung kombiniert."""
|
||||||
|
roadmap_qa = build_roadmap_qa_snapshot(
|
||||||
|
llm_qa=None,
|
||||||
|
llm_applied=False,
|
||||||
|
gaps=gaps,
|
||||||
|
multistage_qa=multistage_qa,
|
||||||
|
)
|
||||||
|
assignment_qa = build_assignment_qa_snapshot(
|
||||||
|
steps=steps,
|
||||||
|
off_topic_steps=off_topic_steps,
|
||||||
|
gaps=gaps,
|
||||||
|
)
|
||||||
|
return merge_path_quality_scores(roadmap_qa, assignment_qa)
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"apply_llm_path_reorder",
|
"apply_llm_path_reorder",
|
||||||
|
"build_assignment_qa_snapshot",
|
||||||
"build_path_qa_summary",
|
"build_path_qa_summary",
|
||||||
|
"build_roadmap_qa_snapshot",
|
||||||
|
"compute_assignment_quality_score",
|
||||||
|
"compute_deterministic_path_quality_score",
|
||||||
|
"compute_roadmap_quality_score",
|
||||||
|
"count_step_assignment_stats",
|
||||||
"detect_off_topic_steps",
|
"detect_off_topic_steps",
|
||||||
"detect_path_gaps",
|
"detect_path_gaps",
|
||||||
"is_roadmap_planned_neighbor_pair",
|
"is_roadmap_planned_neighbor_pair",
|
||||||
|
"merge_path_quality_scores",
|
||||||
"strip_off_topic_steps_from_path",
|
"strip_off_topic_steps_from_path",
|
||||||
"find_step_pair_index",
|
"find_step_pair_index",
|
||||||
"insert_bridge_exercises",
|
"insert_bridge_exercises",
|
||||||
|
|||||||
@@ -14,10 +14,14 @@ from planning_exercise_profiles import (
|
|||||||
load_exercise_match_profiles_bulk,
|
load_exercise_match_profiles_bulk,
|
||||||
score_exercise_against_target,
|
score_exercise_against_target,
|
||||||
)
|
)
|
||||||
|
from exercise_ai import strip_html_to_plain
|
||||||
from planning_exercise_semantics import (
|
from planning_exercise_semantics import (
|
||||||
PlanningSemanticBrief,
|
PlanningSemanticBrief,
|
||||||
|
build_stage_match_brief,
|
||||||
exercise_passes_path_semantic_gate,
|
exercise_passes_path_semantic_gate,
|
||||||
|
exercise_passes_stage_fit,
|
||||||
score_exercise_semantic_relevance,
|
score_exercise_semantic_relevance,
|
||||||
|
score_exercise_stage_fit,
|
||||||
)
|
)
|
||||||
|
|
||||||
_MAX_LIBRARY_ROWS = 8000
|
_MAX_LIBRARY_ROWS = 8000
|
||||||
@@ -54,6 +58,119 @@ def _normalize_exercise_kind_filter(exercise_kind_any: Optional[List[str]]) -> L
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
_EXERCISE_ROW_SELECT = """
|
||||||
|
SELECT e.id, e.title, e.summary, e.method_archetype,
|
||||||
|
e.visibility, e.club_id, e.created_by,
|
||||||
|
(
|
||||||
|
SELECT fa.name FROM exercise_focus_areas efa
|
||||||
|
JOIN focus_areas fa ON fa.id = efa.focus_area_id
|
||||||
|
WHERE efa.exercise_id = e.id
|
||||||
|
ORDER BY efa.is_primary DESC NULLS LAST, fa.name ASC
|
||||||
|
LIMIT 1
|
||||||
|
) AS primary_focus_name,
|
||||||
|
0.0::float AS ft_rank
|
||||||
|
FROM exercises e
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_exercise_rows_by_ids(
|
||||||
|
cur,
|
||||||
|
exercise_ids: Sequence[int],
|
||||||
|
*,
|
||||||
|
vis_sql: str,
|
||||||
|
vis_params: Sequence[Any],
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Lädt konkrete Übungen nach, wenn sie im Graph/Slot verankert sind (Pin-Sicherheit)."""
|
||||||
|
ids = sorted({int(x) for x in exercise_ids if int(x) > 0})
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
ph = ",".join(["%s"] * len(ids))
|
||||||
|
sql = f"""
|
||||||
|
{_EXERCISE_ROW_SELECT.strip()}
|
||||||
|
WHERE e.id IN ({ph})
|
||||||
|
AND ({vis_sql})
|
||||||
|
AND COALESCE(e.status, '') <> %s
|
||||||
|
"""
|
||||||
|
params: List[Any] = list(ids) + list(vis_params) + ["archived"]
|
||||||
|
cur.execute(sql, params)
|
||||||
|
return [dict(r) for r in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_exercise_rows_by_ids_for_graph(
|
||||||
|
cur,
|
||||||
|
exercise_ids: Sequence[int],
|
||||||
|
*,
|
||||||
|
graph_visibility: str,
|
||||||
|
graph_club_id: Optional[int],
|
||||||
|
profile_id: int,
|
||||||
|
role: str,
|
||||||
|
exercise_allowed_fn,
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
Lädt Übungen nach ID mit Graph-Sichtbarkeitsregeln (nicht Library-vis_sql).
|
||||||
|
|
||||||
|
Ermöglicht Re-Match für im Graph verankerte private Übungen auf Club-Graphen
|
||||||
|
(eigene private) bzw. alle graph-konformen Übungen.
|
||||||
|
"""
|
||||||
|
ids = sorted({int(x) for x in exercise_ids if int(x) > 0})
|
||||||
|
if not ids:
|
||||||
|
return []
|
||||||
|
ph = ",".join(["%s"] * len(ids))
|
||||||
|
sql = f"""
|
||||||
|
{_EXERCISE_ROW_SELECT.strip()}
|
||||||
|
WHERE e.id IN ({ph})
|
||||||
|
AND COALESCE(e.status, '') <> %s
|
||||||
|
"""
|
||||||
|
cur.execute(sql, [*ids, "archived"])
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
for row in cur.fetchall() or []:
|
||||||
|
if exercise_allowed_fn(
|
||||||
|
row,
|
||||||
|
graph_visibility=graph_visibility,
|
||||||
|
graph_club_id=graph_club_id,
|
||||||
|
profile_id=profile_id,
|
||||||
|
role=role,
|
||||||
|
):
|
||||||
|
out.append(dict(row))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def trim_hits_preserving_priority_ids(
|
||||||
|
hits: Sequence[Mapping[str, Any]],
|
||||||
|
priority_ids: Optional[Sequence[int]],
|
||||||
|
*,
|
||||||
|
limit: int = 48,
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Behält priorisierte Graph-/Slot-Übungen im Kandidatenpool (vor pick_best_path_hit)."""
|
||||||
|
priority_set = {int(x) for x in (priority_ids or []) if int(x) > 0}
|
||||||
|
if not priority_set:
|
||||||
|
return list(hits)[:limit]
|
||||||
|
by_id: Dict[int, Dict[str, Any]] = {}
|
||||||
|
for hit in hits:
|
||||||
|
try:
|
||||||
|
by_id[int(hit["id"])] = dict(hit)
|
||||||
|
except (TypeError, ValueError, KeyError):
|
||||||
|
continue
|
||||||
|
priority_hits = [by_id[eid] for eid in sorted(priority_set) if eid in by_id]
|
||||||
|
rest = [dict(h) for h in hits if int(h.get("id") or 0) not in priority_set]
|
||||||
|
merged = priority_hits + rest
|
||||||
|
return merged[: max(limit, len(priority_hits))]
|
||||||
|
|
||||||
|
|
||||||
|
def merge_supplemental_exercise_rows(
|
||||||
|
rows: Sequence[Dict[str, Any]],
|
||||||
|
supplemental: Sequence[Dict[str, Any]],
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
seen = {int(r["id"]) for r in rows if r.get("id") is not None}
|
||||||
|
out = list(rows)
|
||||||
|
for row in supplemental:
|
||||||
|
rid = int(row["id"])
|
||||||
|
if rid not in seen:
|
||||||
|
seen.add(rid)
|
||||||
|
out.append(dict(row))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def fetch_all_visible_exercise_rows(
|
def fetch_all_visible_exercise_rows(
|
||||||
cur,
|
cur,
|
||||||
*,
|
*,
|
||||||
@@ -148,7 +265,7 @@ def _load_exercise_goals_chunked(cur, exercise_ids: Sequence[int], *, batch: int
|
|||||||
ph = ",".join(["%s"] * len(chunk))
|
ph = ",".join(["%s"] * len(chunk))
|
||||||
cur.execute(f"SELECT id, goal FROM exercises WHERE id IN ({ph})", chunk)
|
cur.execute(f"SELECT id, goal FROM exercises WHERE id IN ({ph})", chunk)
|
||||||
for row in cur.fetchall():
|
for row in cur.fetchall():
|
||||||
out[int(row["id"])] = str(row.get("goal") or "")
|
out[int(row["id"])] = strip_html_to_plain(row.get("goal"), max_len=1200)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -200,6 +317,21 @@ def rank_visible_library_hits(
|
|||||||
semantic_brief = semantic_brief_raw
|
semantic_brief = semantic_brief_raw
|
||||||
step_phase = pack.get("path_step_phase")
|
step_phase = pack.get("path_step_phase")
|
||||||
path_mode = pack.get("context_mode") == "progression_path"
|
path_mode = pack.get("context_mode") == "progression_path"
|
||||||
|
stage_learning_goal = (pack.get("stage_learning_goal") or "").strip()
|
||||||
|
roadmap_stage_match = bool(pack.get("roadmap_stage_match"))
|
||||||
|
stage_match_brief_raw = pack.get("stage_match_brief")
|
||||||
|
stage_match_brief: Optional[PlanningSemanticBrief] = None
|
||||||
|
if isinstance(stage_match_brief_raw, PlanningSemanticBrief):
|
||||||
|
stage_match_brief = stage_match_brief_raw
|
||||||
|
elif roadmap_stage_match and stage_learning_goal:
|
||||||
|
stage_match_brief = build_stage_match_brief(
|
||||||
|
learning_goal=stage_learning_goal,
|
||||||
|
anti_patterns=pack.get("stage_anti_patterns"),
|
||||||
|
success_criteria=pack.get("stage_success_criteria"),
|
||||||
|
load_profile=pack.get("stage_load_profile"),
|
||||||
|
phase=step_phase,
|
||||||
|
path_context_note=pack.get("path_context_note"),
|
||||||
|
)
|
||||||
|
|
||||||
last_planned_skills: Set[int] = set()
|
last_planned_skills: Set[int] = set()
|
||||||
planned_ids = pack.get("planned_exercise_ids") or []
|
planned_ids = pack.get("planned_exercise_ids") or []
|
||||||
@@ -226,7 +358,11 @@ def rank_visible_library_hits(
|
|||||||
skills_by_ex = _load_skill_sets_chunked(cur, cand_ids)
|
skills_by_ex = _load_skill_sets_chunked(cur, cand_ids)
|
||||||
goals_by_ex: Dict[int, str] = {}
|
goals_by_ex: Dict[int, str] = {}
|
||||||
variants_by_ex: Dict[int, List[str]] = {}
|
variants_by_ex: Dict[int, List[str]] = {}
|
||||||
if semantic_brief and semantic_brief.semantic_strength > 0.05:
|
need_exercise_semantic_text = (
|
||||||
|
(semantic_brief and semantic_brief.semantic_strength > 0.05)
|
||||||
|
or (stage_match_brief and stage_match_brief.semantic_strength > 0.05)
|
||||||
|
)
|
||||||
|
if need_exercise_semantic_text:
|
||||||
goals_by_ex = _load_exercise_goals_chunked(cur, cand_ids)
|
goals_by_ex = _load_exercise_goals_chunked(cur, cand_ids)
|
||||||
variants_by_ex = _load_variant_names_chunked(cur, cand_ids)
|
variants_by_ex = _load_variant_names_chunked(cur, cand_ids)
|
||||||
|
|
||||||
@@ -267,37 +403,99 @@ def rank_visible_library_hits(
|
|||||||
emp, target, intent=intent
|
emp, target, intent=intent
|
||||||
)
|
)
|
||||||
|
|
||||||
|
title_s = str(row.get("title") or "")
|
||||||
|
summary_s = str(row.get("summary") or "")
|
||||||
|
goal_s = goals_by_ex.get(eid, "")
|
||||||
|
|
||||||
semantic_score = 0.0
|
semantic_score = 0.0
|
||||||
semantic_reasons: List[str] = []
|
semantic_reasons: List[str] = []
|
||||||
if semantic_brief and semantic_brief.semantic_strength > 0.05:
|
if semantic_brief and semantic_brief.semantic_strength > 0.05:
|
||||||
semantic_score, semantic_reasons = score_exercise_semantic_relevance(
|
semantic_score, semantic_reasons = score_exercise_semantic_relevance(
|
||||||
title=str(row.get("title") or ""),
|
title=title_s,
|
||||||
summary=str(row.get("summary") or ""),
|
summary=summary_s,
|
||||||
goal=goals_by_ex.get(eid, ""),
|
goal=goal_s,
|
||||||
variant_names=variants_by_ex.get(eid, []),
|
variant_names=variants_by_ex.get(eid, []),
|
||||||
brief=semantic_brief,
|
brief=semantic_brief,
|
||||||
step_phase=step_phase,
|
step_phase=step_phase,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
stage_semantic_score = 0.0
|
||||||
|
stage_semantic_reasons: List[str] = []
|
||||||
|
if stage_match_brief and stage_match_brief.semantic_strength > 0.05:
|
||||||
|
stage_semantic_score, stage_semantic_reasons = score_exercise_stage_fit(
|
||||||
|
title=title_s,
|
||||||
|
summary=summary_s,
|
||||||
|
goal=goal_s,
|
||||||
|
variant_names=variants_by_ex.get(eid, []),
|
||||||
|
stage_brief=stage_match_brief,
|
||||||
|
step_phase=step_phase,
|
||||||
|
)
|
||||||
|
|
||||||
|
rank_stage_sem = stage_semantic_score
|
||||||
|
stage_lg = (stage_learning_goal or "").strip()
|
||||||
|
if roadmap_stage_match and stage_lg:
|
||||||
|
raw_brief = build_stage_match_brief(
|
||||||
|
learning_goal=stage_lg,
|
||||||
|
anti_patterns=pack.get("stage_anti_patterns"),
|
||||||
|
phase=step_phase,
|
||||||
|
)
|
||||||
|
raw_sem, raw_reasons = score_exercise_stage_fit(
|
||||||
|
title=title_s,
|
||||||
|
summary=summary_s,
|
||||||
|
goal=goal_s,
|
||||||
|
variant_names=variants_by_ex.get(eid, []),
|
||||||
|
stage_brief=raw_brief,
|
||||||
|
step_phase=step_phase,
|
||||||
|
)
|
||||||
|
rank_stage_sem = max(stage_semantic_score, raw_sem)
|
||||||
|
if raw_sem > stage_semantic_score and raw_reasons:
|
||||||
|
for rr in raw_reasons:
|
||||||
|
if rr not in stage_semantic_reasons:
|
||||||
|
stage_semantic_reasons.append(rr)
|
||||||
|
|
||||||
|
effective_semantic = (
|
||||||
|
rank_stage_sem
|
||||||
|
if roadmap_stage_match and stage_match_brief
|
||||||
|
else semantic_score
|
||||||
|
)
|
||||||
|
|
||||||
|
score_penalty = 0.0
|
||||||
|
stage_match_reason: Optional[str] = None
|
||||||
if (
|
if (
|
||||||
path_mode
|
path_mode
|
||||||
|
and not roadmap_stage_match
|
||||||
and semantic_brief
|
and semantic_brief
|
||||||
and semantic_brief.semantic_strength >= 0.55
|
and semantic_brief.semantic_strength >= 0.55
|
||||||
and not exercise_passes_path_semantic_gate(
|
and not exercise_passes_path_semantic_gate(
|
||||||
semantic_score=semantic_score,
|
semantic_score=semantic_score,
|
||||||
title=str(row.get("title") or ""),
|
title=title_s,
|
||||||
summary=str(row.get("summary") or ""),
|
summary=summary_s,
|
||||||
goal=goals_by_ex.get(eid, ""),
|
goal=goal_s,
|
||||||
brief=semantic_brief,
|
brief=semantic_brief,
|
||||||
strict=True,
|
strict=True,
|
||||||
)
|
)
|
||||||
):
|
):
|
||||||
score_penalty = 0.42
|
score_penalty = 0.42
|
||||||
|
if roadmap_stage_match and stage_learning_goal:
|
||||||
|
if exercise_passes_stage_fit(
|
||||||
|
learning_goal=stage_learning_goal,
|
||||||
|
title=title_s,
|
||||||
|
summary=summary_s,
|
||||||
|
goal=goal_s,
|
||||||
|
stage_brief=stage_match_brief,
|
||||||
|
stage_semantic_score=rank_stage_sem,
|
||||||
|
anti_patterns=pack.get("stage_anti_patterns"),
|
||||||
|
step_phase=step_phase,
|
||||||
|
path_primary_topic=pack.get("path_primary_topic"),
|
||||||
|
path_technique_excludes=pack.get("path_technique_excludes"),
|
||||||
|
):
|
||||||
|
score_penalty = max(0.0, score_penalty - 0.10)
|
||||||
|
stage_match_reason = "Passt zum Stufen-Lernziel"
|
||||||
else:
|
else:
|
||||||
score_penalty = 0.0
|
score_penalty += 0.48
|
||||||
|
|
||||||
score = (
|
score = (
|
||||||
weights.get("semantic", 0.0) * semantic_score
|
weights.get("semantic", 0.0) * effective_semantic
|
||||||
+ weights["fulltext"] * ft_norm
|
+ weights["fulltext"] * ft_norm
|
||||||
+ weights["progression"] * prog_hit
|
+ weights["progression"] * prog_hit
|
||||||
+ weights["skill"] * skill_sim
|
+ weights["skill"] * skill_sim
|
||||||
@@ -309,7 +507,13 @@ def rank_visible_library_hits(
|
|||||||
)
|
)
|
||||||
|
|
||||||
reasons: List[str] = []
|
reasons: List[str] = []
|
||||||
if semantic_score >= 0.35 and semantic_reasons:
|
if stage_match_reason:
|
||||||
|
reasons.append(stage_match_reason)
|
||||||
|
if roadmap_stage_match and stage_semantic_score >= 0.30 and stage_semantic_reasons:
|
||||||
|
for sr in stage_semantic_reasons:
|
||||||
|
if sr not in reasons:
|
||||||
|
reasons.append(sr)
|
||||||
|
elif semantic_score >= 0.35 and semantic_reasons:
|
||||||
for sr in semantic_reasons:
|
for sr in semantic_reasons:
|
||||||
if sr not in reasons:
|
if sr not in reasons:
|
||||||
reasons.append(sr)
|
reasons.append(sr)
|
||||||
@@ -345,6 +549,9 @@ def rank_visible_library_hits(
|
|||||||
"score": round(max(0.0, min(1.0, score)), 4),
|
"score": round(max(0.0, min(1.0, score)), 4),
|
||||||
"reasons": reasons,
|
"reasons": reasons,
|
||||||
"semantic_score": round(semantic_score, 4),
|
"semantic_score": round(semantic_score, 4),
|
||||||
|
"stage_semantic_score": round(stage_semantic_score, 4),
|
||||||
|
"stage_rank_semantic": round(rank_stage_sem, 4),
|
||||||
|
"goal": goal_s,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
succ_variants = pack.get("progression_successor_variants") or {}
|
succ_variants = pack.get("progression_successor_variants") or {}
|
||||||
@@ -367,6 +574,8 @@ def run_multistage_planning_retrieval(
|
|||||||
intent: str,
|
intent: str,
|
||||||
intent_weights: Mapping[str, float],
|
intent_weights: Mapping[str, float],
|
||||||
pack: Mapping[str, Any],
|
pack: Mapping[str, Any],
|
||||||
|
supplemental_exercise_ids: Optional[Sequence[int]] = None,
|
||||||
|
supplemental_rows_preloaded: Optional[Sequence[Dict[str, Any]]] = None,
|
||||||
) -> Tuple[List[Dict[str, Any]], Dict[int, Set[int]], bool]:
|
) -> Tuple[List[Dict[str, Any]], Dict[int, Set[int]], bool]:
|
||||||
"""Orchestriert S1b-0 → S1b-1 (Voll-Library-Ranking)."""
|
"""Orchestriert S1b-0 → S1b-1 (Voll-Library-Ranking)."""
|
||||||
rows = fetch_all_visible_exercise_rows(
|
rows = fetch_all_visible_exercise_rows(
|
||||||
@@ -376,6 +585,16 @@ def run_multistage_planning_retrieval(
|
|||||||
query=pack.get("retrieval_query") or query,
|
query=pack.get("retrieval_query") or query,
|
||||||
exercise_kind_any=exercise_kind_any,
|
exercise_kind_any=exercise_kind_any,
|
||||||
)
|
)
|
||||||
|
if supplemental_rows_preloaded:
|
||||||
|
rows = merge_supplemental_exercise_rows(rows, supplemental_rows_preloaded)
|
||||||
|
elif supplemental_exercise_ids:
|
||||||
|
extra = fetch_exercise_rows_by_ids(
|
||||||
|
cur,
|
||||||
|
supplemental_exercise_ids,
|
||||||
|
vis_sql=vis_sql,
|
||||||
|
vis_params=vis_params,
|
||||||
|
)
|
||||||
|
rows = merge_supplemental_exercise_rows(rows, extra)
|
||||||
hits, skills_by_ex = rank_visible_library_hits(
|
hits, skills_by_ex = rank_visible_library_hits(
|
||||||
cur,
|
cur,
|
||||||
rows,
|
rows,
|
||||||
@@ -411,8 +630,10 @@ def profile_preselect_rows(
|
|||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"fetch_all_visible_exercise_rows",
|
"fetch_all_visible_exercise_rows",
|
||||||
|
"fetch_exercise_rows_by_ids",
|
||||||
"fetch_retrieval_candidate_rows",
|
"fetch_retrieval_candidate_rows",
|
||||||
"hybrid_score_planning_hits",
|
"hybrid_score_planning_hits",
|
||||||
|
"merge_supplemental_exercise_rows",
|
||||||
"profile_preselect_rows",
|
"profile_preselect_rows",
|
||||||
"rank_visible_library_hits",
|
"rank_visible_library_hits",
|
||||||
"run_multistage_planning_retrieval",
|
"run_multistage_planning_retrieval",
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,262 @@
|
|||||||
|
"""
|
||||||
|
Gemeinsame Intent-Anreicherung für Planungs-Retrieval.
|
||||||
|
|
||||||
|
Progressionsgraph (Roadmap stage_specs) und später Trainingsplanung
|
||||||
|
(Abschnitt/Slot) nutzen dieselben Bausteine:
|
||||||
|
Intent-Kontext bauen → Specs finalisieren → Matching-Gates.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
||||||
|
|
||||||
|
from planning_exercise_semantics import (
|
||||||
|
PlanningSemanticBrief,
|
||||||
|
resolve_path_anti_patterns,
|
||||||
|
technique_sibling_excludes,
|
||||||
|
)
|
||||||
|
|
||||||
|
_NEGATION_CLAUSE_RE = re.compile(
|
||||||
|
r"\b(?:ohne|kein(?:e|en|er|em)?|nicht)\s+[^,.;\n]+",
|
||||||
|
flags=re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_explicit_exclusions(*texts: Optional[str]) -> List[str]:
|
||||||
|
"""Lesbare Negationsklauseln aus Freitext (ohne Themen-Raten)."""
|
||||||
|
out: List[str] = []
|
||||||
|
for raw in texts:
|
||||||
|
s = (raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
continue
|
||||||
|
for m in _NEGATION_CLAUSE_RE.finditer(s):
|
||||||
|
clause = m.group(0).strip().rstrip(".,;")
|
||||||
|
if clause and clause.lower() not in {x.lower() for x in out}:
|
||||||
|
out.append(clause[:220])
|
||||||
|
return out[:12]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PlanningIntentContext:
|
||||||
|
"""Pfad-/Abschnittsweiter Planungs-Intent — domänenneutral."""
|
||||||
|
|
||||||
|
source_query: str = ""
|
||||||
|
primary_topic: str = ""
|
||||||
|
path_anti_patterns: List[str] = field(default_factory=list)
|
||||||
|
path_success_criteria: List[str] = field(default_factory=list)
|
||||||
|
explicit_exclusions: List[str] = field(default_factory=list)
|
||||||
|
context_notes: str = ""
|
||||||
|
topic_type: str = "general"
|
||||||
|
technique_sibling_excludes: List[str] = field(default_factory=list)
|
||||||
|
catalog_exercise_hints: Optional[str] = None
|
||||||
|
|
||||||
|
def to_api_dict(self) -> Dict[str, Any]:
|
||||||
|
out = {
|
||||||
|
"source_query": self.source_query,
|
||||||
|
"primary_topic": self.primary_topic,
|
||||||
|
"topic_type": self.topic_type,
|
||||||
|
"path_anti_patterns": self.path_anti_patterns[:16],
|
||||||
|
"path_success_criteria": self.path_success_criteria[:10],
|
||||||
|
"explicit_exclusions": self.explicit_exclusions[:10],
|
||||||
|
"technique_sibling_excludes": self.technique_sibling_excludes[:16],
|
||||||
|
"context_notes": self.context_notes[:1200] or None,
|
||||||
|
}
|
||||||
|
hints = (self.catalog_exercise_hints or "").strip()
|
||||||
|
if hints:
|
||||||
|
out["catalog_exercise_hints"] = hints[:2000]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def build_planning_intent_context(
|
||||||
|
goal_query: str,
|
||||||
|
*,
|
||||||
|
semantic_brief: Optional[PlanningSemanticBrief] = None,
|
||||||
|
goal_analysis: Optional[Mapping[str, Any]] = None,
|
||||||
|
extra_context: Optional[str] = None,
|
||||||
|
primary_topic: Optional[str] = None,
|
||||||
|
cur=None,
|
||||||
|
catalog=None,
|
||||||
|
) -> PlanningIntentContext:
|
||||||
|
"""Intent aus Anfrage, Zielanalyse und optionalem Kontext — ohne Sonderregeln pro Thema."""
|
||||||
|
ga = dict(goal_analysis or {})
|
||||||
|
notes_parts = [extra_context or ""]
|
||||||
|
constraints = ga.get("constraints") if isinstance(ga.get("constraints"), dict) else {}
|
||||||
|
if isinstance(constraints, dict):
|
||||||
|
trainer_notes = str(constraints.get("trainer_notes") or "").strip()
|
||||||
|
if trainer_notes:
|
||||||
|
notes_parts.append(trainer_notes)
|
||||||
|
|
||||||
|
combined_notes = " ".join(p.strip() for p in notes_parts if p and p.strip())
|
||||||
|
explicit = extract_explicit_exclusions(goal_query, combined_notes or None)
|
||||||
|
ga_excluded = constraints.get("excluded_themes") if isinstance(constraints, dict) else None
|
||||||
|
if isinstance(ga_excluded, list):
|
||||||
|
for item in ga_excluded:
|
||||||
|
s = str(item or "").strip()
|
||||||
|
if s and s.lower() not in {x.lower() for x in explicit}:
|
||||||
|
explicit.append(s[:220])
|
||||||
|
|
||||||
|
path_anti = resolve_path_anti_patterns(
|
||||||
|
goal_query,
|
||||||
|
semantic_brief=semantic_brief,
|
||||||
|
extra_context=combined_notes or None,
|
||||||
|
)
|
||||||
|
path_success: List[str] = []
|
||||||
|
for item in ga.get("success_criteria") or []:
|
||||||
|
s = str(item or "").strip()
|
||||||
|
if s and s not in path_success:
|
||||||
|
path_success.append(s[:240])
|
||||||
|
target = str(ga.get("target_state") or "").strip()
|
||||||
|
if target and len(target) >= 8:
|
||||||
|
line = f"Zielzustand erreichbar: {target[:200]}"
|
||||||
|
if line not in path_success:
|
||||||
|
path_success.append(line)
|
||||||
|
|
||||||
|
topic = (primary_topic or ga.get("primary_topic") or "").strip()
|
||||||
|
topic_type = "general"
|
||||||
|
siblings: List[str] = []
|
||||||
|
if semantic_brief:
|
||||||
|
if not topic:
|
||||||
|
topic = (semantic_brief.primary_topic or "").strip()
|
||||||
|
topic_type = (semantic_brief.topic_type or "general").strip().lower()
|
||||||
|
if topic_type == "technique" and topic:
|
||||||
|
siblings = technique_sibling_excludes(topic)
|
||||||
|
for raw in semantic_brief.exclude_phrases or []:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if s and s.lower() not in {x.lower() for x in siblings}:
|
||||||
|
siblings.append(s[:120])
|
||||||
|
|
||||||
|
if topic_type == "technique" and topic:
|
||||||
|
line = f"Haupttechnik {topic} in Kurzbeschreibung oder Übungsziel erkennbar"
|
||||||
|
if line not in path_success:
|
||||||
|
path_success.insert(0, line)
|
||||||
|
|
||||||
|
catalog_hints = ""
|
||||||
|
if cur is not None and catalog is not None:
|
||||||
|
from planning_prompt_variables import catalog_exercise_hints_block
|
||||||
|
|
||||||
|
catalog_hints = catalog_exercise_hints_block(cur, catalog)
|
||||||
|
|
||||||
|
return PlanningIntentContext(
|
||||||
|
source_query=(goal_query or "").strip(),
|
||||||
|
primary_topic=topic,
|
||||||
|
topic_type=topic_type,
|
||||||
|
path_anti_patterns=path_anti,
|
||||||
|
path_success_criteria=path_success,
|
||||||
|
explicit_exclusions=explicit,
|
||||||
|
technique_sibling_excludes=siblings[:16],
|
||||||
|
context_notes=combined_notes[:1200],
|
||||||
|
catalog_exercise_hints=catalog_hints or None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe_preserve(items: Sequence[str], *, limit: int = 14) -> List[str]:
|
||||||
|
out: List[str] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
for raw in items:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
continue
|
||||||
|
key = s.lower()
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
out.append(s[:240])
|
||||||
|
if len(out) >= limit:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def finalize_stage_spec_artifact(
|
||||||
|
spec: "StageSpecArtifact",
|
||||||
|
*,
|
||||||
|
major_step: Optional["MajorStep"] = None,
|
||||||
|
intent: PlanningIntentContext,
|
||||||
|
) -> "StageSpecArtifact":
|
||||||
|
"""Pfad-Intent in eine Stufenspezifikation mergen (LLM oder heuristisch)."""
|
||||||
|
from planning_progression_roadmap import MajorStep, StageSpecArtifact
|
||||||
|
|
||||||
|
learning_goal = (spec.learning_goal or (major_step.learning_goal if major_step else "")).strip()
|
||||||
|
phase = (major_step.phase if major_step else "").strip().lower()
|
||||||
|
|
||||||
|
anti = _dedupe_preserve(
|
||||||
|
[
|
||||||
|
*(spec.anti_patterns or []),
|
||||||
|
*intent.explicit_exclusions,
|
||||||
|
*intent.path_anti_patterns,
|
||||||
|
*intent.technique_sibling_excludes,
|
||||||
|
(
|
||||||
|
f"andere Technik als {intent.primary_topic}"
|
||||||
|
if intent.topic_type == "technique" and intent.primary_topic
|
||||||
|
else ""
|
||||||
|
),
|
||||||
|
],
|
||||||
|
limit=14,
|
||||||
|
)
|
||||||
|
stage_start = (spec.start_state or "").strip()
|
||||||
|
stage_target = (spec.target_state or "").strip()
|
||||||
|
success = _dedupe_preserve(
|
||||||
|
[
|
||||||
|
*(spec.success_criteria or []),
|
||||||
|
*intent.path_success_criteria,
|
||||||
|
(f"Soll-Start der Stufe erreichbar: {stage_start[:180]}" if stage_start else ""),
|
||||||
|
(f"Stufen-Ziel erreichbar: {stage_target[:180]}" if stage_target else ""),
|
||||||
|
(
|
||||||
|
f"Übung liefert messbar: {learning_goal[:160]}"
|
||||||
|
if learning_goal
|
||||||
|
else ""
|
||||||
|
),
|
||||||
|
(
|
||||||
|
f"Kurzbeschreibung und Übungsziel passen zur Phase {phase}"
|
||||||
|
if phase
|
||||||
|
else "Kurzbeschreibung und Übungsziel passen zum Stufen-Lernziel"
|
||||||
|
),
|
||||||
|
],
|
||||||
|
limit=8,
|
||||||
|
)
|
||||||
|
|
||||||
|
idx = spec.major_step_index
|
||||||
|
if major_step is not None:
|
||||||
|
idx = major_step.index
|
||||||
|
|
||||||
|
return StageSpecArtifact(
|
||||||
|
major_step_index=idx,
|
||||||
|
learning_goal=learning_goal,
|
||||||
|
load_profile=list(spec.load_profile or []),
|
||||||
|
exercise_type=(spec.exercise_type or "").strip(),
|
||||||
|
success_criteria=success,
|
||||||
|
anti_patterns=anti,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def finalize_stage_specs_with_intent(
|
||||||
|
specs: Sequence["StageSpecArtifact"],
|
||||||
|
major_steps: Sequence["MajorStep"],
|
||||||
|
*,
|
||||||
|
intent: PlanningIntentContext,
|
||||||
|
fallback_specs: Optional[Sequence["StageSpecArtifact"]] = None,
|
||||||
|
) -> List["StageSpecArtifact"]:
|
||||||
|
"""Alle Stufen mit gleichem Pfad-Intent anreichern; fehlende Indizes aus Fallback."""
|
||||||
|
from planning_progression_roadmap import MajorStep, StageSpecArtifact
|
||||||
|
|
||||||
|
by_idx = {int(s.major_step_index): s for s in specs}
|
||||||
|
fallback_by_idx = {int(s.major_step_index): s for s in (fallback_specs or [])}
|
||||||
|
out: List[StageSpecArtifact] = []
|
||||||
|
for major in major_steps:
|
||||||
|
raw = by_idx.get(major.index) or fallback_by_idx.get(major.index)
|
||||||
|
if raw is None:
|
||||||
|
raw = StageSpecArtifact(
|
||||||
|
major_step_index=major.index,
|
||||||
|
learning_goal=major.learning_goal,
|
||||||
|
)
|
||||||
|
out.append(finalize_stage_spec_artifact(raw, major_step=major, intent=intent))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"PlanningIntentContext",
|
||||||
|
"build_planning_intent_context",
|
||||||
|
"extract_explicit_exclusions",
|
||||||
|
"finalize_stage_spec_artifact",
|
||||||
|
"finalize_stage_specs_with_intent",
|
||||||
|
]
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""
|
||||||
|
Zähler für produktive OpenRouter-Aufrufe innerhalb einer Planungs-API-Anfrage.
|
||||||
|
|
||||||
|
Wird per ContextVar gesetzt (Router: ``planning_llm_call_meter``); ``openrouter_chat_completion``
|
||||||
|
erhöht den Zähler nach erfolgreicher Antwort — nur wenn ein Meter aktiv ist.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from contextvars import ContextVar
|
||||||
|
from typing import Iterator, Optional
|
||||||
|
|
||||||
|
_llm_call_counter: ContextVar[Optional["PlanningLlmCallCounter"]] = ContextVar(
|
||||||
|
"planning_llm_call_counter",
|
||||||
|
default=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PlanningLlmCallCounter:
|
||||||
|
"""Anzahl erfolgreicher OpenRouter-Chat-Completions in einem Request-Kontext."""
|
||||||
|
|
||||||
|
__slots__ = ("count",)
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.count = 0
|
||||||
|
|
||||||
|
def record(self, amount: int = 1) -> None:
|
||||||
|
try:
|
||||||
|
n = int(amount)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
n = 1
|
||||||
|
if n > 0:
|
||||||
|
self.count += n
|
||||||
|
|
||||||
|
|
||||||
|
def current_planning_llm_call_counter() -> Optional[PlanningLlmCallCounter]:
|
||||||
|
return _llm_call_counter.get()
|
||||||
|
|
||||||
|
|
||||||
|
def record_planning_llm_call(amount: int = 1) -> None:
|
||||||
|
counter = _llm_call_counter.get()
|
||||||
|
if counter is not None:
|
||||||
|
counter.record(amount)
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def planning_llm_call_meter() -> Iterator[PlanningLlmCallCounter]:
|
||||||
|
"""Aktiviert LLM-Zählung für den umschlossenen Block (inkl. verschachtelter Aufrufe)."""
|
||||||
|
counter = PlanningLlmCallCounter()
|
||||||
|
token = _llm_call_counter.set(counter)
|
||||||
|
try:
|
||||||
|
yield counter
|
||||||
|
finally:
|
||||||
|
_llm_call_counter.reset(token)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"PlanningLlmCallCounter",
|
||||||
|
"current_planning_llm_call_counter",
|
||||||
|
"planning_llm_call_meter",
|
||||||
|
"record_planning_llm_call",
|
||||||
|
]
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""
|
||||||
|
Mehrstufige Pfad-QS — Findings pro Stufe, daraus Optimierungspotenziale ableiten.
|
||||||
|
|
||||||
|
Stufen (allgemein, domänenneutral):
|
||||||
|
1. deterministische Gates (Technik-Scope, Ausschlüsse, Stufen-Fit)
|
||||||
|
2. Übergangs-Kohärenz (Lücken zwischen Schritten)
|
||||||
|
3. LLM-Ganzpfad-Bewertung (Empfehlungen, keine Auto-Patches)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
||||||
|
|
||||||
|
|
||||||
|
_ACTION_BY_ISSUE: Dict[str, str] = {
|
||||||
|
"technique_scope": "rematch_slot",
|
||||||
|
"path_exclude": "rematch_slot",
|
||||||
|
"stage_mismatch": "refine_stage_spec",
|
||||||
|
"off_topic": "rematch_slot",
|
||||||
|
"gap": "bridge_or_gap_fill",
|
||||||
|
"large_gap": "bridge_or_gap_fill",
|
||||||
|
"roadmap_unfilled": "rematch_slot",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _action_for_finding(finding: Mapping[str, Any]) -> str:
|
||||||
|
issue = str(finding.get("issue") or finding.get("type") or "").strip().lower()
|
||||||
|
if finding.get("is_large_gap"):
|
||||||
|
return "bridge_or_gap_fill"
|
||||||
|
return _ACTION_BY_ISSUE.get(issue, "review")
|
||||||
|
|
||||||
|
|
||||||
|
def _hint_from_finding(finding: Mapping[str, Any], *, tier: str) -> Dict[str, Any]:
|
||||||
|
step_index = finding.get("step_index")
|
||||||
|
if step_index is None:
|
||||||
|
step_index = finding.get("major_step_index")
|
||||||
|
issue = str(finding.get("issue") or finding.get("type") or tier)
|
||||||
|
action = _action_for_finding(finding)
|
||||||
|
title = str(finding.get("title") or finding.get("removed_title") or "").strip()
|
||||||
|
reasons = finding.get("reasons") or []
|
||||||
|
reason = reasons[0] if reasons else str(finding.get("rationale") or finding.get("detail") or "")
|
||||||
|
|
||||||
|
hint: Dict[str, Any] = {
|
||||||
|
"tier": tier,
|
||||||
|
"action": action,
|
||||||
|
"issue": issue,
|
||||||
|
"step_index": step_index,
|
||||||
|
"title": title or None,
|
||||||
|
"reason": (reason or "")[:400] or None,
|
||||||
|
}
|
||||||
|
if finding.get("roadmap_learning_goal"):
|
||||||
|
hint["roadmap_learning_goal"] = finding.get("roadmap_learning_goal")
|
||||||
|
if finding.get("roadmap_major_step_index") is not None:
|
||||||
|
hint["roadmap_major_step_index"] = finding.get("roadmap_major_step_index")
|
||||||
|
return {k: v for k, v in hint.items() if v is not None and v != ""}
|
||||||
|
|
||||||
|
|
||||||
|
def derive_optimization_hints(
|
||||||
|
tiers: Sequence[Mapping[str, Any]],
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Aus QS-Stufen konkrete Optimierungsaktionen (ohne anfrage-spezifische Heuristiken)."""
|
||||||
|
hints: List[Dict[str, Any]] = []
|
||||||
|
seen: set[tuple] = set()
|
||||||
|
for tier in tiers:
|
||||||
|
tier_id = str(tier.get("id") or "")
|
||||||
|
for finding in tier.get("findings") or []:
|
||||||
|
if not isinstance(finding, dict):
|
||||||
|
continue
|
||||||
|
hint = _hint_from_finding(finding, tier=tier_id)
|
||||||
|
key = (
|
||||||
|
hint.get("tier"),
|
||||||
|
hint.get("action"),
|
||||||
|
hint.get("step_index"),
|
||||||
|
hint.get("issue"),
|
||||||
|
)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
hints.append(hint)
|
||||||
|
return hints[:24]
|
||||||
|
|
||||||
|
|
||||||
|
def run_multistage_path_qa(
|
||||||
|
*,
|
||||||
|
off_topic_steps: Sequence[Mapping[str, Any]],
|
||||||
|
stripped_off_topic: Sequence[Mapping[str, Any]],
|
||||||
|
gaps: Sequence[Mapping[str, Any]],
|
||||||
|
llm_qa: Optional[Mapping[str, Any]] = None,
|
||||||
|
llm_applied: bool = False,
|
||||||
|
roadmap_unfilled: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""Orchestriert QS-Stufen und leitet Optimierungspotenziale ab."""
|
||||||
|
tier1_findings: List[Dict[str, Any]] = []
|
||||||
|
for item in stripped_off_topic or off_topic_steps or []:
|
||||||
|
if isinstance(item, dict):
|
||||||
|
tier1_findings.append(dict(item))
|
||||||
|
|
||||||
|
tier2_findings: List[Dict[str, Any]] = [dict(g) for g in gaps if isinstance(g, dict)]
|
||||||
|
|
||||||
|
tier3_findings: List[Dict[str, Any]] = []
|
||||||
|
llm_recommendations: List[str] = []
|
||||||
|
if llm_applied and llm_qa:
|
||||||
|
q_score = llm_qa.get("quality_score")
|
||||||
|
tier3_findings.append(
|
||||||
|
{
|
||||||
|
"issue": "llm_assessment",
|
||||||
|
"quality_score": q_score,
|
||||||
|
"overall_ok": llm_qa.get("overall_ok"),
|
||||||
|
"detail": llm_qa.get("summary") or llm_qa.get("assessment"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
for raw in llm_qa.get("recommendations") or llm_qa.get("suggestions") or []:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if s:
|
||||||
|
llm_recommendations.append(s[:500])
|
||||||
|
|
||||||
|
unfilled = list(roadmap_unfilled or [])
|
||||||
|
if unfilled:
|
||||||
|
for item in unfilled:
|
||||||
|
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||||
|
idx, spec = item[0], item[1]
|
||||||
|
tier1_findings.append(
|
||||||
|
{
|
||||||
|
"issue": "roadmap_unfilled",
|
||||||
|
"step_index": int(idx),
|
||||||
|
"roadmap_major_step_index": getattr(spec, "major_step_index", idx),
|
||||||
|
"roadmap_learning_goal": getattr(spec, "learning_goal", None),
|
||||||
|
"reasons": ["Keine passende Übung für Roadmap-Stufe"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif isinstance(item, dict):
|
||||||
|
tier1_findings.append({**item, "issue": item.get("issue") or "roadmap_unfilled"})
|
||||||
|
|
||||||
|
tiers: List[Dict[str, Any]] = [
|
||||||
|
{
|
||||||
|
"id": "tier1_deterministic",
|
||||||
|
"label": "Deterministische Gates",
|
||||||
|
"finding_count": len(tier1_findings),
|
||||||
|
"findings": tier1_findings[:16],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "tier2_transitions",
|
||||||
|
"label": "Übergangs-Kohärenz",
|
||||||
|
"finding_count": len(tier2_findings),
|
||||||
|
"findings": tier2_findings[:12],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "tier3_llm_holistic",
|
||||||
|
"label": "LLM-Ganzpfad",
|
||||||
|
"finding_count": len(tier3_findings),
|
||||||
|
"findings": tier3_findings,
|
||||||
|
"recommendations": llm_recommendations[:8],
|
||||||
|
"applied": bool(llm_applied),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
optimization_hints = derive_optimization_hints(tiers)
|
||||||
|
for rec in llm_recommendations[:5]:
|
||||||
|
optimization_hints.append(
|
||||||
|
{
|
||||||
|
"tier": "tier3_llm_holistic",
|
||||||
|
"action": "review_roadmap",
|
||||||
|
"issue": "llm_recommendation",
|
||||||
|
"reason": rec,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"qa_tiers": tiers,
|
||||||
|
"optimization_hints": optimization_hints[:28],
|
||||||
|
"optimization_hint_count": len(optimization_hints),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"derive_optimization_hints",
|
||||||
|
"run_multistage_path_qa",
|
||||||
|
]
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
"""
|
||||||
|
Phase C: Stufen-Spec verfeinern nach stage_mismatch, dann Rematch.
|
||||||
|
|
||||||
|
Deterministisch — keine LLM-Ratelosigkeit. Schärft anti_patterns / success_criteria
|
||||||
|
aus QS-Finding, schließt abgelehnte Übung aus.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||||
|
|
||||||
|
from planning_exercise_semantics import (
|
||||||
|
is_trainer_stage_anti_marker,
|
||||||
|
merge_stage_exclude_phrases,
|
||||||
|
parse_stage_goal_constraints,
|
||||||
|
stage_refinement_criteria_from_learning_goal,
|
||||||
|
)
|
||||||
|
from planning_progression_roadmap import ProgressionRoadmapContext, StageSpecArtifact
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_major_index(
|
||||||
|
item: Mapping[str, Any],
|
||||||
|
stage_specs: Sequence[StageSpecArtifact],
|
||||||
|
) -> Optional[int]:
|
||||||
|
raw = item.get("roadmap_major_step_index")
|
||||||
|
if raw is not None:
|
||||||
|
return int(raw)
|
||||||
|
si = item.get("step_index")
|
||||||
|
if si is not None:
|
||||||
|
pos = int(si)
|
||||||
|
specs = list(stage_specs or [])
|
||||||
|
if 0 <= pos < len(specs):
|
||||||
|
return int(specs[pos].major_step_index)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def collect_refine_stage_targets(
|
||||||
|
*,
|
||||||
|
optimization_hints: Sequence[Mapping[str, Any]],
|
||||||
|
off_topic_steps: Sequence[Mapping[str, Any]],
|
||||||
|
stage_specs: Sequence[StageSpecArtifact],
|
||||||
|
) -> Dict[int, Mapping[str, Any]]:
|
||||||
|
"""Major-Step-Indizes mit stage_mismatch / refine_stage_spec + Quell-Finding."""
|
||||||
|
targets: Dict[int, Mapping[str, Any]] = {}
|
||||||
|
|
||||||
|
def _register(midx: int, source: Mapping[str, Any]) -> None:
|
||||||
|
if midx not in targets:
|
||||||
|
targets[int(midx)] = dict(source)
|
||||||
|
|
||||||
|
for hint in optimization_hints or []:
|
||||||
|
if not isinstance(hint, dict):
|
||||||
|
continue
|
||||||
|
if str(hint.get("action") or "") != "refine_stage_spec":
|
||||||
|
continue
|
||||||
|
midx = _resolve_major_index(hint, stage_specs)
|
||||||
|
if midx is not None:
|
||||||
|
_register(midx, hint)
|
||||||
|
|
||||||
|
for item in off_topic_steps or []:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
if str(item.get("issue") or "") != "stage_mismatch":
|
||||||
|
continue
|
||||||
|
midx = _resolve_major_index(item, stage_specs)
|
||||||
|
if midx is not None:
|
||||||
|
_register(midx, item)
|
||||||
|
|
||||||
|
return targets
|
||||||
|
|
||||||
|
|
||||||
|
def _append_unique_strings(dest: List[str], items: Sequence[str], *, limit: int = 14) -> List[str]:
|
||||||
|
out = list(dest or [])
|
||||||
|
for raw in items:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if not s or s in out:
|
||||||
|
continue
|
||||||
|
out.append(s[:200])
|
||||||
|
if len(out) >= limit:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _rejected_exercise_marker(title: str) -> str:
|
||||||
|
return f"keine Übung wie „{title[:120]}“"
|
||||||
|
|
||||||
|
|
||||||
|
def refine_stage_spec_artifact(
|
||||||
|
spec: StageSpecArtifact,
|
||||||
|
*,
|
||||||
|
finding: Mapping[str, Any],
|
||||||
|
goal_query: str = "",
|
||||||
|
semantic_brief: Optional[Any] = None,
|
||||||
|
path_anti_patterns: Optional[Sequence[str]] = None,
|
||||||
|
) -> Tuple[StageSpecArtifact, List[str]]:
|
||||||
|
"""
|
||||||
|
Schärft eine StageSpec aus QS-Finding. Returns (neue Spec, Änderungsliste).
|
||||||
|
|
||||||
|
Pfad-Ausschlüsse werden beim Match separat gemerged — nicht in stage_spec duplizieren.
|
||||||
|
"""
|
||||||
|
del goal_query, semantic_brief, path_anti_patterns
|
||||||
|
learning_goal = (
|
||||||
|
str(finding.get("roadmap_learning_goal") or spec.learning_goal or "").strip()
|
||||||
|
or spec.learning_goal
|
||||||
|
)
|
||||||
|
anti = [a for a in list(spec.anti_patterns or []) if not is_trainer_stage_anti_marker(a)]
|
||||||
|
success = list(spec.success_criteria or [])
|
||||||
|
changes: List[str] = []
|
||||||
|
|
||||||
|
rejected_title = str(finding.get("title") or "").strip()
|
||||||
|
if rejected_title:
|
||||||
|
marker = _rejected_exercise_marker(rejected_title)
|
||||||
|
if marker not in anti:
|
||||||
|
anti.append(marker)
|
||||||
|
changes.append(f"Ausschluss abgelehnter Übung: {rejected_title[:80]}")
|
||||||
|
|
||||||
|
goal_excludes = parse_stage_goal_constraints(learning_goal).exclude_phrases
|
||||||
|
for phrase in goal_excludes or []:
|
||||||
|
if phrase and phrase not in anti:
|
||||||
|
anti.append(phrase)
|
||||||
|
changes.append(f"Ausschluss aus Lernziel: {phrase[:60]}")
|
||||||
|
|
||||||
|
for phrase in stage_refinement_criteria_from_learning_goal(learning_goal):
|
||||||
|
crit = f"Bezug zu Stufen-Lernziel: {phrase[:100]}"
|
||||||
|
if crit not in success:
|
||||||
|
success.append(crit)
|
||||||
|
changes.append(f"Erfolgskriterium: {phrase[:60]}")
|
||||||
|
|
||||||
|
for raw in finding.get("reasons") or []:
|
||||||
|
r = str(raw or "").strip()
|
||||||
|
if len(r) < 8:
|
||||||
|
continue
|
||||||
|
if r == "Kern-Thema der Anfrage im Übungstext":
|
||||||
|
continue
|
||||||
|
crit = f"QS-Hinweis: {r[:120]}"
|
||||||
|
if crit not in success:
|
||||||
|
success.append(crit)
|
||||||
|
if len(changes) < 6:
|
||||||
|
changes.append(f"Kriterium aus QS: {r[:60]}")
|
||||||
|
if len(success) >= 8:
|
||||||
|
break
|
||||||
|
|
||||||
|
if not changes:
|
||||||
|
return spec, []
|
||||||
|
|
||||||
|
refined = StageSpecArtifact(
|
||||||
|
major_step_index=spec.major_step_index,
|
||||||
|
learning_goal=learning_goal or spec.learning_goal,
|
||||||
|
start_state=spec.start_state,
|
||||||
|
target_state=spec.target_state,
|
||||||
|
load_profile=list(spec.load_profile or []),
|
||||||
|
exercise_type=spec.exercise_type,
|
||||||
|
success_criteria=success[:8],
|
||||||
|
anti_patterns=merge_stage_exclude_phrases(learning_goal, anti)[:14],
|
||||||
|
)
|
||||||
|
return refined, changes
|
||||||
|
|
||||||
|
|
||||||
|
def apply_stage_spec_refinements(
|
||||||
|
roadmap_ctx: ProgressionRoadmapContext,
|
||||||
|
*,
|
||||||
|
optimization_hints: Sequence[Mapping[str, Any]],
|
||||||
|
off_topic_steps: Sequence[Mapping[str, Any]],
|
||||||
|
goal_query: str,
|
||||||
|
semantic_brief: Optional[Any] = None,
|
||||||
|
) -> Tuple[List[StageSpecArtifact], List[Dict[str, Any]]]:
|
||||||
|
"""
|
||||||
|
Wendet refine_stage_spec auf betroffene Slots an (mutiert stage_specs in ctx).
|
||||||
|
|
||||||
|
Returns: (stage_specs, refine_log)
|
||||||
|
"""
|
||||||
|
del goal_query, semantic_brief
|
||||||
|
stage_specs = list(roadmap_ctx.stage_specs or [])
|
||||||
|
if not stage_specs:
|
||||||
|
return stage_specs, []
|
||||||
|
|
||||||
|
targets = collect_refine_stage_targets(
|
||||||
|
optimization_hints=optimization_hints,
|
||||||
|
off_topic_steps=off_topic_steps,
|
||||||
|
stage_specs=stage_specs,
|
||||||
|
)
|
||||||
|
if not targets:
|
||||||
|
return stage_specs, []
|
||||||
|
|
||||||
|
spec_by_major = {int(s.major_step_index): s for s in stage_specs}
|
||||||
|
refine_log: List[Dict[str, Any]] = []
|
||||||
|
|
||||||
|
for midx in sorted(targets):
|
||||||
|
spec = spec_by_major.get(int(midx))
|
||||||
|
if spec is None:
|
||||||
|
continue
|
||||||
|
refined_spec, changes = refine_stage_spec_artifact(
|
||||||
|
spec,
|
||||||
|
finding=targets[midx],
|
||||||
|
)
|
||||||
|
if not changes:
|
||||||
|
continue
|
||||||
|
spec_by_major[int(midx)] = refined_spec
|
||||||
|
rejected_id = targets[midx].get("exercise_id")
|
||||||
|
refine_log.append(
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": int(midx),
|
||||||
|
"action": "refined",
|
||||||
|
"issue": "stage_mismatch",
|
||||||
|
"rejected_title": targets[midx].get("title"),
|
||||||
|
"rejected_exercise_id": int(rejected_id) if rejected_id else None,
|
||||||
|
"changes": changes[:6],
|
||||||
|
"reason": (changes[0] if changes else "refine_stage_spec")[:400],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if not refine_log:
|
||||||
|
return stage_specs, []
|
||||||
|
|
||||||
|
ordered = [spec_by_major[int(s.major_step_index)] for s in stage_specs]
|
||||||
|
roadmap_ctx.stage_specs = ordered
|
||||||
|
return ordered, refine_log
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"apply_stage_spec_refinements",
|
||||||
|
"collect_refine_stage_targets",
|
||||||
|
"refine_stage_spec_artifact",
|
||||||
|
]
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
"""
|
||||||
|
Auto-Rematch nach Pfad-QS — betroffene Roadmap-Slots erneut matchen (Phase A/B).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
||||||
|
|
||||||
|
from planning_progression_roadmap import ProgressionRoadmapContext, StageSpecArtifact
|
||||||
|
|
||||||
|
_UNFILLED_REMATCH_REASON = "Keine passende Übung für Roadmap-Stufe"
|
||||||
|
|
||||||
|
|
||||||
|
def _slot_priority_for_rematch(
|
||||||
|
body,
|
||||||
|
*,
|
||||||
|
major_idx: int,
|
||||||
|
old: Optional[Mapping[str, Any]],
|
||||||
|
rejected_by_major: Optional[Mapping[int, Set[int]]],
|
||||||
|
) -> Optional[int]:
|
||||||
|
"""Bestehende Slot-Zuordnung beim Rematch bevorzugen — außer explizit abgelehnt."""
|
||||||
|
priority_id: Optional[int] = None
|
||||||
|
if body is not None:
|
||||||
|
for raw in getattr(body, "slot_assignments", None) or []:
|
||||||
|
midx = getattr(raw, "roadmap_major_step_index", None)
|
||||||
|
if midx is None or int(midx) != int(major_idx):
|
||||||
|
continue
|
||||||
|
eid = getattr(raw, "exercise_id", None)
|
||||||
|
if eid is not None:
|
||||||
|
try:
|
||||||
|
priority_id = int(eid)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
priority_id = None
|
||||||
|
break
|
||||||
|
if priority_id is None and old and old.get("exercise_id") is not None:
|
||||||
|
try:
|
||||||
|
priority_id = int(old["exercise_id"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
priority_id = None
|
||||||
|
if priority_id is None or priority_id < 1:
|
||||||
|
return None
|
||||||
|
rejected = rejected_by_major.get(int(major_idx), set()) if rejected_by_major else set()
|
||||||
|
if priority_id in rejected:
|
||||||
|
return None
|
||||||
|
return priority_id
|
||||||
|
|
||||||
|
|
||||||
|
def collect_rematch_slot_indices(
|
||||||
|
*,
|
||||||
|
stripped_off_topic: Sequence[Mapping[str, Any]],
|
||||||
|
off_topic_steps: Sequence[Mapping[str, Any]],
|
||||||
|
optimization_hints: Sequence[Mapping[str, Any]],
|
||||||
|
stage_specs: Sequence[StageSpecArtifact],
|
||||||
|
roadmap_unfilled: Optional[Sequence[Any]] = None,
|
||||||
|
) -> Tuple[Set[int], Dict[int, str]]:
|
||||||
|
"""Major-Step-Indizes für rematch_slot + Begründung pro Slot."""
|
||||||
|
spec_by_pos = list(stage_specs)
|
||||||
|
indices: Set[int] = set()
|
||||||
|
reasons: Dict[int, str] = {}
|
||||||
|
|
||||||
|
def _register(midx: int, reason: str) -> None:
|
||||||
|
indices.add(int(midx))
|
||||||
|
if midx not in reasons and reason:
|
||||||
|
reasons[int(midx)] = reason[:400]
|
||||||
|
|
||||||
|
def _resolve_major(item: Mapping[str, Any]) -> Optional[int]:
|
||||||
|
raw = item.get("roadmap_major_step_index")
|
||||||
|
if raw is not None:
|
||||||
|
return int(raw)
|
||||||
|
si = item.get("step_index")
|
||||||
|
if si is not None:
|
||||||
|
pos = int(si)
|
||||||
|
if 0 <= pos < len(spec_by_pos):
|
||||||
|
return int(spec_by_pos[pos].major_step_index)
|
||||||
|
return None
|
||||||
|
|
||||||
|
for item in stripped_off_topic or []:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
midx = _resolve_major(item)
|
||||||
|
if midx is not None:
|
||||||
|
issue = str(item.get("issue") or "stripped_off_topic")
|
||||||
|
r = (item.get("reasons") or [issue])[0] if item.get("reasons") else issue
|
||||||
|
_register(midx, str(r))
|
||||||
|
|
||||||
|
for item in off_topic_steps or []:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
midx = _resolve_major(item)
|
||||||
|
if midx is None:
|
||||||
|
continue
|
||||||
|
issue = str(item.get("issue") or "off_topic")
|
||||||
|
r = (item.get("reasons") or [issue])[0] if item.get("reasons") else issue
|
||||||
|
_register(midx, str(r))
|
||||||
|
|
||||||
|
for hint in optimization_hints or []:
|
||||||
|
if not isinstance(hint, dict):
|
||||||
|
continue
|
||||||
|
if str(hint.get("action") or "") != "rematch_slot":
|
||||||
|
continue
|
||||||
|
midx = _resolve_major(hint)
|
||||||
|
if midx is not None:
|
||||||
|
_register(midx, str(hint.get("reason") or hint.get("issue") or "rematch_slot"))
|
||||||
|
|
||||||
|
for item in roadmap_unfilled or []:
|
||||||
|
if isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||||
|
idx, spec = item[0], item[1]
|
||||||
|
midx = getattr(spec, "major_step_index", idx)
|
||||||
|
_register(int(midx), _UNFILLED_REMATCH_REASON)
|
||||||
|
elif isinstance(item, dict):
|
||||||
|
midx = _resolve_major(item)
|
||||||
|
if midx is not None:
|
||||||
|
issue = str(item.get("issue") or "roadmap_unfilled")
|
||||||
|
r = (item.get("reasons") or [issue])[0] if item.get("reasons") else issue
|
||||||
|
_register(midx, str(r))
|
||||||
|
|
||||||
|
return indices, reasons
|
||||||
|
|
||||||
|
|
||||||
|
def apply_rematch_catalog_guard(
|
||||||
|
slot_indices: Set[int],
|
||||||
|
rematch_reasons: Mapping[int, str],
|
||||||
|
*,
|
||||||
|
rematch_guard: Optional[str],
|
||||||
|
) -> Set[int]:
|
||||||
|
"""
|
||||||
|
Bei gesetztem rematch_guard (Katalog-Slot): kein Auto-Rematch nur wegen leerer Roadmap-Stufe.
|
||||||
|
Off-Topic, explizite QS-Hinweise und Stufen-Verfeinerung bleiben aktiv.
|
||||||
|
"""
|
||||||
|
if not (rematch_guard or "").strip():
|
||||||
|
return set(slot_indices)
|
||||||
|
return {
|
||||||
|
idx
|
||||||
|
for idx in slot_indices
|
||||||
|
if str(rematch_reasons.get(idx) or "").strip() != _UNFILLED_REMATCH_REASON
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def filter_rematch_slot_indices(
|
||||||
|
steps: Sequence[Mapping[str, Any]],
|
||||||
|
slot_indices: Set[int],
|
||||||
|
*,
|
||||||
|
stripped_off_topic: Sequence[Mapping[str, Any]],
|
||||||
|
off_topic_steps: Sequence[Mapping[str, Any]],
|
||||||
|
) -> Set[int]:
|
||||||
|
"""Trainer-Zuordnungen (slot_best_match) nicht rematchen, außer Slot ist explizit beanstandet."""
|
||||||
|
flagged: Set[int] = set()
|
||||||
|
for item in list(stripped_off_topic or []) + list(off_topic_steps or []):
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
midx = item.get("roadmap_major_step_index")
|
||||||
|
if midx is not None:
|
||||||
|
try:
|
||||||
|
flagged.add(int(midx))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
preserved: Set[int] = set()
|
||||||
|
for raw in steps or []:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
midx = raw.get("roadmap_major_step_index")
|
||||||
|
if midx is None:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
major_idx = int(midx)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if raw.get("roadmap_match_source") == "slot_best_match" or raw.get("slot_status") == "preserved":
|
||||||
|
if major_idx not in flagged:
|
||||||
|
preserved.add(major_idx)
|
||||||
|
|
||||||
|
return {idx for idx in slot_indices if idx not in preserved}
|
||||||
|
|
||||||
|
|
||||||
|
def _context_before_major(
|
||||||
|
steps_by_major: Mapping[int, Mapping[str, Any]],
|
||||||
|
target_major: int,
|
||||||
|
) -> Tuple[List[int], Optional[int], Optional[int]]:
|
||||||
|
planned: List[int] = []
|
||||||
|
anchor: Optional[int] = None
|
||||||
|
anchor_vid: Optional[int] = None
|
||||||
|
for midx in sorted(steps_by_major):
|
||||||
|
if midx >= target_major:
|
||||||
|
break
|
||||||
|
step = steps_by_major[midx]
|
||||||
|
eid = step.get("exercise_id")
|
||||||
|
if eid is not None:
|
||||||
|
planned.append(int(eid))
|
||||||
|
anchor = int(eid)
|
||||||
|
vid = step.get("variant_id")
|
||||||
|
anchor_vid = int(vid) if vid is not None else None
|
||||||
|
return planned, anchor, anchor_vid
|
||||||
|
|
||||||
|
|
||||||
|
def rematch_roadmap_slots(
|
||||||
|
cur,
|
||||||
|
*,
|
||||||
|
tenant,
|
||||||
|
body,
|
||||||
|
goal_query: str,
|
||||||
|
max_steps: int,
|
||||||
|
semantic_brief,
|
||||||
|
path_target_profile,
|
||||||
|
path_intent: str,
|
||||||
|
roadmap_ctx: ProgressionRoadmapContext,
|
||||||
|
steps: Sequence[Mapping[str, Any]],
|
||||||
|
slot_indices: Set[int],
|
||||||
|
rematch_reasons: Mapping[int, str],
|
||||||
|
match_slot_fn,
|
||||||
|
rejected_by_major: Optional[Mapping[int, Set[int]]] = None,
|
||||||
|
slot_assignment_history: Optional[Mapping[int, Set[int]]] = None,
|
||||||
|
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Tuple[int, StageSpecArtifact]]]:
|
||||||
|
"""
|
||||||
|
Ersetzt nur betroffene Slots; andere Schritte und used-Set bleiben konsistent.
|
||||||
|
|
||||||
|
match_slot_fn: _match_roadmap_slot aus path_builder (Injection gegen Zirkularität).
|
||||||
|
"""
|
||||||
|
stage_specs = list(roadmap_ctx.stage_specs or [])[:max_steps]
|
||||||
|
if not stage_specs or not slot_indices:
|
||||||
|
return list(steps), [], []
|
||||||
|
|
||||||
|
spec_by_major = {int(s.major_step_index): s for s in stage_specs}
|
||||||
|
steps_by_major: Dict[int, Dict[str, Any]] = {}
|
||||||
|
for raw in steps:
|
||||||
|
step = dict(raw)
|
||||||
|
midx = step.get("roadmap_major_step_index")
|
||||||
|
if midx is not None:
|
||||||
|
steps_by_major[int(midx)] = step
|
||||||
|
|
||||||
|
rematch_log: List[Dict[str, Any]] = []
|
||||||
|
new_unfilled: List[Tuple[int, StageSpecArtifact]] = []
|
||||||
|
|
||||||
|
for major_idx in sorted(slot_indices):
|
||||||
|
stage_spec = spec_by_major.get(int(major_idx))
|
||||||
|
if stage_spec is None:
|
||||||
|
continue
|
||||||
|
step_index = next(
|
||||||
|
(i for i, sp in enumerate(stage_specs) if int(sp.major_step_index) == int(major_idx)),
|
||||||
|
major_idx,
|
||||||
|
)
|
||||||
|
old = steps_by_major.pop(int(major_idx), None)
|
||||||
|
used = {
|
||||||
|
int(s["exercise_id"])
|
||||||
|
for m, s in steps_by_major.items()
|
||||||
|
if s.get("exercise_id") is not None
|
||||||
|
}
|
||||||
|
if old and old.get("exercise_id") is not None:
|
||||||
|
used.add(int(old["exercise_id"]))
|
||||||
|
for rejected_id in rejected_by_major.get(int(major_idx), set()) if rejected_by_major else set():
|
||||||
|
if rejected_id > 0:
|
||||||
|
used.add(int(rejected_id))
|
||||||
|
planned_ids, anchor_id, anchor_variant_id = _context_before_major(
|
||||||
|
steps_by_major, int(major_idx)
|
||||||
|
)
|
||||||
|
|
||||||
|
new_step, unfilled_spec = match_slot_fn(
|
||||||
|
cur,
|
||||||
|
tenant=tenant,
|
||||||
|
body=body,
|
||||||
|
goal_query=goal_query,
|
||||||
|
max_steps=max_steps,
|
||||||
|
semantic_brief=semantic_brief,
|
||||||
|
path_target_profile=path_target_profile,
|
||||||
|
path_intent=path_intent,
|
||||||
|
roadmap_ctx=roadmap_ctx,
|
||||||
|
stage_spec=stage_spec,
|
||||||
|
step_index=step_index,
|
||||||
|
stage_count=len(stage_specs),
|
||||||
|
planned_ids=planned_ids,
|
||||||
|
anchor_id=anchor_id,
|
||||||
|
anchor_variant_id=anchor_variant_id,
|
||||||
|
used=used,
|
||||||
|
slot_priority_exercise_id=_slot_priority_for_rematch(
|
||||||
|
body,
|
||||||
|
major_idx=major_idx,
|
||||||
|
old=old,
|
||||||
|
rejected_by_major=rejected_by_major,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
reason = str(rematch_reasons.get(int(major_idx)) or "rematch_slot")
|
||||||
|
if new_step:
|
||||||
|
try:
|
||||||
|
new_eid = int(new_step.get("exercise_id") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
new_eid = 0
|
||||||
|
rejected = (
|
||||||
|
rejected_by_major.get(int(major_idx), set()) if rejected_by_major else set()
|
||||||
|
)
|
||||||
|
if new_eid > 0 and new_eid in rejected:
|
||||||
|
new_step = None
|
||||||
|
if new_step:
|
||||||
|
steps_by_major[int(major_idx)] = new_step
|
||||||
|
rematch_log.append(
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": int(major_idx),
|
||||||
|
"action": "replaced",
|
||||||
|
"reason": reason,
|
||||||
|
"replaced_exercise_id": old.get("exercise_id") if old else None,
|
||||||
|
"replaced_title": old.get("title") if old else None,
|
||||||
|
"new_exercise_id": new_step.get("exercise_id"),
|
||||||
|
"new_title": new_step.get("title"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
if old and old.get("exercise_id") is not None:
|
||||||
|
try:
|
||||||
|
old_eid = int(old["exercise_id"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
old_eid = 0
|
||||||
|
rejected = (
|
||||||
|
rejected_by_major.get(int(major_idx), set()) if rejected_by_major else set()
|
||||||
|
)
|
||||||
|
if old_eid > 0 and old_eid not in rejected:
|
||||||
|
steps_by_major[int(major_idx)] = dict(old)
|
||||||
|
rematch_log.append(
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": int(major_idx),
|
||||||
|
"action": "restored",
|
||||||
|
"reason": reason,
|
||||||
|
"restored_exercise_id": old_eid,
|
||||||
|
"restored_title": old.get("title"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
goal = (stage_spec.learning_goal or "").strip()
|
||||||
|
major = None
|
||||||
|
if roadmap_ctx.roadmap:
|
||||||
|
major = next(
|
||||||
|
(m for m in roadmap_ctx.roadmap.major_steps if int(m.index) == int(major_idx)),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
steps_by_major[int(major_idx)] = {
|
||||||
|
"exercise_id": None,
|
||||||
|
"variant_id": None,
|
||||||
|
"title": goal or f"Slot {major_idx + 1}",
|
||||||
|
"is_ai_proposal": False,
|
||||||
|
"roadmap_major_step_index": int(major_idx),
|
||||||
|
"roadmap_phase": major.phase if major else None,
|
||||||
|
"roadmap_learning_goal": goal or None,
|
||||||
|
"roadmap_match_source": "unfilled",
|
||||||
|
"slot_status": "unfilled",
|
||||||
|
"reasons": ["Keine passende Übung für Roadmap-Stufe"],
|
||||||
|
}
|
||||||
|
if unfilled_spec is not None:
|
||||||
|
new_unfilled.append((step_index, unfilled_spec))
|
||||||
|
elif stage_spec is not None:
|
||||||
|
new_unfilled.append((step_index, stage_spec))
|
||||||
|
rematch_log.append(
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": int(major_idx),
|
||||||
|
"action": "rematch_unfilled",
|
||||||
|
"reason": reason,
|
||||||
|
"replaced_exercise_id": old.get("exercise_id") if old else None,
|
||||||
|
"replaced_title": old.get("title") if old else None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
ordered: List[Dict[str, Any]] = []
|
||||||
|
for spec in sorted(stage_specs, key=lambda s: s.major_step_index):
|
||||||
|
midx = int(spec.major_step_index)
|
||||||
|
if midx in steps_by_major:
|
||||||
|
ordered.append(steps_by_major[midx])
|
||||||
|
|
||||||
|
return ordered, rematch_log, new_unfilled
|
||||||
|
|
||||||
|
|
||||||
|
def prune_stripped_after_rematch(
|
||||||
|
stripped_off_topic: Sequence[Mapping[str, Any]],
|
||||||
|
rematch_log: Sequence[Mapping[str, Any]],
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Entfernt aus stripped_off_topic Slots, die per Rematch ersetzt wurden."""
|
||||||
|
replaced: Set[int] = set()
|
||||||
|
for entry in rematch_log or []:
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
continue
|
||||||
|
if str(entry.get("action") or "") != "replaced":
|
||||||
|
continue
|
||||||
|
midx = entry.get("roadmap_major_step_index")
|
||||||
|
if midx is not None:
|
||||||
|
replaced.add(int(midx))
|
||||||
|
if not replaced:
|
||||||
|
return list(stripped_off_topic or [])
|
||||||
|
out: List[Dict[str, Any]] = []
|
||||||
|
for item in stripped_off_topic or []:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
midx = item.get("roadmap_major_step_index")
|
||||||
|
if midx is not None and int(midx) in replaced:
|
||||||
|
continue
|
||||||
|
out.append(dict(item))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"apply_rematch_catalog_guard",
|
||||||
|
"collect_rematch_slot_indices",
|
||||||
|
"filter_rematch_slot_indices",
|
||||||
|
"prune_stripped_after_rematch",
|
||||||
|
"rematch_roadmap_slots",
|
||||||
|
]
|
||||||
@@ -18,6 +18,8 @@ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
|||||||
from pydantic import BaseModel, Field, ValidationError
|
from pydantic import BaseModel, Field, ValidationError
|
||||||
|
|
||||||
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
|
from ai_prompt_runtime import AiPromptUnavailableError, load_and_render_ai_prompt
|
||||||
|
from planning_catalog_context import ProgressionPlanningCatalogContext
|
||||||
|
from planning_prompt_variables import merge_planning_prompt_variables
|
||||||
from openrouter_chat import (
|
from openrouter_chat import (
|
||||||
effective_openrouter_model_for_prompt_row,
|
effective_openrouter_model_for_prompt_row,
|
||||||
normalize_openrouter_env,
|
normalize_openrouter_env,
|
||||||
@@ -104,6 +106,10 @@ class RoadmapArtifact(BaseModel):
|
|||||||
class StageSpecArtifact(BaseModel):
|
class StageSpecArtifact(BaseModel):
|
||||||
major_step_index: int = Field(ge=0)
|
major_step_index: int = Field(ge=0)
|
||||||
learning_goal: str = ""
|
learning_goal: str = ""
|
||||||
|
"""Soll-Start dieser Stufe (= Zielzustand der vorherigen Stufe / Pfad-Start)."""
|
||||||
|
start_state: str = ""
|
||||||
|
"""Zielzustand dieser Stufe (= Soll für den nächsten Schritt)."""
|
||||||
|
target_state: str = ""
|
||||||
load_profile: List[str] = Field(default_factory=list)
|
load_profile: List[str] = Field(default_factory=list)
|
||||||
exercise_type: str = ""
|
exercise_type: str = ""
|
||||||
success_criteria: List[str] = Field(default_factory=list)
|
success_criteria: List[str] = Field(default_factory=list)
|
||||||
@@ -186,12 +192,20 @@ def _run_prompt_json(
|
|||||||
cur,
|
cur,
|
||||||
slug: str,
|
slug: str,
|
||||||
variables: Dict[str, str],
|
variables: Dict[str, str],
|
||||||
|
*,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Optional[Dict[str, Any]]:
|
) -> Optional[Dict[str, Any]]:
|
||||||
api_key, _ = normalize_openrouter_env()
|
api_key, _ = normalize_openrouter_env()
|
||||||
if not api_key or cur is None:
|
if not api_key or cur is None:
|
||||||
return None
|
return None
|
||||||
|
merged = merge_planning_prompt_variables(
|
||||||
|
cur,
|
||||||
|
variables,
|
||||||
|
catalog=catalog,
|
||||||
|
slug=slug,
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
prow, rendered = load_and_render_ai_prompt(cur, slug, variables)
|
prow, rendered = load_and_render_ai_prompt(cur, slug, merged)
|
||||||
model = effective_openrouter_model_for_prompt_row(prow)
|
model = effective_openrouter_model_for_prompt_row(prow)
|
||||||
raw = openrouter_chat_completion(api_key=api_key, model=model, user_content=rendered.text)
|
raw = openrouter_chat_completion(api_key=api_key, model=model, user_content=rendered.text)
|
||||||
return _extract_json_object(raw)
|
return _extract_json_object(raw)
|
||||||
@@ -208,6 +222,7 @@ def try_llm_start_target_extract(
|
|||||||
goal_query: str,
|
goal_query: str,
|
||||||
brief: PlanningSemanticBrief,
|
brief: PlanningSemanticBrief,
|
||||||
user_notes: str = "",
|
user_notes: str = "",
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Tuple[Optional[StartTargetExtractArtifact], bool]:
|
) -> Tuple[Optional[StartTargetExtractArtifact], bool]:
|
||||||
obj = _run_prompt_json(
|
obj = _run_prompt_json(
|
||||||
cur,
|
cur,
|
||||||
@@ -217,6 +232,7 @@ def try_llm_start_target_extract(
|
|||||||
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
|
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
|
||||||
"user_notes": (user_notes or "").strip(),
|
"user_notes": (user_notes or "").strip(),
|
||||||
},
|
},
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
if not obj:
|
if not obj:
|
||||||
return None, False
|
return None, False
|
||||||
@@ -232,6 +248,7 @@ def try_llm_goal_analysis(
|
|||||||
*,
|
*,
|
||||||
goal_query: str,
|
goal_query: str,
|
||||||
brief: PlanningSemanticBrief,
|
brief: PlanningSemanticBrief,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Tuple[Optional[GoalAnalysisArtifact], bool]:
|
) -> Tuple[Optional[GoalAnalysisArtifact], bool]:
|
||||||
obj = _run_prompt_json(
|
obj = _run_prompt_json(
|
||||||
cur,
|
cur,
|
||||||
@@ -240,6 +257,7 @@ def try_llm_goal_analysis(
|
|||||||
"goal_query": goal_query or "",
|
"goal_query": goal_query or "",
|
||||||
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
|
"semantic_brief_json": json.dumps(brief_to_summary_dict(brief), ensure_ascii=False),
|
||||||
},
|
},
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
if not obj:
|
if not obj:
|
||||||
return None, False
|
return None, False
|
||||||
@@ -257,6 +275,7 @@ def try_llm_roadmap(
|
|||||||
brief: PlanningSemanticBrief,
|
brief: PlanningSemanticBrief,
|
||||||
goal_analysis: GoalAnalysisArtifact,
|
goal_analysis: GoalAnalysisArtifact,
|
||||||
max_steps: int,
|
max_steps: int,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Tuple[Optional[RoadmapArtifact], bool]:
|
) -> Tuple[Optional[RoadmapArtifact], bool]:
|
||||||
obj = _run_prompt_json(
|
obj = _run_prompt_json(
|
||||||
cur,
|
cur,
|
||||||
@@ -267,6 +286,7 @@ def try_llm_roadmap(
|
|||||||
"goal_analysis_json": json.dumps(goal_analysis.model_dump(), ensure_ascii=False),
|
"goal_analysis_json": json.dumps(goal_analysis.model_dump(), ensure_ascii=False),
|
||||||
"max_steps": str(int(max_steps)),
|
"max_steps": str(int(max_steps)),
|
||||||
},
|
},
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
if not obj:
|
if not obj:
|
||||||
return None, False
|
return None, False
|
||||||
@@ -298,6 +318,9 @@ def try_llm_stage_specs(
|
|||||||
goal_query: str,
|
goal_query: str,
|
||||||
goal_analysis: GoalAnalysisArtifact,
|
goal_analysis: GoalAnalysisArtifact,
|
||||||
major_steps: Sequence[MajorStep],
|
major_steps: Sequence[MajorStep],
|
||||||
|
intent_context: Optional[Mapping[str, Any]] = None,
|
||||||
|
semantic_brief: Optional[PlanningSemanticBrief] = None,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Tuple[Optional[List[StageSpecArtifact]], bool]:
|
) -> Tuple[Optional[List[StageSpecArtifact]], bool]:
|
||||||
obj = _run_prompt_json(
|
obj = _run_prompt_json(
|
||||||
cur,
|
cur,
|
||||||
@@ -306,7 +329,13 @@ def try_llm_stage_specs(
|
|||||||
"goal_query": goal_query or "",
|
"goal_query": goal_query or "",
|
||||||
"goal_analysis_json": json.dumps(goal_analysis.model_dump(), ensure_ascii=False),
|
"goal_analysis_json": json.dumps(goal_analysis.model_dump(), ensure_ascii=False),
|
||||||
"major_steps_json": json.dumps([m.model_dump() for m in major_steps], ensure_ascii=False),
|
"major_steps_json": json.dumps([m.model_dump() for m in major_steps], ensure_ascii=False),
|
||||||
|
"intent_context_json": json.dumps(dict(intent_context or {}), ensure_ascii=False),
|
||||||
|
"semantic_brief_json": json.dumps(
|
||||||
|
brief_to_summary_dict(semantic_brief) if semantic_brief else {},
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
},
|
},
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
if not obj:
|
if not obj:
|
||||||
return None, False
|
return None, False
|
||||||
@@ -369,6 +398,7 @@ def resolve_roadmap_structured_input(
|
|||||||
brief: PlanningSemanticBrief,
|
brief: PlanningSemanticBrief,
|
||||||
cur=None,
|
cur=None,
|
||||||
include_llm: bool = False,
|
include_llm: bool = False,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> Tuple[RoadmapStructuredInput, StartTargetResolveMeta, Optional[StartTargetExtractArtifact]]:
|
) -> Tuple[RoadmapStructuredInput, StartTargetResolveMeta, Optional[StartTargetExtractArtifact]]:
|
||||||
"""Priorität je Feld: Trainer-Eingabe > LLM-Extraktion > Regex (von … bis …)."""
|
"""Priorität je Feld: Trainer-Eingabe > LLM-Extraktion > Regex (von … bis …)."""
|
||||||
user = structured or RoadmapStructuredInput()
|
user = structured or RoadmapStructuredInput()
|
||||||
@@ -384,6 +414,7 @@ def resolve_roadmap_structured_input(
|
|||||||
goal_query=goal_query,
|
goal_query=goal_query,
|
||||||
brief=brief,
|
brief=brief,
|
||||||
user_notes=user_notes,
|
user_notes=user_notes,
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
|
|
||||||
parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query)
|
parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query)
|
||||||
@@ -522,9 +553,14 @@ def build_goal_analysis(
|
|||||||
if notes.strip():
|
if notes.strip():
|
||||||
criteria.append(f"Berücksichtigung: {notes.strip()[:200]}")
|
criteria.append(f"Berücksichtigung: {notes.strip()[:200]}")
|
||||||
|
|
||||||
|
from planning_intent_context import extract_explicit_exclusions
|
||||||
|
|
||||||
constraints: Dict[str, Any] = {"partner_required": False, "group_analysis": False}
|
constraints: Dict[str, Any] = {"partner_required": False, "group_analysis": False}
|
||||||
if notes.strip():
|
if notes.strip():
|
||||||
constraints["trainer_notes"] = notes.strip()[:500]
|
constraints["trainer_notes"] = notes.strip()[:500]
|
||||||
|
excluded = extract_explicit_exclusions(goal_query, notes or None)
|
||||||
|
if excluded:
|
||||||
|
constraints["excluded_themes"] = excluded
|
||||||
|
|
||||||
return GoalAnalysisArtifact(
|
return GoalAnalysisArtifact(
|
||||||
primary_topic=topic,
|
primary_topic=topic,
|
||||||
@@ -840,19 +876,31 @@ def build_roadmap_unfilled_gap_specs(
|
|||||||
"roadmap_major_step_index": stage_spec.major_step_index,
|
"roadmap_major_step_index": stage_spec.major_step_index,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return specs[:5]
|
return specs[:12]
|
||||||
|
|
||||||
|
|
||||||
def build_stage_specs(
|
def build_stage_specs(
|
||||||
major_steps: Sequence[MajorStep],
|
major_steps: Sequence[MajorStep],
|
||||||
*,
|
*,
|
||||||
goal_analysis: GoalAnalysisArtifact,
|
goal_analysis: GoalAnalysisArtifact,
|
||||||
|
goal_query: str = "",
|
||||||
|
semantic_brief: Optional[PlanningSemanticBrief] = None,
|
||||||
) -> List[StageSpecArtifact]:
|
) -> List[StageSpecArtifact]:
|
||||||
"""Phase C — Stufenspezifikation je Major Step (heuristisch)."""
|
"""Phase C — Stufenspezifikation je Major Step (heuristisch)."""
|
||||||
|
from planning_exercise_semantics import resolve_path_anti_patterns
|
||||||
|
|
||||||
topic = goal_analysis.primary_topic or "Technik"
|
topic = goal_analysis.primary_topic or "Technik"
|
||||||
|
path_anti = resolve_path_anti_patterns(goal_query, semantic_brief=semantic_brief)
|
||||||
specs: List[StageSpecArtifact] = []
|
specs: List[StageSpecArtifact] = []
|
||||||
for step in major_steps:
|
for step in major_steps:
|
||||||
phase = (step.phase or "vertiefung").lower()
|
phase = (step.phase or "vertiefung").lower()
|
||||||
|
anti = [
|
||||||
|
"reine Kraftübung ohne Technikbezug",
|
||||||
|
f"andere Technik als {topic}" if topic else "themenfremde Übung",
|
||||||
|
]
|
||||||
|
for item in path_anti:
|
||||||
|
if item not in anti:
|
||||||
|
anti.append(item)
|
||||||
specs.append(
|
specs.append(
|
||||||
StageSpecArtifact(
|
StageSpecArtifact(
|
||||||
major_step_index=step.index,
|
major_step_index=step.index,
|
||||||
@@ -863,10 +911,7 @@ def build_stage_specs(
|
|||||||
f"Bezug zu {topic}",
|
f"Bezug zu {topic}",
|
||||||
f"Phase {phase} erkennbar im Übungsziel",
|
f"Phase {phase} erkennbar im Übungsziel",
|
||||||
],
|
],
|
||||||
anti_patterns=[
|
anti_patterns=anti[:14],
|
||||||
"reine Kraftübung ohne Technikbezug",
|
|
||||||
f"andere Technik als {topic}" if topic else "themenfremde Übung",
|
|
||||||
],
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return specs
|
return specs
|
||||||
@@ -920,6 +965,8 @@ def roadmap_context_from_override(
|
|||||||
StageSpecArtifact(
|
StageSpecArtifact(
|
||||||
major_step_index=i,
|
major_step_index=i,
|
||||||
learning_goal=(spec.learning_goal or majors[i].learning_goal).strip(),
|
learning_goal=(spec.learning_goal or majors[i].learning_goal).strip(),
|
||||||
|
start_state=(spec.start_state or "").strip(),
|
||||||
|
target_state=(spec.target_state or "").strip(),
|
||||||
load_profile=list(spec.load_profile or []),
|
load_profile=list(spec.load_profile or []),
|
||||||
exercise_type=(spec.exercise_type or "").strip(),
|
exercise_type=(spec.exercise_type or "").strip(),
|
||||||
success_criteria=list(spec.success_criteria or []),
|
success_criteria=list(spec.success_criteria or []),
|
||||||
@@ -927,19 +974,81 @@ def roadmap_context_from_override(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
if not all(s.exercise_type for s in stage_specs):
|
if not all(s.exercise_type for s in stage_specs):
|
||||||
rebuilt = build_stage_specs(majors, goal_analysis=goal_analysis)
|
rebuilt = build_stage_specs(
|
||||||
|
majors,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
goal_query=goal_query.strip(),
|
||||||
|
semantic_brief=semantic_brief,
|
||||||
|
)
|
||||||
for i, spec in enumerate(stage_specs):
|
for i, spec in enumerate(stage_specs):
|
||||||
if not spec.exercise_type:
|
if not spec.exercise_type:
|
||||||
spec.exercise_type = rebuilt[i].exercise_type
|
spec.exercise_type = rebuilt[i].exercise_type
|
||||||
if not spec.load_profile:
|
if not spec.load_profile:
|
||||||
spec.load_profile = list(rebuilt[i].load_profile)
|
spec.load_profile = list(rebuilt[i].load_profile)
|
||||||
else:
|
else:
|
||||||
stage_specs = build_stage_specs(majors, goal_analysis=goal_analysis)
|
stage_specs = build_stage_specs(
|
||||||
|
majors,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
goal_query=goal_query.strip(),
|
||||||
|
semantic_brief=semantic_brief,
|
||||||
|
)
|
||||||
|
|
||||||
|
from planning_exercise_semantics import enrich_brief_with_path_constraints
|
||||||
|
from planning_intent_context import (
|
||||||
|
build_planning_intent_context,
|
||||||
|
finalize_stage_specs_with_intent,
|
||||||
|
)
|
||||||
|
|
||||||
|
enriched_brief = enrich_brief_with_path_constraints(
|
||||||
|
semantic_brief,
|
||||||
|
goal_query.strip(),
|
||||||
|
extra_context=_merge_roadmap_notes(
|
||||||
|
structured.roadmap_notes if structured else None,
|
||||||
|
structured.start_situation if structured else None,
|
||||||
|
structured.target_state if structured else None,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
intent = build_planning_intent_context(
|
||||||
|
goal_query.strip(),
|
||||||
|
semantic_brief=enriched_brief,
|
||||||
|
goal_analysis=goal_analysis.model_dump(),
|
||||||
|
extra_context=_merge_roadmap_notes(
|
||||||
|
structured.roadmap_notes if structured else None,
|
||||||
|
structured.start_situation if structured else None,
|
||||||
|
structured.target_state if structured else None,
|
||||||
|
),
|
||||||
|
primary_topic=goal_analysis.primary_topic,
|
||||||
|
)
|
||||||
|
stage_specs = finalize_stage_specs_with_intent(
|
||||||
|
stage_specs,
|
||||||
|
majors,
|
||||||
|
intent=intent,
|
||||||
|
fallback_specs=build_stage_specs(
|
||||||
|
majors,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
goal_query=goal_query.strip(),
|
||||||
|
semantic_brief=enriched_brief,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
from planning_stage_context import derive_stage_specs_transition_states, resolve_path_start_target
|
||||||
|
|
||||||
|
path_start, path_target = resolve_path_start_target(
|
||||||
|
structured=structured,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
)
|
||||||
|
stage_specs = derive_stage_specs_transition_states(
|
||||||
|
stage_specs,
|
||||||
|
majors,
|
||||||
|
path_start=path_start,
|
||||||
|
path_target=path_target,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
)
|
||||||
|
|
||||||
return ProgressionRoadmapContext(
|
return ProgressionRoadmapContext(
|
||||||
goal_query=goal_query.strip(),
|
goal_query=goal_query.strip(),
|
||||||
max_steps=effective_max,
|
max_steps=effective_max,
|
||||||
semantic_brief=brief_to_summary_dict(semantic_brief),
|
semantic_brief=brief_to_summary_dict(semantic_brief),
|
||||||
|
resolved_structured=structured,
|
||||||
goal_analysis=goal_analysis,
|
goal_analysis=goal_analysis,
|
||||||
roadmap=RoadmapArtifact(major_steps=majors),
|
roadmap=RoadmapArtifact(major_steps=majors),
|
||||||
stage_specs=stage_specs,
|
stage_specs=stage_specs,
|
||||||
@@ -979,6 +1088,7 @@ def run_start_target_resolve_only(
|
|||||||
cur=None,
|
cur=None,
|
||||||
include_llm_start_target: bool = True,
|
include_llm_start_target: bool = True,
|
||||||
structured: Optional[RoadmapStructuredInput] = None,
|
structured: Optional[RoadmapStructuredInput] = None,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> ProgressionRoadmapContext:
|
) -> ProgressionRoadmapContext:
|
||||||
"""Nur Start/Ziel/Ergänzungen auflösen — ohne Roadmap-Stufen (Review vor Major Steps)."""
|
"""Nur Start/Ziel/Ergänzungen auflösen — ohne Roadmap-Stufen (Review vor Major Steps)."""
|
||||||
brief = semantic_brief or build_semantic_brief(goal_query)
|
brief = semantic_brief or build_semantic_brief(goal_query)
|
||||||
@@ -988,6 +1098,7 @@ def run_start_target_resolve_only(
|
|||||||
brief=brief,
|
brief=brief,
|
||||||
cur=cur,
|
cur=cur,
|
||||||
include_llm=include_llm_start_target,
|
include_llm=include_llm_start_target,
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
topic_override = None
|
topic_override = None
|
||||||
if llm_extract and (llm_extract.primary_topic or "").strip():
|
if llm_extract and (llm_extract.primary_topic or "").strip():
|
||||||
@@ -1023,6 +1134,7 @@ def run_progression_roadmap_pipeline(
|
|||||||
include_llm_roadmap: bool = False,
|
include_llm_roadmap: bool = False,
|
||||||
include_llm_start_target: bool = False,
|
include_llm_start_target: bool = False,
|
||||||
structured: Optional[RoadmapStructuredInput] = None,
|
structured: Optional[RoadmapStructuredInput] = None,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
) -> ProgressionRoadmapContext:
|
) -> ProgressionRoadmapContext:
|
||||||
"""Workflow-lite: Phase A → B → C. LLM über ai_prompts-Slugs; deterministischer Fallback."""
|
"""Workflow-lite: Phase A → B → C. LLM über ai_prompts-Slugs; deterministischer Fallback."""
|
||||||
brief = semantic_brief or build_semantic_brief(goal_query)
|
brief = semantic_brief or build_semantic_brief(goal_query)
|
||||||
@@ -1032,6 +1144,7 @@ def run_progression_roadmap_pipeline(
|
|||||||
brief=brief,
|
brief=brief,
|
||||||
cur=cur,
|
cur=cur,
|
||||||
include_llm=include_llm_start_target,
|
include_llm=include_llm_start_target,
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query)
|
parsed_start, parsed_target = parse_start_target_from_goal_query(goal_query)
|
||||||
llm_goal_query = _roadmap_llm_goal_block(
|
llm_goal_query = _roadmap_llm_goal_block(
|
||||||
@@ -1063,7 +1176,9 @@ def run_progression_roadmap_pipeline(
|
|||||||
topic_override=topic_override,
|
topic_override=topic_override,
|
||||||
)
|
)
|
||||||
if include_llm_roadmap and cur is not None:
|
if include_llm_roadmap and cur is not None:
|
||||||
llm_ga, ga_ok = try_llm_goal_analysis(cur, goal_query=llm_goal_query, brief=brief)
|
llm_ga, ga_ok = try_llm_goal_analysis(
|
||||||
|
cur, goal_query=llm_goal_query, brief=brief, catalog=catalog
|
||||||
|
)
|
||||||
if ga_ok and llm_ga:
|
if ga_ok and llm_ga:
|
||||||
goal_analysis = _merge_structured_into_goal_analysis(
|
goal_analysis = _merge_structured_into_goal_analysis(
|
||||||
llm_ga,
|
llm_ga,
|
||||||
@@ -1083,6 +1198,7 @@ def run_progression_roadmap_pipeline(
|
|||||||
brief=brief,
|
brief=brief,
|
||||||
goal_analysis=goal_analysis,
|
goal_analysis=goal_analysis,
|
||||||
max_steps=max_steps,
|
max_steps=max_steps,
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
if rm_ok and llm_rm:
|
if rm_ok and llm_rm:
|
||||||
roadmap = llm_rm
|
roadmap = llm_rm
|
||||||
@@ -1103,19 +1219,75 @@ def run_progression_roadmap_pipeline(
|
|||||||
)
|
)
|
||||||
ctx.roadmap = roadmap
|
ctx.roadmap = roadmap
|
||||||
|
|
||||||
stage_specs = build_stage_specs(roadmap.major_steps, goal_analysis=goal_analysis)
|
from planning_exercise_semantics import enrich_brief_with_path_constraints
|
||||||
|
from planning_intent_context import (
|
||||||
|
build_planning_intent_context,
|
||||||
|
finalize_stage_specs_with_intent,
|
||||||
|
)
|
||||||
|
|
||||||
|
brief = enrich_brief_with_path_constraints(
|
||||||
|
brief,
|
||||||
|
goal_query,
|
||||||
|
extra_context=_merge_roadmap_notes(
|
||||||
|
resolved.roadmap_notes,
|
||||||
|
resolved.start_situation,
|
||||||
|
resolved.target_state,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
intent = build_planning_intent_context(
|
||||||
|
goal_query,
|
||||||
|
semantic_brief=brief,
|
||||||
|
goal_analysis=goal_analysis.model_dump(),
|
||||||
|
extra_context=_merge_roadmap_notes(
|
||||||
|
resolved.roadmap_notes,
|
||||||
|
resolved.start_situation,
|
||||||
|
resolved.target_state,
|
||||||
|
),
|
||||||
|
primary_topic=goal_analysis.primary_topic,
|
||||||
|
cur=cur,
|
||||||
|
catalog=catalog,
|
||||||
|
)
|
||||||
|
|
||||||
|
heuristic_specs = build_stage_specs(
|
||||||
|
roadmap.major_steps,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
goal_query=goal_query,
|
||||||
|
semantic_brief=brief,
|
||||||
|
)
|
||||||
|
stage_specs = list(heuristic_specs)
|
||||||
if include_llm_roadmap and cur is not None:
|
if include_llm_roadmap and cur is not None:
|
||||||
llm_specs, spec_ok = try_llm_stage_specs(
|
llm_specs, spec_ok = try_llm_stage_specs(
|
||||||
cur,
|
cur,
|
||||||
goal_query=llm_goal_query,
|
goal_query=llm_goal_query,
|
||||||
goal_analysis=goal_analysis,
|
goal_analysis=goal_analysis,
|
||||||
major_steps=roadmap.major_steps,
|
major_steps=roadmap.major_steps,
|
||||||
|
intent_context=intent.to_api_dict(),
|
||||||
|
semantic_brief=brief,
|
||||||
|
catalog=catalog,
|
||||||
)
|
)
|
||||||
if spec_ok and llm_specs:
|
if spec_ok and llm_specs:
|
||||||
stage_specs = llm_specs
|
stage_specs = list(llm_specs)
|
||||||
ctx.llm_stage_spec_applied = True
|
ctx.llm_stage_spec_applied = True
|
||||||
ctx.prompt_slugs.append(PROMPT_SLUG_STAGE_SPEC)
|
ctx.prompt_slugs.append(PROMPT_SLUG_STAGE_SPEC)
|
||||||
ctx.stage_specs = stage_specs
|
ctx.stage_specs = finalize_stage_specs_with_intent(
|
||||||
|
stage_specs,
|
||||||
|
roadmap.major_steps,
|
||||||
|
intent=intent,
|
||||||
|
fallback_specs=heuristic_specs,
|
||||||
|
)
|
||||||
|
from planning_stage_context import derive_stage_specs_transition_states, resolve_path_start_target
|
||||||
|
|
||||||
|
path_start, path_target = resolve_path_start_target(
|
||||||
|
structured=resolved,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
)
|
||||||
|
ctx.stage_specs = derive_stage_specs_transition_states(
|
||||||
|
ctx.stage_specs,
|
||||||
|
roadmap.major_steps,
|
||||||
|
path_start=path_start,
|
||||||
|
path_target=path_target,
|
||||||
|
goal_analysis=goal_analysis,
|
||||||
|
)
|
||||||
|
|
||||||
if ctx.llm_goal_analysis_applied or ctx.llm_roadmap_applied or ctx.llm_stage_spec_applied:
|
if ctx.llm_goal_analysis_applied or ctx.llm_roadmap_applied or ctx.llm_stage_spec_applied:
|
||||||
ctx.pipeline_phase = "roadmap_v1_llm"
|
ctx.pipeline_phase = "roadmap_v1_llm"
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""
|
||||||
|
Zentrale Mustache-Variablen für Planungs-KI-Prompts.
|
||||||
|
|
||||||
|
Orchestratoren bauen domänenspezifische Basis-Variablen; dieses Modul merged
|
||||||
|
erweiterbare Provider (Katalog-Slots, später weitere Kontexte).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Callable, Dict, Mapping, Optional
|
||||||
|
|
||||||
|
from catalog_prompt_slots import all_placeholder_keys, empty_catalog_variables
|
||||||
|
from planning_catalog_context import ProgressionPlanningCatalogContext
|
||||||
|
|
||||||
|
PlanningPromptVariableProvider = Callable[..., Dict[str, str]]
|
||||||
|
|
||||||
|
|
||||||
|
def _catalog_slot_variables(
|
||||||
|
*,
|
||||||
|
cur,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
|
slug: Optional[str] = None,
|
||||||
|
**_: Any,
|
||||||
|
) -> Dict[str, str]:
|
||||||
|
if cur is None or catalog is None:
|
||||||
|
return empty_catalog_variables()
|
||||||
|
from catalog_prompt_slots import resolve_catalog_prompt_variables
|
||||||
|
|
||||||
|
resolved = resolve_catalog_prompt_variables(cur, catalog, slug=slug)
|
||||||
|
return {k: str(resolved.get(k) or "") for k in all_placeholder_keys()}
|
||||||
|
|
||||||
|
|
||||||
|
_PLANNING_PROMPT_VARIABLE_PROVIDERS: tuple[PlanningPromptVariableProvider, ...] = (
|
||||||
|
_catalog_slot_variables,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def catalog_exercise_hints_block(
|
||||||
|
cur,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
|
*,
|
||||||
|
slug: Optional[str] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Kombinierte hints_on_exercise aus aktivem Katalog-Kontext (Gap-Fill / Intent)."""
|
||||||
|
if cur is None or catalog is None:
|
||||||
|
return ""
|
||||||
|
from catalog_prompt_slots import CATALOG_KINDS, placeholder_key
|
||||||
|
|
||||||
|
merged = merge_planning_prompt_variables(cur, {}, catalog=catalog, slug=slug)
|
||||||
|
lines: list[str] = []
|
||||||
|
for cfg in CATALOG_KINDS:
|
||||||
|
key = placeholder_key(cfg.kind, "hints_on_exercise")
|
||||||
|
text = (merged.get(key) or "").strip()
|
||||||
|
if text:
|
||||||
|
lines.append(f"{cfg.label_de}: {text}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def merge_planning_prompt_variables(
|
||||||
|
cur,
|
||||||
|
base_variables: Mapping[str, str],
|
||||||
|
*,
|
||||||
|
catalog: Optional[ProgressionPlanningCatalogContext] = None,
|
||||||
|
slug: Optional[str] = None,
|
||||||
|
) -> Dict[str, str]:
|
||||||
|
"""Merged Basis-Variablen mit allen registrierten Planungs-Providern."""
|
||||||
|
out = {str(k): "" if v is None else str(v) for k, v in base_variables.items()}
|
||||||
|
ctx: Dict[str, Any] = {"cur": cur, "catalog": catalog, "slug": slug}
|
||||||
|
for provider in _PLANNING_PROMPT_VARIABLE_PROVIDERS:
|
||||||
|
out.update(provider(**ctx))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def planning_prompt_placeholder_catalog() -> dict:
|
||||||
|
"""Platzhalter-Katalog für Admin — Slot-Typ × Dimension + Aggregat."""
|
||||||
|
from catalog_prompt_slots import CATALOG_KINDS, SLOT_KEYS, placeholder_key
|
||||||
|
|
||||||
|
slot_labels = {
|
||||||
|
"description": "Allgemeine Beschreibung",
|
||||||
|
"hints_on_progression": "Hinweise Progressionsgraph / Stufen",
|
||||||
|
"hints_on_exercise": "Hinweise Übungsanlage / Gap-Fill",
|
||||||
|
"hints_on_path_qa": "Bewertungsmaßstäbe Pfad-QS",
|
||||||
|
"anti_patterns": "Anti-Patterns (Fehlbewertung vermeiden)",
|
||||||
|
"rematch_guard": "Rematch-Guard (primär Code, optional Prompt)",
|
||||||
|
}
|
||||||
|
kind_labels = {c.kind: c.label_de for c in CATALOG_KINDS}
|
||||||
|
|
||||||
|
slugs_common = [
|
||||||
|
"planning_exercise_path_qa",
|
||||||
|
"planning_progression_roadmap",
|
||||||
|
"planning_progression_stage_spec",
|
||||||
|
"planning_progression_goal_analysis",
|
||||||
|
"planning_progression_start_target",
|
||||||
|
]
|
||||||
|
|
||||||
|
defs = []
|
||||||
|
for cfg in CATALOG_KINDS:
|
||||||
|
for slot in SLOT_KEYS:
|
||||||
|
key = placeholder_key(cfg.kind, slot)
|
||||||
|
defs.append(
|
||||||
|
{
|
||||||
|
"key": key,
|
||||||
|
"placeholder": "{{" + key + "}}",
|
||||||
|
"description": (
|
||||||
|
f"{kind_labels.get(cfg.kind, cfg.kind)} — "
|
||||||
|
f"{slot_labels.get(slot, slot)} (aktiver Eintrag aus planning_catalog_context)."
|
||||||
|
),
|
||||||
|
"used_by_slugs": slugs_common,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
defs.extend(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"key": "catalog_guidance_block",
|
||||||
|
"placeholder": "{{catalog_guidance_block}}",
|
||||||
|
"description": "Aggregierter Markdown-Block aus aktiven Slots (slug-spezifisches Profil).",
|
||||||
|
"used_by_slugs": slugs_common,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "catalog_context_json",
|
||||||
|
"placeholder": "{{catalog_context_json}}",
|
||||||
|
"description": "Audit-JSON der gewählten Katalog-Einträge und befüllten Slots.",
|
||||||
|
"used_by_slugs": slugs_common[:3],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "has_catalog_guidance",
|
||||||
|
"placeholder": "{{has_catalog_guidance}}",
|
||||||
|
"description": "„true“ wenn mindestens ein LLM-Slot gesetzt; sonst leer.",
|
||||||
|
"used_by_slugs": slugs_common[:3],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return {"context": "planning", "placeholders": defs}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"catalog_exercise_hints_block",
|
||||||
|
"merge_planning_prompt_variables",
|
||||||
|
"planning_prompt_placeholder_catalog",
|
||||||
|
]
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
"""
|
||||||
|
Wiederverwendbare Fähigkeiten-Erwartungen für Planungs-KI.
|
||||||
|
|
||||||
|
Domänen-Scopes (gleiches Input-/Output-Modell):
|
||||||
|
- ``progression_stage`` — ein Major Step / stage_spec im Progressionsgraphen
|
||||||
|
- ``progression_path`` — gesamter Pfad (Ziel + Start/Ziel)
|
||||||
|
- ``training_section`` — Abschnitt einer Trainingseinheit (Phase G, später)
|
||||||
|
- ``framework_slot`` — Rahmen-Session-Slot (Phase G, später)
|
||||||
|
|
||||||
|
Konsumenten mergen ``skill_weights`` in ``PlanningTargetProfile`` (Retrieval)
|
||||||
|
oder liefern ``expected_skills`` an Übungs-KI (planning_context).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
||||||
|
|
||||||
|
from planning_exercise_profiles import _merge_weight_maps, _normalize_weight_map
|
||||||
|
from planning_exercise_semantics import PlanningSemanticBrief, resolve_semantic_skill_weights
|
||||||
|
from planning_exercise_text_signals import _load_skills_for_text_match, _match_skills_in_text
|
||||||
|
|
||||||
|
# Scope-Strings — stabil für API/UI und spätere Trainingsplanung
|
||||||
|
SCOPE_PROGRESSION_STAGE = "progression_stage"
|
||||||
|
SCOPE_PROGRESSION_PATH = "progression_path"
|
||||||
|
SCOPE_TRAINING_SECTION = "training_section"
|
||||||
|
SCOPE_FRAMEWORK_SLOT = "framework_slot"
|
||||||
|
|
||||||
|
_LOAD_PROFILE_SKILL_TERMS: Dict[str, Tuple[str, ...]] = {
|
||||||
|
"koordination": ("Koordination",),
|
||||||
|
"präzision": ("Präzision",),
|
||||||
|
"praezision": ("Präzision",),
|
||||||
|
"kraft": ("Kraft", "Kime"),
|
||||||
|
"geschwindigkeit": ("Geschwindigkeit", "Schnelligkeit"),
|
||||||
|
"schnelligkeit": ("Schnelligkeit", "Geschwindigkeit"),
|
||||||
|
"timing": ("Timing", "Reaktion"),
|
||||||
|
"reaktion": ("Reaktion", "Timing"),
|
||||||
|
"distanz": ("Distanz",),
|
||||||
|
"raum": ("Raum", "Distanz"),
|
||||||
|
"gleichgewicht": ("Gleichgewicht",),
|
||||||
|
"kime": ("Kime",),
|
||||||
|
"ausdauer": ("Ausdauer",),
|
||||||
|
"beweglichkeit": ("Beweglichkeit",),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PlanningSkillExpectationInput:
|
||||||
|
scope: str = SCOPE_PROGRESSION_STAGE
|
||||||
|
primary_topic: str = ""
|
||||||
|
goal_query: str = ""
|
||||||
|
start_situation: str = ""
|
||||||
|
target_state: str = ""
|
||||||
|
stage_learning_goal: str = ""
|
||||||
|
roadmap_notes: str = ""
|
||||||
|
load_profile: List[str] = field(default_factory=list)
|
||||||
|
phase: str = ""
|
||||||
|
skill_hints: List[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PlanningSkillExpectationItem:
|
||||||
|
skill_id: int
|
||||||
|
skill_name: str
|
||||||
|
weight: float
|
||||||
|
source: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PlanningSkillExpectations:
|
||||||
|
scope: str
|
||||||
|
skill_weights: Dict[int, float]
|
||||||
|
items: List[PlanningSkillExpectationItem]
|
||||||
|
sources: List[str]
|
||||||
|
|
||||||
|
def to_api_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"scope": self.scope,
|
||||||
|
"sources": list(self.sources),
|
||||||
|
"expected_skills": [
|
||||||
|
{
|
||||||
|
"skill_id": it.skill_id,
|
||||||
|
"skill_name": it.skill_name,
|
||||||
|
"weight": round(it.weight, 4),
|
||||||
|
"source": it.source,
|
||||||
|
}
|
||||||
|
for it in self.items
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_load_key(s: str) -> str:
|
||||||
|
return (s or "").strip().lower().replace("ä", "ae").replace("ö", "oe").replace("ü", "ue")
|
||||||
|
|
||||||
|
|
||||||
|
def _text_blob(inp: PlanningSkillExpectationInput) -> str:
|
||||||
|
parts = [
|
||||||
|
inp.primary_topic,
|
||||||
|
inp.goal_query,
|
||||||
|
inp.start_situation,
|
||||||
|
inp.target_state,
|
||||||
|
inp.stage_learning_goal,
|
||||||
|
inp.roadmap_notes,
|
||||||
|
inp.phase,
|
||||||
|
" ".join(inp.load_profile or []),
|
||||||
|
" ".join(inp.skill_hints or []),
|
||||||
|
]
|
||||||
|
return "\n".join(p for p in parts if (p or "").strip()).lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_skills_by_name_terms(
|
||||||
|
cur,
|
||||||
|
terms: Sequence[str],
|
||||||
|
*,
|
||||||
|
weight: float = 0.9,
|
||||||
|
source: str,
|
||||||
|
weights: Dict[int, float],
|
||||||
|
items: Dict[int, PlanningSkillExpectationItem],
|
||||||
|
) -> bool:
|
||||||
|
found = False
|
||||||
|
for name in terms:
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, name FROM skills
|
||||||
|
WHERE (status IS NULL OR status = 'active')
|
||||||
|
AND LOWER(name) LIKE %s
|
||||||
|
ORDER BY CASE WHEN LOWER(name) = %s THEN 0 WHEN LOWER(name) LIKE %s THEN 1 ELSE 2 END,
|
||||||
|
LENGTH(name) ASC
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(f"%{name.lower()}%", name.lower(), f"{name.lower()}%"),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
continue
|
||||||
|
sid = int(row["id"])
|
||||||
|
w = max(weights.get(sid, 0.0), weight)
|
||||||
|
weights[sid] = w
|
||||||
|
items[sid] = PlanningSkillExpectationItem(
|
||||||
|
skill_id=sid,
|
||||||
|
skill_name=str(row.get("name") or "").strip(),
|
||||||
|
weight=w,
|
||||||
|
source=source,
|
||||||
|
)
|
||||||
|
found = True
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_weights_into(
|
||||||
|
weights: Dict[int, float],
|
||||||
|
items: Dict[int, PlanningSkillExpectationItem],
|
||||||
|
incoming: Dict[int, float],
|
||||||
|
*,
|
||||||
|
source: str,
|
||||||
|
skill_rows: Sequence[Tuple[int, str, int]],
|
||||||
|
) -> None:
|
||||||
|
name_by_id = {sid: name for sid, name, _ in skill_rows}
|
||||||
|
for sid, w in incoming.items():
|
||||||
|
if w <= 0:
|
||||||
|
continue
|
||||||
|
merged = max(weights.get(sid, 0.0), float(w))
|
||||||
|
weights[sid] = merged
|
||||||
|
items[sid] = PlanningSkillExpectationItem(
|
||||||
|
skill_id=sid,
|
||||||
|
skill_name=name_by_id.get(sid, f"Skill #{sid}"),
|
||||||
|
weight=merged,
|
||||||
|
source=source,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_planning_skill_expectations(
|
||||||
|
cur,
|
||||||
|
inp: PlanningSkillExpectationInput,
|
||||||
|
*,
|
||||||
|
semantic_brief: Optional[PlanningSemanticBrief] = None,
|
||||||
|
) -> PlanningSkillExpectations:
|
||||||
|
"""Deterministisch: Thema + Text + load_profile → skill_weights."""
|
||||||
|
weights: Dict[int, float] = {}
|
||||||
|
items: Dict[int, PlanningSkillExpectationItem] = {}
|
||||||
|
sources: List[str] = []
|
||||||
|
|
||||||
|
skill_rows = _load_skills_for_text_match(cur)
|
||||||
|
|
||||||
|
if semantic_brief is not None:
|
||||||
|
topic_weights = resolve_semantic_skill_weights(cur, semantic_brief)
|
||||||
|
if topic_weights:
|
||||||
|
sources.append("semantic_topic")
|
||||||
|
_merge_weights_into(
|
||||||
|
weights, items, topic_weights, source="semantic_topic", skill_rows=skill_rows
|
||||||
|
)
|
||||||
|
|
||||||
|
blob = _text_blob(inp)
|
||||||
|
if blob:
|
||||||
|
text_weights = _match_skills_in_text(blob, skill_rows)
|
||||||
|
if text_weights:
|
||||||
|
sources.append("text_match")
|
||||||
|
_merge_weights_into(
|
||||||
|
weights, items, text_weights, source="text_match", skill_rows=skill_rows
|
||||||
|
)
|
||||||
|
|
||||||
|
load_found = False
|
||||||
|
for raw in inp.load_profile or []:
|
||||||
|
key = _norm_load_key(str(raw))
|
||||||
|
terms = _LOAD_PROFILE_SKILL_TERMS.get(key, (str(raw).strip(),) if key else ())
|
||||||
|
if _resolve_skills_by_name_terms(
|
||||||
|
cur, terms, weight=0.88, source="load_profile", weights=weights, items=items
|
||||||
|
):
|
||||||
|
load_found = True
|
||||||
|
if load_found and "load_profile" not in sources:
|
||||||
|
sources.append("load_profile")
|
||||||
|
|
||||||
|
normalized = _normalize_weight_map(weights)
|
||||||
|
out_items = sorted(
|
||||||
|
[
|
||||||
|
PlanningSkillExpectationItem(
|
||||||
|
skill_id=sid,
|
||||||
|
skill_name=items[sid].skill_name,
|
||||||
|
weight=normalized[sid],
|
||||||
|
source=items[sid].source,
|
||||||
|
)
|
||||||
|
for sid in normalized
|
||||||
|
],
|
||||||
|
key=lambda x: (-x.weight, x.skill_name.lower()),
|
||||||
|
)[:8]
|
||||||
|
|
||||||
|
return PlanningSkillExpectations(
|
||||||
|
scope=inp.scope or SCOPE_PROGRESSION_STAGE,
|
||||||
|
skill_weights=normalized,
|
||||||
|
items=out_items,
|
||||||
|
sources=sources,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def expectation_input_from_progression_stage(
|
||||||
|
*,
|
||||||
|
goal_query: str,
|
||||||
|
goal_analysis: Optional[Mapping[str, Any]] = None,
|
||||||
|
resolved_structured: Optional[Mapping[str, Any]] = None,
|
||||||
|
stage_spec: Optional[Mapping[str, Any]] = None,
|
||||||
|
semantic_brief_summary: Optional[Mapping[str, Any]] = None,
|
||||||
|
major_step: Optional[Mapping[str, Any]] = None,
|
||||||
|
) -> PlanningSkillExpectationInput:
|
||||||
|
"""Roadmap-Stufe → PlanningSkillExpectationInput (Progressionsgraph)."""
|
||||||
|
ga = dict(goal_analysis or {})
|
||||||
|
rs = dict(resolved_structured or {})
|
||||||
|
spec = dict(stage_spec or {})
|
||||||
|
brief = dict(semantic_brief_summary or {})
|
||||||
|
major = dict(major_step or {})
|
||||||
|
|
||||||
|
skill_hints: List[str] = []
|
||||||
|
for item in (brief.get("must_phrases") or [])[:4]:
|
||||||
|
s = str(item or "").strip()
|
||||||
|
if s:
|
||||||
|
skill_hints.append(s)
|
||||||
|
|
||||||
|
return PlanningSkillExpectationInput(
|
||||||
|
scope=SCOPE_PROGRESSION_STAGE,
|
||||||
|
primary_topic=str(ga.get("primary_topic") or brief.get("primary_topic") or "").strip(),
|
||||||
|
goal_query=(goal_query or "").strip(),
|
||||||
|
start_situation=str(rs.get("start_situation") or ga.get("start_assumption") or "").strip(),
|
||||||
|
target_state=str(rs.get("target_state") or ga.get("target_state") or "").strip(),
|
||||||
|
stage_learning_goal=str(
|
||||||
|
spec.get("learning_goal") or major.get("learning_goal") or ""
|
||||||
|
).strip(),
|
||||||
|
roadmap_notes=str(rs.get("roadmap_notes") or "").strip(),
|
||||||
|
load_profile=[str(x).strip() for x in (spec.get("load_profile") or []) if str(x).strip()],
|
||||||
|
phase=str(spec.get("phase") or major.get("phase") or "").strip(),
|
||||||
|
skill_hints=skill_hints,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def expectation_input_from_progression_path(
|
||||||
|
*,
|
||||||
|
goal_query: str,
|
||||||
|
goal_analysis: Optional[Mapping[str, Any]] = None,
|
||||||
|
resolved_structured: Optional[Mapping[str, Any]] = None,
|
||||||
|
semantic_brief_summary: Optional[Mapping[str, Any]] = None,
|
||||||
|
) -> PlanningSkillExpectationInput:
|
||||||
|
"""Gesamtpfad-Kontext (z. B. einmaliges Pfad-Profil)."""
|
||||||
|
ga = dict(goal_analysis or {})
|
||||||
|
rs = dict(resolved_structured or {})
|
||||||
|
brief = dict(semantic_brief_summary or {})
|
||||||
|
skill_hints: List[str] = []
|
||||||
|
for item in (brief.get("must_phrases") or [])[:4]:
|
||||||
|
s = str(item or "").strip()
|
||||||
|
if s:
|
||||||
|
skill_hints.append(s)
|
||||||
|
return PlanningSkillExpectationInput(
|
||||||
|
scope=SCOPE_PROGRESSION_PATH,
|
||||||
|
primary_topic=str(ga.get("primary_topic") or brief.get("primary_topic") or "").strip(),
|
||||||
|
goal_query=(goal_query or "").strip(),
|
||||||
|
start_situation=str(rs.get("start_situation") or ga.get("start_assumption") or "").strip(),
|
||||||
|
target_state=str(rs.get("target_state") or ga.get("target_state") or "").strip(),
|
||||||
|
roadmap_notes=str(rs.get("roadmap_notes") or "").strip(),
|
||||||
|
skill_hints=skill_hints,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_expectations_to_target(target, expectations: PlanningSkillExpectations):
|
||||||
|
"""Merge Erwartungs-Skills in PlanningTargetProfile (Retrieval)."""
|
||||||
|
from planning_exercise_semantics import enrich_target_with_semantic_expectations
|
||||||
|
|
||||||
|
if not expectations.skill_weights:
|
||||||
|
return target
|
||||||
|
return enrich_target_with_semantic_expectations(
|
||||||
|
target, skill_weights=dict(expectations.skill_weights)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def merge_expectation_skill_weights(
|
||||||
|
base: Dict[int, float],
|
||||||
|
extra: Dict[int, float],
|
||||||
|
*,
|
||||||
|
extra_scale: float = 1.0,
|
||||||
|
) -> Dict[int, float]:
|
||||||
|
merged = _merge_weight_maps(base, extra, scale=extra_scale)
|
||||||
|
return _normalize_weight_map(merged)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"SCOPE_FRAMEWORK_SLOT",
|
||||||
|
"SCOPE_PROGRESSION_PATH",
|
||||||
|
"SCOPE_PROGRESSION_STAGE",
|
||||||
|
"SCOPE_TRAINING_SECTION",
|
||||||
|
"PlanningSkillExpectationInput",
|
||||||
|
"PlanningSkillExpectationItem",
|
||||||
|
"PlanningSkillExpectations",
|
||||||
|
"apply_expectations_to_target",
|
||||||
|
"build_planning_skill_expectations",
|
||||||
|
"expectation_input_from_progression_path",
|
||||||
|
"expectation_input_from_progression_stage",
|
||||||
|
"merge_expectation_skill_weights",
|
||||||
|
]
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""
|
||||||
|
Stufen-Kontext im Gesamtziel — Start/Ziel pro Roadmap-Stufe für Matching und QS.
|
||||||
|
|
||||||
|
Übertragbar auf Trainingsplanung: Abschnitt-Soll (= Ende Vorabschnitt), Abschnitt-Ziel.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import List, Optional, Sequence
|
||||||
|
|
||||||
|
from planning_progression_roadmap import (
|
||||||
|
GoalAnalysisArtifact,
|
||||||
|
MajorStep,
|
||||||
|
RoadmapStructuredInput,
|
||||||
|
StageSpecArtifact,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_contextualized_stage_goal(
|
||||||
|
*,
|
||||||
|
learning_goal: str,
|
||||||
|
start_state: str = "",
|
||||||
|
target_state: str = "",
|
||||||
|
path_target_state: str = "",
|
||||||
|
path_start_state: str = "",
|
||||||
|
stage_index: int = 0,
|
||||||
|
stage_count: int = 1,
|
||||||
|
) -> str:
|
||||||
|
"""Stufen-Lernziel eingebettet in Übergang und Gesamtziel (für Brief/Retrieval)."""
|
||||||
|
lg = (learning_goal or "").strip()
|
||||||
|
if not lg:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
parts: List[str] = []
|
||||||
|
start = (start_state or "").strip()
|
||||||
|
target = (target_state or "").strip()
|
||||||
|
path_end = (path_target_state or "").strip()
|
||||||
|
path_begin = (path_start_state or "").strip()
|
||||||
|
|
||||||
|
if start:
|
||||||
|
parts.append(f"Soll-Start: {start[:220]}")
|
||||||
|
elif path_begin and stage_index == 0:
|
||||||
|
parts.append(f"Pfad-Start: {path_begin[:220]}")
|
||||||
|
if target:
|
||||||
|
parts.append(f"Stufen-Ziel: {target[:220]}")
|
||||||
|
parts.append(f"Lernziel: {lg[:280]}")
|
||||||
|
if path_end:
|
||||||
|
if stage_index >= max(0, stage_count - 1):
|
||||||
|
parts.append(f"Gesamtziel: {path_end[:220]}")
|
||||||
|
else:
|
||||||
|
parts.append(f"Gesamtziel (Kontext): {path_end[:180]}")
|
||||||
|
|
||||||
|
return " | ".join(parts)[:900]
|
||||||
|
|
||||||
|
|
||||||
|
def derive_stage_specs_transition_states(
|
||||||
|
stage_specs: Sequence[StageSpecArtifact],
|
||||||
|
major_steps: Sequence[MajorStep],
|
||||||
|
*,
|
||||||
|
path_start: str = "",
|
||||||
|
path_target: str = "",
|
||||||
|
goal_analysis: Optional[GoalAnalysisArtifact] = None,
|
||||||
|
) -> List[StageSpecArtifact]:
|
||||||
|
"""
|
||||||
|
Verkettete Soll-/Zielzustände je Stufe.
|
||||||
|
|
||||||
|
- Stufe 0 start = Pfad-Start
|
||||||
|
- Stufe n start = Zielzustand Stufe n-1 (Ziel des vorherigen Schritts)
|
||||||
|
- Letzte Stufe target = Pfad-Gesamtziel (falls gesetzt)
|
||||||
|
"""
|
||||||
|
start_path = (path_start or "").strip()
|
||||||
|
end_path = (path_target or "").strip()
|
||||||
|
if goal_analysis:
|
||||||
|
if not start_path:
|
||||||
|
start_path = (goal_analysis.start_assumption or "").strip()
|
||||||
|
if not end_path:
|
||||||
|
end_path = (goal_analysis.target_state or "").strip()
|
||||||
|
|
||||||
|
by_idx = {int(s.major_step_index): s for s in stage_specs}
|
||||||
|
majors = sorted(major_steps, key=lambda m: m.index)
|
||||||
|
if not majors:
|
||||||
|
return list(stage_specs)
|
||||||
|
|
||||||
|
out: List[StageSpecArtifact] = []
|
||||||
|
prev_target = start_path
|
||||||
|
last_idx = majors[-1].index
|
||||||
|
|
||||||
|
for major in majors:
|
||||||
|
spec = by_idx.get(major.index)
|
||||||
|
if spec is None:
|
||||||
|
spec = StageSpecArtifact(
|
||||||
|
major_step_index=major.index,
|
||||||
|
learning_goal=major.learning_goal,
|
||||||
|
)
|
||||||
|
|
||||||
|
explicit_start = (spec.start_state or "").strip()
|
||||||
|
explicit_target = (spec.target_state or "").strip()
|
||||||
|
stage_start = explicit_start or prev_target or start_path
|
||||||
|
if explicit_target:
|
||||||
|
stage_target = explicit_target
|
||||||
|
elif major.index == last_idx and end_path:
|
||||||
|
stage_target = end_path
|
||||||
|
else:
|
||||||
|
stage_target = (major.learning_goal or spec.learning_goal or "").strip()
|
||||||
|
|
||||||
|
prev_target = stage_target
|
||||||
|
out.append(
|
||||||
|
spec.model_copy(
|
||||||
|
update={
|
||||||
|
"start_state": (stage_start or "")[:500],
|
||||||
|
"target_state": (stage_target or "")[:500],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_path_start_target(
|
||||||
|
*,
|
||||||
|
structured: Optional[RoadmapStructuredInput] = None,
|
||||||
|
goal_analysis: Optional[GoalAnalysisArtifact] = None,
|
||||||
|
) -> tuple[str, str]:
|
||||||
|
"""Pfadweiter Start- und Zielzustand für Stufen-Verkettung."""
|
||||||
|
start = ""
|
||||||
|
target = ""
|
||||||
|
if structured:
|
||||||
|
start = (structured.start_situation or "").strip()
|
||||||
|
target = (structured.target_state or "").strip()
|
||||||
|
if goal_analysis:
|
||||||
|
if not start:
|
||||||
|
start = (goal_analysis.start_assumption or "").strip()
|
||||||
|
if not target:
|
||||||
|
target = (goal_analysis.target_state or "").strip()
|
||||||
|
return start, target
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"build_contextualized_stage_goal",
|
||||||
|
"derive_stage_specs_transition_states",
|
||||||
|
"resolve_path_start_target",
|
||||||
|
]
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Validierung und Normalisierung des Planungs-Artefakts am Progressionsgraph."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
|
ARTIFACT_SCHEMA_VERSION = 1
|
||||||
|
_MAX_JSON_BYTES = 64_000
|
||||||
|
|
||||||
|
|
||||||
|
class SlotExerciseContent(BaseModel):
|
||||||
|
kind: str = Field(default="empty", pattern=r"^(empty|library|proposal)$")
|
||||||
|
exercise_id: Optional[int] = Field(default=None, ge=1)
|
||||||
|
variant_id: Optional[int] = Field(default=None, ge=1)
|
||||||
|
title: Optional[str] = Field(default=None, max_length=500)
|
||||||
|
variant_name: Optional[str] = Field(default=None, max_length=200)
|
||||||
|
proposal_key: Optional[str] = Field(default=None, max_length=120)
|
||||||
|
ai_suggestion: Optional[Dict[str, Any]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class SlotContentEntry(BaseModel):
|
||||||
|
major_step_index: int = Field(ge=0, le=20)
|
||||||
|
primary: SlotExerciseContent = Field(default_factory=SlotExerciseContent)
|
||||||
|
siblings: List[SlotExerciseContent] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
class GraphPlanningRoadmapArtifact(BaseModel):
|
||||||
|
schema_version: int = Field(default=ARTIFACT_SCHEMA_VERSION, ge=1, le=1)
|
||||||
|
goal_query: str = Field(default="", max_length=2000)
|
||||||
|
start_situation: Optional[str] = Field(default=None, max_length=2000)
|
||||||
|
target_state: Optional[str] = Field(default=None, max_length=2000)
|
||||||
|
roadmap_notes: Optional[str] = Field(default=None, max_length=2000)
|
||||||
|
max_steps: int = Field(default=5, ge=2, le=10)
|
||||||
|
progression_roadmap: Optional[Dict[str, Any]] = None
|
||||||
|
path_skill_expectations: Optional[Dict[str, Any]] = None
|
||||||
|
slot_contents: Optional[List[SlotContentEntry]] = None
|
||||||
|
last_findings: Optional[Dict[str, Any]] = None
|
||||||
|
findings_stale: bool = Field(default=False)
|
||||||
|
planning_catalog_context: Optional[Dict[str, Any]] = None
|
||||||
|
|
||||||
|
@field_validator("progression_roadmap", "path_skill_expectations", "last_findings", "planning_catalog_context", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _empty_dict_to_none(cls, v):
|
||||||
|
if v == {}:
|
||||||
|
return None
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator("slot_contents", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _empty_slot_list_to_none(cls, v):
|
||||||
|
if v == []:
|
||||||
|
return None
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_planning_roadmap_payload(raw: Any) -> Optional[Dict[str, Any]]:
|
||||||
|
"""None erlaubt (löschen); sonst validiertes Dict."""
|
||||||
|
if raw is None:
|
||||||
|
return None
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
raise ValueError("planning_roadmap muss ein JSON-Objekt sein")
|
||||||
|
artifact = GraphPlanningRoadmapArtifact.model_validate(raw)
|
||||||
|
out = artifact.model_dump(exclude_none=True)
|
||||||
|
blob = json.dumps(out, ensure_ascii=False)
|
||||||
|
if len(blob.encode("utf-8")) > _MAX_JSON_BYTES:
|
||||||
|
raise ValueError("planning_roadmap ist zu groß (max. 64 KB)")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ARTIFACT_SCHEMA_VERSION",
|
||||||
|
"GraphPlanningRoadmapArtifact",
|
||||||
|
"SlotContentEntry",
|
||||||
|
"SlotExerciseContent",
|
||||||
|
"normalize_planning_roadmap_payload",
|
||||||
|
]
|
||||||
@@ -10,5 +10,5 @@ bcrypt==4.1.3
|
|||||||
slowapi==0.1.9
|
slowapi==0.1.9
|
||||||
psycopg2-binary==2.9.9
|
psycopg2-binary==2.9.9
|
||||||
python-dateutil==2.9.0
|
python-dateutil==2.9.0
|
||||||
tzdata>=2024.1 # ZoneInfo (Europe/Berlin) auch unter Windows
|
tzdata>=2024.1; sys_platform == "win32" # ZoneInfo lokal; Linux/Docker: apt tzdata
|
||||||
sqlparse>=0.5.0 # Migrationen: Statements splitten (Fallback ohne psql)
|
sqlparse>=0.5.0 # Migrationen: Statements splitten (Fallback ohne psql)
|
||||||
@@ -13,7 +13,7 @@ router = APIRouter(prefix="/api/admin", tags=["admin_users"])
|
|||||||
|
|
||||||
_SAFE_PROFILE_COLS = """
|
_SAFE_PROFILE_COLS = """
|
||||||
id, name, email, role, tier, email_verified, active_club_id,
|
id, name, email, role, tier, email_verified, active_club_id,
|
||||||
created_at, updated_at, auth_type
|
created_at, updated_at, auth_type, totp_enabled
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -14,9 +14,16 @@ from auth import require_auth
|
|||||||
from club_tenancy import is_superadmin
|
from club_tenancy import is_superadmin
|
||||||
from ai_prompt_context import ExerciseFormAiPromptContext
|
from ai_prompt_context import ExerciseFormAiPromptContext
|
||||||
from ai_prompt_job import resolve_exercise_form_variables
|
from ai_prompt_job import resolve_exercise_form_variables
|
||||||
|
from ai_prompt_planning_preview import (
|
||||||
|
PlanningPromptPreviewInput,
|
||||||
|
is_planning_prompt_slug,
|
||||||
|
resolve_planning_prompt_preview_variables,
|
||||||
|
)
|
||||||
from ai_prompt_runtime import render_ai_prompt_template_for_row
|
from ai_prompt_runtime import render_ai_prompt_template_for_row
|
||||||
from db import get_cursor, get_db, r2d
|
from db import get_cursor, get_db, r2d
|
||||||
|
from openrouter_chat import normalize_openrouter_model_id
|
||||||
from prompt_resolver import exercise_placeholder_catalog
|
from prompt_resolver import exercise_placeholder_catalog
|
||||||
|
from planning_prompt_variables import planning_prompt_placeholder_catalog
|
||||||
|
|
||||||
router = APIRouter(tags=["admin_ai_prompts"])
|
router = APIRouter(tags=["admin_ai_prompts"])
|
||||||
|
|
||||||
@@ -41,7 +48,7 @@ def _fetch_prompt_any(cur, prompt_id: int) -> Dict[str, Any]:
|
|||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
SELECT id, slug, display_name, description, template, category, output_format,
|
SELECT id, slug, display_name, description, template, category, output_format,
|
||||||
output_schema, is_system_default, default_template, openrouter_model,
|
output_schema, is_system_default, default_template, openrouter_model, model_role,
|
||||||
active, sort_order, created_at, updated_at
|
active, sort_order, created_at, updated_at
|
||||||
FROM ai_prompts WHERE id = %s
|
FROM ai_prompts WHERE id = %s
|
||||||
""",
|
""",
|
||||||
@@ -62,12 +69,22 @@ class AiPromptUpdateBody(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class AiPromptPreviewBody(ExerciseFormAiPromptContext):
|
class AiPromptPreviewBody(ExerciseFormAiPromptContext):
|
||||||
"""Preview-POST: gleiche Felder wie ExerciseFormAiPromptContext (focus_hint, nicht focus_area_hint)."""
|
"""Preview-POST: Übungs-KI und Planungs-Prompts."""
|
||||||
|
|
||||||
|
goal_query: Optional[str] = Field(default=None, max_length=2000)
|
||||||
|
user_notes: Optional[str] = Field(default=None, max_length=2000)
|
||||||
|
max_steps: Optional[int] = Field(default=None, ge=2, le=10)
|
||||||
|
search_query: Optional[str] = Field(default=None, max_length=2000)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/admin/ai-prompts/catalog/placeholders")
|
@router.get("/api/admin/ai-prompts/catalog/placeholders")
|
||||||
def get_ai_prompt_placeholders_catalog(session: dict = Depends(_require_superadmin)):
|
def get_ai_prompt_placeholders_catalog(session: dict = Depends(_require_superadmin)):
|
||||||
return exercise_placeholder_catalog()
|
exercise = exercise_placeholder_catalog()
|
||||||
|
planning = planning_prompt_placeholder_catalog()
|
||||||
|
return {
|
||||||
|
"context": "all",
|
||||||
|
"placeholders": list(exercise.get("placeholders") or []) + list(planning.get("placeholders") or []),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/admin/ai-prompts")
|
@router.get("/api/admin/ai-prompts")
|
||||||
@@ -79,7 +96,7 @@ def list_ai_prompts(session: dict = Depends(_require_superadmin)):
|
|||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
SELECT id, slug, display_name, description, category, output_format, active,
|
SELECT id, slug, display_name, description, category, output_format, active,
|
||||||
sort_order, is_system_default, default_template, openrouter_model
|
sort_order, is_system_default, default_template, openrouter_model, model_role
|
||||||
FROM ai_prompts
|
FROM ai_prompts
|
||||||
ORDER BY sort_order ASC NULLS LAST, id ASC
|
ORDER BY sort_order ASC NULLS LAST, id ASC
|
||||||
"""
|
"""
|
||||||
@@ -145,10 +162,10 @@ def update_ai_prompt(
|
|||||||
|
|
||||||
next_openrouter = old.get("openrouter_model")
|
next_openrouter = old.get("openrouter_model")
|
||||||
if body.openrouter_model is not None:
|
if body.openrouter_model is not None:
|
||||||
cand = body.openrouter_model.strip() if isinstance(body.openrouter_model, str) else ""
|
try:
|
||||||
if any(c in cand for c in ("\r", "\n", "\t")):
|
next_openrouter = normalize_openrouter_model_id(body.openrouter_model)
|
||||||
raise HTTPException(status_code=400, detail="openrouter_model: keine Steuerzeichen erlaubt.")
|
except ValueError as exc:
|
||||||
next_openrouter = cand or None
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"""
|
"""
|
||||||
@@ -157,7 +174,7 @@ def update_ai_prompt(
|
|||||||
openrouter_model = %s, updated_at = NOW()
|
openrouter_model = %s, updated_at = NOW()
|
||||||
WHERE id = %s
|
WHERE id = %s
|
||||||
RETURNING id, slug, display_name, description, template, category, output_format,
|
RETURNING id, slug, display_name, description, template, category, output_format,
|
||||||
output_schema, is_system_default, default_template, openrouter_model,
|
output_schema, is_system_default, default_template, openrouter_model, model_role,
|
||||||
active, sort_order,
|
active, sort_order,
|
||||||
created_at, updated_at
|
created_at, updated_at
|
||||||
""",
|
""",
|
||||||
@@ -190,7 +207,7 @@ def reset_ai_prompt_template(prompt_id: int, session: dict = Depends(_require_su
|
|||||||
SET template = default_template, updated_at = NOW()
|
SET template = default_template, updated_at = NOW()
|
||||||
WHERE id = %s AND default_template IS NOT NULL
|
WHERE id = %s AND default_template IS NOT NULL
|
||||||
RETURNING id, slug, display_name, description, template, category, output_format,
|
RETURNING id, slug, display_name, description, template, category, output_format,
|
||||||
output_schema, is_system_default, default_template, openrouter_model,
|
output_schema, is_system_default, default_template, openrouter_model, model_role,
|
||||||
active, sort_order,
|
active, sort_order,
|
||||||
created_at, updated_at
|
created_at, updated_at
|
||||||
""",
|
""",
|
||||||
@@ -223,6 +240,17 @@ def preview_ai_prompt(prompt_id: int, body: AiPromptPreviewBody, session: dict =
|
|||||||
vars_map = resolve_exercise_form_variables(cur, slug, body)
|
vars_map = resolve_exercise_form_variables(cur, slug, body)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||||
|
elif is_planning_prompt_slug(slug):
|
||||||
|
planning_in = PlanningPromptPreviewInput(
|
||||||
|
goal_query=(body.goal_query or "Mae Geri vom Grundschritt bis zur Kumite-Nähe").strip(),
|
||||||
|
user_notes=(body.user_notes or "").strip(),
|
||||||
|
max_steps=body.max_steps if body.max_steps is not None else 5,
|
||||||
|
search_query=(body.search_query or body.goal_query or "").strip() or None,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
vars_map = resolve_planning_prompt_preview_variables(cur, slug, planning_in)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||||
elif slug == "pipeline":
|
elif slug == "pipeline":
|
||||||
vars_map = {}
|
vars_map = {}
|
||||||
warn = "Pipeline-Slug: keine Kontextsubstitution fuer Vorschau."
|
warn = "Pipeline-Slug: keine Kontextsubstitution fuer Vorschau."
|
||||||
|
|||||||
+449
-72
@@ -14,12 +14,41 @@ from email.mime.text import MIMEText
|
|||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, Header, Depends
|
from fastapi import APIRouter, HTTPException, Header, Depends
|
||||||
from starlette.requests import Request
|
from starlette.requests import Request
|
||||||
|
import ipaddress
|
||||||
|
|
||||||
from slowapi import Limiter
|
from slowapi import Limiter
|
||||||
from slowapi.util import get_remote_address
|
|
||||||
|
|
||||||
from db import get_db, get_cursor
|
from db import get_db, get_cursor
|
||||||
from auth import hash_pin, verify_pin, make_token, require_auth
|
from auth import (
|
||||||
from models import LoginRequest, PasswordResetRequest, PasswordResetConfirm, RegisterRequest
|
get_limited_session,
|
||||||
|
get_session,
|
||||||
|
hash_pin,
|
||||||
|
make_token,
|
||||||
|
require_auth,
|
||||||
|
revoke_profile_sessions,
|
||||||
|
session_lifetime_days,
|
||||||
|
verify_pin,
|
||||||
|
verify_pin_for_login,
|
||||||
|
)
|
||||||
|
from media_grant import MEDIA_GRANT_TTL_SECONDS, issue_media_grant
|
||||||
|
from models import (
|
||||||
|
ChangePasswordRequest,
|
||||||
|
LoginRequest,
|
||||||
|
LoginTotpRequest,
|
||||||
|
PasswordResetRequest,
|
||||||
|
PasswordResetConfirm,
|
||||||
|
RegisterRequest,
|
||||||
|
ResendVerificationRequest,
|
||||||
|
TotpCodeRequest,
|
||||||
|
TotpDisableRequest,
|
||||||
|
)
|
||||||
|
from totp_auth import (
|
||||||
|
generate_recovery_codes,
|
||||||
|
generate_totp_secret,
|
||||||
|
hash_recovery_code,
|
||||||
|
otpauth_uri,
|
||||||
|
verify_totp,
|
||||||
|
)
|
||||||
from password_reset_mail import (
|
from password_reset_mail import (
|
||||||
insert_password_reset_session,
|
insert_password_reset_session,
|
||||||
password_reset_email_body,
|
password_reset_email_body,
|
||||||
@@ -27,47 +56,158 @@ from password_reset_mail import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||||
limiter = Limiter(key_func=get_remote_address)
|
|
||||||
|
LOGIN_LOCK_AFTER = 8
|
||||||
|
LOGIN_LOCK_MINUTES = 15
|
||||||
|
_ADMIN_ROLES = ("admin", "superadmin")
|
||||||
|
|
||||||
|
|
||||||
@router.post("/login")
|
def _client_ip(request: Request) -> str:
|
||||||
@limiter.limit("30/minute")
|
"""Echte Client-IP nur, wenn der direkte Peer ein vertrauenswürdiger Proxy ist."""
|
||||||
async def login(req: LoginRequest, request: Request):
|
peer = request.client.host if request.client and request.client.host else ""
|
||||||
"""Login with email + password."""
|
if _is_trusted_proxy(peer):
|
||||||
with get_db() as conn:
|
real = (request.headers.get("x-real-ip") or "").split(",")[0].strip()
|
||||||
cur = get_cursor(conn)
|
if real:
|
||||||
cur.execute("SELECT * FROM profiles WHERE email=%s", (req.email.lower().strip(),))
|
return real[:64]
|
||||||
prof = cur.fetchone()
|
return peer or "unknown"
|
||||||
if not prof:
|
|
||||||
raise HTTPException(401, "Ungültige Zugangsdaten")
|
|
||||||
|
|
||||||
# Verify password
|
|
||||||
if not verify_pin(req.password, prof['pin_hash']):
|
|
||||||
raise HTTPException(401, "Ungültige Zugangsdaten")
|
|
||||||
|
|
||||||
# Auto-upgrade from SHA256 to bcrypt
|
def _is_trusted_proxy(host: str) -> bool:
|
||||||
if prof['pin_hash'] and not prof['pin_hash'].startswith('$2'):
|
if not host:
|
||||||
new_hash = hash_pin(req.password)
|
return False
|
||||||
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, prof['id']))
|
try:
|
||||||
|
ip = ipaddress.ip_address(host)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
return ip.is_private or ip.is_loopback or ip.is_link_local
|
||||||
|
|
||||||
# Create session
|
|
||||||
|
limiter = Limiter(key_func=_client_ip)
|
||||||
|
|
||||||
|
|
||||||
|
def _admin_totp_required() -> bool:
|
||||||
|
"""Nur wenn REQUIRE_ADMIN_TOTP ausdrücklich an ist. Standard: der Nutzer entscheidet selbst."""
|
||||||
|
raw = (os.getenv("REQUIRE_ADMIN_TOTP") or "").strip().lower()
|
||||||
|
return raw in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
def _issue_session(cur, profile_id: int, *, days: int, purpose: str = "full") -> tuple[str, datetime]:
|
||||||
token = make_token()
|
token = make_token()
|
||||||
session_days = prof.get('session_days', 30)
|
expires = datetime.now(timezone.utc) + timedelta(days=days if purpose == "full" else 0, minutes=0)
|
||||||
expires = datetime.now() + timedelta(days=session_days)
|
if purpose == "totp_challenge":
|
||||||
cur.execute("INSERT INTO sessions (token, profile_id, expires_at, created_at) VALUES (%s,%s,%s,CURRENT_TIMESTAMP)",
|
expires = datetime.now(timezone.utc) + timedelta(minutes=5)
|
||||||
(token, prof['id'], expires.isoformat()))
|
elif purpose == "totp_enroll":
|
||||||
|
expires = datetime.now(timezone.utc) + timedelta(minutes=30)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sessions (token, profile_id, expires_at, created_at, purpose)
|
||||||
|
VALUES (%s, %s, %s, CURRENT_TIMESTAMP, %s)
|
||||||
|
""",
|
||||||
|
(token, profile_id, expires, purpose),
|
||||||
|
)
|
||||||
|
return token, expires
|
||||||
|
|
||||||
|
|
||||||
|
def _login_payload(prof: dict, token: str, expires: datetime) -> dict:
|
||||||
return {
|
return {
|
||||||
"token": token,
|
"token": token,
|
||||||
"profile_id": prof['id'],
|
"profile_id": prof["id"],
|
||||||
"email": prof.get("email"),
|
"email": prof.get("email"),
|
||||||
"name": prof.get("name"),
|
"name": prof.get("name"),
|
||||||
"role": prof.get("role"),
|
"role": prof.get("role"),
|
||||||
"tier": prof.get("tier"),
|
"tier": prof.get("tier"),
|
||||||
"expires_at": expires.isoformat(),
|
"expires_at": expires.isoformat(),
|
||||||
|
"totp_enabled": bool(prof.get("totp_enabled")),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _record_failed_login(cur, profile_id: int) -> None:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE profiles
|
||||||
|
SET failed_login_count = CASE
|
||||||
|
WHEN failed_login_count + 1 >= %s THEN 0
|
||||||
|
ELSE failed_login_count + 1
|
||||||
|
END,
|
||||||
|
locked_until = CASE
|
||||||
|
WHEN failed_login_count + 1 >= %s
|
||||||
|
THEN CURRENT_TIMESTAMP + (%s * INTERVAL '1 minute')
|
||||||
|
ELSE locked_until
|
||||||
|
END
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(LOGIN_LOCK_AFTER, LOGIN_LOCK_AFTER, LOGIN_LOCK_MINUTES, profile_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _clear_login_lock(cur, profile_id: int) -> None:
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE profiles SET failed_login_count = 0, locked_until = NULL WHERE id = %s",
|
||||||
|
(profile_id,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login")
|
||||||
|
@limiter.limit("10/minute")
|
||||||
|
async def login(req: LoginRequest, request: Request):
|
||||||
|
"""Login with email + password. Bei aktivem TOTP folgt ein zweiter Schritt."""
|
||||||
|
email = req.email.lower().strip()
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT *,
|
||||||
|
(locked_until IS NOT NULL AND locked_until > CURRENT_TIMESTAMP) AS is_locked
|
||||||
|
FROM profiles WHERE email=%s
|
||||||
|
""",
|
||||||
|
(email,),
|
||||||
|
)
|
||||||
|
prof = cur.fetchone()
|
||||||
|
password_ok = verify_pin_for_login(req.password, prof["pin_hash"] if prof else None)
|
||||||
|
if not prof or not password_ok:
|
||||||
|
if prof and not prof.get("is_locked"):
|
||||||
|
_record_failed_login(cur, prof["id"])
|
||||||
|
outcome = "invalid"
|
||||||
|
elif prof.get("is_locked"):
|
||||||
|
outcome = "locked"
|
||||||
|
else:
|
||||||
|
outcome = "ok"
|
||||||
|
if prof["pin_hash"] and not str(prof["pin_hash"]).startswith("$2"):
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE profiles SET pin_hash=%s WHERE id=%s",
|
||||||
|
(hash_pin(req.password), prof["id"]),
|
||||||
|
)
|
||||||
|
_clear_login_lock(cur, prof["id"])
|
||||||
|
|
||||||
|
if outcome == "invalid":
|
||||||
|
raise HTTPException(401, "Ungültige Zugangsdaten")
|
||||||
|
if outcome == "locked":
|
||||||
|
raise HTTPException(429, "Zu viele Anmeldeversuche. Bitte später erneut versuchen.")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
role = (prof.get("role") or "").strip().lower()
|
||||||
|
if prof.get("totp_enabled"):
|
||||||
|
token, expires = _issue_session(cur, prof["id"], days=1, purpose="totp_challenge")
|
||||||
|
return {
|
||||||
|
"totp_required": True,
|
||||||
|
"challenge_token": token,
|
||||||
|
"expires_at": expires.isoformat(),
|
||||||
|
}
|
||||||
|
if role in _ADMIN_ROLES and _admin_totp_required() and not prof.get("totp_enabled"):
|
||||||
|
token, expires = _issue_session(cur, prof["id"], days=1, purpose="totp_enroll")
|
||||||
|
return {
|
||||||
|
"totp_enrollment_required": True,
|
||||||
|
"token": token,
|
||||||
|
"email": prof.get("email"),
|
||||||
|
"expires_at": expires.isoformat(),
|
||||||
|
}
|
||||||
|
|
||||||
|
token, expires = _issue_session(cur, prof["id"], days=session_lifetime_days(prof))
|
||||||
|
|
||||||
|
return _login_payload(prof, token, expires)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/logout")
|
@router.post("/logout")
|
||||||
def logout(x_auth_token: Optional[str]=Header(default=None)):
|
def logout(x_auth_token: Optional[str]=Header(default=None)):
|
||||||
"""Logout (delete session)."""
|
"""Logout (delete session)."""
|
||||||
@@ -94,21 +234,246 @@ def auth_status():
|
|||||||
|
|
||||||
|
|
||||||
@router.put("/pin")
|
@router.put("/pin")
|
||||||
def change_pin(req: dict, session: dict=Depends(require_auth)):
|
def change_pin(req: ChangePasswordRequest, session: dict = Depends(require_auth)):
|
||||||
"""Change PIN/password for current user."""
|
"""Passwort wechseln. Das aktuelle Passwort ist Pflicht; alle Sitzungen werden ersetzt."""
|
||||||
pid = session['profile_id']
|
pid = session["profile_id"]
|
||||||
new_pin = req.get('pin', '')
|
|
||||||
if len(new_pin) < 8:
|
|
||||||
raise HTTPException(400, "Passwort muss mind. 8 Zeichen haben")
|
|
||||||
|
|
||||||
new_hash = hash_pin(new_pin)
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not verify_pin(req.current_password, prof["pin_hash"]):
|
||||||
|
raise HTTPException(400, "Aktuelles Passwort ist falsch")
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE profiles SET pin_hash=%s WHERE id=%s",
|
||||||
|
(hash_pin(req.new_password), pid),
|
||||||
|
)
|
||||||
|
revoke_profile_sessions(cur, int(pid))
|
||||||
|
token, expires = _issue_session(cur, int(pid), days=session_lifetime_days(prof))
|
||||||
|
return {"ok": True, "token": token, "expires_at": expires.isoformat()}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login/totp")
|
||||||
|
@limiter.limit("10/minute")
|
||||||
|
async def login_totp(req: LoginTotpRequest, request: Request):
|
||||||
|
"""Zweiter Login-Schritt: Authenticator-Code oder Wiederherstellungscode."""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT s.*, p.role, p.name, p.email
|
||||||
|
FROM sessions s JOIN profiles p ON s.profile_id = p.id
|
||||||
|
WHERE s.token = %s AND s.expires_at > CURRENT_TIMESTAMP AND s.purpose = 'totp_challenge'
|
||||||
|
""",
|
||||||
|
(req.challenge_token,),
|
||||||
|
)
|
||||||
|
challenge = cur.fetchone()
|
||||||
|
error = None
|
||||||
|
payload = None
|
||||||
|
if not challenge:
|
||||||
|
error = "Anmeldung abgelaufen. Bitte erneut anmelden."
|
||||||
|
else:
|
||||||
|
pid = int(challenge["profile_id"])
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not prof.get("totp_enabled"):
|
||||||
|
error = "Anmeldung abgelaufen. Bitte erneut anmelden."
|
||||||
|
else:
|
||||||
|
code_ok = verify_totp(prof.get("totp_secret"), req.code) or _consume_recovery_code(
|
||||||
|
cur, pid, req.code
|
||||||
|
)
|
||||||
|
if not code_ok:
|
||||||
|
attempts = int(challenge.get("failed_attempts") or 0) + 1
|
||||||
|
if attempts >= 5:
|
||||||
|
cur.execute("DELETE FROM sessions WHERE token=%s", (req.challenge_token,))
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE sessions SET failed_attempts=%s WHERE token=%s",
|
||||||
|
(attempts, req.challenge_token),
|
||||||
|
)
|
||||||
|
error = "Ungültiger Code"
|
||||||
|
else:
|
||||||
|
revoke_profile_sessions(cur, pid)
|
||||||
|
token, expires = _issue_session(cur, pid, days=session_lifetime_days(prof))
|
||||||
|
payload = _login_payload(prof, token, expires)
|
||||||
|
if error:
|
||||||
|
raise HTTPException(401, error)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _consume_recovery_code(cur, profile_id: int, code: str) -> bool:
|
||||||
|
digest = hash_recovery_code(code)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE profile_recovery_codes
|
||||||
|
SET used_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE profile_id = %s AND code_hash = %s AND used_at IS NULL
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(profile_id, digest),
|
||||||
|
)
|
||||||
|
return cur.fetchone() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _setup_session_or_401(token: str) -> dict:
|
||||||
|
full = None
|
||||||
|
if token:
|
||||||
|
full = get_session(token)
|
||||||
|
if full:
|
||||||
|
return full
|
||||||
|
enroll = get_limited_session(token, "totp_enroll") if token else None
|
||||||
|
if not enroll:
|
||||||
|
raise HTTPException(401, "Nicht eingeloggt")
|
||||||
|
return enroll
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/totp/status")
|
||||||
|
def totp_status(x_auth_token: Optional[str] = Header(default=None)):
|
||||||
|
session = _setup_session_or_401(x_auth_token or "")
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT email, role, totp_enabled FROM profiles WHERE id=%s",
|
||||||
|
(session["profile_id"],),
|
||||||
|
)
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof:
|
||||||
|
raise HTTPException(401, "Nicht eingeloggt")
|
||||||
|
role = (prof.get("role") or session.get("role") or "").strip().lower()
|
||||||
|
enrollment = (session.get("purpose") or "full") == "totp_enroll"
|
||||||
|
return {
|
||||||
|
"totp_enabled": bool(prof.get("totp_enabled")),
|
||||||
|
"enrollment_required": enrollment or (
|
||||||
|
role in _ADMIN_ROLES and _admin_totp_required() and not prof.get("totp_enabled")
|
||||||
|
),
|
||||||
|
"email": prof.get("email"),
|
||||||
|
"role": role,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/totp/setup")
|
||||||
|
def totp_setup(x_auth_token: Optional[str] = Header(default=None)):
|
||||||
|
"""Neues Geheimnis erzeugen. Wirksam erst nach /totp/confirm."""
|
||||||
|
session = _setup_session_or_401(x_auth_token or "")
|
||||||
|
secret = generate_totp_secret()
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT email FROM profiles WHERE id=%s", (session["profile_id"],))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof:
|
||||||
|
raise HTTPException(404, "Profil nicht gefunden")
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE profiles SET totp_pending_secret=%s WHERE id=%s",
|
||||||
|
(secret, session["profile_id"]),
|
||||||
|
)
|
||||||
|
email = prof.get("email") or "konto"
|
||||||
|
return {
|
||||||
|
"secret": secret,
|
||||||
|
"otpauth_uri": otpauth_uri(secret=secret, account_name=email),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/totp/confirm")
|
||||||
|
def totp_confirm(req: TotpCodeRequest, x_auth_token: Optional[str] = Header(default=None)):
|
||||||
|
session = _setup_session_or_401(x_auth_token or "")
|
||||||
|
pid = int(session["profile_id"])
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not prof.get("totp_pending_secret"):
|
||||||
|
raise HTTPException(400, "Zuerst ein neues Geheimnis erzeugen")
|
||||||
|
if not verify_totp(prof.get("totp_pending_secret"), req.code):
|
||||||
|
raise HTTPException(400, "Code stimmt nicht. Uhrzeit des Geräts prüfen.")
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE profiles
|
||||||
|
SET totp_secret=%s, totp_pending_secret=NULL, totp_enabled=TRUE
|
||||||
|
WHERE id=%s
|
||||||
|
""",
|
||||||
|
(prof["totp_pending_secret"], pid),
|
||||||
|
)
|
||||||
|
plain_codes = _replace_recovery_codes(cur, pid)
|
||||||
|
prof = dict(prof)
|
||||||
|
prof["totp_enabled"] = True
|
||||||
|
prof["totp_secret"] = None
|
||||||
|
revoke_profile_sessions(cur, pid)
|
||||||
|
token, expires = _issue_session(cur, pid, days=session_lifetime_days(prof))
|
||||||
|
payload = _login_payload(prof, token, expires)
|
||||||
|
payload["recovery_codes"] = plain_codes
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_recovery_codes(cur, profile_id: int) -> list[str]:
|
||||||
|
cur.execute("DELETE FROM profile_recovery_codes WHERE profile_id=%s", (profile_id,))
|
||||||
|
plain_codes = generate_recovery_codes()
|
||||||
|
for code in plain_codes:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO profile_recovery_codes (profile_id, code_hash)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
""",
|
||||||
|
(profile_id, hash_recovery_code(code)),
|
||||||
|
)
|
||||||
|
return plain_codes
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/totp/recovery-codes")
|
||||||
|
def regenerate_recovery_codes(req: TotpDisableRequest, session: dict = Depends(require_auth)):
|
||||||
|
"""Neue Codes ausgeben. Die bisherigen werden ungültig. Passwort und aktueller App-Code sind Pflicht."""
|
||||||
|
pid = int(session["profile_id"])
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not prof.get("totp_enabled"):
|
||||||
|
raise HTTPException(400, "Zwei-Faktor ist nicht aktiv")
|
||||||
|
if not verify_pin(req.current_password, prof["pin_hash"]):
|
||||||
|
raise HTTPException(400, "Aktuelles Passwort ist falsch")
|
||||||
|
if not verify_totp(prof.get("totp_secret"), req.code):
|
||||||
|
raise HTTPException(400, "Code aus der App stimmt nicht")
|
||||||
|
plain_codes = _replace_recovery_codes(cur, pid)
|
||||||
|
return {"recovery_codes": plain_codes}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/totp/disable")
|
||||||
|
def totp_disable(req: TotpDisableRequest, session: dict = Depends(require_auth)):
|
||||||
|
pid = int(session["profile_id"])
|
||||||
|
role = (session.get("role") or "").strip().lower()
|
||||||
|
if role in _ADMIN_ROLES and _admin_totp_required():
|
||||||
|
raise HTTPException(400, "Für Plattform-Admins bleibt die Zwei-Faktor-Anmeldung aktiv.")
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT * FROM profiles WHERE id=%s", (pid,))
|
||||||
|
prof = cur.fetchone()
|
||||||
|
if not prof or not verify_pin(req.current_password, prof["pin_hash"]):
|
||||||
|
raise HTTPException(400, "Aktuelles Passwort ist falsch")
|
||||||
|
if not (
|
||||||
|
verify_totp(prof.get("totp_secret"), req.code)
|
||||||
|
or _consume_recovery_code(cur, pid, req.code)
|
||||||
|
):
|
||||||
|
raise HTTPException(400, "Code stimmt nicht")
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE profiles
|
||||||
|
SET totp_enabled=FALSE, totp_secret=NULL, totp_pending_secret=NULL
|
||||||
|
WHERE id=%s
|
||||||
|
""",
|
||||||
|
(pid,),
|
||||||
|
)
|
||||||
|
cur.execute("DELETE FROM profile_recovery_codes WHERE profile_id=%s", (pid,))
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/media-grant")
|
||||||
|
def media_grant(session: dict = Depends(require_auth)):
|
||||||
|
"""Kurzlebiges Token nur für Medien-Dateien. Ersetzt das Sitzungstoken in Bild-URLs."""
|
||||||
|
token, exp = issue_media_grant(int(session["profile_id"]), ttl_seconds=MEDIA_GRANT_TTL_SECONDS)
|
||||||
|
return {
|
||||||
|
"token": token,
|
||||||
|
"expires_at": datetime.fromtimestamp(exp, tz=timezone.utc).isoformat(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/forgot-password")
|
@router.post("/forgot-password")
|
||||||
@limiter.limit("3/minute")
|
@limiter.limit("3/minute")
|
||||||
async def password_reset_request(req: PasswordResetRequest, request: Request):
|
async def password_reset_request(req: PasswordResetRequest, request: Request):
|
||||||
@@ -146,10 +511,17 @@ def password_reset_confirm(req: PasswordResetConfirm):
|
|||||||
if not sess:
|
if not sess:
|
||||||
raise HTTPException(400, "Ungültiger oder abgelaufener Reset-Link")
|
raise HTTPException(400, "Ungültiger oder abgelaufener Reset-Link")
|
||||||
|
|
||||||
pid = sess['profile_id']
|
pid = sess["profile_id"]
|
||||||
new_hash = hash_pin(req.new_password)
|
new_hash = hash_pin(req.new_password)
|
||||||
cur.execute("UPDATE profiles SET pin_hash=%s WHERE id=%s", (new_hash, pid))
|
cur.execute(
|
||||||
cur.execute("DELETE FROM sessions WHERE token=%s", (f"reset_{req.token}",))
|
"""
|
||||||
|
UPDATE profiles
|
||||||
|
SET pin_hash=%s, failed_login_count=0, locked_until=NULL
|
||||||
|
WHERE id=%s
|
||||||
|
""",
|
||||||
|
(new_hash, pid),
|
||||||
|
)
|
||||||
|
revoke_profile_sessions(cur, int(pid))
|
||||||
|
|
||||||
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
|
return {"ok": True, "message": "Passwort erfolgreich zurückgesetzt"}
|
||||||
|
|
||||||
@@ -272,11 +644,14 @@ async def register(req: RegisterRequest, request: Request):
|
|||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
# Check if email already exists
|
cur.execute("SELECT id, name FROM profiles WHERE email=%s", (email,))
|
||||||
cur.execute("SELECT id FROM profiles WHERE email=%s", (email,))
|
existing = cur.fetchone()
|
||||||
if cur.fetchone():
|
if existing:
|
||||||
raise HTTPException(400, "E-Mail-Adresse bereits registriert")
|
existing_name = existing.get("name")
|
||||||
|
else:
|
||||||
|
existing_name = None
|
||||||
|
|
||||||
|
if existing is None:
|
||||||
# Generate verification token
|
# Generate verification token
|
||||||
verification_token = secrets.token_urlsafe(32)
|
verification_token = secrets.token_urlsafe(32)
|
||||||
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
||||||
@@ -322,6 +697,24 @@ async def register(req: RegisterRequest, request: Request):
|
|||||||
(new_profile_id, int(req_club)),
|
(new_profile_id, int(req_club)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
generic = {
|
||||||
|
"ok": True,
|
||||||
|
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach und bestätige deine E-Mail-Adresse.",
|
||||||
|
}
|
||||||
|
if existing is not None:
|
||||||
|
send_email(
|
||||||
|
email,
|
||||||
|
"Shinkan Jinkendo – Registrierung",
|
||||||
|
f"""Hallo {existing_name or name},
|
||||||
|
|
||||||
|
für diese E-Mail-Adresse gibt es bereits ein Konto. Es wurde kein neues Passwort gesetzt.
|
||||||
|
Wenn du den Zugang brauchst, melde dich an oder fordere ein neues Passwort an.
|
||||||
|
|
||||||
|
Dein Shinkan Jinkendo Team
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
return generic
|
||||||
|
|
||||||
verify_url = verification_link(verification_token)
|
verify_url = verification_link(verification_token)
|
||||||
|
|
||||||
email_body = f"""Hallo {name},
|
email_body = f"""Hallo {name},
|
||||||
@@ -340,10 +733,7 @@ Dein Shinkan Jinkendo Team
|
|||||||
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
|
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
|
||||||
print("[SMTP] Verifizierungs-Mail konnte nicht gesendet werden — Logs prüfen, SMTP_* in der Laufzeitumgebung.")
|
print("[SMTP] Verifizierungs-Mail konnte nicht gesendet werden — Logs prüfen, SMTP_* in der Laufzeitumgebung.")
|
||||||
|
|
||||||
return {
|
return generic
|
||||||
"ok": True,
|
|
||||||
"message": "Registrierung erfolgreich! Bitte prüfe dein E-Mail-Postfach und bestätige deine E-Mail-Adresse."
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/verify/{token}")
|
@router.get("/verify/{token}")
|
||||||
@@ -402,44 +792,34 @@ async def verify_email(token: str):
|
|||||||
|
|
||||||
@router.post("/resend-verification")
|
@router.post("/resend-verification")
|
||||||
@limiter.limit("3/hour")
|
@limiter.limit("3/hour")
|
||||||
async def resend_verification(req: dict, request: Request):
|
async def resend_verification(req: ResendVerificationRequest, request: Request):
|
||||||
"""Resend verification email for unverified account."""
|
"""Bestätigung erneut senden. Bekannte und unbekannte Adressen antworten gleich."""
|
||||||
email = req.get('email', '').strip().lower()
|
email = str(req.email).lower().strip()
|
||||||
|
generic = {
|
||||||
if not email:
|
"ok": True,
|
||||||
raise HTTPException(400, "E-Mail-Adresse erforderlich")
|
"message": "Falls ein Account mit dieser E-Mail existiert, wurde eine Bestätigungs-E-Mail versendet.",
|
||||||
|
}
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
|
||||||
# Find profile by email
|
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
SELECT id, name, email, email_verified, verification_token, verification_expires
|
SELECT id, name, email, email_verified, verification_token, verification_expires
|
||||||
FROM profiles
|
FROM profiles
|
||||||
WHERE email=%s
|
WHERE email=%s
|
||||||
""", (email,))
|
""", (email,))
|
||||||
|
|
||||||
prof = cur.fetchone()
|
prof = cur.fetchone()
|
||||||
|
if not prof or prof["email_verified"]:
|
||||||
|
return generic
|
||||||
|
|
||||||
if not prof:
|
|
||||||
# Don't leak info about existing emails
|
|
||||||
return {"ok": True, "message": "Falls ein Account mit dieser E-Mail existiert, wurde eine Bestätigungs-E-Mail versendet."}
|
|
||||||
|
|
||||||
if prof['email_verified']:
|
|
||||||
raise HTTPException(400, "E-Mail-Adresse bereits bestätigt")
|
|
||||||
|
|
||||||
# Generate new verification token
|
|
||||||
verification_token = secrets.token_urlsafe(32)
|
verification_token = secrets.token_urlsafe(32)
|
||||||
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
verification_expires = datetime.now(timezone.utc) + timedelta(hours=24)
|
||||||
|
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
UPDATE profiles
|
UPDATE profiles
|
||||||
SET verification_token=%s, verification_expires=%s
|
SET verification_token=%s, verification_expires=%s
|
||||||
WHERE id=%s
|
WHERE id=%s
|
||||||
""", (verification_token, verification_expires, prof['id']))
|
""", (verification_token, verification_expires, prof["id"]))
|
||||||
|
|
||||||
verify_url = verification_link(verification_token)
|
verify_url = verification_link(verification_token)
|
||||||
|
|
||||||
email_body = f"""Hallo {prof['name']},
|
email_body = f"""Hallo {prof['name']},
|
||||||
|
|
||||||
du hast eine neue Bestätigungs-E-Mail angefordert.
|
du hast eine neue Bestätigungs-E-Mail angefordert.
|
||||||
@@ -452,8 +832,5 @@ Dieser Link ist 24 Stunden gültig.
|
|||||||
|
|
||||||
Dein Shinkan Jinkendo Team
|
Dein Shinkan Jinkendo Team
|
||||||
"""
|
"""
|
||||||
|
send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body)
|
||||||
if not send_email(email, "Shinkan Jinkendo – E-Mail bestätigen", email_body):
|
return generic
|
||||||
raise HTTPException(502, "E-Mail konnte nicht versendet werden. SMTP-Einstellungen und Container-Logs prüfen.")
|
|
||||||
|
|
||||||
return {"ok": True, "message": "Bestätigungs-E-Mail wurde erneut versendet."}
|
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"""
|
||||||
|
API: Katalog-Prompt-Slots (Stammdaten × Slot-Typ).
|
||||||
|
|
||||||
|
Globaler Admin-Katalog (wie catalogs.py) — require_auth + Admin-Rolle, kein TenantContext.
|
||||||
|
Eingetragen in backend/scripts/check_access_layer_hints.py EXEMPT_ROUTERS.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from catalog_prompt_slots import (
|
||||||
|
CATALOG_KINDS,
|
||||||
|
get_catalog_entry_slots,
|
||||||
|
list_slot_type_definitions,
|
||||||
|
upsert_catalog_entry_slots,
|
||||||
|
)
|
||||||
|
from db import get_cursor, get_db
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api", tags=["catalog_prompt_slots"])
|
||||||
|
|
||||||
|
_VALID_KINDS = frozenset(c.kind for c in CATALOG_KINDS)
|
||||||
|
|
||||||
|
|
||||||
|
class CatalogPromptSlotsBody(BaseModel):
|
||||||
|
slots: Dict[str, Optional[str]] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_admin(session: dict = Depends(require_auth)) -> dict:
|
||||||
|
role = (session.get("role") or "").strip().lower()
|
||||||
|
if role not in ("admin", "superadmin"):
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Admins")
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def _slots_table_ready(cur) -> bool:
|
||||||
|
cur.execute("SELECT to_regclass(%s)::text AS t", ("public.catalog_prompt_slots",))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return False
|
||||||
|
val = row.get("t") if isinstance(row, dict) else row[0]
|
||||||
|
return val is not None and str(val).strip() != ""
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/catalog-prompt-slot-types")
|
||||||
|
def api_list_catalog_prompt_slot_types(session: dict = Depends(_require_admin)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _slots_table_ready(cur):
|
||||||
|
raise HTTPException(status_code=503, detail="Tabelle catalog_prompt_slots fehlt.")
|
||||||
|
return {"slot_types": list_slot_type_definitions(cur)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/catalog-prompt-slots/{catalog_kind}/{catalog_id}")
|
||||||
|
def api_get_catalog_prompt_slots(
|
||||||
|
catalog_kind: str,
|
||||||
|
catalog_id: int,
|
||||||
|
session: dict = Depends(_require_admin),
|
||||||
|
):
|
||||||
|
kind = (catalog_kind or "").strip().lower()
|
||||||
|
if kind not in _VALID_KINDS:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Unbekannter catalog_kind: {catalog_kind!r}")
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _slots_table_ready(cur):
|
||||||
|
raise HTTPException(status_code=503, detail="Tabelle catalog_prompt_slots fehlt.")
|
||||||
|
try:
|
||||||
|
return get_catalog_entry_slots(cur, kind, catalog_id)
|
||||||
|
except LookupError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/catalog-prompt-slots/{catalog_kind}/{catalog_id}")
|
||||||
|
def api_put_catalog_prompt_slots(
|
||||||
|
catalog_kind: str,
|
||||||
|
catalog_id: int,
|
||||||
|
body: CatalogPromptSlotsBody,
|
||||||
|
session: dict = Depends(_require_admin),
|
||||||
|
):
|
||||||
|
kind = (catalog_kind or "").strip().lower()
|
||||||
|
if kind not in _VALID_KINDS:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Unbekannter catalog_kind: {catalog_kind!r}")
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
if not _slots_table_ready(cur):
|
||||||
|
raise HTTPException(status_code=503, detail="Tabelle catalog_prompt_slots fehlt.")
|
||||||
|
try:
|
||||||
|
return upsert_catalog_entry_slots(cur, kind, catalog_id, body.slots or {})
|
||||||
|
except LookupError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
@@ -28,11 +28,12 @@ import os
|
|||||||
import re
|
import re
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||||
from pydantic import BaseModel, Field, field_validator
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
from club_tenancy import is_platform_admin, is_superadmin
|
from club_tenancy import is_platform_admin, is_superadmin
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
|
from routers.auth import limiter
|
||||||
from media_legal_hold import (
|
from media_legal_hold import (
|
||||||
LEGAL_HOLD_REASON_CODES,
|
LEGAL_HOLD_REASON_CODES,
|
||||||
assert_superadmin_for_legal_hold,
|
assert_superadmin_for_legal_hold,
|
||||||
@@ -324,6 +325,7 @@ def _resolve_optional_auth(cur, x_auth_token: Optional[str]) -> tuple[Optional[i
|
|||||||
INNER JOIN profiles p ON p.id = s.profile_id
|
INNER JOIN profiles p ON p.id = s.profile_id
|
||||||
WHERE s.token = %s
|
WHERE s.token = %s
|
||||||
AND (s.expires_at IS NULL OR s.expires_at > NOW())
|
AND (s.expires_at IS NULL OR s.expires_at > NOW())
|
||||||
|
AND COALESCE(s.purpose, 'full') = 'full'
|
||||||
""",
|
""",
|
||||||
(x_auth_token,),
|
(x_auth_token,),
|
||||||
)
|
)
|
||||||
@@ -431,8 +433,17 @@ def _report_row_to_dict(row) -> dict:
|
|||||||
|
|
||||||
# ─── Endpoints ──────────────────────────────────────────────────────────────
|
# ─── Endpoints ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _content_report_rate_marker(request: Request) -> None:
|
||||||
|
"""SlowAPI-Ziel für 10 Meldungen pro Stunde. Nicht als Route: der Decorator bricht die Annotationen."""
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
limiter.limit("10/hour")(_content_report_rate_marker)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/content-reports", status_code=201)
|
@router.post("/content-reports", status_code=201)
|
||||||
def submit_content_report(
|
def submit_content_report(
|
||||||
|
request: Request,
|
||||||
body: ContentReportCreate,
|
body: ContentReportCreate,
|
||||||
x_auth_token: Optional[str] = Header(default=None),
|
x_auth_token: Optional[str] = Header(default=None),
|
||||||
):
|
):
|
||||||
@@ -450,6 +461,7 @@ def submit_content_report(
|
|||||||
status_code=400,
|
status_code=400,
|
||||||
detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.",
|
detail="Die Gutglaubenserklärung (good_faith_confirmed) muss bestätigt werden.",
|
||||||
)
|
)
|
||||||
|
limiter._check_request_limit(request, _content_report_rate_marker, False)
|
||||||
|
|
||||||
priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal"
|
priority = "high" if body.report_reason in HIGH_PRIORITY_REASONS else "normal"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,613 @@
|
|||||||
|
"""Distributionsfreigabe: Maschinenabruf und Redaktion.
|
||||||
|
|
||||||
|
Maschinenabruf authentifiziert allein über den Distributions-Schlüssel.
|
||||||
|
# ACCESS_LAYER exempt: kein Trainer-Mandant; Kanal kommt aus der Anbindung.
|
||||||
|
Die Redaktions- und Verwaltungsrouten nutzen TenantContext.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||||
|
from fastapi.responses import FileResponse, Response
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from club_tenancy import is_superadmin
|
||||||
|
from db import get_cursor, get_db
|
||||||
|
from distribution_contract import (
|
||||||
|
InvalidCursor,
|
||||||
|
cursor_secret,
|
||||||
|
decode_cursor,
|
||||||
|
distribution_enabled,
|
||||||
|
)
|
||||||
|
from distribution_service import (
|
||||||
|
access_home,
|
||||||
|
assert_exercise_object,
|
||||||
|
backlog_count,
|
||||||
|
confirm_draft,
|
||||||
|
create_draft,
|
||||||
|
create_named_key,
|
||||||
|
issue_key,
|
||||||
|
list_changes,
|
||||||
|
list_release_drift,
|
||||||
|
load_catalog,
|
||||||
|
load_catalog_exercise,
|
||||||
|
load_asset,
|
||||||
|
load_availability,
|
||||||
|
load_manifest,
|
||||||
|
overview,
|
||||||
|
resolve_bearer,
|
||||||
|
retire_release,
|
||||||
|
revoke_named_key,
|
||||||
|
set_club_api,
|
||||||
|
target_for_key,
|
||||||
|
update_draft,
|
||||||
|
withdraw_release,
|
||||||
|
)
|
||||||
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/distribution/v1", tags=["distribution"])
|
||||||
|
editorial = APIRouter(tags=["distribution-editorial"])
|
||||||
|
|
||||||
|
NO_STORE = {"Cache-Control": "private, no-store"}
|
||||||
|
|
||||||
|
|
||||||
|
def _machine(authorization: Optional[str]):
|
||||||
|
if not distribution_enabled():
|
||||||
|
raise HTTPException(status_code=404, detail="Nicht gefunden", headers=NO_STORE)
|
||||||
|
if not authorization or not authorization.lower().startswith("bearer "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail={"code": "invalid_key", "message": "Schlüssel ungültig."},
|
||||||
|
headers=NO_STORE,
|
||||||
|
)
|
||||||
|
token = authorization.split(" ", 1)[1].strip()
|
||||||
|
held: Optional[HTTPException] = None
|
||||||
|
binding = None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
try:
|
||||||
|
binding = resolve_bearer(cur, token)
|
||||||
|
except HTTPException as exc:
|
||||||
|
held = exc
|
||||||
|
if held is not None:
|
||||||
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||||
|
raise held
|
||||||
|
return binding
|
||||||
|
|
||||||
|
|
||||||
|
def _superadmin(tenant: TenantContext) -> None:
|
||||||
|
if not is_superadmin(tenant.global_role):
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Superadmins dürfen die Distribution verwalten.")
|
||||||
|
|
||||||
|
|
||||||
|
class PublisherBody(BaseModel):
|
||||||
|
name: str = Field(min_length=1, max_length=200)
|
||||||
|
kind: str
|
||||||
|
club_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class RecipientBody(BaseModel):
|
||||||
|
name: str = Field(min_length=1, max_length=200)
|
||||||
|
|
||||||
|
|
||||||
|
class RelationshipBody(BaseModel):
|
||||||
|
publisher_id: str
|
||||||
|
recipient_id: str
|
||||||
|
|
||||||
|
|
||||||
|
class BindingBody(BaseModel):
|
||||||
|
recipient_id: str
|
||||||
|
name: str = Field(min_length=1, max_length=200)
|
||||||
|
|
||||||
|
|
||||||
|
class KeyBody(BaseModel):
|
||||||
|
expires_at: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProfileBody(BaseModel):
|
||||||
|
profile_id: int
|
||||||
|
|
||||||
|
|
||||||
|
class ExerciseAssignBody(BaseModel):
|
||||||
|
exercise_id: int
|
||||||
|
|
||||||
|
|
||||||
|
class SuspendBody(BaseModel):
|
||||||
|
kind: str
|
||||||
|
id: str
|
||||||
|
|
||||||
|
|
||||||
|
class DraftBody(BaseModel):
|
||||||
|
publisher_id: Optional[str] = None
|
||||||
|
recipient_id: Optional[str] = None
|
||||||
|
key_id: Optional[str] = None
|
||||||
|
cut: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
|
class AccessKeyBody(BaseModel):
|
||||||
|
name: str = Field(min_length=1, max_length=200)
|
||||||
|
objects: list[str]
|
||||||
|
visibilities: list[str]
|
||||||
|
context_kind: str = "user"
|
||||||
|
club_id: Optional[int] = None
|
||||||
|
club_ids: list[int] = []
|
||||||
|
|
||||||
|
|
||||||
|
class ClubApiBody(BaseModel):
|
||||||
|
enabled: bool
|
||||||
|
|
||||||
|
|
||||||
|
class CutBody(BaseModel):
|
||||||
|
cut: dict
|
||||||
|
|
||||||
|
|
||||||
|
class ReasonBody(BaseModel):
|
||||||
|
reason_code: str
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/catalog")
|
||||||
|
def get_catalog(cursor: Optional[str] = None, authorization: Optional[str] = Header(default=None)):
|
||||||
|
binding = _machine(authorization)
|
||||||
|
try:
|
||||||
|
assert_exercise_object(binding.get("objects"))
|
||||||
|
except HTTPException as exc:
|
||||||
|
exc.headers = {**(exc.headers or {}), **NO_STORE}
|
||||||
|
raise exc
|
||||||
|
held: Optional[HTTPException] = None
|
||||||
|
payload = None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
try:
|
||||||
|
payload = load_catalog(cur, binding, cursor)
|
||||||
|
except InvalidCursor:
|
||||||
|
held = HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
|
||||||
|
)
|
||||||
|
except HTTPException as exc:
|
||||||
|
held = exc
|
||||||
|
else:
|
||||||
|
conn.commit()
|
||||||
|
if held is not None:
|
||||||
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||||
|
raise held
|
||||||
|
return Response(
|
||||||
|
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||||
|
media_type="application/json",
|
||||||
|
headers=NO_STORE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/catalog/{source_id}")
|
||||||
|
def get_catalog_exercise(source_id: str, authorization: Optional[str] = Header(default=None)):
|
||||||
|
binding = _machine(authorization)
|
||||||
|
try:
|
||||||
|
assert_exercise_object(binding.get("objects"))
|
||||||
|
except HTTPException as exc:
|
||||||
|
exc.headers = {**(exc.headers or {}), **NO_STORE}
|
||||||
|
raise exc
|
||||||
|
held: Optional[HTTPException] = None
|
||||||
|
payload = None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
try:
|
||||||
|
payload = load_catalog_exercise(cur, binding, source_id)
|
||||||
|
except HTTPException as exc:
|
||||||
|
held = exc
|
||||||
|
if held is not None:
|
||||||
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||||
|
raise held
|
||||||
|
return Response(
|
||||||
|
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||||
|
media_type="application/json",
|
||||||
|
headers=NO_STORE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/changes")
|
||||||
|
def get_changes(
|
||||||
|
cursor: Optional[str] = None,
|
||||||
|
limit: Optional[int] = Query(default=None),
|
||||||
|
authorization: Optional[str] = Header(default=None),
|
||||||
|
):
|
||||||
|
binding = _machine(authorization)
|
||||||
|
if limit is None:
|
||||||
|
limit = 50
|
||||||
|
elif limit < 1 or limit > 100:
|
||||||
|
raise HTTPException(status_code=400, detail={"code": "invalid_limit", "message": "limit ist 1 bis 100."}, headers=NO_STORE)
|
||||||
|
try:
|
||||||
|
seq = decode_cursor(cursor_secret(), binding["recipient_id"], cursor)
|
||||||
|
except InvalidCursor:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
|
||||||
|
headers=NO_STORE,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
assert_exercise_object(binding.get("objects"))
|
||||||
|
except HTTPException as exc:
|
||||||
|
exc.headers = {**(exc.headers or {}), **NO_STORE}
|
||||||
|
raise exc
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
payload = list_changes(cur, binding["recipient_id"], seq, limit, binding)
|
||||||
|
return Response(
|
||||||
|
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||||
|
media_type="application/json",
|
||||||
|
headers=NO_STORE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/exercises/{source_id}/availability")
|
||||||
|
def get_availability(source_id: str, authorization: Optional[str] = Header(default=None)):
|
||||||
|
binding = _machine(authorization)
|
||||||
|
held: Optional[HTTPException] = None
|
||||||
|
payload = None
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
try:
|
||||||
|
assert_exercise_object(binding.get("objects"))
|
||||||
|
payload = load_availability(
|
||||||
|
cur, binding["recipient_id"], source_id, binding.get("visibilities"), binding
|
||||||
|
)
|
||||||
|
except HTTPException as exc:
|
||||||
|
held = exc
|
||||||
|
if held is not None:
|
||||||
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||||
|
raise held
|
||||||
|
return Response(
|
||||||
|
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||||
|
media_type="application/json",
|
||||||
|
headers=NO_STORE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/releases/{release_id}")
|
||||||
|
def get_release(release_id: str, authorization: Optional[str] = Header(default=None)):
|
||||||
|
binding = _machine(authorization)
|
||||||
|
held: Optional[HTTPException] = None
|
||||||
|
body = b""
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
try:
|
||||||
|
assert_exercise_object(binding.get("objects"))
|
||||||
|
body = load_manifest(cur, binding["recipient_id"], release_id, binding.get("visibilities"), binding)
|
||||||
|
except HTTPException as exc:
|
||||||
|
held = exc
|
||||||
|
if held is not None:
|
||||||
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||||
|
raise held
|
||||||
|
return Response(content=body, media_type="application/json", headers=NO_STORE)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/releases/{release_id}/assets/{asset_id}")
|
||||||
|
def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Header(default=None)):
|
||||||
|
binding = _machine(authorization)
|
||||||
|
held: Optional[HTTPException] = None
|
||||||
|
path = None
|
||||||
|
media_type = "application/octet-stream"
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
try:
|
||||||
|
assert_exercise_object(binding.get("objects"))
|
||||||
|
path, media_type = load_asset(
|
||||||
|
cur, binding["recipient_id"], release_id, asset_id, binding.get("visibilities"), binding
|
||||||
|
)
|
||||||
|
except HTTPException as exc:
|
||||||
|
held = exc
|
||||||
|
if held is not None:
|
||||||
|
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||||
|
raise held
|
||||||
|
return FileResponse(path, media_type=media_type, headers=NO_STORE)
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.get("/api/exercises/{exercise_id}/distribution")
|
||||||
|
def exercise_distribution(exercise_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
return overview(cur, exercise_id, tenant.profile_id, tenant.global_role or "")
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts")
|
||||||
|
def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
from routers.exercises import _assert_can_edit_exercise
|
||||||
|
|
||||||
|
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||||
|
if body.key_id:
|
||||||
|
publisher_id, recipient_id = target_for_key(
|
||||||
|
cur, exercise_id, body.key_id, tenant.profile_id, tenant.global_role or ""
|
||||||
|
)
|
||||||
|
elif body.publisher_id and body.recipient_id:
|
||||||
|
publisher_id, recipient_id = body.publisher_id, body.recipient_id
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=400, detail="Wähle einen API-Schlüssel.")
|
||||||
|
result = create_draft(
|
||||||
|
cur,
|
||||||
|
exercise_id,
|
||||||
|
publisher_id,
|
||||||
|
recipient_id,
|
||||||
|
tenant.profile_id,
|
||||||
|
tenant.global_role or "",
|
||||||
|
body.cut,
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.put("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}")
|
||||||
|
def put_draft(exercise_id: int, draft_id: str, body: CutBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
from routers.exercises import _assert_can_edit_exercise
|
||||||
|
|
||||||
|
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||||
|
result = update_draft(
|
||||||
|
cur, exercise_id, draft_id, body.cut, tenant.profile_id, tenant.global_role or ""
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}/confirm")
|
||||||
|
def post_confirm(exercise_id: int, draft_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = confirm_draft(cur, exercise_id, draft_id, tenant.profile_id, tenant.global_role or "")
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/releases/{release_id}/retire")
|
||||||
|
def post_retire(release_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = retire_release(cur, release_id, tenant.profile_id, tenant.global_role or "")
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/releases/{release_id}/withdraw")
|
||||||
|
def post_withdraw(release_id: str, body: ReasonBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = withdraw_release(cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "release", None)
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/releases/{release_id}/variants/{variant_id}/withdraw")
|
||||||
|
def post_withdraw_variant(
|
||||||
|
release_id: str,
|
||||||
|
variant_id: str,
|
||||||
|
body: ReasonBody,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = withdraw_release(
|
||||||
|
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "variant", variant_id
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/releases/{release_id}/assets/{asset_id}/withdraw")
|
||||||
|
def post_withdraw_asset(
|
||||||
|
release_id: str,
|
||||||
|
asset_id: str,
|
||||||
|
body: ReasonBody,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = withdraw_release(
|
||||||
|
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "asset", asset_id
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/publishers")
|
||||||
|
def post_publisher(body: PublisherBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
if body.kind not in ("platform", "own", "club"):
|
||||||
|
raise HTTPException(status_code=400, detail="kind ist platform, own oder club.")
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO distribution_publishers (name, kind, club_id)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(body.name, body.kind, body.club_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
conn.commit()
|
||||||
|
return {"id": str(row["id"])}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/recipients")
|
||||||
|
def post_recipient(body: RecipientBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id",
|
||||||
|
(body.name,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
conn.commit()
|
||||||
|
return {"id": str(row["id"])}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/relationships")
|
||||||
|
def post_relationship(body: RelationshipBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO distribution_relationships (publisher_id, recipient_id)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(body.publisher_id, body.recipient_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
conn.commit()
|
||||||
|
return {"id": str(row["id"])}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/bindings")
|
||||||
|
def post_binding(body: BindingBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO distribution_bindings (recipient_id, name)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(body.recipient_id, body.name),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
conn.commit()
|
||||||
|
return {"id": str(row["id"])}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/bindings/{binding_id}/keys")
|
||||||
|
def post_key(binding_id: str, body: KeyBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = issue_key(cur, binding_id, body.expires_at)
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/keys/{key_prefix}/revoke")
|
||||||
|
def post_revoke(key_prefix: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE distribution_keys SET revoked_at = NOW() WHERE key_prefix = %s AND revoked_at IS NULL",
|
||||||
|
(key_prefix,),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/releasers")
|
||||||
|
def post_releaser(publisher_id: str, body: ProfileBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO distribution_releasers (publisher_id, profile_id)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT DO NOTHING
|
||||||
|
""",
|
||||||
|
(publisher_id, body.profile_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/exercises")
|
||||||
|
def post_assign(publisher_id: str, body: ExerciseAssignBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO distribution_publisher_exercises (publisher_id, exercise_id)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT DO NOTHING
|
||||||
|
""",
|
||||||
|
(publisher_id, body.exercise_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/admin/suspend")
|
||||||
|
def post_suspend(body: SuspendBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
table = {
|
||||||
|
"publisher": "distribution_publishers",
|
||||||
|
"recipient": "distribution_recipients",
|
||||||
|
"binding": "distribution_bindings",
|
||||||
|
}.get(body.kind)
|
||||||
|
if table is None:
|
||||||
|
raise HTTPException(status_code=400, detail="kind ist publisher, recipient oder binding.")
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(f"UPDATE {table} SET status = 'suspended' WHERE id = %s", (body.id,))
|
||||||
|
conn.commit()
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.get("/api/distribution/admin/backlog")
|
||||||
|
def get_backlog(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
_superadmin(tenant)
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
return {"count": backlog_count(cur)}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.get("/api/distribution/release-updates")
|
||||||
|
def get_release_updates(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
return {"items": list_release_drift(cur, tenant.profile_id, tenant.global_role or "")}
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.get("/api/distribution/access")
|
||||||
|
def get_access(tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
return access_home(cur, tenant.profile_id, tenant.global_role or "")
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.put("/api/distribution/access/clubs/{club_id}")
|
||||||
|
def put_club_api(club_id: int, body: ClubApiBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = set_club_api(cur, club_id, body.enabled, tenant.global_role or "")
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/access/keys")
|
||||||
|
def post_access_key(body: AccessKeyBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = create_named_key(
|
||||||
|
cur,
|
||||||
|
name=body.name,
|
||||||
|
objects=body.objects,
|
||||||
|
visibilities=body.visibilities,
|
||||||
|
context_kind=body.context_kind,
|
||||||
|
club_id=body.club_id,
|
||||||
|
club_ids=body.club_ids,
|
||||||
|
profile_id=tenant.profile_id,
|
||||||
|
role=tenant.global_role or "",
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@editorial.post("/api/distribution/access/keys/{key_id}/revoke")
|
||||||
|
def post_revoke_named(key_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
result = revoke_named_key(cur, key_id, tenant.profile_id, tenant.global_role or "")
|
||||||
|
conn.commit()
|
||||||
|
return result
|
||||||
@@ -3,19 +3,23 @@ Progressionsgraph zwischen Übungen (Übung → Übung), Migration 032–034.
|
|||||||
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
|
Optional Übungsvarianten als Knoten-Endpunkte; Sequenz-Bulk-Anlage.
|
||||||
AuthZ analog training_plan_templates: Bearbeiten/Löschen wie Übungen; Governance-Übergänge zentral.
|
AuthZ analog training_plan_templates: Bearbeiten/Löschen wie Übungen; Governance-Übergänge zentral.
|
||||||
"""
|
"""
|
||||||
from typing import Any, List, Optional
|
import json
|
||||||
|
from typing import Any, Dict, List, Mapping, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from pydantic import BaseModel, Field, model_validator
|
from pydantic import BaseModel, Field, model_validator
|
||||||
from psycopg2 import IntegrityError
|
from psycopg2 import IntegrityError
|
||||||
|
from psycopg2.extras import Json
|
||||||
|
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
|
from progression_graph_planning_artifact import normalize_planning_roadmap_payload
|
||||||
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
from tenant_context import TenantContext, get_tenant_context, library_content_visibility_sql
|
||||||
from club_tenancy import (
|
from club_tenancy import (
|
||||||
assert_library_content_deletable,
|
assert_library_content_deletable,
|
||||||
assert_library_content_editable,
|
assert_library_content_editable,
|
||||||
assert_library_content_governance_transition,
|
assert_library_content_governance_transition,
|
||||||
assert_valid_governance_visibility,
|
assert_valid_governance_visibility,
|
||||||
|
is_platform_admin,
|
||||||
library_content_visible_to_profile,
|
library_content_visible_to_profile,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -36,6 +40,7 @@ class ProgressionGraphUpdate(BaseModel):
|
|||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
|
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
|
||||||
club_id: Optional[int] = None
|
club_id: Optional[int] = None
|
||||||
|
planning_roadmap: Optional[Dict[str, Any]] = None
|
||||||
|
|
||||||
|
|
||||||
class ProgressionEdgeCreate(BaseModel):
|
class ProgressionEdgeCreate(BaseModel):
|
||||||
@@ -59,6 +64,7 @@ class SequenceStep(BaseModel):
|
|||||||
class ProgressionSequenceCreate(BaseModel):
|
class ProgressionSequenceCreate(BaseModel):
|
||||||
steps: List[SequenceStep] = Field(..., min_length=2)
|
steps: List[SequenceStep] = Field(..., min_length=2)
|
||||||
segment_notes: Optional[List[Optional[str]]] = None
|
segment_notes: Optional[List[Optional[str]]] = None
|
||||||
|
planning_roadmap: Optional[Dict[str, Any]] = None
|
||||||
"""Länge muss len(steps)-1 sein, wenn gesetzt; Notiz pro Kante Zwischen je zwei Schritten."""
|
"""Länge muss len(steps)-1 sein, wenn gesetzt; Notiz pro Kante Zwischen je zwei Schritten."""
|
||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
@@ -116,6 +122,17 @@ def _assert_graph_writable(cur, row: dict, profile_id: int, role: str) -> None:
|
|||||||
assert_library_content_editable(cur, profile_id, role, row)
|
assert_library_content_editable(cur, profile_id, role, row)
|
||||||
|
|
||||||
|
|
||||||
|
def _persist_graph_planning_roadmap(cur, graph_id: int, raw: Optional[Dict[str, Any]]) -> None:
|
||||||
|
try:
|
||||||
|
normalized = normalize_planning_roadmap_payload(raw)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE exercise_progression_graphs SET planning_roadmap = %s WHERE id = %s",
|
||||||
|
(Json(normalized) if normalized is not None else None, graph_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
def _require_graph_read(cur, graph_id: int, profile_id: int, role: str) -> dict:
|
||||||
row = _graph_row(cur, graph_id)
|
row = _graph_row(cur, graph_id)
|
||||||
_assert_graph_readable(cur, row, profile_id, role)
|
_assert_graph_readable(cur, row, profile_id, role)
|
||||||
@@ -160,6 +177,87 @@ def _assert_variant_for_exercise(cur, exercise_id: int, variant_id: Optional[int
|
|||||||
raise HTTPException(status_code=400, detail="Variante gehört nicht zur gewählten Übung")
|
raise HTTPException(status_code=400, detail="Variante gehört nicht zur gewählten Übung")
|
||||||
|
|
||||||
|
|
||||||
|
def _exercise_allowed_in_progression_graph(
|
||||||
|
exercise_row: Mapping[str, Any],
|
||||||
|
*,
|
||||||
|
graph_visibility: str,
|
||||||
|
graph_club_id: Optional[int],
|
||||||
|
profile_id: int,
|
||||||
|
role: str,
|
||||||
|
) -> bool:
|
||||||
|
"""Prüft, ob eine Übung zur Sichtbarkeit des Progressionsgraphen passt."""
|
||||||
|
ex_vis = (exercise_row.get("visibility") or "private").strip().lower()
|
||||||
|
gvis = (graph_visibility or "private").strip().lower()
|
||||||
|
if gvis == "private":
|
||||||
|
if ex_vis == "official":
|
||||||
|
return True
|
||||||
|
if ex_vis == "club":
|
||||||
|
return True
|
||||||
|
if ex_vis == "private":
|
||||||
|
if is_platform_admin(role):
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
return int(exercise_row.get("created_by") or 0) == int(profile_id)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
return False
|
||||||
|
if gvis == "club":
|
||||||
|
if ex_vis == "official":
|
||||||
|
return True
|
||||||
|
if ex_vis != "club":
|
||||||
|
return False
|
||||||
|
ex_club = exercise_row.get("club_id")
|
||||||
|
if ex_club is None:
|
||||||
|
return False
|
||||||
|
if graph_club_id is None:
|
||||||
|
return True
|
||||||
|
return int(ex_club) == int(graph_club_id)
|
||||||
|
return ex_vis == "official"
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_exercises_allowed_in_graph(
|
||||||
|
cur,
|
||||||
|
graph_id: int,
|
||||||
|
profile_id: int,
|
||||||
|
role: str,
|
||||||
|
*exercise_ids: int,
|
||||||
|
) -> None:
|
||||||
|
"""400 wenn eine Übung nicht zur Graph-Sichtbarkeit passt."""
|
||||||
|
row = _graph_row(cur, graph_id)
|
||||||
|
gvis = (row.get("visibility") or "private").strip().lower()
|
||||||
|
gclub_raw = row.get("club_id")
|
||||||
|
gclub = int(gclub_raw) if gclub_raw is not None else None
|
||||||
|
unique = list(dict.fromkeys(exercise_ids))
|
||||||
|
if not unique:
|
||||||
|
return
|
||||||
|
ph = ",".join(["%s"] * len(unique))
|
||||||
|
cur.execute(
|
||||||
|
f"SELECT id, title, visibility, club_id, created_by FROM exercises WHERE id IN ({ph})",
|
||||||
|
tuple(unique),
|
||||||
|
)
|
||||||
|
by_id = {int(r2d(r)["id"]): r2d(r) for r in cur.fetchall()}
|
||||||
|
for eid in unique:
|
||||||
|
ex = by_id.get(int(eid))
|
||||||
|
if not ex:
|
||||||
|
continue
|
||||||
|
if _exercise_allowed_in_progression_graph(
|
||||||
|
ex,
|
||||||
|
graph_visibility=gvis,
|
||||||
|
graph_club_id=gclub,
|
||||||
|
profile_id=profile_id,
|
||||||
|
role=role,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
title = (ex.get("title") or "").strip() or f"#{eid}"
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=(
|
||||||
|
f"Übung „{title}“ (Sichtbarkeit: {ex.get('visibility') or 'private'}) "
|
||||||
|
f"passt nicht zum Progressionsgraphen ({gvis})."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _insert_edge_row(
|
def _insert_edge_row(
|
||||||
cur,
|
cur,
|
||||||
graph_id: int,
|
graph_id: int,
|
||||||
@@ -241,6 +339,150 @@ def get_progression_graph(
|
|||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def _exercise_ids_from_planning_roadmap(artifact: Optional[Dict[str, Any]]) -> set[int]:
|
||||||
|
ids: set[int] = set()
|
||||||
|
if not artifact or not isinstance(artifact, dict):
|
||||||
|
return ids
|
||||||
|
for slot in artifact.get("slot_contents") or []:
|
||||||
|
if not isinstance(slot, dict):
|
||||||
|
continue
|
||||||
|
primary = slot.get("primary") if isinstance(slot.get("primary"), dict) else {}
|
||||||
|
if primary.get("kind") == "library" and primary.get("exercise_id") is not None:
|
||||||
|
try:
|
||||||
|
ids.add(int(primary["exercise_id"]))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
for sib in slot.get("siblings") or []:
|
||||||
|
if not isinstance(sib, dict):
|
||||||
|
continue
|
||||||
|
if sib.get("kind") == "library" and sib.get("exercise_id") is not None:
|
||||||
|
try:
|
||||||
|
ids.add(int(sib["exercise_id"]))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def _collect_graph_referenced_exercise_ids(cur, graph_id: int) -> set[int]:
|
||||||
|
ids: set[int] = set()
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT from_exercise_id, to_exercise_id
|
||||||
|
FROM exercise_progression_edges
|
||||||
|
WHERE graph_id = %s
|
||||||
|
""",
|
||||||
|
(graph_id,),
|
||||||
|
)
|
||||||
|
for row in cur.fetchall():
|
||||||
|
for key in ("from_exercise_id", "to_exercise_id"):
|
||||||
|
raw = row.get(key)
|
||||||
|
if raw is not None:
|
||||||
|
ids.add(int(raw))
|
||||||
|
cur.execute(
|
||||||
|
"SELECT planning_roadmap FROM exercise_progression_graphs WHERE id = %s",
|
||||||
|
(graph_id,),
|
||||||
|
)
|
||||||
|
prow = cur.fetchone()
|
||||||
|
if prow and prow.get("planning_roadmap"):
|
||||||
|
art = prow["planning_roadmap"]
|
||||||
|
if isinstance(art, str):
|
||||||
|
try:
|
||||||
|
art = json.loads(art)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
art = None
|
||||||
|
ids |= _exercise_ids_from_planning_roadmap(art if isinstance(art, dict) else None)
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def _graph_promotion_transition(graph_visibility: str, target_visibility: str) -> Optional[tuple[str, ...]]:
|
||||||
|
"""
|
||||||
|
Erlaubte Graph-Promotions und welche Übungs-Sichtbarkeiten mit angehoben werden müssen.
|
||||||
|
|
||||||
|
Returns None wenn kein Übungs-Promotion-Hinweis nötig.
|
||||||
|
"""
|
||||||
|
gvis = (graph_visibility or "private").strip().lower()
|
||||||
|
tvis = (target_visibility or "").strip().lower()
|
||||||
|
transitions: Dict[tuple[str, str], tuple[str, ...]] = {
|
||||||
|
("private", "club"): ("private",),
|
||||||
|
("private", "official"): ("private", "club"),
|
||||||
|
("club", "official"): ("private", "club"),
|
||||||
|
}
|
||||||
|
return transitions.get((gvis, tvis))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/exercise-progression-graphs/{graph_id}/visibility-promotion-candidates")
|
||||||
|
def list_visibility_promotion_candidates(
|
||||||
|
graph_id: int,
|
||||||
|
target_visibility: str = Query(default="club", pattern="^(club|official)$"),
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Übungen im Graph, die bei Promotion des Graphen mit angehoben werden müssten.
|
||||||
|
|
||||||
|
Unterstützt: private→club, private→official, club→official.
|
||||||
|
"""
|
||||||
|
profile_id = tenant.profile_id
|
||||||
|
role = tenant.global_role
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
row = _require_graph_read(cur, graph_id, profile_id, role)
|
||||||
|
graph_vis = (row.get("visibility") or "private").strip().lower()
|
||||||
|
target_vis = (target_visibility or "club").strip().lower()
|
||||||
|
need_vis = _graph_promotion_transition(graph_vis, target_vis)
|
||||||
|
if not need_vis:
|
||||||
|
return {
|
||||||
|
"graph_id": graph_id,
|
||||||
|
"graph_visibility": graph_vis,
|
||||||
|
"target_visibility": target_vis,
|
||||||
|
"exercises": [],
|
||||||
|
}
|
||||||
|
ref_ids = _collect_graph_referenced_exercise_ids(cur, graph_id)
|
||||||
|
if not ref_ids:
|
||||||
|
return {
|
||||||
|
"graph_id": graph_id,
|
||||||
|
"graph_visibility": graph_vis,
|
||||||
|
"target_visibility": target_vis,
|
||||||
|
"exercises": [],
|
||||||
|
}
|
||||||
|
vis_placeholders = ",".join(["%s"] * len(need_vis))
|
||||||
|
ph = ",".join(["%s"] * len(ref_ids))
|
||||||
|
cur.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, title, visibility, club_id, created_by
|
||||||
|
FROM exercises
|
||||||
|
WHERE id IN ({ph})
|
||||||
|
AND LOWER(TRIM(COALESCE(visibility, ''))) IN ({vis_placeholders})
|
||||||
|
ORDER BY title
|
||||||
|
""",
|
||||||
|
list(ref_ids) + list(need_vis),
|
||||||
|
)
|
||||||
|
exercises = []
|
||||||
|
for ex in cur.fetchall():
|
||||||
|
exd = r2d(ex)
|
||||||
|
if not library_content_visible_to_profile(
|
||||||
|
cur,
|
||||||
|
profile_id,
|
||||||
|
(exd.get("visibility") or "private").strip().lower(),
|
||||||
|
exd.get("club_id"),
|
||||||
|
exd.get("created_by"),
|
||||||
|
role,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
exercises.append(
|
||||||
|
{
|
||||||
|
"id": exd["id"],
|
||||||
|
"title": exd.get("title"),
|
||||||
|
"visibility": exd.get("visibility"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"graph_id": graph_id,
|
||||||
|
"graph_visibility": graph_vis,
|
||||||
|
"target_visibility": target_vis,
|
||||||
|
"exercises": exercises,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/exercise-progression-graphs", status_code=201)
|
@router.post("/exercise-progression-graphs", status_code=201)
|
||||||
def create_progression_graph(
|
def create_progression_graph(
|
||||||
body: ProgressionGraphCreate,
|
body: ProgressionGraphCreate,
|
||||||
@@ -353,15 +595,24 @@ def update_progression_graph(
|
|||||||
fields.append("club_id = %s")
|
fields.append("club_id = %s")
|
||||||
params.append(next_club if next_vis == "club" else None)
|
params.append(next_club if next_vis == "club" else None)
|
||||||
|
|
||||||
if not fields:
|
if "planning_roadmap" in original:
|
||||||
|
_persist_graph_planning_roadmap(cur, graph_id, original.get("planning_roadmap"))
|
||||||
|
|
||||||
|
if not fields and "planning_roadmap" not in original:
|
||||||
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
||||||
|
|
||||||
|
if fields:
|
||||||
fields.append("updated_at = NOW()")
|
fields.append("updated_at = NOW()")
|
||||||
params.append(graph_id)
|
params.append(graph_id)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
f"UPDATE exercise_progression_graphs SET {', '.join(fields)} WHERE id = %s",
|
f"UPDATE exercise_progression_graphs SET {', '.join(fields)} WHERE id = %s",
|
||||||
tuple(params),
|
tuple(params),
|
||||||
)
|
)
|
||||||
|
elif "planning_roadmap" in original:
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE exercise_progression_graphs SET updated_at = NOW() WHERE id = %s",
|
||||||
|
(graph_id,),
|
||||||
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
return get_progression_graph(graph_id, include_edges=False, tenant=tenant)
|
||||||
@@ -419,6 +670,9 @@ def create_progression_edge(
|
|||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_require_graph_write(cur, graph_id, profile_id, role)
|
_require_graph_write(cur, graph_id, profile_id, role)
|
||||||
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
|
_assert_exercises_exist(cur, body.from_exercise_id, body.to_exercise_id)
|
||||||
|
_assert_exercises_allowed_in_graph(
|
||||||
|
cur, graph_id, profile_id, role, body.from_exercise_id, body.to_exercise_id
|
||||||
|
)
|
||||||
fv = body.from_exercise_variant_id
|
fv = body.from_exercise_variant_id
|
||||||
tv = body.to_exercise_variant_id
|
tv = body.to_exercise_variant_id
|
||||||
_assert_variant_for_exercise(cur, body.from_exercise_id, fv)
|
_assert_variant_for_exercise(cur, body.from_exercise_id, fv)
|
||||||
@@ -467,6 +721,7 @@ def create_progression_sequence(
|
|||||||
|
|
||||||
ex_ids = [s.exercise_id for s in steps]
|
ex_ids = [s.exercise_id for s in steps]
|
||||||
_assert_exercises_exist(cur, *ex_ids)
|
_assert_exercises_exist(cur, *ex_ids)
|
||||||
|
_assert_exercises_allowed_in_graph(cur, graph_id, profile_id, role, *ex_ids)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for i in range(n_seg):
|
for i in range(n_seg):
|
||||||
@@ -488,6 +743,12 @@ def create_progression_sequence(
|
|||||||
note,
|
note,
|
||||||
)
|
)
|
||||||
created.append(row)
|
created.append(row)
|
||||||
|
if body.planning_roadmap is not None:
|
||||||
|
_persist_graph_planning_roadmap(cur, graph_id, body.planning_roadmap)
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE exercise_progression_graphs SET updated_at = NOW() WHERE id = %s",
|
||||||
|
(graph_id,),
|
||||||
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
except IntegrityError as e:
|
except IntegrityError as e:
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from club_tenancy import (
|
|||||||
club_admin_shares_club_with_creator,
|
club_admin_shares_club_with_creator,
|
||||||
has_club_role,
|
has_club_role,
|
||||||
is_platform_admin,
|
is_platform_admin,
|
||||||
|
is_superadmin,
|
||||||
library_content_visible_to_profile,
|
library_content_visible_to_profile,
|
||||||
)
|
)
|
||||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
||||||
@@ -39,6 +40,8 @@ from ai_prompt_context import ExerciseFormAiFocusRow, ExerciseFormAiPromptContex
|
|||||||
from ai_prompt_job import run_exercise_form_ai_suggestion
|
from ai_prompt_job import run_exercise_form_ai_suggestion
|
||||||
from account_lifecycle import assert_min_account_state
|
from account_lifecycle import assert_min_account_state
|
||||||
from capabilities import probe_capability
|
from capabilities import probe_capability
|
||||||
|
from distribution_contract import OFFICIAL_WRITE_DENIED, official_write_allowed
|
||||||
|
from distribution_service import blocks_exercise_delete, blocks_media_delete, blocks_variant_delete
|
||||||
from club_features import (
|
from club_features import (
|
||||||
consume_club_feature_with_usage,
|
consume_club_feature_with_usage,
|
||||||
merge_feature_usage_into_response,
|
merge_feature_usage_into_response,
|
||||||
@@ -163,24 +166,9 @@ ALLOWED_UPLOAD_MIMES = frozenset(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
# Dateiendung → MIME wenn der Client keinen sinnvollen Content-Type sendet (häufig mobil / iOS).
|
|
||||||
_UPLOAD_FILENAME_MIME_FALLBACK = {
|
|
||||||
".jpg": "image/jpeg",
|
|
||||||
".jpeg": "image/jpeg",
|
|
||||||
".png": "image/png",
|
|
||||||
".gif": "image/gif",
|
|
||||||
".heic": "image/heic",
|
|
||||||
".heif": "image/heif",
|
|
||||||
".mp4": "video/mp4",
|
|
||||||
".mov": "video/quicktime",
|
|
||||||
".pdf": "application/pdf",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
|
def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
|
||||||
"""Erkennt erlaubte MIME-Typen anhand weniger Magic Bytes (ohne Pillow/python-magic)."""
|
"""Erkennt erlaubte MIME-Typen anhand weniger Magic Bytes (ohne Pillow/python-magic)."""
|
||||||
if len(raw) < 12:
|
|
||||||
return None
|
|
||||||
if raw[:3] == b"\xff\xd8\xff":
|
if raw[:3] == b"\xff\xd8\xff":
|
||||||
return "image/jpeg"
|
return "image/jpeg"
|
||||||
if raw[:8] == b"\x89PNG\r\n\x1a\n":
|
if raw[:8] == b"\x89PNG\r\n\x1a\n":
|
||||||
@@ -189,7 +177,7 @@ def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
|
|||||||
return "image/gif"
|
return "image/gif"
|
||||||
if raw[:4] == b"%PDF":
|
if raw[:4] == b"%PDF":
|
||||||
return "application/pdf"
|
return "application/pdf"
|
||||||
if raw[4:8] != b"ftyp":
|
if len(raw) < 12 or raw[4:8] != b"ftyp":
|
||||||
return None
|
return None
|
||||||
brand = raw[8:12]
|
brand = raw[8:12]
|
||||||
# HEIC / HEIF (u. a. iPhone „高效率“)
|
# HEIC / HEIF (u. a. iPhone „高效率“)
|
||||||
@@ -208,17 +196,11 @@ def resolve_upload_mime_type(
|
|||||||
content_type: Optional[str],
|
content_type: Optional[str],
|
||||||
filename: Optional[str],
|
filename: Optional[str],
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Ermittelt ein erlaubtes MIME (Client-Header, Magic Bytes oder Dateiendung)."""
|
"""MIME nur aus dem Dateiinhalt. Client-Header und Dateiendung entscheiden nicht."""
|
||||||
ct = (content_type or "").split(";")[0].strip().lower()
|
|
||||||
if ct in ALLOWED_UPLOAD_MIMES:
|
|
||||||
return ct
|
|
||||||
guessed = _sniff_allowed_upload_mime(raw)
|
guessed = _sniff_allowed_upload_mime(raw)
|
||||||
if guessed in ALLOWED_UPLOAD_MIMES:
|
if guessed in ALLOWED_UPLOAD_MIMES:
|
||||||
return guessed
|
return guessed
|
||||||
ext = Path(filename or "").suffix.lower()
|
ct = (content_type or "").split(";")[0].strip().lower()
|
||||||
fb = _UPLOAD_FILENAME_MIME_FALLBACK.get(ext)
|
|
||||||
if fb in ALLOWED_UPLOAD_MIMES:
|
|
||||||
return fb
|
|
||||||
raise ValueError(f"Dateityp nicht erlaubt: {ct or 'unbekannt'}")
|
raise ValueError(f"Dateityp nicht erlaubt: {ct or 'unbekannt'}")
|
||||||
|
|
||||||
|
|
||||||
@@ -469,6 +451,11 @@ _MAX_BULK_METADATA_IDS = 500
|
|||||||
_MAX_BULK_RELATION_IDS_PER_KIND = 80
|
_MAX_BULK_RELATION_IDS_PER_KIND = 80
|
||||||
|
|
||||||
|
|
||||||
|
class ExerciseApiOfferingPatch(BaseModel):
|
||||||
|
exercise_ids: list[int] = Field(..., min_length=1, max_length=_MAX_BULK_METADATA_IDS)
|
||||||
|
api_offered: bool
|
||||||
|
|
||||||
|
|
||||||
class ExerciseBulkMetadataPatch(BaseModel):
|
class ExerciseBulkMetadataPatch(BaseModel):
|
||||||
"""Massenänderung: Sichtbarkeit/Status und/oder Zuordnungen (Kataloge)."""
|
"""Massenänderung: Sichtbarkeit/Status und/oder Zuordnungen (Kataloge)."""
|
||||||
|
|
||||||
@@ -584,11 +571,13 @@ def _assert_can_edit_exercise(cur, exercise_id: int, tenant: TenantContext) -> N
|
|||||||
owner = rd.get("created_by")
|
owner = rd.get("created_by")
|
||||||
if owner is not None:
|
if owner is not None:
|
||||||
owner = int(owner)
|
owner = int(owner)
|
||||||
|
ex_vis = (rd.get("visibility") or "private").strip().lower()
|
||||||
|
if not official_write_allowed(ex_vis, role):
|
||||||
|
raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
|
||||||
if owner == profile_id:
|
if owner == profile_id:
|
||||||
return
|
return
|
||||||
if is_platform_admin(role):
|
if is_platform_admin(role):
|
||||||
return
|
return
|
||||||
ex_vis = (rd.get("visibility") or "private").strip().lower()
|
|
||||||
ex_cid_raw = rd.get("club_id")
|
ex_cid_raw = rd.get("club_id")
|
||||||
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||||
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, profile_id, ex_cid, role):
|
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, profile_id, ex_cid, role):
|
||||||
@@ -1479,9 +1468,13 @@ def _exercise_delete_usage_message(counts: dict) -> str:
|
|||||||
def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
||||||
pid = tenant.profile_id
|
pid = tenant.profile_id
|
||||||
role = tenant.global_role
|
role = tenant.global_role
|
||||||
|
vis = str(row.get("visibility") or "private").strip().lower()
|
||||||
|
if vis == "official":
|
||||||
|
if not is_superadmin(role):
|
||||||
|
raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
|
||||||
|
return
|
||||||
if is_platform_admin(role):
|
if is_platform_admin(role):
|
||||||
return
|
return
|
||||||
vis = str(row.get("visibility") or "private").strip().lower()
|
|
||||||
cid = row.get("club_id")
|
cid = row.get("club_id")
|
||||||
creator = row.get("created_by")
|
creator = row.get("created_by")
|
||||||
try:
|
try:
|
||||||
@@ -1489,11 +1482,6 @@ def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
|||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
creator_int = None
|
creator_int = None
|
||||||
|
|
||||||
if vis == "official":
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Globale Übungen dürfen nur von Plattform-Admins gelöscht werden.",
|
|
||||||
)
|
|
||||||
if vis == "club":
|
if vis == "club":
|
||||||
try:
|
try:
|
||||||
ex_club = int(cid) if cid is not None else None
|
ex_club = int(cid) if cid is not None else None
|
||||||
@@ -1518,6 +1506,41 @@ def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/exercises/api-offering")
|
||||||
|
def patch_exercise_api_offering(
|
||||||
|
body: ExerciseApiOfferingPatch,
|
||||||
|
tenant: TenantContext = Depends(get_tenant_context),
|
||||||
|
):
|
||||||
|
"""Schaltet die aktuelle API-Bereitstellung. Rechte sind die Bearbeitungsrechte der Übung."""
|
||||||
|
unique_ids = sorted({int(item) for item in body.exercise_ids if item is not None and int(item) > 0})
|
||||||
|
if not unique_ids:
|
||||||
|
raise HTTPException(status_code=400, detail="Keine gültigen Übungs-IDs")
|
||||||
|
updated: List[Dict[str, Any]] = []
|
||||||
|
denied: List[Dict[str, Any]] = []
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
for ex_id in unique_ids:
|
||||||
|
cur.execute("SELECT id, title FROM exercises WHERE id = %s", (ex_id,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
denied.append({"id": ex_id, "detail": "Übung nicht gefunden"})
|
||||||
|
continue
|
||||||
|
item = r2d(row)
|
||||||
|
try:
|
||||||
|
_assert_can_edit_exercise(cur, ex_id, tenant)
|
||||||
|
except HTTPException as exc:
|
||||||
|
detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
|
||||||
|
denied.append({"id": ex_id, "title": item.get("title"), "detail": detail})
|
||||||
|
continue
|
||||||
|
cur.execute(
|
||||||
|
"UPDATE exercises SET api_offered = %s, updated_at = NOW() WHERE id = %s",
|
||||||
|
(bool(body.api_offered), ex_id),
|
||||||
|
)
|
||||||
|
updated.append({"id": ex_id, "title": item.get("title"), "api_offered": bool(body.api_offered)})
|
||||||
|
conn.commit()
|
||||||
|
return {"updated": updated, "denied": denied}
|
||||||
|
|
||||||
|
|
||||||
@router.patch("/exercises/bulk-metadata")
|
@router.patch("/exercises/bulk-metadata")
|
||||||
def bulk_patch_exercises_metadata(
|
def bulk_patch_exercises_metadata(
|
||||||
body: ExerciseBulkMetadataPatch,
|
body: ExerciseBulkMetadataPatch,
|
||||||
@@ -1619,6 +1642,9 @@ def bulk_patch_exercises_metadata(
|
|||||||
owner = int(owner)
|
owner = int(owner)
|
||||||
|
|
||||||
ex_vis = (rowd.get("visibility") or "private").strip().lower()
|
ex_vis = (rowd.get("visibility") or "private").strip().lower()
|
||||||
|
if not official_write_allowed(ex_vis, role):
|
||||||
|
failed.append({"id": ex_id, "detail": OFFICIAL_WRITE_DENIED})
|
||||||
|
continue
|
||||||
ex_cid_raw = rowd.get("club_id")
|
ex_cid_raw = rowd.get("club_id")
|
||||||
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||||
|
|
||||||
@@ -2154,7 +2180,7 @@ def list_exercises(
|
|||||||
|
|
||||||
# Query (primary_focus_name für Listen-Ansicht gemäß Spec-Beispiel „focus_area“-Label)
|
# Query (primary_focus_name für Listen-Ansicht gemäß Spec-Beispiel „focus_area“-Label)
|
||||||
query = f"""
|
query = f"""
|
||||||
SELECT e.id, e.title, e.summary, e.visibility, e.status,
|
SELECT e.id, e.title, e.summary, e.visibility, e.status, e.api_offered,
|
||||||
e.exercise_kind, e.method_archetype,
|
e.exercise_kind, e.method_archetype,
|
||||||
e.created_by, p.name as creator_name,
|
e.created_by, p.name as creator_name,
|
||||||
e.club_id, c.name as club_name,
|
e.club_id, c.name as club_name,
|
||||||
@@ -2227,6 +2253,7 @@ def list_exercises(
|
|||||||
d["training_type_names"] = _coerce_json_str_list(d.get("training_type_names"))
|
d["training_type_names"] = _coerce_json_str_list(d.get("training_type_names"))
|
||||||
d["variant_count"] = int(d.get("variant_count") or 0)
|
d["variant_count"] = int(d.get("variant_count") or 0)
|
||||||
d["media_count"] = int(d.get("media_count") or 0)
|
d["media_count"] = int(d.get("media_count") or 0)
|
||||||
|
d["api_offered"] = bool(d.get("api_offered"))
|
||||||
if include_variants:
|
if include_variants:
|
||||||
v = d.get("variants")
|
v = d.get("variants")
|
||||||
if isinstance(v, str):
|
if isinstance(v, str):
|
||||||
@@ -2854,6 +2881,11 @@ def delete_exercise(
|
|||||||
usage_msg = _exercise_delete_usage_message(counts)
|
usage_msg = _exercise_delete_usage_message(counts)
|
||||||
if usage_msg:
|
if usage_msg:
|
||||||
raise HTTPException(status_code=409, detail=usage_msg)
|
raise HTTPException(status_code=409, detail=usage_msg)
|
||||||
|
if blocks_exercise_delete(cur, exercise_id):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail="Die Übung hat eine externe Freigabe und kann nicht gelöscht werden.",
|
||||||
|
)
|
||||||
|
|
||||||
cur.execute("DELETE FROM exercises WHERE id = %s", (exercise_id,))
|
cur.execute("DELETE FROM exercises WHERE id = %s", (exercise_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
@@ -3061,6 +3093,11 @@ def delete_exercise_variant(
|
|||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||||
assert_exercise_not_combination(cur, exercise_id)
|
assert_exercise_not_combination(cur, exercise_id)
|
||||||
|
if blocks_variant_delete(cur, variant_id):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail="Die Variante ist Teil einer externen Freigabe und kann nicht gelöscht werden.",
|
||||||
|
)
|
||||||
_fetch_variant_row(cur, exercise_id, variant_id)
|
_fetch_variant_row(cur, exercise_id, variant_id)
|
||||||
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
@@ -3083,16 +3120,28 @@ def delete_exercise_variant(
|
|||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
def _content_disposition_inline(filename: Optional[str]) -> str:
|
def _safe_download_name(filename: Optional[str]) -> str:
|
||||||
"""Inline-Darstellung im Browser (<video>/<img>), keine attachment-Download-Leiste."""
|
"""Dateiname ohne Steuerzeichen und ohne Anführungszeichen für Content-Disposition."""
|
||||||
if not filename:
|
if not filename:
|
||||||
return "inline"
|
return ""
|
||||||
fn = str(filename).strip()
|
cleaned = []
|
||||||
|
for ch in str(filename):
|
||||||
|
if ch < " " or ch == "\x7f" or ch in {'"', "\\", ";"}:
|
||||||
|
continue
|
||||||
|
cleaned.append(ch)
|
||||||
|
return "".join(cleaned).strip()[:180]
|
||||||
|
|
||||||
|
|
||||||
|
def _content_disposition(filename: Optional[str], *, attachment: bool) -> str:
|
||||||
|
"""Bilder und Videos inline. PDF als Anhang. Dateiname ohne Steuerzeichen."""
|
||||||
|
disposition = "attachment" if attachment else "inline"
|
||||||
|
fn = _safe_download_name(filename)
|
||||||
|
if not fn:
|
||||||
|
return disposition
|
||||||
quoted = quote(fn, safe="")
|
quoted = quote(fn, safe="")
|
||||||
escaped = fn.replace('"', "\\")
|
|
||||||
if quoted != fn:
|
if quoted != fn:
|
||||||
return f"inline; filename*=utf-8''{quoted}"
|
return f"{disposition}; filename*=utf-8''{quoted}"
|
||||||
return f'inline; filename="{escaped}"'
|
return f'{disposition}; filename="{fn}"'
|
||||||
|
|
||||||
|
|
||||||
def _parse_bytes_range_single(range_header: str, file_size: int) -> Optional[Tuple[int, int]]:
|
def _parse_bytes_range_single(range_header: str, file_size: int) -> Optional[Tuple[int, int]]:
|
||||||
@@ -3152,7 +3201,10 @@ def _binary_media_response(
|
|||||||
path_str = str(path_arg.resolve())
|
path_str = str(path_arg.resolve())
|
||||||
stat_r = os.stat(path_str)
|
stat_r = os.stat(path_str)
|
||||||
file_size = int(stat_r.st_size)
|
file_size = int(stat_r.st_size)
|
||||||
cd_val = _content_disposition_inline(download_name)
|
cd_val = _content_disposition(
|
||||||
|
download_name,
|
||||||
|
attachment=(mime_type or "").split(";")[0].strip().lower() == "application/pdf",
|
||||||
|
)
|
||||||
base_h = {"accept-ranges": "bytes", "content-disposition": cd_val}
|
base_h = {"accept-ranges": "bytes", "content-disposition": cd_val}
|
||||||
|
|
||||||
if request.method.upper() == "HEAD":
|
if request.method.upper() == "HEAD":
|
||||||
@@ -3224,7 +3276,7 @@ def download_exercise_media_file(
|
|||||||
tenant: TenantContext = Depends(get_tenant_context_flexible),
|
tenant: TenantContext = Depends(get_tenant_context_flexible),
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Dateiauslieferung mit Governance wie GET Übung — Auth via X-Auth-Token oder ?ssetoken (für <img>/<video>).
|
Dateiauslieferung mit Governance wie GET Übung — Header-Sitzung oder kurzlebiges Medien-Token (?ssetoken).
|
||||||
Unterstützt HTTP Range (206) für MP4-Streaming und Content-Disposition: inline (kein attachment).
|
Unterstützt HTTP Range (206) für MP4-Streaming und Content-Disposition: inline (kein attachment).
|
||||||
"""
|
"""
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
@@ -3846,6 +3898,11 @@ def delete_exercise_media(
|
|||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||||
|
if blocks_media_delete(cur, media_id):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail="Das Medium ist Teil einer externen Freigabe und kann nicht gelöst werden.",
|
||||||
|
)
|
||||||
rec = r2d(row)
|
rec = r2d(row)
|
||||||
media_asset_id = rec.get("media_asset_id")
|
media_asset_id = rec.get("media_asset_id")
|
||||||
if media_asset_id:
|
if media_asset_id:
|
||||||
|
|||||||
@@ -1225,7 +1225,7 @@ def download_media_asset_file(
|
|||||||
asset_id: int,
|
asset_id: int,
|
||||||
tenant: TenantContext = Depends(get_tenant_context_flexible),
|
tenant: TenantContext = Depends(get_tenant_context_flexible),
|
||||||
):
|
):
|
||||||
"""Direktzugriff auf Archiv-Datei (Thumbnail/Vorschau); Auth wie Übungs-Medien (?ssetoken)."""
|
"""Direktzugriff auf Archiv-Datei. Auth per Header oder kurzlebigem Medien-Token (?ssetoken)."""
|
||||||
from routers.exercises import _binary_media_response
|
from routers.exercises import _binary_media_response
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
|
|||||||
@@ -0,0 +1,312 @@
|
|||||||
|
"""
|
||||||
|
Superadmin: OpenRouter-Modellkatalog und Plattform-Standardmodell.
|
||||||
|
|
||||||
|
# ACCESS_LAYER exempt: Plattform-KI-Konfiguration ohne Vereinsbezug;
|
||||||
|
# require_auth + is_superadmin, kein TenantContext.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from club_tenancy import is_superadmin
|
||||||
|
from db import get_cursor, get_db, r2d
|
||||||
|
from ai_model_roles import ROLE_KEYS, resolve_prompt_openrouter_model
|
||||||
|
from openrouter_chat import (
|
||||||
|
OpenRouterError,
|
||||||
|
env_openrouter_model_id,
|
||||||
|
fetch_openrouter_model_catalog,
|
||||||
|
normalize_openrouter_model_id,
|
||||||
|
resolve_default_openrouter_model_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(tags=["admin_openrouter"])
|
||||||
|
|
||||||
|
|
||||||
|
def _require_superadmin(session: dict = Depends(require_auth)) -> dict:
|
||||||
|
role = (session.get("role") or "").strip().lower()
|
||||||
|
if not is_superadmin(role):
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Superadmins")
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
class OpenRouterSettingsUpdate(BaseModel):
|
||||||
|
openrouter_model: Optional[str] = Field(None, max_length=200)
|
||||||
|
|
||||||
|
|
||||||
|
class OpenRouterRoleUpdate(BaseModel):
|
||||||
|
openrouter_model: Optional[str] = Field(None, max_length=200)
|
||||||
|
|
||||||
|
|
||||||
|
class OpenRouterPromptRoleUpdate(BaseModel):
|
||||||
|
model_config = ConfigDict(protected_namespaces=())
|
||||||
|
model_role: Optional[str] = Field(None, max_length=40)
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(value: Any) -> Optional[str]:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if hasattr(value, "isoformat"):
|
||||||
|
return value.isoformat()
|
||||||
|
text = str(value).strip()
|
||||||
|
return text or None
|
||||||
|
|
||||||
|
|
||||||
|
def _settings_payload(stored: Optional[str], updated_at: Any = None) -> dict:
|
||||||
|
effective, source = resolve_default_openrouter_model_id(stored)
|
||||||
|
return {
|
||||||
|
"openrouter_model": stored or None,
|
||||||
|
"effective_model": effective,
|
||||||
|
"env_model": env_openrouter_model_id(),
|
||||||
|
"source": source,
|
||||||
|
"updated_at": _iso(updated_at),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _missing_table(exc: Exception) -> bool:
|
||||||
|
text = str(exc).lower()
|
||||||
|
return "platform_ai_settings" in text or "does not exist" in text or "undefinedtable" in text
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/openrouter/settings")
|
||||||
|
def get_openrouter_settings(session: dict = Depends(_require_superadmin)):
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT openrouter_model, updated_at FROM platform_ai_settings WHERE id = 1"
|
||||||
|
)
|
||||||
|
row = r2d(cur.fetchone())
|
||||||
|
except Exception as exc:
|
||||||
|
if _missing_table(exc):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=503,
|
||||||
|
detail="Tabelle platform_ai_settings fehlt. Migration 097 ausführen.",
|
||||||
|
) from exc
|
||||||
|
raise
|
||||||
|
if not row:
|
||||||
|
return _settings_payload(None, None)
|
||||||
|
stored = str(row.get("openrouter_model") or "").strip() or None
|
||||||
|
return _settings_payload(stored, row.get("updated_at"))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/admin/openrouter/settings")
|
||||||
|
def put_openrouter_settings(
|
||||||
|
body: OpenRouterSettingsUpdate,
|
||||||
|
session: dict = Depends(_require_superadmin),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
model = normalize_openrouter_model_id(body.openrouter_model)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
profile_id = session.get("profile_id")
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO platform_ai_settings (id, openrouter_model, updated_at, updated_by_profile_id)
|
||||||
|
VALUES (1, %s, NOW(), %s)
|
||||||
|
ON CONFLICT (id) DO UPDATE
|
||||||
|
SET openrouter_model = EXCLUDED.openrouter_model,
|
||||||
|
updated_at = NOW(),
|
||||||
|
updated_by_profile_id = EXCLUDED.updated_by_profile_id
|
||||||
|
RETURNING openrouter_model, updated_at
|
||||||
|
""",
|
||||||
|
(model, profile_id),
|
||||||
|
)
|
||||||
|
row = r2d(cur.fetchone())
|
||||||
|
except Exception as exc:
|
||||||
|
if _missing_table(exc):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=503,
|
||||||
|
detail="Tabelle platform_ai_settings fehlt. Migration 097 ausführen.",
|
||||||
|
) from exc
|
||||||
|
raise
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=500, detail="platform_ai_settings konnte nicht gespeichert werden.")
|
||||||
|
stored = str(row.get("openrouter_model") or "").strip() or None
|
||||||
|
return _settings_payload(stored, row.get("updated_at"))
|
||||||
|
|
||||||
|
|
||||||
|
def _prompt_view(row: dict, role_models: dict, platform_model: Optional[str], env_model: str) -> dict:
|
||||||
|
prompt_model = str(row.get("openrouter_model") or "").strip() or None
|
||||||
|
role_key = str(row.get("model_role") or "").strip() or None
|
||||||
|
effective, source = resolve_prompt_openrouter_model(
|
||||||
|
prompt_model=prompt_model,
|
||||||
|
role_model=role_models.get(role_key or ""),
|
||||||
|
platform_model=platform_model,
|
||||||
|
env_model=env_model,
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"id": row.get("id"),
|
||||||
|
"slug": row.get("slug"),
|
||||||
|
"display_name": row.get("display_name"),
|
||||||
|
"model_role": role_key,
|
||||||
|
"openrouter_model": prompt_model,
|
||||||
|
"effective_model": effective,
|
||||||
|
"source": source,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _load_role_overview(cur) -> dict:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT role_key, display_name, description, openrouter_model, sort_order
|
||||||
|
FROM platform_ai_model_roles
|
||||||
|
ORDER BY sort_order ASC, role_key ASC
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
role_rows = [r2d(r) if not isinstance(r, dict) else r for r in cur.fetchall()]
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, slug, display_name, model_role, openrouter_model, sort_order
|
||||||
|
FROM ai_prompts
|
||||||
|
ORDER BY sort_order ASC NULLS LAST, id ASC
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
prompt_rows = [r2d(r) if not isinstance(r, dict) else r for r in cur.fetchall()]
|
||||||
|
cur.execute("SELECT openrouter_model FROM platform_ai_settings WHERE id = 1")
|
||||||
|
settings = r2d(cur.fetchone())
|
||||||
|
platform_model = str((settings or {}).get("openrouter_model") or "").strip() or None
|
||||||
|
env_model = env_openrouter_model_id()
|
||||||
|
role_models = {
|
||||||
|
str(row.get("role_key") or ""): str(row.get("openrouter_model") or "").strip() or None
|
||||||
|
for row in role_rows
|
||||||
|
}
|
||||||
|
prompts = [_prompt_view(row, role_models, platform_model, env_model) for row in prompt_rows]
|
||||||
|
roles = []
|
||||||
|
for row in role_rows:
|
||||||
|
key = str(row.get("role_key") or "")
|
||||||
|
stored = role_models.get(key)
|
||||||
|
effective, source = resolve_prompt_openrouter_model(
|
||||||
|
prompt_model=None,
|
||||||
|
role_model=stored,
|
||||||
|
platform_model=platform_model,
|
||||||
|
env_model=env_model,
|
||||||
|
)
|
||||||
|
roles.append(
|
||||||
|
{
|
||||||
|
"role_key": key,
|
||||||
|
"display_name": row.get("display_name"),
|
||||||
|
"description": row.get("description"),
|
||||||
|
"openrouter_model": stored,
|
||||||
|
"effective_model": effective,
|
||||||
|
"source": source,
|
||||||
|
"prompts": [p for p in prompts if p.get("model_role") == key],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"roles": roles,
|
||||||
|
"unassigned": [p for p in prompts if not p.get("model_role")],
|
||||||
|
"platform_model": platform_model,
|
||||||
|
"env_model": env_model,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/openrouter/roles")
|
||||||
|
def get_openrouter_roles(session: dict = Depends(_require_superadmin)):
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
return _load_role_overview(cur)
|
||||||
|
except Exception as exc:
|
||||||
|
if _missing_table(exc) or "platform_ai_model_roles" in str(exc).lower():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=503,
|
||||||
|
detail="Tabelle platform_ai_model_roles fehlt. Migration 098 ausführen.",
|
||||||
|
) from exc
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/admin/openrouter/roles/{role_key}")
|
||||||
|
def put_openrouter_role(
|
||||||
|
role_key: str,
|
||||||
|
body: OpenRouterRoleUpdate,
|
||||||
|
session: dict = Depends(_require_superadmin),
|
||||||
|
):
|
||||||
|
key = (role_key or "").strip()
|
||||||
|
if key not in ROLE_KEYS:
|
||||||
|
raise HTTPException(status_code=404, detail="Unbekannte Aufgabengruppe.")
|
||||||
|
try:
|
||||||
|
model = normalize_openrouter_model_id(body.openrouter_model)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
profile_id = session.get("profile_id")
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE platform_ai_model_roles
|
||||||
|
SET openrouter_model = %s, updated_at = NOW(), updated_by_profile_id = %s
|
||||||
|
WHERE role_key = %s
|
||||||
|
RETURNING role_key
|
||||||
|
""",
|
||||||
|
(model, profile_id, key),
|
||||||
|
)
|
||||||
|
updated = cur.fetchone()
|
||||||
|
if not updated:
|
||||||
|
raise HTTPException(status_code=404, detail="Aufgabengruppe fehlt.")
|
||||||
|
return _load_role_overview(cur)
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
if "platform_ai_model_roles" in str(exc).lower() or _missing_table(exc):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=503,
|
||||||
|
detail="Tabelle platform_ai_model_roles fehlt. Migration 098 ausführen.",
|
||||||
|
) from exc
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/admin/openrouter/prompts/{prompt_id}/role")
|
||||||
|
def put_openrouter_prompt_role(
|
||||||
|
prompt_id: int,
|
||||||
|
body: OpenRouterPromptRoleUpdate,
|
||||||
|
session: dict = Depends(_require_superadmin),
|
||||||
|
):
|
||||||
|
role = str(body.model_role or "").strip() or None
|
||||||
|
if role and role not in ROLE_KEYS:
|
||||||
|
raise HTTPException(status_code=400, detail="Unbekannte Aufgabengruppe.")
|
||||||
|
try:
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE ai_prompts
|
||||||
|
SET model_role = %s, updated_at = NOW()
|
||||||
|
WHERE id = %s
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(role, prompt_id),
|
||||||
|
)
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise HTTPException(status_code=404, detail="Prompt nicht gefunden.")
|
||||||
|
return _load_role_overview(cur)
|
||||||
|
except HTTPException:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
if "model_role" in str(exc).lower() or "platform_ai_model_roles" in str(exc).lower():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=503,
|
||||||
|
detail="Aufgabengruppen fehlen. Migration 098 ausführen.",
|
||||||
|
) from exc
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/admin/openrouter/models")
|
||||||
|
def list_openrouter_models(
|
||||||
|
refresh: bool = Query(False),
|
||||||
|
session: dict = Depends(_require_superadmin),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
return fetch_openrouter_model_catalog(force=refresh)
|
||||||
|
except OpenRouterError as exc:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=502,
|
||||||
|
detail=f"OpenRouter-Modellliste nicht erreichbar: {exc}",
|
||||||
|
) from exc
|
||||||
@@ -7,6 +7,7 @@ from db import get_db, get_cursor
|
|||||||
from tenant_context import TenantContext, get_tenant_context
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
from planning_exercise_suggest import PlanningExerciseSuggestRequest, suggest_planning_exercises
|
from planning_exercise_suggest import PlanningExerciseSuggestRequest, suggest_planning_exercises
|
||||||
from planning_exercise_path_builder import ProgressionPathSuggestRequest, suggest_progression_path
|
from planning_exercise_path_builder import ProgressionPathSuggestRequest, suggest_progression_path
|
||||||
|
from planning_llm_usage import planning_llm_call_meter
|
||||||
from account_lifecycle import assert_min_account_state
|
from account_lifecycle import assert_min_account_state
|
||||||
from capabilities import probe_capability
|
from capabilities import probe_capability
|
||||||
from club_features import (
|
from club_features import (
|
||||||
@@ -46,19 +47,25 @@ def post_planning_exercise_suggest(
|
|||||||
)
|
)
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
with planning_llm_call_meter() as llm_meter:
|
||||||
result = suggest_planning_exercises(cur, tenant=tenant, body=body)
|
result = suggest_planning_exercises(cur, tenant=tenant, body=body)
|
||||||
if uses_ai:
|
if uses_ai and llm_meter.count > 0:
|
||||||
usage = consume_club_feature_with_usage(
|
usage = consume_club_feature_with_usage(
|
||||||
feature_id="ai_calls",
|
feature_id="ai_calls",
|
||||||
club_id=club_id,
|
club_id=club_id,
|
||||||
profile_id=tenant.profile_id,
|
profile_id=tenant.profile_id,
|
||||||
portal_role=tenant.global_role,
|
portal_role=tenant.global_role,
|
||||||
action="planning_suggest",
|
action="planning_suggest",
|
||||||
|
amount=llm_meter.count,
|
||||||
cur=cur,
|
cur=cur,
|
||||||
tenant=tenant,
|
tenant=tenant,
|
||||||
conn=conn,
|
conn=conn,
|
||||||
)
|
)
|
||||||
result = merge_feature_usage_into_response(result, usage)
|
result = merge_feature_usage_into_response(result, usage)
|
||||||
|
if isinstance(result, dict):
|
||||||
|
result["llm_call_count"] = llm_meter.count
|
||||||
|
elif uses_ai and isinstance(result, dict):
|
||||||
|
result["llm_call_count"] = 0
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@@ -70,7 +77,6 @@ def post_progression_path_suggest(
|
|||||||
uses_ai = (
|
uses_ai = (
|
||||||
body.include_llm_intent
|
body.include_llm_intent
|
||||||
or body.include_llm_path_qa
|
or body.include_llm_path_qa
|
||||||
or body.include_ai_gap_fill
|
|
||||||
or body.include_llm_roadmap
|
or body.include_llm_roadmap
|
||||||
or body.include_llm_start_target
|
or body.include_llm_start_target
|
||||||
or (body.start_target_only and body.include_llm_start_target)
|
or (body.start_target_only and body.include_llm_start_target)
|
||||||
@@ -98,17 +104,23 @@ def post_progression_path_suggest(
|
|||||||
)
|
)
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
cur = get_cursor(conn)
|
cur = get_cursor(conn)
|
||||||
|
with planning_llm_call_meter() as llm_meter:
|
||||||
result = suggest_progression_path(cur, tenant=tenant, body=body)
|
result = suggest_progression_path(cur, tenant=tenant, body=body)
|
||||||
if uses_ai:
|
if uses_ai and llm_meter.count > 0:
|
||||||
usage = consume_club_feature_with_usage(
|
usage = consume_club_feature_with_usage(
|
||||||
feature_id="ai_calls",
|
feature_id="ai_calls",
|
||||||
club_id=club_id,
|
club_id=club_id,
|
||||||
profile_id=tenant.profile_id,
|
profile_id=tenant.profile_id,
|
||||||
portal_role=tenant.global_role,
|
portal_role=tenant.global_role,
|
||||||
action="progression_path_suggest",
|
action="progression_path_suggest",
|
||||||
|
amount=llm_meter.count,
|
||||||
cur=cur,
|
cur=cur,
|
||||||
tenant=tenant,
|
tenant=tenant,
|
||||||
conn=conn,
|
conn=conn,
|
||||||
)
|
)
|
||||||
result = merge_feature_usage_into_response(result, usage)
|
result = merge_feature_usage_into_response(result, usage)
|
||||||
|
if isinstance(result, dict):
|
||||||
|
result["llm_call_count"] = llm_meter.count
|
||||||
|
elif uses_ai and isinstance(result, dict):
|
||||||
|
result["llm_call_count"] = 0
|
||||||
return result
|
return result
|
||||||
+56
-10
@@ -14,7 +14,7 @@ from psycopg2.extras import Json
|
|||||||
from pydantic import BaseModel, Field, field_validator
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
from db import get_db, get_cursor, r2d
|
from db import get_db, get_cursor, r2d
|
||||||
from auth import require_auth, hash_pin
|
from auth import require_auth, hash_pin, revoke_profile_sessions
|
||||||
from club_tenancy import (
|
from club_tenancy import (
|
||||||
assert_club_member,
|
assert_club_member,
|
||||||
club_ids_for_profile_with_roles,
|
club_ids_for_profile_with_roles,
|
||||||
@@ -30,6 +30,19 @@ router = APIRouter(prefix="/api", tags=["profiles"])
|
|||||||
|
|
||||||
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
_ALLOWED_PORTAL_ROLES = frozenset({"user", "trainer", "admin", "superadmin"})
|
||||||
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
|
_CLUB_BLOCKED_PORTAL_TARGETS = frozenset({"admin", "superadmin"})
|
||||||
|
_PROFILE_SECRET_FIELDS = (
|
||||||
|
"pin_hash",
|
||||||
|
"totp_secret",
|
||||||
|
"totp_pending_secret",
|
||||||
|
"verification_token",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _public_profile_row(row) -> dict:
|
||||||
|
data = r2d(row)
|
||||||
|
for key in _PROFILE_SECRET_FIELDS:
|
||||||
|
data.pop(key, None)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
class ManagementPasswordResetBody(BaseModel):
|
class ManagementPasswordResetBody(BaseModel):
|
||||||
@@ -103,8 +116,7 @@ def get_current_profile(
|
|||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, "Profil nicht gefunden")
|
raise HTTPException(404, "Profil nicht gefunden")
|
||||||
data = r2d(row)
|
data = _public_profile_row(row)
|
||||||
data.pop("pin_hash", None)
|
|
||||||
clubs = memberships_with_roles(cur, profile_id, active_only=False)
|
clubs = memberships_with_roles(cur, profile_id, active_only=False)
|
||||||
data["clubs"] = clubs
|
data["clubs"] = clubs
|
||||||
ac_raw = data.get("active_club_id")
|
ac_raw = data.get("active_club_id")
|
||||||
@@ -140,9 +152,7 @@ def list_profiles(session=Depends(require_auth)):
|
|||||||
rows = cur.fetchall()
|
rows = cur.fetchall()
|
||||||
out = []
|
out = []
|
||||||
for r in rows:
|
for r in rows:
|
||||||
d = r2d(r)
|
out.append(_public_profile_row(r))
|
||||||
d.pop("pin_hash", None)
|
|
||||||
out.append(d)
|
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -203,9 +213,7 @@ def profile_document(pid: str) -> dict:
|
|||||||
row = cur.fetchone()
|
row = cur.fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, "Profil nicht gefunden")
|
raise HTTPException(404, "Profil nicht gefunden")
|
||||||
d = r2d(row)
|
return _public_profile_row(row)
|
||||||
d.pop("pin_hash", None)
|
|
||||||
return d
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/profiles/{pid}/management-password-reset")
|
@router.post("/profiles/{pid}/management-password-reset")
|
||||||
@@ -245,9 +253,14 @@ def management_password_reset(
|
|||||||
_assert_can_management_password_help(cur, tenant, target, via_email=False)
|
_assert_can_management_password_help(cur, tenant, target, via_email=False)
|
||||||
new_hash = hash_pin(body.new_password)
|
new_hash = hash_pin(body.new_password)
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"UPDATE profiles SET pin_hash = %s, updated_at = NOW() WHERE id = %s",
|
"""
|
||||||
|
UPDATE profiles
|
||||||
|
SET pin_hash = %s, failed_login_count = 0, locked_until = NULL, updated_at = NOW()
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
(new_hash, target),
|
(new_hash, target),
|
||||||
)
|
)
|
||||||
|
revoke_profile_sessions(cur, target)
|
||||||
return {"ok": True, "mode": "direct"}
|
return {"ok": True, "mode": "direct"}
|
||||||
|
|
||||||
_assert_can_management_password_help(cur, tenant, target, via_email=True)
|
_assert_can_management_password_help(cur, tenant, target, via_email=True)
|
||||||
@@ -270,6 +283,39 @@ def management_password_reset(
|
|||||||
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
|
return {"ok": True, "mode": "email", "email_sent": bool(sent)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/profiles/{pid}/totp-reset")
|
||||||
|
def management_totp_reset(pid: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||||
|
"""Superadmin schaltet Zwei-Faktor ab, wenn der Nutzer den Authenticator nicht mehr hat."""
|
||||||
|
if not is_superadmin(tenant.global_role or ""):
|
||||||
|
raise HTTPException(status_code=403, detail="Nur Super-Admins")
|
||||||
|
try:
|
||||||
|
target = int(pid)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=400, detail="Ungültige Profil-ID")
|
||||||
|
if target == int(tenant.profile_id):
|
||||||
|
raise HTTPException(status_code=400, detail="Eigenen Zwei-Faktor unter Einstellungen ändern")
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
cur = get_cursor(conn)
|
||||||
|
cur.execute("SELECT id, totp_enabled FROM profiles WHERE id=%s", (target,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise HTTPException(status_code=404, detail="Profil nicht gefunden")
|
||||||
|
if not row.get("totp_enabled"):
|
||||||
|
return {"ok": True, "totp_enabled": False, "changed": False}
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE profiles
|
||||||
|
SET totp_enabled=FALSE, totp_secret=NULL, totp_pending_secret=NULL, updated_at=NOW()
|
||||||
|
WHERE id=%s
|
||||||
|
""",
|
||||||
|
(target,),
|
||||||
|
)
|
||||||
|
cur.execute("DELETE FROM profile_recovery_codes WHERE profile_id=%s", (target,))
|
||||||
|
revoke_profile_sessions(cur, target)
|
||||||
|
return {"ok": True, "totp_enabled": False, "changed": True}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/profiles/{pid}")
|
@router.get("/profiles/{pid}")
|
||||||
def get_profile(pid: str, session=Depends(require_auth)):
|
def get_profile(pid: str, session=Depends(require_auth)):
|
||||||
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
|
"""Profil nach ID — nur eigenes Profil oder Plattform-Admin (wie PUT)."""
|
||||||
|
|||||||
@@ -25,10 +25,12 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
|
|||||||
"legal_documents.py", # ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug; öffentlicher Endpoint ohne Auth, Admin-Endpoints require_auth + is_superadmin()
|
"legal_documents.py", # ACCESS_LAYER exempt: Plattform-Rechtstexte ohne Vereinsbezug; öffentlicher Endpoint ohne Auth, Admin-Endpoints require_auth + is_superadmin()
|
||||||
"ai_skill_retrieval_admin.py", # Superadmin-Plattform-Konfiguration Skill-KI-Retrieval; require_auth + is_superadmin — kein Vereinsmandant
|
"ai_skill_retrieval_admin.py", # Superadmin-Plattform-Konfiguration Skill-KI-Retrieval; require_auth + is_superadmin — kein Vereinsmandant
|
||||||
"ai_prompts_admin.py", # Superadmin ai_prompts; require_auth + is_superadmin — kein Vereinsmandant
|
"ai_prompts_admin.py", # Superadmin ai_prompts; require_auth + is_superadmin — kein Vereinsmandant
|
||||||
|
"openrouter_admin.py", # Superadmin OpenRouter-Modell; require_auth + is_superadmin — kein Vereinsmandant
|
||||||
"exercise_enrichment_admin.py", # Superadmin Batch-Übungs-Anreicherung KI; require_auth + is_superadmin — kein Vereinsmandant
|
"exercise_enrichment_admin.py", # Superadmin Batch-Übungs-Anreicherung KI; require_auth + is_superadmin — kein Vereinsmandant
|
||||||
"admin_user_content.py", # Superadmin Moderation nutzerangelegter Inhalte; require_auth + is_superadmin — kein Vereinsmandant
|
"admin_user_content.py", # Superadmin Moderation nutzerangelegter Inhalte; require_auth + is_superadmin — kein Vereinsmandant
|
||||||
"admin_rights.py", # Superadmin Rollen/Rechte (Capabilities, Kontingent-Bypass, Pläne); require_auth + is_superadmin — kein Vereinsmandant
|
"admin_rights.py", # Superadmin Rollen/Rechte (Capabilities, Kontingent-Bypass, Pläne); require_auth + is_superadmin — kein Vereinsmandant
|
||||||
"catalogs.py",
|
"catalogs.py",
|
||||||
|
"catalog_prompt_slots.py", # Admin Stammdaten KI-Prompt-Slots; require_auth + admin/superadmin — globaler Katalog, kein Vereinsmandant
|
||||||
"skills.py",
|
"skills.py",
|
||||||
"maturity_models.py",
|
"maturity_models.py",
|
||||||
"matrix_stack_bundle.py",
|
"matrix_stack_bundle.py",
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
"""
|
"""
|
||||||
Automatische Medien-Retention (Papierkorb Stufe 1→2, Purge wenn fällig).
|
Automatische Medien-Retention (Papierkorb Stufe 1→2, Purge wenn fällig).
|
||||||
|
|
||||||
Lauf z. B. täglich per Cron:
|
Einzellauf (der tägliche Planer ist media_retention_scheduler.py):
|
||||||
cd /path/to/backend && python scripts/media_retention_job.py
|
cd /path/to/backend && python scripts/media_retention_job.py
|
||||||
|
|
||||||
Umgebung wie Backend (DB_*), optional:
|
Umgebung wie Backend (DB_*), optional:
|
||||||
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS (Default 30)
|
MEDIA_TRASH_SOFT_TO_HIDDEN_DAYS (Default 30)
|
||||||
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 90)
|
MEDIA_TRASH_HIDDEN_TO_PURGE_DAYS (Default 30)
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Täglicher Start von media_retention_job.py um 03:00 Europe/Berlin.
|
||||||
|
|
||||||
|
Der Prozess löscht beim Start nichts. Ein Lauf sofort nach dem Start nur mit
|
||||||
|
RETENTION_RUN_ON_START=1. Ein fehlgeschlagener Lauf bleibt im Log
|
||||||
|
(RETENTION_FAIL); der Prozess bleibt aktiv, damit Docker ihn nicht sofort
|
||||||
|
erneut startet.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
LOG = logging.getLogger("retention.scheduler")
|
||||||
|
|
||||||
|
DEFAULT_TZ = "Europe/Berlin"
|
||||||
|
_RUN_ON_START = "RETENTION_RUN_ON_START"
|
||||||
|
_TZ_ENV = "RETENTION_TZ"
|
||||||
|
|
||||||
|
|
||||||
|
def retention_zone() -> ZoneInfo:
|
||||||
|
name = os.environ.get(_TZ_ENV, DEFAULT_TZ).strip() or DEFAULT_TZ
|
||||||
|
return ZoneInfo(name)
|
||||||
|
|
||||||
|
|
||||||
|
def next_run_at(now: datetime, *, hour: int = 3) -> datetime:
|
||||||
|
"""Nächste Uhrzeit `hour`:00 in der Zeitzone von `now`.
|
||||||
|
|
||||||
|
`now` muss zeitzonenbewusst sein. Die Zone von `now` ist die Planungszone.
|
||||||
|
"""
|
||||||
|
if now.tzinfo is None:
|
||||||
|
raise ValueError("now muss eine Zeitzone tragen")
|
||||||
|
zone = now.tzinfo
|
||||||
|
local = now.astimezone(zone)
|
||||||
|
day = local.date()
|
||||||
|
target = datetime(day.year, day.month, day.day, hour, 0, 0, tzinfo=zone)
|
||||||
|
if target.timestamp() <= local.timestamp():
|
||||||
|
day = day + timedelta(days=1)
|
||||||
|
target = datetime(day.year, day.month, day.day, hour, 0, 0, tzinfo=zone)
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def seconds_until_next_0300(now: datetime, *, hour: int = 3) -> float:
|
||||||
|
"""Sekunden bis zum nächsten Lauf, als absolute Dauer.
|
||||||
|
|
||||||
|
`target - now` zieht bei gleicher tzinfo die Wanduhr ab und liegt an
|
||||||
|
Umstellungstagen um eine Stunde daneben. `timestamp()` rechnet in UTC.
|
||||||
|
"""
|
||||||
|
target = next_run_at(now, hour=hour)
|
||||||
|
local = now.astimezone(target.tzinfo)
|
||||||
|
return target.timestamp() - local.timestamp()
|
||||||
|
|
||||||
|
|
||||||
|
def _job_path() -> str:
|
||||||
|
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "media_retention_job.py")
|
||||||
|
|
||||||
|
|
||||||
|
def _run_on_start() -> bool:
|
||||||
|
return os.environ.get(_RUN_ON_START, "").strip() == "1"
|
||||||
|
|
||||||
|
|
||||||
|
def run_job() -> int:
|
||||||
|
"""Startet den Retention-Job. Führt keine Löschung in diesem Prozess aus."""
|
||||||
|
LOG.info("Retention-Lauf startet")
|
||||||
|
completed = subprocess.run([sys.executable, "-u", _job_path()], check=False)
|
||||||
|
if completed.returncode != 0:
|
||||||
|
LOG.error("RETENTION_FAIL exit=%s", completed.returncode)
|
||||||
|
else:
|
||||||
|
LOG.info("RETENTION_OK")
|
||||||
|
return int(completed.returncode)
|
||||||
|
|
||||||
|
|
||||||
|
def serve(
|
||||||
|
*,
|
||||||
|
iterations: int | None = None,
|
||||||
|
sleep=time.sleep,
|
||||||
|
clock=None,
|
||||||
|
run=None,
|
||||||
|
) -> None:
|
||||||
|
zone = retention_zone()
|
||||||
|
if clock is None:
|
||||||
|
def clock() -> datetime:
|
||||||
|
return datetime.now(zone)
|
||||||
|
|
||||||
|
execute = run if run is not None else run_job
|
||||||
|
if _run_on_start():
|
||||||
|
LOG.info("Sofortlauf wegen RETENTION_RUN_ON_START=1")
|
||||||
|
execute()
|
||||||
|
|
||||||
|
completed = 0
|
||||||
|
while iterations is None or completed < iterations:
|
||||||
|
target = next_run_at(clock())
|
||||||
|
LOG.info("Nächster Retention-Lauf %s", target.isoformat(timespec="seconds"))
|
||||||
|
while True:
|
||||||
|
remaining = target.timestamp() - clock().timestamp()
|
||||||
|
if remaining <= 1:
|
||||||
|
break
|
||||||
|
LOG.info("Warte %.0f Sekunden bis %s", remaining, target.isoformat(timespec="seconds"))
|
||||||
|
sleep(remaining)
|
||||||
|
execute()
|
||||||
|
completed += 1
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(message)s",
|
||||||
|
stream=sys.stdout,
|
||||||
|
force=True,
|
||||||
|
)
|
||||||
|
serve()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -108,6 +108,57 @@ def library_content_visibility_sql(
|
|||||||
return "(" + " OR ".join(parts) + ")", params
|
return "(" + " OR ".join(parts) + ")", params
|
||||||
|
|
||||||
|
|
||||||
|
def library_content_visibility_for_progression_graph_sql(
|
||||||
|
*,
|
||||||
|
alias: str,
|
||||||
|
profile_id: int,
|
||||||
|
role: str,
|
||||||
|
effective_club_id: Optional[int],
|
||||||
|
graph_visibility: str,
|
||||||
|
graph_club_id: Optional[int] = None,
|
||||||
|
) -> tuple[str, List[Any]]:
|
||||||
|
"""
|
||||||
|
Übungs-Sichtbarkeit für Progressionsgraph-Match/Planung.
|
||||||
|
|
||||||
|
- private Graph: private (eigene) + Verein + offiziell — volle Nutzer-Bibliothek
|
||||||
|
- club Graph: nur Verein (aktiver Graph-Verein) + offiziell
|
||||||
|
- official Graph: nur offiziell
|
||||||
|
"""
|
||||||
|
gvis = (graph_visibility or "private").strip().lower()
|
||||||
|
if gvis == "private":
|
||||||
|
return library_content_visibility_sql(
|
||||||
|
alias=alias,
|
||||||
|
profile_id=profile_id,
|
||||||
|
role=role,
|
||||||
|
effective_club_id=effective_club_id,
|
||||||
|
)
|
||||||
|
if gvis == "club":
|
||||||
|
parts: List[str] = [f"{alias}.visibility = 'official'"]
|
||||||
|
params: List[Any] = []
|
||||||
|
club_id = graph_club_id if graph_club_id is not None else effective_club_id
|
||||||
|
if club_id is not None:
|
||||||
|
plat = is_platform_admin(role)
|
||||||
|
if plat:
|
||||||
|
parts.append(f"({alias}.visibility = 'club' AND {alias}.club_id = %s)")
|
||||||
|
params.append(int(club_id))
|
||||||
|
else:
|
||||||
|
parts.append(
|
||||||
|
f"""(
|
||||||
|
{alias}.visibility = 'club'
|
||||||
|
AND {alias}.club_id = %s
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM club_members cm
|
||||||
|
WHERE cm.profile_id = %s
|
||||||
|
AND cm.club_id = {alias}.club_id
|
||||||
|
AND cm.status = 'active'
|
||||||
|
)
|
||||||
|
)"""
|
||||||
|
)
|
||||||
|
params.extend([int(club_id), profile_id])
|
||||||
|
return "(" + " OR ".join(parts) + ")", params
|
||||||
|
return f"({alias}.visibility = 'official')", []
|
||||||
|
|
||||||
|
|
||||||
def club_library_visibility_sql(
|
def club_library_visibility_sql(
|
||||||
*,
|
*,
|
||||||
alias: str,
|
alias: str,
|
||||||
|
|||||||
@@ -0,0 +1,493 @@
|
|||||||
|
{
|
||||||
|
"fixture_version": 1,
|
||||||
|
"note": "Synthetische Inhalte ohne produktive Rechte. Die Medienbytes dienen der Testung von Groesse und Hash. Sie sind keine abspielbare Filmdatei.",
|
||||||
|
"manifest_serialization": "UTF-8, JSON ohne Leerraum, Reihenfolge der Felder aus manifest, kein abschliessender Zeilenumbruch",
|
||||||
|
"channels": {
|
||||||
|
"lara_felix": {
|
||||||
|
"recipient_id": "caa20000-0000-4000-8000-0000000001f5",
|
||||||
|
"events": [
|
||||||
|
{
|
||||||
|
"event_id": "caa20000-0000-4000-8000-000000000258",
|
||||||
|
"type": "release.published",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||||
|
"occurred_at": "2026-11-23T09:01:00Z",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||||
|
"revision": 1,
|
||||||
|
"manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event_id": "caa20000-0000-4000-8000-000000000259",
|
||||||
|
"type": "release.published",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||||
|
"occurred_at": "2026-11-23T09:02:00Z",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000b",
|
||||||
|
"revision": 1,
|
||||||
|
"manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event_id": "caa20000-0000-4000-8000-00000000025a",
|
||||||
|
"type": "release.published",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||||
|
"occurred_at": "2026-11-23T09:03:00Z",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||||
|
"revision": 2,
|
||||||
|
"manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event_id": "caa20000-0000-4000-8000-00000000025b",
|
||||||
|
"type": "release.retired",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||||
|
"occurred_at": "2026-11-23T09:04:00Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event_id": "caa20000-0000-4000-8000-00000000025c",
|
||||||
|
"type": "asset.withdrawn",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||||
|
"occurred_at": "2026-11-23T09:05:00Z",
|
||||||
|
"target_id": "caa20000-0000-4000-8000-00000000012c",
|
||||||
|
"reason_code": "rights"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event_id": "caa20000-0000-4000-8000-00000000025d",
|
||||||
|
"type": "asset.withdrawn",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||||
|
"occurred_at": "2026-11-23T09:05:00Z",
|
||||||
|
"target_id": "caa20000-0000-4000-8000-00000000012c",
|
||||||
|
"reason_code": "rights"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"zweiter_verein": {
|
||||||
|
"recipient_id": "caa20000-0000-4000-8000-0000000001f6",
|
||||||
|
"events": [
|
||||||
|
{
|
||||||
|
"event_id": "caa20000-0000-4000-8000-0000000002bc",
|
||||||
|
"type": "release.published",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000cc",
|
||||||
|
"occurred_at": "2026-11-23T09:03:00Z",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000c",
|
||||||
|
"revision": 1,
|
||||||
|
"manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"releases": {
|
||||||
|
"vereinsfassung_1": {
|
||||||
|
"channel": "lara_felix",
|
||||||
|
"manifest_sha256": "fcebc8c4db56328a55dc7f350e705822cef19f02392f26625274e68c0abc239c",
|
||||||
|
"manifest": {
|
||||||
|
"schema_version": 1,
|
||||||
|
"resource_type": "exercise",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||||
|
"revision": 1,
|
||||||
|
"publisher_id": "caa20000-0000-4000-8000-00000000177a",
|
||||||
|
"published_at": "2026-11-23T09:01:00Z",
|
||||||
|
"exercise": {
|
||||||
|
"title": "Raum und Wege wahrnehmen",
|
||||||
|
"audience": "Kursleitungen",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000065",
|
||||||
|
"role": "goal",
|
||||||
|
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000066",
|
||||||
|
"role": "instructions",
|
||||||
|
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000067",
|
||||||
|
"role": "trainer_notes",
|
||||||
|
"text": "Vorab genug Platz vorsehen.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000068",
|
||||||
|
"role": "instructions",
|
||||||
|
"text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000012c",
|
||||||
|
"role": "demonstration",
|
||||||
|
"media_type": "video/mp4",
|
||||||
|
"size_bytes": 32,
|
||||||
|
"sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000192",
|
||||||
|
"label": "Demonstrationsfilm"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"common_part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000065",
|
||||||
|
"caa20000-0000-4000-8000-000000000067"
|
||||||
|
],
|
||||||
|
"common_asset_ids": [],
|
||||||
|
"variants": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000006b",
|
||||||
|
"label": "Kartenvariante",
|
||||||
|
"part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000066"
|
||||||
|
],
|
||||||
|
"asset_ids": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000006c",
|
||||||
|
"label": "Filmvariante",
|
||||||
|
"part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000068"
|
||||||
|
],
|
||||||
|
"asset_ids": [
|
||||||
|
"caa20000-0000-4000-8000-00000000012c"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"rights": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"evidence_ref": "test-textrechte",
|
||||||
|
"actions": [
|
||||||
|
"store",
|
||||||
|
"render",
|
||||||
|
"grant_customer_use",
|
||||||
|
"commercial_course_use"
|
||||||
|
],
|
||||||
|
"territories": [
|
||||||
|
"DE"
|
||||||
|
],
|
||||||
|
"valid_from": "2026-11-23T09:00:00Z",
|
||||||
|
"valid_until": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000192",
|
||||||
|
"evidence_ref": "test-filmrechte",
|
||||||
|
"actions": [
|
||||||
|
"store",
|
||||||
|
"stream",
|
||||||
|
"course_display",
|
||||||
|
"grant_customer_use",
|
||||||
|
"commercial_course_use"
|
||||||
|
],
|
||||||
|
"territories": [
|
||||||
|
"DE"
|
||||||
|
],
|
||||||
|
"valid_from": "2026-11-23T09:00:00Z",
|
||||||
|
"valid_until": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"synthetic_asset_base64_by_id": {
|
||||||
|
"caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"eigener_bestand": {
|
||||||
|
"channel": "lara_felix",
|
||||||
|
"manifest_sha256": "7dad43afb3077fb2d9fb3aa490bb91daf53f175c06575d648411021d352a1744",
|
||||||
|
"manifest": {
|
||||||
|
"schema_version": 1,
|
||||||
|
"resource_type": "exercise",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000b",
|
||||||
|
"revision": 1,
|
||||||
|
"publisher_id": "caa20000-0000-4000-8000-00000000177b",
|
||||||
|
"published_at": "2026-11-23T09:02:00Z",
|
||||||
|
"exercise": {
|
||||||
|
"title": "Aufmerksam im Raum ankommen",
|
||||||
|
"audience": "Kursleitungen",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000006f",
|
||||||
|
"role": "goal",
|
||||||
|
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000070",
|
||||||
|
"role": "instructions",
|
||||||
|
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000071",
|
||||||
|
"role": "trainer_notes",
|
||||||
|
"text": "Vorab genug Platz vorsehen.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"assets": [],
|
||||||
|
"common_part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-00000000006f",
|
||||||
|
"caa20000-0000-4000-8000-000000000071"
|
||||||
|
],
|
||||||
|
"common_asset_ids": [],
|
||||||
|
"variants": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000075",
|
||||||
|
"label": "Kartenvariante",
|
||||||
|
"part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000070"
|
||||||
|
],
|
||||||
|
"asset_ids": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"rights": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"evidence_ref": "test-textrechte",
|
||||||
|
"actions": [
|
||||||
|
"store",
|
||||||
|
"render",
|
||||||
|
"grant_customer_use",
|
||||||
|
"commercial_course_use"
|
||||||
|
],
|
||||||
|
"territories": [
|
||||||
|
"DE"
|
||||||
|
],
|
||||||
|
"valid_from": "2026-11-23T09:00:00Z",
|
||||||
|
"valid_until": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"synthetic_asset_base64_by_id": {}
|
||||||
|
},
|
||||||
|
"vereinsfassung_2": {
|
||||||
|
"channel": "lara_felix",
|
||||||
|
"manifest_sha256": "f0c8051cee6feb0e6399f1bc5681e0ef1ecd640c1cbe6b634c5df1c1b1df9ed0",
|
||||||
|
"manifest": {
|
||||||
|
"schema_version": 1,
|
||||||
|
"resource_type": "exercise",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000a",
|
||||||
|
"revision": 2,
|
||||||
|
"publisher_id": "caa20000-0000-4000-8000-00000000177a",
|
||||||
|
"published_at": "2026-11-23T09:03:00Z",
|
||||||
|
"exercise": {
|
||||||
|
"title": "Raum und Wege wahrnehmen",
|
||||||
|
"audience": "Kursleitungen",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000065",
|
||||||
|
"role": "goal",
|
||||||
|
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000066",
|
||||||
|
"role": "instructions",
|
||||||
|
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000067",
|
||||||
|
"role": "trainer_notes",
|
||||||
|
"text": "Vorab genug Platz vorsehen und die Laufwege gemeinsam prüfen.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000068",
|
||||||
|
"role": "instructions",
|
||||||
|
"text": "Den kurzen Film ansehen und danach die gezeigten Wege vergleichen.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000012c",
|
||||||
|
"role": "demonstration",
|
||||||
|
"media_type": "video/mp4",
|
||||||
|
"size_bytes": 32,
|
||||||
|
"sha256": "0fb807ef5ec44b003f181dfa9ce317becbcfd5755ebf91a57702d2024df2b915",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000192",
|
||||||
|
"label": "Demonstrationsfilm"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"common_part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000065",
|
||||||
|
"caa20000-0000-4000-8000-000000000067"
|
||||||
|
],
|
||||||
|
"common_asset_ids": [],
|
||||||
|
"variants": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000006b",
|
||||||
|
"label": "Kartenvariante",
|
||||||
|
"part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000066"
|
||||||
|
],
|
||||||
|
"asset_ids": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000006c",
|
||||||
|
"label": "Filmvariante",
|
||||||
|
"part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000068"
|
||||||
|
],
|
||||||
|
"asset_ids": [
|
||||||
|
"caa20000-0000-4000-8000-00000000012c"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"rights": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"evidence_ref": "test-textrechte",
|
||||||
|
"actions": [
|
||||||
|
"store",
|
||||||
|
"render",
|
||||||
|
"grant_customer_use",
|
||||||
|
"commercial_course_use"
|
||||||
|
],
|
||||||
|
"territories": [
|
||||||
|
"DE"
|
||||||
|
],
|
||||||
|
"valid_from": "2026-11-23T09:00:00Z",
|
||||||
|
"valid_until": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000192",
|
||||||
|
"evidence_ref": "test-filmrechte",
|
||||||
|
"actions": [
|
||||||
|
"store",
|
||||||
|
"stream",
|
||||||
|
"course_display",
|
||||||
|
"grant_customer_use",
|
||||||
|
"commercial_course_use"
|
||||||
|
],
|
||||||
|
"territories": [
|
||||||
|
"DE"
|
||||||
|
],
|
||||||
|
"valid_from": "2026-11-23T09:00:00Z",
|
||||||
|
"valid_until": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"synthetic_asset_base64_by_id": {
|
||||||
|
"caa20000-0000-4000-8000-00000000012c": "U2hpbmthbiBkaXN0cmlidXRpb24gZml4dHVyZSB2MQo="
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"zweiter_verein": {
|
||||||
|
"channel": "zweiter_verein",
|
||||||
|
"manifest_sha256": "3e34007864d308ac1cf6b555bb7fd00dd6962fb6f396eca16492ace0fec59603",
|
||||||
|
"manifest": {
|
||||||
|
"schema_version": 1,
|
||||||
|
"resource_type": "exercise",
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000cc",
|
||||||
|
"source_id": "caa20000-0000-4000-8000-00000000000c",
|
||||||
|
"revision": 1,
|
||||||
|
"publisher_id": "caa20000-0000-4000-8000-00000000177c",
|
||||||
|
"published_at": "2026-11-23T09:03:00Z",
|
||||||
|
"exercise": {
|
||||||
|
"title": "Gemeinsam den Raum erkunden",
|
||||||
|
"audience": "Kursleitungen",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000079",
|
||||||
|
"role": "goal",
|
||||||
|
"text": "Die Gruppe nimmt freie Wege im Raum wahr.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000007a",
|
||||||
|
"role": "instructions",
|
||||||
|
"text": "Die Kursleitung legt Karten aus und bespricht die freien Wege.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000007b",
|
||||||
|
"role": "trainer_notes",
|
||||||
|
"text": "Vorab genug Platz vorsehen.",
|
||||||
|
"rights_id": "caa20000-0000-4000-8000-000000000191"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"assets": [],
|
||||||
|
"common_part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-000000000079",
|
||||||
|
"caa20000-0000-4000-8000-00000000007b"
|
||||||
|
],
|
||||||
|
"common_asset_ids": [],
|
||||||
|
"variants": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-00000000007f",
|
||||||
|
"label": "Kartenvariante",
|
||||||
|
"part_ids": [
|
||||||
|
"caa20000-0000-4000-8000-00000000007a"
|
||||||
|
],
|
||||||
|
"asset_ids": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"rights": [
|
||||||
|
{
|
||||||
|
"id": "caa20000-0000-4000-8000-000000000191",
|
||||||
|
"evidence_ref": "test-textrechte",
|
||||||
|
"actions": [
|
||||||
|
"store",
|
||||||
|
"render",
|
||||||
|
"grant_customer_use",
|
||||||
|
"commercial_course_use"
|
||||||
|
],
|
||||||
|
"territories": [
|
||||||
|
"DE"
|
||||||
|
],
|
||||||
|
"valid_from": "2026-11-23T09:00:00Z",
|
||||||
|
"valid_until": null
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"synthetic_asset_base64_by_id": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"plans": {
|
||||||
|
"plan_a_mit_film": {
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||||
|
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||||
|
},
|
||||||
|
"plan_b_mit_karten": {
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||||
|
"variant_id": "caa20000-0000-4000-8000-00000000006b"
|
||||||
|
},
|
||||||
|
"plan_c_mit_film_neuere_fassung": {
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000cb",
|
||||||
|
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||||
|
},
|
||||||
|
"plan_d_eigener_bestand": {
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000ca",
|
||||||
|
"variant_id": "caa20000-0000-4000-8000-000000000075"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"expected": {
|
||||||
|
"plan_binding_after_revision": {
|
||||||
|
"release_id": "caa20000-0000-4000-8000-0000000000c9",
|
||||||
|
"variant_id": "caa20000-0000-4000-8000-00000000006c"
|
||||||
|
},
|
||||||
|
"blocked_plans_after_withdrawal": [
|
||||||
|
"plan_a_mit_film",
|
||||||
|
"plan_c_mit_film_neuere_fassung"
|
||||||
|
],
|
||||||
|
"available_plans_after_withdrawal": [
|
||||||
|
"plan_b_mit_karten",
|
||||||
|
"plan_d_eigener_bestand"
|
||||||
|
],
|
||||||
|
"lara_felix_can_retrieve_after_withdrawal": [
|
||||||
|
"caa20000-0000-4000-8000-0000000000ca"
|
||||||
|
],
|
||||||
|
"zweiter_verein_can_retrieve": [
|
||||||
|
"caa20000-0000-4000-8000-0000000000cc"
|
||||||
|
],
|
||||||
|
"course_film_allowed": true,
|
||||||
|
"film_download_allowed": false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,12 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
from tenant_context import library_content_visibility_sql, parse_active_club_header, resolve_tenant_context
|
from tenant_context import (
|
||||||
|
library_content_visibility_for_progression_graph_sql,
|
||||||
|
library_content_visibility_sql,
|
||||||
|
parse_active_club_header,
|
||||||
|
resolve_tenant_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_library_visibility_sql_platform_admin_restricts_club_by_membership():
|
def test_library_visibility_sql_platform_admin_restricts_club_by_membership():
|
||||||
@@ -41,6 +46,37 @@ def test_library_visibility_sql_trainer_without_active_club_no_shared_club_branc
|
|||||||
assert params == [42]
|
assert params == [42]
|
||||||
|
|
||||||
|
|
||||||
|
def test_progression_graph_visibility_sql_private_matches_library():
|
||||||
|
base_sql, base_params = library_content_visibility_sql(
|
||||||
|
alias="e", profile_id=5, role="trainer", effective_club_id=12
|
||||||
|
)
|
||||||
|
graph_sql, graph_params = library_content_visibility_for_progression_graph_sql(
|
||||||
|
alias="e",
|
||||||
|
profile_id=5,
|
||||||
|
role="trainer",
|
||||||
|
effective_club_id=12,
|
||||||
|
graph_visibility="private",
|
||||||
|
graph_club_id=None,
|
||||||
|
)
|
||||||
|
assert graph_sql == base_sql
|
||||||
|
assert graph_params == base_params
|
||||||
|
|
||||||
|
|
||||||
|
def test_progression_graph_visibility_sql_club_excludes_private():
|
||||||
|
sql, params = library_content_visibility_for_progression_graph_sql(
|
||||||
|
alias="e",
|
||||||
|
profile_id=5,
|
||||||
|
role="trainer",
|
||||||
|
effective_club_id=12,
|
||||||
|
graph_visibility="club",
|
||||||
|
graph_club_id=12,
|
||||||
|
)
|
||||||
|
assert "official" in sql
|
||||||
|
assert "visibility = 'club'" in sql
|
||||||
|
assert "visibility = 'private'" not in sql
|
||||||
|
assert 12 in params
|
||||||
|
|
||||||
|
|
||||||
def test_library_visibility_sql_user_with_active_club_includes_club_branch():
|
def test_library_visibility_sql_user_with_active_club_includes_club_branch():
|
||||||
sql, params = library_content_visibility_sql(
|
sql, params = library_content_visibility_sql(
|
||||||
alias="t",
|
alias="t",
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""Admin-Vorschau für Planungs-Prompt-Slugs."""
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from ai_prompt_planning_preview import (
|
||||||
|
PLANNING_PROMPT_SLUGS,
|
||||||
|
PlanningPromptPreviewInput,
|
||||||
|
is_planning_prompt_slug,
|
||||||
|
resolve_planning_prompt_preview_variables,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_planning_prompt_slug():
|
||||||
|
assert is_planning_prompt_slug("planning_progression_roadmap")
|
||||||
|
assert is_planning_prompt_slug("PLANNING_EXERCISE_PATH_QA")
|
||||||
|
assert not is_planning_prompt_slug("exercise_summary")
|
||||||
|
assert not is_planning_prompt_slug("")
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_roadmap_preview_variables():
|
||||||
|
body = PlanningPromptPreviewInput(goal_query="Mae Geri Basics", max_steps=4)
|
||||||
|
vars_map = resolve_planning_prompt_preview_variables(
|
||||||
|
MagicMock(),
|
||||||
|
"planning_progression_roadmap",
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
assert vars_map["goal_query"] == "Mae Geri Basics"
|
||||||
|
assert vars_map["max_steps"] == "4"
|
||||||
|
assert "goal_analysis_json" in vars_map
|
||||||
|
assert "semantic_brief_json" in vars_map
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_stage_spec_includes_intent_context():
|
||||||
|
body = PlanningPromptPreviewInput(user_notes="Breitensport")
|
||||||
|
vars_map = resolve_planning_prompt_preview_variables(
|
||||||
|
MagicMock(),
|
||||||
|
"planning_progression_stage_spec",
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
assert "intent_context_json" in vars_map
|
||||||
|
assert "major_steps_json" in vars_map
|
||||||
|
|
||||||
|
|
||||||
|
@patch("ai_prompt_planning_preview._load_catalog_variables")
|
||||||
|
def test_resolve_search_intent_includes_catalogs(mock_catalog):
|
||||||
|
mock_catalog.return_value = {
|
||||||
|
"skills_catalog_json": "[]",
|
||||||
|
"focus_areas_catalog_json": "[]",
|
||||||
|
"training_types_catalog_json": "[]",
|
||||||
|
"style_directions_catalog_json": "[]",
|
||||||
|
"target_groups_catalog_json": "[]",
|
||||||
|
}
|
||||||
|
body = PlanningPromptPreviewInput(search_query="Mae Geri nächster Schritt")
|
||||||
|
vars_map = resolve_planning_prompt_preview_variables(
|
||||||
|
MagicMock(),
|
||||||
|
"planning_exercise_search_intent",
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
assert vars_map["search_query"] == "Mae Geri nächster Schritt"
|
||||||
|
assert vars_map["skills_catalog_json"] == "[]"
|
||||||
|
|
||||||
|
|
||||||
|
def test_non_planning_slug_raises():
|
||||||
|
with pytest.raises(ValueError, match="Kein Planungs-Prompt-Slug"):
|
||||||
|
resolve_planning_prompt_preview_variables(
|
||||||
|
MagicMock(),
|
||||||
|
"exercise_summary",
|
||||||
|
PlanningPromptPreviewInput(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_registered_slugs_resolve():
|
||||||
|
for slug in PLANNING_PROMPT_SLUGS:
|
||||||
|
with patch("ai_prompt_planning_preview._load_catalog_variables") as mock_catalog:
|
||||||
|
mock_catalog.return_value = {
|
||||||
|
"skills_catalog_json": "[]",
|
||||||
|
"focus_areas_catalog_json": "[]",
|
||||||
|
"training_types_catalog_json": "[]",
|
||||||
|
"style_directions_catalog_json": "[]",
|
||||||
|
"target_groups_catalog_json": "[]",
|
||||||
|
}
|
||||||
|
vars_map = resolve_planning_prompt_preview_variables(
|
||||||
|
MagicMock(),
|
||||||
|
slug,
|
||||||
|
PlanningPromptPreviewInput(),
|
||||||
|
)
|
||||||
|
assert isinstance(vars_map, dict)
|
||||||
|
assert len(vars_map) >= 1
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""Login-Sperre, TOTP und Medien-Grant ohne Datenbank."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||||
|
os.environ.setdefault("REQUIRE_ADMIN_TOTP", "0")
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from main import app
|
||||||
|
from media_grant import issue_media_grant, profile_id_from_media_grant
|
||||||
|
from totp_auth import generate_totp_secret, totp_code, verify_totp
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client() -> TestClient:
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_totp_accepts_current_code() -> None:
|
||||||
|
secret = generate_totp_secret()
|
||||||
|
code = totp_code(secret, int(time.time()) // 30)
|
||||||
|
assert verify_totp(secret, code)
|
||||||
|
assert not verify_totp(secret, "000000") or code == "000000"
|
||||||
|
|
||||||
|
|
||||||
|
def test_media_grant_rejects_session_shaped_token() -> None:
|
||||||
|
assert profile_id_from_media_grant("not-a-media-grant") is None
|
||||||
|
token, _exp = issue_media_grant(42, ttl_seconds=60)
|
||||||
|
assert profile_id_from_media_grant(token) == 42
|
||||||
|
assert profile_id_from_media_grant(token + "x") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_change_password_requires_current_password() -> None:
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from models import ChangePasswordRequest
|
||||||
|
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
ChangePasswordRequest.model_validate({"pin": "neuespasswort"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_password_reset_rejects_header_injection() -> None:
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from models import PasswordResetRequest, ResendVerificationRequest
|
||||||
|
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
PasswordResetRequest.model_validate({"email": "trainer@example.com\nBcc: x@y.z"})
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
ResendVerificationRequest.model_validate({"email": "nicht-eine-email"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_mime_comes_from_bytes_not_client_header() -> None:
|
||||||
|
from routers.exercises import _content_disposition, resolve_upload_mime_type
|
||||||
|
|
||||||
|
jpeg = b"\xff\xd8\xff" + b"\x00" * 16
|
||||||
|
assert resolve_upload_mime_type(jpeg, "text/html", "evil.html") == "image/jpeg"
|
||||||
|
pdf = b"%PDF-1.4\n" + b"0" * 8
|
||||||
|
assert resolve_upload_mime_type(pdf, "image/png", "bild.png") == "application/pdf"
|
||||||
|
try:
|
||||||
|
resolve_upload_mime_type(b"<html><script>alert(1)</script></html>", "image/jpeg", "x.jpg")
|
||||||
|
raised = False
|
||||||
|
except ValueError:
|
||||||
|
raised = True
|
||||||
|
assert raised
|
||||||
|
disposition = _content_disposition('bericht.pdf\r\nX-Evil: 1', attachment=True)
|
||||||
|
assert disposition.startswith("attachment")
|
||||||
|
assert "\r" not in disposition
|
||||||
|
assert "\n" not in disposition
|
||||||
|
|
||||||
|
|
||||||
|
def test_totp_reset_requires_auth(client: TestClient) -> None:
|
||||||
|
response = client.post("/api/profiles/1/totp-reset")
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_rejects_oversized_password(client: TestClient) -> None:
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": "trainer@example.com", "password": "x" * 200},
|
||||||
|
)
|
||||||
|
assert response.status_code == 422
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Tests Namens-Fallback für Katalog-Prompt-Slots."""
|
||||||
|
from catalog_slot_fallbacks import get_fallback_slots_for_entry, merge_stored_slots_with_fallbacks
|
||||||
|
from catalog_prompt_slots import _resolve_entry_slot_values
|
||||||
|
|
||||||
|
|
||||||
|
def test_karate_fallback_has_path_qa():
|
||||||
|
pack = get_fallback_slots_for_entry("focus_area", "Karate")
|
||||||
|
assert "Kohärente Progression" in pack.get("hints_on_path_qa", "")
|
||||||
|
|
||||||
|
|
||||||
|
def test_db_value_overrides_fallback():
|
||||||
|
merged = merge_stored_slots_with_fallbacks(
|
||||||
|
{"hints_on_path_qa": "Eigener QS-Text."},
|
||||||
|
catalog_kind="focus_area",
|
||||||
|
name="Karate",
|
||||||
|
stammdaten_description="Traditionelles Karate",
|
||||||
|
)
|
||||||
|
assert merged["hints_on_path_qa"] == "Eigener QS-Text."
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_db_uses_karate_fallback():
|
||||||
|
merged = _resolve_entry_slot_values(
|
||||||
|
{},
|
||||||
|
{"name": "Karate", "description": "Traditionelles Karate"},
|
||||||
|
"focus_area",
|
||||||
|
)
|
||||||
|
assert "Kihon-Progression" in merged["description"] or "Technik-Curriculum" in merged["description"]
|
||||||
|
assert "Kohärente Progression" in merged["hints_on_path_qa"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_gewaltschutz_fallback_no_kumite():
|
||||||
|
merged = _resolve_entry_slot_values(
|
||||||
|
{},
|
||||||
|
{"name": "Gewaltschutz", "description": "Gewaltprävention"},
|
||||||
|
"focus_area",
|
||||||
|
)
|
||||||
|
assert "Deeskalation" in merged["hints_on_path_qa"]
|
||||||
|
assert "Kumite-Tiefe" in merged["anti_patterns"]
|
||||||
@@ -0,0 +1,435 @@
|
|||||||
|
"""Vertrag v1, Referenzfall, Rollen und Bestätigung nach Rückzug."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import inspect
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from distribution_service import _lock_recipient, release_keys_for_exercise
|
||||||
|
from distribution_contract import (
|
||||||
|
InvalidCursor,
|
||||||
|
actions_cover,
|
||||||
|
cursor_secret,
|
||||||
|
decide_confirm,
|
||||||
|
decode_cursor,
|
||||||
|
encode_cursor,
|
||||||
|
exercise_offerable,
|
||||||
|
package_state,
|
||||||
|
scope_denial,
|
||||||
|
manifest_bytes,
|
||||||
|
official_write_allowed,
|
||||||
|
plan_available,
|
||||||
|
rate_decision,
|
||||||
|
catalog_available,
|
||||||
|
catalog_changes,
|
||||||
|
catalog_document,
|
||||||
|
catalog_hash,
|
||||||
|
changed_areas,
|
||||||
|
release_denial,
|
||||||
|
retrievable_release_ids,
|
||||||
|
sha256_bytes,
|
||||||
|
)
|
||||||
|
from main import app
|
||||||
|
from routers.exercises import _assert_can_edit_exercise
|
||||||
|
from tenant_context import TenantContext, get_tenant_context
|
||||||
|
|
||||||
|
# Liegt im Backend-Baum, weil Pytest im API-Image läuft und dort kein Repo-docs-Ordner existiert.
|
||||||
|
FIXTURE = json.loads(
|
||||||
|
(Path(__file__).resolve().parent / "fixtures" / "Shinkan_Lara_Felix_Referenzfall_v1.json").read_text(encoding="utf-8")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fixture_manifest_hashes_match_contract_order() -> None:
|
||||||
|
for release in FIXTURE["releases"].values():
|
||||||
|
body = manifest_bytes(release["manifest"])
|
||||||
|
assert sha256_bytes(body) == release["manifest_sha256"]
|
||||||
|
assert not body.endswith(b"\n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_reference_case_retrieval_and_plan_effect() -> None:
|
||||||
|
lara_events = FIXTURE["channels"]["lara_felix"]["events"]
|
||||||
|
second_events = FIXTURE["channels"]["zweiter_verein"]["events"]
|
||||||
|
assert retrievable_release_ids(lara_events) == set(FIXTURE["expected"]["lara_felix_can_retrieve_after_withdrawal"])
|
||||||
|
assert retrievable_release_ids(second_events) == set(FIXTURE["expected"]["zweiter_verein_can_retrieve"])
|
||||||
|
manifests = {item["manifest"]["release_id"]: item["manifest"] for item in FIXTURE["releases"].values()}
|
||||||
|
blocked = []
|
||||||
|
available = []
|
||||||
|
for name, plan in FIXTURE["plans"].items():
|
||||||
|
if plan_available(plan, manifests[plan["release_id"]], lara_events):
|
||||||
|
available.append(name)
|
||||||
|
else:
|
||||||
|
blocked.append(name)
|
||||||
|
assert set(blocked) == set(FIXTURE["expected"]["blocked_plans_after_withdrawal"])
|
||||||
|
assert set(available) == set(FIXTURE["expected"]["available_plans_after_withdrawal"])
|
||||||
|
film_actions = FIXTURE["releases"]["vereinsfassung_1"]["manifest"]["rights"][1]["actions"]
|
||||||
|
assert actions_cover(film_actions, ["stream", "course_display", "commercial_course_use"]) is FIXTURE["expected"]["course_film_allowed"]
|
||||||
|
assert ("download" in film_actions) is FIXTURE["expected"]["film_download_allowed"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> None:
|
||||||
|
drafts: dict[str, str] = {}
|
||||||
|
releases: dict[str, dict] = {}
|
||||||
|
events: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
def confirm(draft_id: str, revision: int, cut: str) -> tuple[str, bool]:
|
||||||
|
release_id, created = decide_confirm(drafts.get(draft_id), f"rel-{len(releases) + 1}")
|
||||||
|
if created:
|
||||||
|
drafts[draft_id] = release_id
|
||||||
|
releases[release_id] = {"withdrawn": False, "revision": revision, "cut": cut}
|
||||||
|
events.append(("published", release_id))
|
||||||
|
return release_id, created
|
||||||
|
|
||||||
|
first, created = confirm("draft-1", 1, "same-cut")
|
||||||
|
again, replayed = confirm("draft-1", 1, "same-cut")
|
||||||
|
assert first == again
|
||||||
|
assert created is True
|
||||||
|
assert replayed is False
|
||||||
|
assert events == [("published", first)]
|
||||||
|
|
||||||
|
releases[first]["withdrawn"] = True
|
||||||
|
second, created_again = confirm("draft-2", 1, "same-cut")
|
||||||
|
assert created_again is True
|
||||||
|
assert second != first
|
||||||
|
assert releases[first]["withdrawn"] is True
|
||||||
|
assert releases[second]["revision"] == 1
|
||||||
|
assert releases[second]["cut"] == "same-cut"
|
||||||
|
assert [kind for kind, _ in events] == ["published", "published"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_key_scope_follows_the_role_context() -> None:
|
||||||
|
assert scope_denial("user", ["exercise"], ["official", "club", "private"]) is None
|
||||||
|
assert scope_denial("personal", ["exercise"], ["private"]) is None
|
||||||
|
assert scope_denial("personal", ["exercise"], ["official"])
|
||||||
|
assert scope_denial("club", ["exercise", "framework"], ["club", "private"]) is None
|
||||||
|
assert scope_denial("club", ["exercise"], ["official"])
|
||||||
|
assert scope_denial("platform", ["training_plan"], ["official", "private"]) is None
|
||||||
|
assert scope_denial("platform", [], ["official"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_availability_keeps_the_copy_and_stops_new_offers() -> None:
|
||||||
|
assert package_state(fetch_blocked=False, retired=False) == "available"
|
||||||
|
assert package_state(fetch_blocked=False, retired=True) == "retired"
|
||||||
|
assert package_state(fetch_blocked=True, retired=True) == "withdrawn"
|
||||||
|
status, offerable = exercise_offerable("approved", ["available"])
|
||||||
|
assert status == "approved" and offerable is True
|
||||||
|
status, offerable = exercise_offerable("archived", ["available"])
|
||||||
|
assert status == "archived" and offerable is False
|
||||||
|
status, offerable = exercise_offerable(None, ["withdrawn"])
|
||||||
|
assert status == "deleted" and offerable is False
|
||||||
|
status, offerable = exercise_offerable("approved", ["retired", "withdrawn"])
|
||||||
|
assert offerable is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_cursor_is_bound_to_recipient() -> None:
|
||||||
|
secret = cursor_secret()
|
||||||
|
token = encode_cursor(secret, "recipient-a", 4)
|
||||||
|
assert decode_cursor(secret, "recipient-a", token) == 4
|
||||||
|
assert decode_cursor(secret, "recipient-a", None) == 0
|
||||||
|
with pytest.raises(InvalidCursor):
|
||||||
|
decode_cursor(secret, "recipient-b", token)
|
||||||
|
|
||||||
|
|
||||||
|
def test_rate_window_blocks_at_sixty() -> None:
|
||||||
|
hits, blocked = rate_decision(59, 10)
|
||||||
|
assert hits == 60 and blocked is False
|
||||||
|
hits, blocked = rate_decision(60, 10)
|
||||||
|
assert blocked is True
|
||||||
|
hits, blocked = rate_decision(60, 61)
|
||||||
|
assert hits == 1 and blocked is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_official_release_and_edit_roles() -> None:
|
||||||
|
assert official_write_allowed("official", "superadmin") is True
|
||||||
|
assert official_write_allowed("official", "admin") is False
|
||||||
|
assert official_write_allowed("official", "club_admin") is False
|
||||||
|
assert official_write_allowed("club", "admin") is True
|
||||||
|
assert release_denial(
|
||||||
|
visibility="official",
|
||||||
|
role="admin",
|
||||||
|
publisher_kind="platform",
|
||||||
|
is_owner=True,
|
||||||
|
is_club_admin=False,
|
||||||
|
)
|
||||||
|
assert release_denial(
|
||||||
|
visibility="official",
|
||||||
|
role="superadmin",
|
||||||
|
publisher_kind="platform",
|
||||||
|
is_owner=False,
|
||||||
|
is_club_admin=False,
|
||||||
|
) is None
|
||||||
|
assert release_denial(
|
||||||
|
visibility="private",
|
||||||
|
role="trainer",
|
||||||
|
publisher_kind="own",
|
||||||
|
is_owner=True,
|
||||||
|
is_club_admin=False,
|
||||||
|
) is None
|
||||||
|
assert release_denial(
|
||||||
|
visibility="private",
|
||||||
|
role="admin",
|
||||||
|
publisher_kind="own",
|
||||||
|
is_owner=False,
|
||||||
|
is_club_admin=False,
|
||||||
|
)
|
||||||
|
assert release_denial(
|
||||||
|
visibility="club",
|
||||||
|
role="trainer",
|
||||||
|
publisher_kind="club",
|
||||||
|
is_owner=True,
|
||||||
|
is_club_admin=False,
|
||||||
|
publisher_club_id=4,
|
||||||
|
exercise_club_id=4,
|
||||||
|
)
|
||||||
|
assert release_denial(
|
||||||
|
visibility="club",
|
||||||
|
role="trainer",
|
||||||
|
publisher_kind="club",
|
||||||
|
is_owner=False,
|
||||||
|
is_club_admin=True,
|
||||||
|
publisher_club_id=4,
|
||||||
|
exercise_club_id=4,
|
||||||
|
) is None
|
||||||
|
assert release_denial(
|
||||||
|
visibility="club",
|
||||||
|
role="trainer",
|
||||||
|
publisher_kind="club",
|
||||||
|
is_owner=False,
|
||||||
|
is_club_admin=True,
|
||||||
|
publisher_club_id=9,
|
||||||
|
exercise_club_id=4,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _tenant(role: str, profile_id: int = 7) -> TenantContext:
|
||||||
|
return TenantContext(
|
||||||
|
profile_id=profile_id,
|
||||||
|
global_role=role,
|
||||||
|
effective_club_id=None,
|
||||||
|
club_ids=frozenset(),
|
||||||
|
memberships=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assert_edit_rejects_admin_and_club_role_for_official() -> None:
|
||||||
|
cur = MagicMock()
|
||||||
|
cur.fetchone.return_value = {"created_by": 7, "visibility": "official", "club_id": None}
|
||||||
|
for role in ("admin", "trainer", "club_admin"):
|
||||||
|
with pytest.raises(HTTPException) as caught:
|
||||||
|
_assert_can_edit_exercise(cur, 3, _tenant(role))
|
||||||
|
assert caught.value.status_code == 403
|
||||||
|
_assert_can_edit_exercise(cur, 3, _tenant("superadmin", profile_id=1))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client() -> TestClient:
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_distribution_read_is_hidden_while_disabled(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.delenv("DISTRIBUTION_ENABLED", raising=False)
|
||||||
|
response = client.get("/api/distribution/v1/changes", headers={"Authorization": "Bearer shk.abc.def"})
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.headers.get("cache-control") == "private, no-store"
|
||||||
|
|
||||||
|
|
||||||
|
def test_cursor_secret_uses_database_password_in_production(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||||
|
monkeypatch.delenv("DISTRIBUTION_CURSOR_SECRET", raising=False)
|
||||||
|
monkeypatch.setenv("DB_PASSWORD", "prod-db-secret")
|
||||||
|
first = cursor_secret()
|
||||||
|
assert first != "shinkan-distribution-dev-cursor"
|
||||||
|
assert "prod-db-secret" not in first
|
||||||
|
assert cursor_secret() == first
|
||||||
|
monkeypatch.setenv("DISTRIBUTION_CURSOR_SECRET", "explicit")
|
||||||
|
assert cursor_secret() == "explicit"
|
||||||
|
|
||||||
|
|
||||||
|
def test_cursor_secret_requires_material_in_production(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||||
|
monkeypatch.delenv("DISTRIBUTION_CURSOR_SECRET", raising=False)
|
||||||
|
monkeypatch.delenv("DB_PASSWORD", raising=False)
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
cursor_secret()
|
||||||
|
|
||||||
|
|
||||||
|
class _DroppingCursor:
|
||||||
|
"""Ein neues execute verwirft ein noch nicht gelesenes Ergebnis, wie psycopg2."""
|
||||||
|
|
||||||
|
def __init__(self, key: dict) -> None:
|
||||||
|
self._key = key
|
||||||
|
self._pending = None
|
||||||
|
|
||||||
|
def execute(self, sql, _params=None):
|
||||||
|
if self._pending is not None:
|
||||||
|
raise AssertionError("Ergebnis wurde vor dem Lesen überschrieben")
|
||||||
|
self._pending = [self._key] if "FROM distribution_keys" in sql else []
|
||||||
|
|
||||||
|
def fetchall(self):
|
||||||
|
rows = self._pending
|
||||||
|
self._pending = None
|
||||||
|
return rows or []
|
||||||
|
|
||||||
|
def fetchone(self):
|
||||||
|
rows = self.fetchall()
|
||||||
|
return rows[0] if rows else None
|
||||||
|
|
||||||
|
|
||||||
|
def test_release_screen_keeps_the_application_key() -> None:
|
||||||
|
key = {
|
||||||
|
"id": "key-1",
|
||||||
|
"label": "Lara",
|
||||||
|
"context_kind": "user",
|
||||||
|
"context_club_id": None,
|
||||||
|
"context_profile_id": 7,
|
||||||
|
"club_ids": [3],
|
||||||
|
"recipient_id": "rec-1",
|
||||||
|
"api_enabled": True,
|
||||||
|
}
|
||||||
|
cur = _DroppingCursor(key)
|
||||||
|
keys, block = release_keys_for_exercise(
|
||||||
|
cur,
|
||||||
|
{"visibility": "official", "club_id": None, "created_by": 7},
|
||||||
|
7,
|
||||||
|
"superadmin",
|
||||||
|
)
|
||||||
|
assert block is None
|
||||||
|
assert [item["label"] for item in keys] == ["Lara"]
|
||||||
|
|
||||||
|
|
||||||
|
def _catalog_exercise() -> dict:
|
||||||
|
return {
|
||||||
|
"public_id": "11111111-1111-1111-1111-111111111111",
|
||||||
|
"title": "Stand",
|
||||||
|
"summary": "",
|
||||||
|
"goal": "Sehen",
|
||||||
|
"execution": "Weg",
|
||||||
|
"preparation": "",
|
||||||
|
"trainer_notes": "",
|
||||||
|
"equipment": None,
|
||||||
|
"duration_min": None,
|
||||||
|
"duration_max": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_reports_variant_and_media_order_changes() -> None:
|
||||||
|
exercise = _catalog_exercise()
|
||||||
|
base_variant = [{"id": 1, "public_id": "var-1", "variant_name": "Karte", "description": "", "execution_changes": "Alt", "sequence_order": 1}]
|
||||||
|
base_media = [
|
||||||
|
{"id": 1, "public_id": "med-1", "media_type": "image", "title": "A", "sort_order": 1},
|
||||||
|
{"id": 2, "public_id": "med-2", "media_type": "image", "title": "B", "sort_order": 2},
|
||||||
|
]
|
||||||
|
original = catalog_hash(catalog_document(exercise, base_variant, base_media))
|
||||||
|
changed_variant = [{**base_variant[0], "execution_changes": "Neu"}]
|
||||||
|
reordered = [base_media[1] | {"sort_order": 1}, base_media[0] | {"sort_order": 2}]
|
||||||
|
assert catalog_hash(catalog_document(exercise, changed_variant, base_media)) != original
|
||||||
|
assert catalog_hash(catalog_document(exercise, base_variant, reordered)) != original
|
||||||
|
assert catalog_hash(catalog_document(exercise, base_variant, base_media)) == original
|
||||||
|
source = exercise["public_id"]
|
||||||
|
assert catalog_changes({source: original}, {source: original}) == []
|
||||||
|
updated = catalog_hash(catalog_document(exercise, changed_variant, base_media))
|
||||||
|
assert catalog_changes({source: original}, {source: updated}) == [
|
||||||
|
{"source_id": source, "change": "updated", "content_hash": updated}
|
||||||
|
]
|
||||||
|
assert catalog_changes({source: original}, {}) == [{"source_id": source, "change": "removed"}]
|
||||||
|
assert catalog_changes({}, {source: original}) == [
|
||||||
|
{"source_id": source, "change": "added", "content_hash": original}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_keeps_stored_html() -> None:
|
||||||
|
exercise = _catalog_exercise()
|
||||||
|
exercise["execution"] = "<p>Stand aufrecht.</p><p>Drehe die <strong>Hüfte</strong>.</p><br><ul><li>eins</li><li>zwei</li></ul>"
|
||||||
|
exercise["goal"] = "<script>alert(1)</script><p>Sehen</p>"
|
||||||
|
variant = [{
|
||||||
|
"id": 1,
|
||||||
|
"public_id": "var-1",
|
||||||
|
"variant_name": "Karte",
|
||||||
|
"description": "Kurzer Text",
|
||||||
|
"execution_changes": "<p>Langsamer.</p><p>Mit Partner.</p>",
|
||||||
|
"sequence_order": 1,
|
||||||
|
}]
|
||||||
|
document = catalog_document(exercise, variant, [])
|
||||||
|
assert document["text_format"] == "html"
|
||||||
|
assert document["execution"] == "<p>Stand aufrecht.</p><p>Drehe die <strong>Hüfte</strong>.</p><br><ul><li>eins</li><li>zwei</li></ul>"
|
||||||
|
assert document["goal"] == "<p>Sehen</p>"
|
||||||
|
assert "<script>" not in document["goal"]
|
||||||
|
assert document["variants"][0]["description"] == "Kurzer Text"
|
||||||
|
assert document["variants"][0]["execution_changes"] == "<p>Langsamer.</p><p>Mit Partner.</p>"
|
||||||
|
assert catalog_hash(catalog_document(exercise, variant, [])) == catalog_hash(document)
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_hides_unselected_and_out_of_scope_exercises() -> None:
|
||||||
|
assert catalog_available(True, True) is True
|
||||||
|
assert catalog_available(False, True) is False
|
||||||
|
assert catalog_available(True, False) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_areas_names_the_edited_instruction() -> None:
|
||||||
|
exercise = {
|
||||||
|
"title": "Stand",
|
||||||
|
"summary": "",
|
||||||
|
"goal": "Sehen",
|
||||||
|
"execution": "Neuer Weg",
|
||||||
|
"preparation": "",
|
||||||
|
"trainer_notes": "",
|
||||||
|
"equipment": None,
|
||||||
|
"duration_min": None,
|
||||||
|
"duration_max": None,
|
||||||
|
}
|
||||||
|
manifest = {
|
||||||
|
"exercise": {
|
||||||
|
"title": "Stand",
|
||||||
|
"summary": None,
|
||||||
|
"parts": [
|
||||||
|
{"role": "goal", "text": "Sehen"},
|
||||||
|
{"role": "instructions", "text": "Alter Weg"},
|
||||||
|
],
|
||||||
|
"variants": [{"id": "v", "label": "Standard"}],
|
||||||
|
"assets": [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert changed_areas(exercise, [], [], manifest) == ["Durchführung"]
|
||||||
|
exercise["execution"] = "Alter Weg"
|
||||||
|
assert changed_areas(exercise, [], [], manifest) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_channel_sequence_is_locked() -> None:
|
||||||
|
assert "FOR UPDATE" in inspect.getsource(_lock_recipient)
|
||||||
|
|
||||||
|
|
||||||
|
def test_variant_and_media_routes_reject_admin_on_official(client: TestClient) -> None:
|
||||||
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 4, "role": "admin"}
|
||||||
|
app.dependency_overrides[get_tenant_context] = lambda: _tenant("admin", 4)
|
||||||
|
mock_cur = MagicMock()
|
||||||
|
mock_cur.fetchone.return_value = {"created_by": 4, "visibility": "official", "club_id": None}
|
||||||
|
mock_cm = MagicMock()
|
||||||
|
mock_cm.__enter__.return_value = MagicMock()
|
||||||
|
mock_cm.__exit__.return_value = False
|
||||||
|
try:
|
||||||
|
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||||
|
"routers.exercises.get_cursor", return_value=mock_cur
|
||||||
|
):
|
||||||
|
variant = client.post(
|
||||||
|
"/api/exercises/9/variants",
|
||||||
|
headers={"X-Auth-Token": "t"},
|
||||||
|
json={"variant_name": "Kartenweg"},
|
||||||
|
)
|
||||||
|
media = client.post(
|
||||||
|
"/api/exercises/9/media/from-asset",
|
||||||
|
headers={"X-Auth-Token": "t"},
|
||||||
|
json={"media_asset_id": 3},
|
||||||
|
)
|
||||||
|
assert variant.status_code == 403
|
||||||
|
assert media.status_code == 403
|
||||||
|
finally:
|
||||||
|
app.dependency_overrides.pop(require_auth, None)
|
||||||
|
app.dependency_overrides.pop(get_tenant_context, None)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Sichtbarkeit: Progressionsgraph ↔ Übungen (Promotion, Kanten, Match)."""
|
||||||
|
from routers.exercise_progression_graphs import (
|
||||||
|
_exercise_allowed_in_progression_graph,
|
||||||
|
_graph_promotion_transition,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_graph_promotion_transition_private_to_club():
|
||||||
|
assert _graph_promotion_transition("private", "club") == ("private",)
|
||||||
|
|
||||||
|
|
||||||
|
def test_graph_promotion_transition_private_to_official():
|
||||||
|
assert _graph_promotion_transition("private", "official") == ("private", "club")
|
||||||
|
|
||||||
|
|
||||||
|
def test_graph_promotion_transition_club_to_official():
|
||||||
|
assert _graph_promotion_transition("club", "official") == ("private", "club")
|
||||||
|
|
||||||
|
|
||||||
|
def test_graph_promotion_transition_noop():
|
||||||
|
assert _graph_promotion_transition("club", "club") is None
|
||||||
|
assert _graph_promotion_transition("official", "club") is None
|
||||||
|
assert _graph_promotion_transition("private", "private") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_club_graph_rejects_private_exercise():
|
||||||
|
assert not _exercise_allowed_in_progression_graph(
|
||||||
|
{"visibility": "private", "club_id": None, "created_by": 1},
|
||||||
|
graph_visibility="club",
|
||||||
|
graph_club_id=5,
|
||||||
|
profile_id=1,
|
||||||
|
role="trainer",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_club_graph_accepts_matching_club_exercise():
|
||||||
|
assert _exercise_allowed_in_progression_graph(
|
||||||
|
{"visibility": "club", "club_id": 5, "created_by": 2},
|
||||||
|
graph_visibility="club",
|
||||||
|
graph_club_id=5,
|
||||||
|
profile_id=1,
|
||||||
|
role="trainer",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_club_graph_accepts_official_exercise():
|
||||||
|
assert _exercise_allowed_in_progression_graph(
|
||||||
|
{"visibility": "official", "club_id": None, "created_by": 99},
|
||||||
|
graph_visibility="club",
|
||||||
|
graph_club_id=5,
|
||||||
|
profile_id=1,
|
||||||
|
role="trainer",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_private_graph_accepts_own_private_exercise():
|
||||||
|
assert _exercise_allowed_in_progression_graph(
|
||||||
|
{"visibility": "private", "club_id": None, "created_by": 7},
|
||||||
|
graph_visibility="private",
|
||||||
|
graph_club_id=None,
|
||||||
|
profile_id=7,
|
||||||
|
role="trainer",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_official_graph_requires_official_exercise():
|
||||||
|
assert not _exercise_allowed_in_progression_graph(
|
||||||
|
{"visibility": "club", "club_id": 5, "created_by": 2},
|
||||||
|
graph_visibility="official",
|
||||||
|
graph_club_id=None,
|
||||||
|
profile_id=1,
|
||||||
|
role="trainer",
|
||||||
|
)
|
||||||
|
assert _exercise_allowed_in_progression_graph(
|
||||||
|
{"visibility": "official", "club_id": None, "created_by": 2},
|
||||||
|
graph_visibility="official",
|
||||||
|
graph_club_id=None,
|
||||||
|
profile_id=1,
|
||||||
|
role="trainer",
|
||||||
|
)
|
||||||
@@ -10,11 +10,31 @@ from exercise_rich_text import (
|
|||||||
assert_no_inline_media_references_on_create,
|
assert_no_inline_media_references_on_create,
|
||||||
collect_inline_exercise_media_ids,
|
collect_inline_exercise_media_ids,
|
||||||
normalize_inline_exercise_media_markup,
|
normalize_inline_exercise_media_markup,
|
||||||
|
sanitize_exercise_rich_html,
|
||||||
validate_inline_exercise_media_ids_for_exercise,
|
validate_inline_exercise_media_ids_for_exercise,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_normalize_curly_to_span() -> None:
|
def test_normalize_strips_script_and_handlers() -> None:
|
||||||
|
raw = '<p onclick="alert(1)">Hallo <script>alert(1)</script></p><a href="javascript:alert(1)">Link</a>'
|
||||||
|
out = normalize_inline_exercise_media_markup(raw)
|
||||||
|
assert out is not None
|
||||||
|
lowered = out.lower()
|
||||||
|
assert "script" not in lowered
|
||||||
|
assert "onclick" not in lowered
|
||||||
|
assert "javascript:" not in lowered
|
||||||
|
assert "Hallo" in out
|
||||||
|
assert "Link" in out
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_keeps_inline_media_span() -> None:
|
||||||
|
raw = '<span class="shinkan-inline-media evil" data-shinkan-exercise-media="7" data-shinkan-exercise-media-size="full">x</span>'
|
||||||
|
out = sanitize_exercise_rich_html(raw)
|
||||||
|
assert out is not None
|
||||||
|
assert 'data-shinkan-exercise-media="7"' in out
|
||||||
|
assert 'data-shinkan-exercise-media-size="full"' in out
|
||||||
|
assert "shinkan-inline-media" in out
|
||||||
|
assert "evil" not in out
|
||||||
s = '<p>Vor {{exerciseMedia: 42 }} nach</p>'
|
s = '<p>Vor {{exerciseMedia: 42 }} nach</p>'
|
||||||
out = normalize_inline_exercise_media_markup(s)
|
out = normalize_inline_exercise_media_markup(s)
|
||||||
assert 'data-shinkan-exercise-media="42"' in out
|
assert 'data-shinkan-exercise-media="42"' in out
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
"""Scheduler für den Papierkorb-Job: 03:00 Europe/Berlin, ohne echten Löschlauf."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from scripts.media_retention_scheduler import (
|
||||||
|
next_run_at,
|
||||||
|
run_job,
|
||||||
|
seconds_until_next_0300,
|
||||||
|
serve,
|
||||||
|
)
|
||||||
|
|
||||||
|
BERLIN = ZoneInfo("Europe/Berlin")
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_file() -> Path | None:
|
||||||
|
"""Repo-Root lokal. Im Backend-Image liegt nur /app, ohne docker-compose.yml."""
|
||||||
|
for parent in Path(__file__).resolve().parents:
|
||||||
|
candidate = parent / "docker-compose.yml"
|
||||||
|
if candidate.is_file():
|
||||||
|
return candidate
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def test_winter_afternoon_waits_until_next_morning() -> None:
|
||||||
|
now = datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)
|
||||||
|
assert next_run_at(now).isoformat() == "2026-01-16T03:00:00+01:00"
|
||||||
|
assert seconds_until_next_0300(now) == 17 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
def test_summer_before_three_is_same_morning() -> None:
|
||||||
|
now = datetime(2026, 7, 15, 2, 0, tzinfo=BERLIN)
|
||||||
|
assert next_run_at(now).isoformat() == "2026-07-15T03:00:00+02:00"
|
||||||
|
assert seconds_until_next_0300(now) == 3600
|
||||||
|
|
||||||
|
|
||||||
|
def test_exactly_0300_waits_until_next_day() -> None:
|
||||||
|
now = datetime(2026, 1, 15, 3, 0, tzinfo=BERLIN)
|
||||||
|
assert next_run_at(now).isoformat() == "2026-01-16T03:00:00+01:00"
|
||||||
|
assert seconds_until_next_0300(now) == 24 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
def test_spring_forward_sleeps_absolute_22_hours() -> None:
|
||||||
|
now = datetime(2026, 3, 28, 4, 0, tzinfo=BERLIN)
|
||||||
|
target = next_run_at(now)
|
||||||
|
assert target.isoformat() == "2026-03-29T03:00:00+02:00"
|
||||||
|
assert seconds_until_next_0300(now) == 22 * 3600
|
||||||
|
assert (target - now).total_seconds() == 23 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
def test_fall_back_sleeps_absolute_24_hours() -> None:
|
||||||
|
now = datetime(2026, 10, 24, 4, 0, tzinfo=BERLIN)
|
||||||
|
target = next_run_at(now)
|
||||||
|
assert target.isoformat() == "2026-10-25T03:00:00+01:00"
|
||||||
|
assert seconds_until_next_0300(now) == 24 * 3600
|
||||||
|
assert (target - now).total_seconds() == 23 * 3600
|
||||||
|
|
||||||
|
|
||||||
|
def test_naive_datetime_is_rejected() -> None:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
next_run_at(datetime(2026, 1, 15, 10, 0))
|
||||||
|
|
||||||
|
|
||||||
|
def test_serve_sleeps_before_first_run(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.delenv("RETENTION_RUN_ON_START", raising=False)
|
||||||
|
state = {"now": datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)}
|
||||||
|
events: list[tuple] = []
|
||||||
|
|
||||||
|
def clock() -> datetime:
|
||||||
|
return state["now"]
|
||||||
|
|
||||||
|
def sleep(seconds: float) -> None:
|
||||||
|
events.append(("sleep", seconds))
|
||||||
|
state["now"] = state["now"] + timedelta(seconds=seconds)
|
||||||
|
|
||||||
|
def run() -> None:
|
||||||
|
events.append(("run",))
|
||||||
|
|
||||||
|
serve(iterations=1, sleep=sleep, clock=clock, run=run)
|
||||||
|
assert events == [("sleep", 17 * 3600), ("run",)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_serve_can_run_once_on_start(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.setenv("RETENTION_RUN_ON_START", "1")
|
||||||
|
state = {"now": datetime(2026, 7, 15, 2, 0, tzinfo=BERLIN)}
|
||||||
|
events: list[str] = []
|
||||||
|
|
||||||
|
def sleep(seconds: float) -> None:
|
||||||
|
events.append("sleep")
|
||||||
|
state["now"] = state["now"] + timedelta(seconds=seconds)
|
||||||
|
|
||||||
|
serve(
|
||||||
|
iterations=1,
|
||||||
|
sleep=sleep,
|
||||||
|
clock=lambda: state["now"],
|
||||||
|
run=lambda: events.append("run"),
|
||||||
|
)
|
||||||
|
assert events == ["run", "sleep", "run"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_serve_continues_after_failed_run(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.delenv("RETENTION_RUN_ON_START", raising=False)
|
||||||
|
state = {"now": datetime(2026, 1, 15, 10, 0, tzinfo=BERLIN)}
|
||||||
|
runs: list[int] = []
|
||||||
|
|
||||||
|
def sleep(seconds: float) -> None:
|
||||||
|
state["now"] = state["now"] + timedelta(seconds=seconds)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
runs.append(1)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
serve(iterations=2, sleep=sleep, clock=lambda: state["now"], run=run)
|
||||||
|
assert runs == [1, 1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_job_logs_failure_without_starting_real_job(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
class Done:
|
||||||
|
returncode = 1
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"scripts.media_retention_scheduler.subprocess.run",
|
||||||
|
lambda *args, **kwargs: Done(),
|
||||||
|
)
|
||||||
|
with caplog.at_level(logging.INFO, logger="retention.scheduler"):
|
||||||
|
assert run_job() == 1
|
||||||
|
assert "RETENTION_FAIL exit=1" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_job_logs_success(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
class Done:
|
||||||
|
returncode = 0
|
||||||
|
|
||||||
|
seen: list[list[str]] = []
|
||||||
|
|
||||||
|
def fake_run(cmd, check=False):
|
||||||
|
seen.append(list(cmd))
|
||||||
|
return Done()
|
||||||
|
|
||||||
|
monkeypatch.setattr("scripts.media_retention_scheduler.subprocess.run", fake_run)
|
||||||
|
with caplog.at_level(logging.INFO, logger="retention.scheduler"):
|
||||||
|
assert run_job() == 0
|
||||||
|
assert seen and seen[0][-1].endswith("media_retention_job.py")
|
||||||
|
assert "RETENTION_OK" in caplog.text
|
||||||
|
assert "RETENTION_FAIL" not in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_compose_starts_scheduler_script() -> None:
|
||||||
|
compose = _compose_file()
|
||||||
|
if compose is None:
|
||||||
|
pytest.skip("docker-compose.yml liegt nicht im Backend-Image")
|
||||||
|
text = compose.read_text(encoding="utf-8")
|
||||||
|
start = text.index(" retention-cron:")
|
||||||
|
block = text[start : text.index("\nvolumes:", start)]
|
||||||
|
assert 'command: ["python", "-u", "scripts/media_retention_scheduler.py"]' in block
|
||||||
|
assert "python -c" not in block
|
||||||
|
assert 'PYTHONUNBUFFERED: "1"' in block
|
||||||
|
assert "RETENTION_RUN_ON_START" not in block
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
"""OpenRouter-Modellkatalog und Plattform-Standard — ohne Live-API."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from main import app
|
||||||
|
from ai_model_roles import resolve_prompt_openrouter_model
|
||||||
|
from openrouter_chat import (
|
||||||
|
clear_openrouter_model_catalog_cache,
|
||||||
|
normalize_openrouter_model_id,
|
||||||
|
parse_openrouter_models_payload,
|
||||||
|
resolve_default_openrouter_model_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client() -> TestClient:
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _clear_overrides():
|
||||||
|
yield
|
||||||
|
app.dependency_overrides.pop(require_auth, None)
|
||||||
|
clear_openrouter_model_catalog_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def _superadmin():
|
||||||
|
return {"profile_id": 7, "role": "superadmin"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_model_id_rejects_free_text():
|
||||||
|
assert normalize_openrouter_model_id(" ") is None
|
||||||
|
assert normalize_openrouter_model_id(None) is None
|
||||||
|
assert normalize_openrouter_model_id("openai/gpt-4o-mini") == "openai/gpt-4o-mini"
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
normalize_openrouter_model_id("claude")
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
normalize_openrouter_model_id("openai/gpt\n4")
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
normalize_openrouter_model_id("openai//gpt")
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_prefers_stored_model():
|
||||||
|
effective, source = resolve_default_openrouter_model_id(
|
||||||
|
"anthropic/claude-3.5-haiku",
|
||||||
|
"openai/gpt-4o",
|
||||||
|
)
|
||||||
|
assert effective == "anthropic/claude-3.5-haiku"
|
||||||
|
assert source == "database"
|
||||||
|
effective, source = resolve_default_openrouter_model_id("", "openai/gpt-4o")
|
||||||
|
assert effective == "openai/gpt-4o"
|
||||||
|
assert source == "environment"
|
||||||
|
effective, source = resolve_default_openrouter_model_id("kein-slash", "openai/gpt-4o")
|
||||||
|
assert effective == "openai/gpt-4o"
|
||||||
|
assert source == "environment"
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_model_resolution_prefers_exception_then_role():
|
||||||
|
model, source = resolve_prompt_openrouter_model(
|
||||||
|
prompt_model="openai/gpt-4o-mini",
|
||||||
|
role_model="anthropic/claude-sonnet-4",
|
||||||
|
platform_model="google/gemini-2.5-pro",
|
||||||
|
env_model="anthropic/claude-3.5-haiku",
|
||||||
|
)
|
||||||
|
assert model == "openai/gpt-4o-mini"
|
||||||
|
assert source == "prompt"
|
||||||
|
model, source = resolve_prompt_openrouter_model(
|
||||||
|
prompt_model="",
|
||||||
|
role_model="anthropic/claude-sonnet-4",
|
||||||
|
platform_model="google/gemini-2.5-pro",
|
||||||
|
env_model="anthropic/claude-3.5-haiku",
|
||||||
|
)
|
||||||
|
assert model == "anthropic/claude-sonnet-4"
|
||||||
|
assert source == "role"
|
||||||
|
model, source = resolve_prompt_openrouter_model(
|
||||||
|
prompt_model=None,
|
||||||
|
role_model=None,
|
||||||
|
platform_model="google/gemini-2.5-pro",
|
||||||
|
env_model="anthropic/claude-3.5-haiku",
|
||||||
|
)
|
||||||
|
assert source == "database"
|
||||||
|
model, source = resolve_prompt_openrouter_model(
|
||||||
|
prompt_model="kein-slash",
|
||||||
|
role_model="",
|
||||||
|
platform_model="",
|
||||||
|
env_model="anthropic/claude-3.5-haiku",
|
||||||
|
)
|
||||||
|
assert model == "anthropic/claude-3.5-haiku"
|
||||||
|
assert source == "environment"
|
||||||
|
|
||||||
|
|
||||||
|
def test_role_update_rejects_unknown_role_and_invalid_model(client: TestClient):
|
||||||
|
app.dependency_overrides[require_auth] = _superadmin
|
||||||
|
missing = client.put(
|
||||||
|
"/api/admin/openrouter/roles/unbekannt",
|
||||||
|
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||||
|
json={"openrouter_model": "openai/gpt-4o-mini"},
|
||||||
|
)
|
||||||
|
assert missing.status_code == 404
|
||||||
|
invalid = client.put(
|
||||||
|
"/api/admin/openrouter/roles/matching",
|
||||||
|
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||||
|
json={"openrouter_model": "nur-text"},
|
||||||
|
)
|
||||||
|
assert invalid.status_code == 400
|
||||||
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
|
||||||
|
forbidden = client.get("/api/admin/openrouter/roles", headers={"X-Auth-Token": "t"})
|
||||||
|
assert forbidden.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_models_payload_keeps_filter_fields():
|
||||||
|
rows = parse_openrouter_models_payload(
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "openai/gpt-4o-mini",
|
||||||
|
"name": "OpenAI: GPT-4o mini",
|
||||||
|
"description": "Klein\nund schnell",
|
||||||
|
"context_length": 128000,
|
||||||
|
"architecture": {
|
||||||
|
"input_modalities": ["text", "image"],
|
||||||
|
"output_modalities": ["text"],
|
||||||
|
},
|
||||||
|
"pricing": {"prompt": "0.00000015", "completion": "0.0000006"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "meta-llama/llama-3.1-8b-instruct:free",
|
||||||
|
"name": "Llama 3.1 8B (free)",
|
||||||
|
"architecture": {"modality": "text->text"},
|
||||||
|
"pricing": {"prompt": "0", "completion": "0"},
|
||||||
|
},
|
||||||
|
{"id": "", "name": "leer"},
|
||||||
|
"kein-objekt",
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
assert [row["id"] for row in rows] == [
|
||||||
|
"meta-llama/llama-3.1-8b-instruct:free",
|
||||||
|
"openai/gpt-4o-mini",
|
||||||
|
]
|
||||||
|
mini = rows[1]
|
||||||
|
assert mini["provider"] == "openai"
|
||||||
|
assert mini["context_length"] == 128000
|
||||||
|
assert mini["input_modalities"] == ["text", "image"]
|
||||||
|
assert mini["is_free"] is False
|
||||||
|
assert "\n" not in mini["description"]
|
||||||
|
assert rows[0]["is_free"] is True
|
||||||
|
assert rows[0]["input_modalities"] == ["text"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_models_requires_superadmin(client: TestClient):
|
||||||
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "admin"}
|
||||||
|
response = client.get("/api/admin/openrouter/models", headers={"X-Auth-Token": "t"})
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_models_returns_catalog_for_superadmin(client: TestClient):
|
||||||
|
app.dependency_overrides[require_auth] = _superadmin
|
||||||
|
payload = {
|
||||||
|
"models": [{"id": "openai/gpt-4o-mini", "name": "GPT-4o mini"}],
|
||||||
|
"count": 1,
|
||||||
|
"cached": False,
|
||||||
|
"stale": False,
|
||||||
|
"fetched_at": "2026-11-23T08:00:00+00:00",
|
||||||
|
}
|
||||||
|
with patch(
|
||||||
|
"routers.openrouter_admin.fetch_openrouter_model_catalog",
|
||||||
|
return_value=payload,
|
||||||
|
) as fetch:
|
||||||
|
response = client.get("/api/admin/openrouter/models?refresh=true", headers={"X-Auth-Token": "t"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["count"] == 1
|
||||||
|
fetch.assert_called_once_with(force=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_put_rejects_invalid_id(client: TestClient):
|
||||||
|
app.dependency_overrides[require_auth] = _superadmin
|
||||||
|
response = client.put(
|
||||||
|
"/api/admin/openrouter/settings",
|
||||||
|
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||||
|
json={"openrouter_model": "nur-text"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
@patch("routers.openrouter_admin.get_db")
|
||||||
|
def test_settings_put_stores_model(mock_get_db, client: TestClient, monkeypatch: pytest.MonkeyPatch):
|
||||||
|
monkeypatch.setenv("OPENROUTER_MODEL", "anthropic/claude-sonnet-4")
|
||||||
|
app.dependency_overrides[require_auth] = _superadmin
|
||||||
|
mock_cm = MagicMock()
|
||||||
|
mock_cm.__enter__.return_value = MagicMock()
|
||||||
|
mock_cm.__exit__.return_value = False
|
||||||
|
mock_get_db.return_value = mock_cm
|
||||||
|
cur = MagicMock()
|
||||||
|
cur.fetchone.return_value = {
|
||||||
|
"openrouter_model": "openai/gpt-4o-mini",
|
||||||
|
"updated_at": "2026-11-23T08:00:00+00:00",
|
||||||
|
}
|
||||||
|
with patch("routers.openrouter_admin.get_cursor", return_value=cur):
|
||||||
|
response = client.put(
|
||||||
|
"/api/admin/openrouter/settings",
|
||||||
|
headers={"X-Auth-Token": "t", "Content-Type": "application/json"},
|
||||||
|
json={"openrouter_model": "openai/gpt-4o-mini"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert body["openrouter_model"] == "openai/gpt-4o-mini"
|
||||||
|
assert body["effective_model"] == "openai/gpt-4o-mini"
|
||||||
|
assert body["source"] == "database"
|
||||||
|
assert body["env_model"] == "anthropic/claude-sonnet-4"
|
||||||
|
params = cur.execute.call_args.args[1]
|
||||||
|
assert params[0] == "openai/gpt-4o-mini"
|
||||||
|
assert params[1] == 7
|
||||||
@@ -73,8 +73,24 @@ def test_submit_requires_good_faith():
|
|||||||
good_faith_confirmed=False,
|
good_faith_confirmed=False,
|
||||||
)
|
)
|
||||||
from routers.content_reports import submit_content_report
|
from routers.content_reports import submit_content_report
|
||||||
|
from starlette.requests import Request
|
||||||
|
|
||||||
|
request = Request(
|
||||||
|
{
|
||||||
|
"type": "http",
|
||||||
|
"http_version": "1.1",
|
||||||
|
"method": "POST",
|
||||||
|
"scheme": "http",
|
||||||
|
"path": "/api/content-reports",
|
||||||
|
"raw_path": b"/api/content-reports",
|
||||||
|
"query_string": b"",
|
||||||
|
"headers": [],
|
||||||
|
"client": ("127.0.0.1", 50000),
|
||||||
|
"server": ("testserver", 80),
|
||||||
|
}
|
||||||
|
)
|
||||||
with pytest.raises(HTTPException) as exc:
|
with pytest.raises(HTTPException) as exc:
|
||||||
submit_content_report(body)
|
submit_content_report(request, body)
|
||||||
assert exc.value.status_code == 400
|
assert exc.value.status_code == 400
|
||||||
assert "Gutglauben" in exc.value.detail
|
assert "Gutglauben" in exc.value.detail
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""Tests Trainer-Pfad-Schutz (preserve_slot_assignments)."""
|
||||||
|
from planning_exercise_path_builder import (
|
||||||
|
EvaluateStepPayload,
|
||||||
|
ProgressionPathSuggestRequest,
|
||||||
|
_assignment_preservation_active,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assignment_preservation_explicit_flag():
|
||||||
|
body = ProgressionPathSuggestRequest(
|
||||||
|
query="Kumite Beinarbeit Progression",
|
||||||
|
preserve_slot_assignments=True,
|
||||||
|
)
|
||||||
|
assert _assignment_preservation_active(body)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assignment_preservation_not_auto_from_slot_assignments():
|
||||||
|
"""Nur explizites preserve_slot_assignments — sonst wäre compare/match blockiert."""
|
||||||
|
body = ProgressionPathSuggestRequest(
|
||||||
|
query="Kumite Beinarbeit Progression",
|
||||||
|
slot_assignments=[
|
||||||
|
EvaluateStepPayload(exercise_id=10, roadmap_major_step_index=0),
|
||||||
|
EvaluateStepPayload(exercise_id=11, roadmap_major_step_index=1),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
assert not _assignment_preservation_active(body)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assignment_preservation_inactive_without_assignments():
|
||||||
|
body = ProgressionPathSuggestRequest(query="Kumite Beinarbeit Progression")
|
||||||
|
assert not _assignment_preservation_active(body)
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Tests Katalog-Kontext für Progressionsgraph-Matching."""
|
||||||
|
from planning_catalog_context import (
|
||||||
|
ProgressionPlanningCatalogContext,
|
||||||
|
PlanningCatalogContextItem,
|
||||||
|
catalog_context_has_items,
|
||||||
|
merge_catalog_context_into_target,
|
||||||
|
)
|
||||||
|
from planning_exercise_profiles import PlanningTargetProfile
|
||||||
|
|
||||||
|
|
||||||
|
def test_catalog_context_has_items():
|
||||||
|
assert not catalog_context_has_items(None)
|
||||||
|
assert not catalog_context_has_items(ProgressionPlanningCatalogContext())
|
||||||
|
assert catalog_context_has_items(
|
||||||
|
ProgressionPlanningCatalogContext(
|
||||||
|
focus_areas=[PlanningCatalogContextItem(id=3, is_primary=True)],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_catalog_context_into_target_sets_focus():
|
||||||
|
base = PlanningTargetProfile(sources=["query_only"])
|
||||||
|
merged = merge_catalog_context_into_target(
|
||||||
|
base,
|
||||||
|
ProgressionPlanningCatalogContext(
|
||||||
|
focus_areas=[PlanningCatalogContextItem(id=7, is_primary=True)],
|
||||||
|
training_types=[PlanningCatalogContextItem(id=2, is_primary=True)],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assert merged.focus_area_ids.get(7, 0) > 0.5
|
||||||
|
assert merged.training_type_ids.get(2, 0) > 0.5
|
||||||
|
assert "catalog_context" in merged.sources
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_planning_roadmap_with_catalog_context():
|
||||||
|
from progression_graph_planning_artifact import normalize_planning_roadmap_payload
|
||||||
|
|
||||||
|
out = normalize_planning_roadmap_payload(
|
||||||
|
{
|
||||||
|
"goal_query": "Deeskalation Kinder",
|
||||||
|
"planning_catalog_context": {
|
||||||
|
"focus_areas": [{"id": 4, "is_primary": True}],
|
||||||
|
"target_groups": [{"id": 9, "is_primary": True}],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
assert out["planning_catalog_context"]["focus_areas"][0]["id"] == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_multistage_qa_splits_llm_highlights_from_fix_hints():
|
||||||
|
from planning_path_qa_pipeline import run_multistage_path_qa
|
||||||
|
|
||||||
|
result = run_multistage_path_qa(
|
||||||
|
off_topic_steps=[],
|
||||||
|
stripped_off_topic=[
|
||||||
|
{
|
||||||
|
"issue": "roadmap_unfilled",
|
||||||
|
"step_index": 1,
|
||||||
|
"reasons": ["Keine passende Übung"],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
gaps=[],
|
||||||
|
llm_qa={
|
||||||
|
"overall_ok": True,
|
||||||
|
"quality_score": 0.88,
|
||||||
|
"recommendations": [
|
||||||
|
"Gute didaktische Progression",
|
||||||
|
"Optional: Vertiefung Koordination",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
llm_applied=True,
|
||||||
|
)
|
||||||
|
hints = result["optimization_hints"]
|
||||||
|
llm_hints = [h for h in hints if h.get("issue") == "llm_recommendation"]
|
||||||
|
fix_hints = [h for h in hints if h.get("issue") != "llm_recommendation"]
|
||||||
|
assert len(llm_hints) >= 2
|
||||||
|
assert any(h.get("issue") == "roadmap_unfilled" for h in fix_hints)
|
||||||
|
assert result["qa_tiers"][2]["recommendations"][0].startswith("Gute didaktische")
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
"""Tests Katalog-Prompt-Slots (H2)."""
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
from catalog_prompt_slots import (
|
||||||
|
build_catalog_guidance_for_prompt,
|
||||||
|
pick_active_catalog_item,
|
||||||
|
placeholder_key,
|
||||||
|
resolve_catalog_prompt_variables,
|
||||||
|
)
|
||||||
|
from planning_catalog_context import PlanningCatalogContextItem, ProgressionPlanningCatalogContext
|
||||||
|
from planning_prompt_variables import merge_planning_prompt_variables
|
||||||
|
|
||||||
|
|
||||||
|
def _mock_cur(
|
||||||
|
rows_by_table=None,
|
||||||
|
slots_by_kind_id=None,
|
||||||
|
slot_types_ready=True,
|
||||||
|
):
|
||||||
|
rows_by_table = rows_by_table or {}
|
||||||
|
slots_by_kind_id = slots_by_kind_id or {}
|
||||||
|
|
||||||
|
cur = MagicMock()
|
||||||
|
|
||||||
|
def execute(sql, params=None):
|
||||||
|
sql_l = (sql or "").lower()
|
||||||
|
if "to_regclass" in sql_l:
|
||||||
|
cur.fetchone.return_value = {"t": "catalog_prompt_slot_types" if slot_types_ready else None}
|
||||||
|
return
|
||||||
|
if "from catalog_prompt_slot_types" in sql_l:
|
||||||
|
cur.fetchall.return_value = []
|
||||||
|
return
|
||||||
|
if "from catalog_prompt_slots" in sql_l:
|
||||||
|
kind, cid = params[0], int(params[1])
|
||||||
|
slot_map = slots_by_kind_id.get((kind, cid), {})
|
||||||
|
cur.fetchall.return_value = [
|
||||||
|
{"slot_key": k, "content": v} for k, v in slot_map.items()
|
||||||
|
]
|
||||||
|
return
|
||||||
|
for table, rows in rows_by_table.items():
|
||||||
|
if f"from {table}" in sql_l:
|
||||||
|
item_id = int(params[0])
|
||||||
|
raw = rows.get(item_id)
|
||||||
|
if raw is None:
|
||||||
|
cur.fetchone.return_value = None
|
||||||
|
elif isinstance(raw, dict):
|
||||||
|
cur.fetchone.return_value = {
|
||||||
|
"id": item_id,
|
||||||
|
"name": raw.get("name", ""),
|
||||||
|
"description": raw.get("description", ""),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
cur.fetchone.return_value = {
|
||||||
|
"id": item_id,
|
||||||
|
"name": str(raw),
|
||||||
|
"description": "",
|
||||||
|
}
|
||||||
|
return
|
||||||
|
cur.fetchone.return_value = None
|
||||||
|
cur.fetchall.return_value = []
|
||||||
|
|
||||||
|
cur.execute.side_effect = execute
|
||||||
|
return cur
|
||||||
|
|
||||||
|
|
||||||
|
def test_pick_active_catalog_item_primary_wins():
|
||||||
|
items = [
|
||||||
|
PlanningCatalogContextItem(id=1, is_primary=False, weight=0.9),
|
||||||
|
PlanningCatalogContextItem(id=2, is_primary=True, weight=0.5),
|
||||||
|
]
|
||||||
|
assert pick_active_catalog_item(items).id == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_granular_placeholder_focus_area_hints_on_path_qa():
|
||||||
|
cur = _mock_cur(
|
||||||
|
rows_by_table={"focus_areas": {4: {"name": "Gewaltschutz"}}},
|
||||||
|
slots_by_kind_id={
|
||||||
|
("focus_area", 4): {
|
||||||
|
"description": "Planung zielt auf Prävention und Deeskalation.",
|
||||||
|
"hints_on_path_qa": "Lücken sind fehlende Deeskalations-Stufen.",
|
||||||
|
"anti_patterns": "Nicht nach Kumite-Tiefe bewerten.",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
catalog = ProgressionPlanningCatalogContext(
|
||||||
|
focus_areas=[PlanningCatalogContextItem(id=4, is_primary=True)],
|
||||||
|
)
|
||||||
|
resolved = resolve_catalog_prompt_variables(cur, catalog, slug="planning_exercise_path_qa")
|
||||||
|
assert "Deeskalation" in resolved[placeholder_key("focus_area", "hints_on_path_qa")]
|
||||||
|
assert "Deeskalation" in resolved["catalog_guidance_block"]
|
||||||
|
assert resolved["has_catalog_guidance"] == "true"
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_focus_uses_default_description_pack():
|
||||||
|
cur = _mock_cur(
|
||||||
|
rows_by_table={
|
||||||
|
"focus_areas": {
|
||||||
|
4: {
|
||||||
|
"name": "Sonderfokus Alpha",
|
||||||
|
"description": "Kurze Stammdaten-Beschreibung",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
slots_by_kind_id={("focus_area", 4): {}},
|
||||||
|
)
|
||||||
|
catalog = ProgressionPlanningCatalogContext(
|
||||||
|
focus_areas=[PlanningCatalogContextItem(id=4, is_primary=True)],
|
||||||
|
)
|
||||||
|
resolved = resolve_catalog_prompt_variables(cur, catalog)
|
||||||
|
desc = resolved[placeholder_key("focus_area", "description")]
|
||||||
|
assert "Technik- oder Themen-Curriculum" in desc
|
||||||
|
assert resolved[placeholder_key("focus_area", "hints_on_path_qa")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_without_catalog():
|
||||||
|
cur = MagicMock()
|
||||||
|
out = build_catalog_guidance_for_prompt(cur, None)
|
||||||
|
assert out["has_catalog_guidance"] is False
|
||||||
|
assert out["catalog_guidance_block"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_entry_gets_default_technique_fallback():
|
||||||
|
cur = _mock_cur(rows_by_table={"focus_areas": {99: {"name": "Unbekannter Fokus XYZ"}}})
|
||||||
|
catalog = ProgressionPlanningCatalogContext(
|
||||||
|
focus_areas=[PlanningCatalogContextItem(id=99, is_primary=True)],
|
||||||
|
)
|
||||||
|
out = build_catalog_guidance_for_prompt(cur, catalog)
|
||||||
|
assert out["has_catalog_guidance"] is True
|
||||||
|
assert "Unbekannter Fokus XYZ" in out["catalog_context_json"]
|
||||||
|
assert "Zwischenstufen" in out["catalog_guidance_block"] or "Progression" in out["catalog_guidance_block"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_planning_prompt_variables_granular_keys():
|
||||||
|
cur = _mock_cur(
|
||||||
|
rows_by_table={"focus_areas": {4: {"name": "Gewaltschutz"}}},
|
||||||
|
slots_by_kind_id={
|
||||||
|
("focus_area", 4): {"hints_on_path_qa": "Deeskalation und Grenzen."}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
catalog = ProgressionPlanningCatalogContext(
|
||||||
|
focus_areas=[PlanningCatalogContextItem(id=4, is_primary=True)],
|
||||||
|
)
|
||||||
|
merged = merge_planning_prompt_variables(
|
||||||
|
cur,
|
||||||
|
{"goal_query": "Deeskalation Kinder"},
|
||||||
|
catalog=catalog,
|
||||||
|
slug="planning_exercise_path_qa",
|
||||||
|
)
|
||||||
|
assert merged[placeholder_key("focus_area", "hints_on_path_qa")].startswith("Deeskalation")
|
||||||
|
assert merged["has_catalog_guidance"] == "true"
|
||||||
|
|
||||||
|
|
||||||
|
def test_priority_order_in_guidance_block():
|
||||||
|
cur = _mock_cur(
|
||||||
|
rows_by_table={
|
||||||
|
"focus_areas": {1: {"name": "Gewaltschutz"}},
|
||||||
|
"training_types": {2: {"name": "Breitensport"}},
|
||||||
|
},
|
||||||
|
slots_by_kind_id={
|
||||||
|
("focus_area", 1): {"description": "Fokus-Text"},
|
||||||
|
("training_type", 2): {"description": "Stil-Text"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
catalog = ProgressionPlanningCatalogContext(
|
||||||
|
focus_areas=[PlanningCatalogContextItem(id=1, is_primary=True)],
|
||||||
|
training_types=[PlanningCatalogContextItem(id=2, is_primary=True)],
|
||||||
|
)
|
||||||
|
block = build_catalog_guidance_for_prompt(cur, catalog)["catalog_guidance_block"]
|
||||||
|
assert block.index("Primärfokus") < block.index("Trainingsstil")
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""Tests Vergleichs-Diffs (triviale ID-Tausche markieren, Rematch-Filter)."""
|
||||||
|
from planning_exercise_path_builder import (
|
||||||
|
_actionable_slot_diffs,
|
||||||
|
_annotate_slot_diffs,
|
||||||
|
_build_progression_compare_response,
|
||||||
|
_build_progression_slot_diffs,
|
||||||
|
_build_rematch_suggestion_diffs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_annotate_trivial_id_swap():
|
||||||
|
diffs = [
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 1,
|
||||||
|
"baseline_exercise_id": 10,
|
||||||
|
"baseline_title": "Rhythmuswechsel in der Kumite-Beinarbeit",
|
||||||
|
"proposed_exercise_id": 99,
|
||||||
|
"proposed_title": "Rhythmuswechsel in der Kumite-Beinarbeit",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
annotated = _annotate_slot_diffs(diffs)
|
||||||
|
assert len(annotated) == 1
|
||||||
|
assert annotated[0]["trivial_id_swap"] is True
|
||||||
|
assert _actionable_slot_diffs(annotated) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_annotate_keeps_real_title_change():
|
||||||
|
diffs = [
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 1,
|
||||||
|
"baseline_exercise_id": 10,
|
||||||
|
"baseline_title": "Alt",
|
||||||
|
"proposed_exercise_id": 99,
|
||||||
|
"proposed_title": "Neu",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
annotated = _annotate_slot_diffs(diffs)
|
||||||
|
assert annotated[0]["trivial_id_swap"] is False
|
||||||
|
assert len(_actionable_slot_diffs(annotated)) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_slot_diffs_then_annotate():
|
||||||
|
baseline = [
|
||||||
|
{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"},
|
||||||
|
{"roadmap_major_step_index": 1, "exercise_id": 10, "title": "Gleich"},
|
||||||
|
]
|
||||||
|
proposed = [
|
||||||
|
{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"},
|
||||||
|
{"roadmap_major_step_index": 1, "exercise_id": 77, "title": "Gleich"},
|
||||||
|
]
|
||||||
|
raw = _build_progression_slot_diffs(baseline, proposed)
|
||||||
|
annotated = _annotate_slot_diffs(raw)
|
||||||
|
assert len(annotated) == 1
|
||||||
|
assert annotated[0]["trivial_id_swap"] is True
|
||||||
|
assert _actionable_slot_diffs(annotated) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_rematch_suggestion_skips_filled_baseline_slot():
|
||||||
|
baseline = [
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 1,
|
||||||
|
"exercise_id": 5727,
|
||||||
|
"title": "Einführung von Richtungswechseln",
|
||||||
|
"slot_status": "preserved",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
rematch_log = [
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 1,
|
||||||
|
"action": "replaced",
|
||||||
|
"round": 3,
|
||||||
|
"new_exercise_id": 5594,
|
||||||
|
"new_title": "Kumite Beinarbeit — vertiefung",
|
||||||
|
"replaced_exercise_id": 5727,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
assert _build_rematch_suggestion_diffs(baseline, rematch_log) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_rematch_suggestion_keeps_empty_baseline_slot():
|
||||||
|
baseline = [
|
||||||
|
{"roadmap_major_step_index": 1, "exercise_id": None, "title": "Lernziel Slot 2"},
|
||||||
|
]
|
||||||
|
rematch_log = [
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 1,
|
||||||
|
"action": "replaced",
|
||||||
|
"round": 1,
|
||||||
|
"new_exercise_id": 101,
|
||||||
|
"new_title": "Rhythmuswechsel in der Kumite-Beinarbeit",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
diffs = _build_rematch_suggestion_diffs(baseline, rematch_log)
|
||||||
|
assert len(diffs) == 1
|
||||||
|
assert diffs[0]["proposed_exercise_id"] == 101
|
||||||
|
|
||||||
|
|
||||||
|
def test_compare_response_no_step_diffs_uses_baseline_qa_not_pipeline():
|
||||||
|
baseline = {
|
||||||
|
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
|
||||||
|
"path_qa": {"overall_ok": True, "quality_score": 0.88},
|
||||||
|
}
|
||||||
|
proposed = {
|
||||||
|
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
|
||||||
|
"path_qa": {"overall_ok": False, "quality_score": 0.65, "rematch_log": [{"action": "replaced"}]},
|
||||||
|
}
|
||||||
|
compare = _build_progression_compare_response(baseline, proposed, proposed_eval=None)
|
||||||
|
assert compare["slot_diff_count"] == 0
|
||||||
|
assert compare["slot_diffs_source"] == "steps"
|
||||||
|
assert compare["proposed_path_qa"]["quality_score"] == 0.65
|
||||||
|
|
||||||
|
|
||||||
|
def test_compare_wrapper_snaps_proposed_qa_to_baseline_without_diffs():
|
||||||
|
baseline = {
|
||||||
|
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
|
||||||
|
"path_qa": {"overall_ok": True, "quality_score": 0.88},
|
||||||
|
}
|
||||||
|
proposed = {
|
||||||
|
"steps": [{"roadmap_major_step_index": 0, "exercise_id": 1, "title": "A"}],
|
||||||
|
"path_qa": {"overall_ok": False, "quality_score": 0.65},
|
||||||
|
}
|
||||||
|
raw = _build_progression_compare_response(baseline, proposed, proposed_eval=None)
|
||||||
|
assert raw["proposed_path_qa"]["quality_score"] == 0.65
|
||||||
|
if raw.get("slot_diff_count", 0) == 0:
|
||||||
|
fair = baseline["path_qa"]
|
||||||
|
raw["proposed_path_qa"] = fair
|
||||||
|
assert raw["proposed_path_qa"]["quality_score"] == 0.88
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Deterministische Pfad-QS ohne LLM."""
|
||||||
|
from planning_exercise_path_qa import compute_deterministic_path_quality_score
|
||||||
|
|
||||||
|
|
||||||
|
def test_deterministic_quality_score_penalizes_off_topic():
|
||||||
|
steps = [{"roadmap_major_step_index": 0, "exercise_id": 1}]
|
||||||
|
base = compute_deterministic_path_quality_score(gaps=[], off_topic_steps=[], steps=steps)
|
||||||
|
with_off = compute_deterministic_path_quality_score(
|
||||||
|
gaps=[],
|
||||||
|
off_topic_steps=[{"roadmap_major_step_index": 1}],
|
||||||
|
steps=steps,
|
||||||
|
)
|
||||||
|
assert with_off < base
|
||||||
|
|
||||||
|
|
||||||
|
def test_deterministic_quality_score_penalizes_empty_slots():
|
||||||
|
filled = [{"roadmap_major_step_index": 0, "exercise_id": 1}]
|
||||||
|
base = compute_deterministic_path_quality_score(gaps=[], off_topic_steps=[], steps=filled)
|
||||||
|
with_empty = compute_deterministic_path_quality_score(
|
||||||
|
gaps=[],
|
||||||
|
off_topic_steps=[],
|
||||||
|
steps=[{"roadmap_major_step_index": 0, "exercise_id": None}, {"roadmap_major_step_index": 1, "exercise_id": 2}],
|
||||||
|
)
|
||||||
|
all_empty = compute_deterministic_path_quality_score(
|
||||||
|
gaps=[],
|
||||||
|
off_topic_steps=[],
|
||||||
|
steps=[{"roadmap_major_step_index": 0, "exercise_id": None}] * 4,
|
||||||
|
)
|
||||||
|
assert with_empty < base
|
||||||
|
assert all_empty <= 0.15
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
"""Tests Planungs-KI Phase D — planning_context für suggestExerciseAi."""
|
"""Tests Planungs-KI Phase D — planning_context für suggestExerciseAi."""
|
||||||
from planning_exercise_form_context import (
|
from planning_exercise_form_context import (
|
||||||
|
build_progression_entry_state,
|
||||||
build_progression_gap_snapshot,
|
build_progression_gap_snapshot,
|
||||||
build_progression_path_gap_planning_context,
|
build_progression_path_gap_planning_context,
|
||||||
|
enrich_gap_snapshot_with_entry_state,
|
||||||
planning_context_prompt_variables,
|
planning_context_prompt_variables,
|
||||||
sanitize_planning_context_for_ai,
|
sanitize_planning_context_for_ai,
|
||||||
)
|
)
|
||||||
@@ -78,3 +80,55 @@ def test_gap_planning_context_carries_snapshot_fields():
|
|||||||
)
|
)
|
||||||
assert ctx["start_situation"] == "Start"
|
assert ctx["start_situation"] == "Start"
|
||||||
assert ctx["stage_learning_goal"] == "Stufenziel"
|
assert ctx["stage_learning_goal"] == "Stufenziel"
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_progression_entry_state_from_prior_steps():
|
||||||
|
entry = build_progression_entry_state(
|
||||||
|
major_step_index=2,
|
||||||
|
prior_steps=[
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 0,
|
||||||
|
"title": "Schritt-Stand",
|
||||||
|
"roadmap_phase": "einstieg",
|
||||||
|
"success_criteria": ["stabile Grundstellung"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 1,
|
||||||
|
"title": "Mawashi Vorbereitung",
|
||||||
|
"roadmap_target_state": "Hüfte dreht vor dem Knie",
|
||||||
|
"roadmap_phase": "grundlage",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
start_situation="Anfänger ohne Kumite-Erfahrung",
|
||||||
|
current_stage_start="Hüfte dreht vor dem Knie, sicherer Stand",
|
||||||
|
)
|
||||||
|
assert entry["entry_state"] == "Hüfte dreht vor dem Knie, sicherer Stand"
|
||||||
|
assert "Mawashi Vorbereitung" in entry["entry_state_detail"]
|
||||||
|
assert "stabile Grundstellung" in entry["prior_achievements"][0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_enrich_gap_snapshot_with_entry_state():
|
||||||
|
snap = enrich_gap_snapshot_with_entry_state(
|
||||||
|
{"start_situation": "Basis", "stage_learning_goal": "Rhythmen"},
|
||||||
|
steps=[
|
||||||
|
{
|
||||||
|
"roadmap_major_step_index": 0,
|
||||||
|
"title": "A",
|
||||||
|
"success_criteria": ["Timing erkannt"],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
major_step_index=1,
|
||||||
|
)
|
||||||
|
assert snap["entry_state"] == "Timing erkannt"
|
||||||
|
assert snap["prior_steps"][0]["title"] == "A"
|
||||||
|
|
||||||
|
|
||||||
|
def test_gap_planning_context_trainer_supplements_and_stage_override():
|
||||||
|
ctx = build_progression_path_gap_planning_context(
|
||||||
|
goal_query="Kumite",
|
||||||
|
stage_spec={"learning_goal": "Original"},
|
||||||
|
stage_learning_goal_override="Angepasstes Stufenziel",
|
||||||
|
gap_trainer_supplements="Nur Partnerübung, Kindergruppe",
|
||||||
|
)
|
||||||
|
assert ctx["stage_learning_goal"] == "Angepasstes Stufenziel"
|
||||||
|
assert ctx["gap_trainer_supplements"] == "Nur Partnerübung, Kindergruppe"
|
||||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user