Compare commits
34
Commits
a1ea3dd0cc
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c547027f2 | ||
|
|
53047b6c16 | ||
|
|
f8af47d1d5 | ||
|
|
9e271a1954 | ||
|
|
39e8084b1a | ||
|
|
4069cb0e01 | ||
|
|
eaa0e25524 | ||
|
|
910b1d7e07 | ||
|
|
f9c207c4f6 | ||
|
|
f8b3ae3011 | ||
|
|
7a5da57bb8 | ||
|
|
88792eeb47 | ||
|
|
598677d343 | ||
|
|
7a6eb3abe8 | ||
|
|
2f631f419a | ||
|
|
101376540a | ||
|
|
45a108b4a0 | ||
|
|
25d3976226 | ||
|
|
564008be13 | ||
|
|
7b96bab1c9 | ||
|
|
b5efdbbc2e | ||
|
|
b29fb2f538 | ||
|
|
1d8e22be82 | ||
|
|
1765daed2d | ||
|
|
a979d0e5f9 | ||
|
|
2b96518a52 | ||
|
|
5cc9282b31 | ||
|
|
486268efd9 | ||
|
|
b1e00bb347 | ||
|
|
0e5bf72dee | ||
|
|
1ce20d8bdb | ||
|
|
0e2b938fbd | ||
|
|
ea445a9263 | ||
|
|
848452f837 |
No files matched your search
@@ -0,0 +1,41 @@
|
||||
---
|
||||
description: Kairo Sprint-0 Architektur-Leitplanken und Dokumentenpriorität
|
||||
globs: backend/**,frontend/**,docs/**,.gitea/**
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Kairo Architecture Rules
|
||||
|
||||
Du arbeitest an **Jinkendo Kairo** (Sprint 0). Kairo ist mandantenfähig und Actor-first.
|
||||
|
||||
## Dokumentenpriorität bei Konflikten
|
||||
|
||||
1. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
2. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
3. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
4. `docs/reference/design-principles/alignment/*`
|
||||
5. Mitai/Shinkan-Einzelprinzipien (nur Begründung, kein Scope)
|
||||
|
||||
## Reference design principles
|
||||
|
||||
Referenzmaterial:
|
||||
|
||||
- `docs/reference/design-principles/mitai/`
|
||||
- `docs/reference/design-principles/shinkan/`
|
||||
- `docs/reference/design-principles/alignment/`
|
||||
|
||||
Nicht automatisch Implementierungs-Scope. Übernahme nur via Principle Gate oder Architecture Decision.
|
||||
|
||||
## Harte Guardrails
|
||||
|
||||
- Kein Single-User ohne Tenant
|
||||
- User ≠ Actor; Agenten sind Actors
|
||||
- Auth, Capability, Feature, Governance trennen
|
||||
- Keine hardcodierten Rechte, Prompts oder Fachkonfiguration
|
||||
- Nummerierte SQL-Migrationen; kein ad-hoc DDL in Routern
|
||||
- Keine Mitai-/Shinkan-Domänenlogik kopieren
|
||||
- Keine Vorhaben-/Projektlogik vor Sprint-0-Abschluss
|
||||
|
||||
## Abweichungen
|
||||
|
||||
Architecture Decision Proposal nach Vorlage in `docs/architecture/ARCHITECTURE_DECISION_PROPOSAL_TEMPLATE.md`.
|
||||
@@ -0,0 +1,23 @@
|
||||
# === .env neben docker-compose.*.yml ==========================================
|
||||
# Pro Umgebung eigene Datei (~/docker/kairo/.env Prod, ~/docker/kairo-dev/.env Dev)
|
||||
|
||||
# ─── DEV (docker-compose.dev-env.yml) ────────────────────────────────────────
|
||||
# DB_NAME=kairo_dev
|
||||
# DB_USER=kairo_dev
|
||||
# DB_PASSWORD=dev_password
|
||||
# APP_URL=https://dev.kairo.jinkendo.de
|
||||
# ALLOWED_ORIGINS=https://dev.kairo.jinkendo.de,http://192.168.2.49:3097
|
||||
# ENVIRONMENT=development
|
||||
# SESSION_DAYS=30
|
||||
# KAIRO_BOOTSTRAP_ADMIN_EMAIL=admin@kairo.local
|
||||
# KAIRO_BOOTSTRAP_ADMIN_PASSWORD=change-me-in-dev-env
|
||||
# KAIRO_BOOTSTRAP_TENANT_SLUG=default
|
||||
# KAIRO_BOOTSTRAP_TENANT_NAME=Default Tenant
|
||||
|
||||
# ─── PROD (docker-compose.yml) ───────────────────────────────────────────────
|
||||
DB_NAME=kairo
|
||||
DB_USER=kairo_user
|
||||
DB_PASSWORD=CHANGE_ME_SECURE_PASSWORD
|
||||
APP_URL=https://kairo.jinkendo.de
|
||||
ALLOWED_ORIGINS=https://kairo.jinkendo.de
|
||||
ENVIRONMENT=production
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Deploy Development
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [develop]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy to Development
|
||||
run: |
|
||||
set -e
|
||||
echo "=== Deploying Kairo to DEVELOPMENT ==="
|
||||
REPO="http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git"
|
||||
TARGET="/home/lars/docker/kairo-dev"
|
||||
mkdir -p "$TARGET"
|
||||
cd "$TARGET"
|
||||
if [ ! -d .git ]; then
|
||||
git clone -b develop "$REPO" .
|
||||
else
|
||||
git fetch origin develop
|
||||
git checkout develop
|
||||
git reset --hard origin/develop
|
||||
fi
|
||||
docker compose -f docker-compose.dev-env.yml build --no-cache backend frontend
|
||||
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
||||
if ! docker compose -f docker-compose.dev-env.yml up -d --wait; then
|
||||
echo "✗ compose up --wait fehlgeschlagen — Backend-Logs:"
|
||||
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||
docker compose -f docker-compose.dev-env.yml ps || true
|
||||
exit 1
|
||||
fi
|
||||
if ! curl -sf http://localhost:8097/api/health; then
|
||||
echo "✗ DEV API nicht erreichbar — Backend-Logs:"
|
||||
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ DEV API /api/health OK"
|
||||
curl -sf http://localhost:3097/api/health && echo "✓ DEV Frontend-Proxy /api/health OK"
|
||||
echo "=== Kairo DEV Deploy complete ==="
|
||||
@@ -0,0 +1,41 @@
|
||||
name: Deploy Production
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy to Production
|
||||
run: |
|
||||
set -e
|
||||
echo "=== Deploying Kairo to PRODUCTION ==="
|
||||
REPO="http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git"
|
||||
TARGET="/home/lars/docker/kairo"
|
||||
mkdir -p "$TARGET"
|
||||
cd "$TARGET"
|
||||
if [ ! -d .git ]; then
|
||||
git clone -b main "$REPO" .
|
||||
else
|
||||
git fetch origin main
|
||||
git checkout main
|
||||
git reset --hard origin/main
|
||||
fi
|
||||
docker compose build --no-cache backend frontend
|
||||
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
||||
if ! docker compose up -d --wait; then
|
||||
echo "✗ compose up --wait fehlgeschlagen — Backend-Logs:"
|
||||
docker compose logs backend --tail 150 || true
|
||||
docker compose ps || true
|
||||
exit 1
|
||||
fi
|
||||
if ! curl -sf http://localhost:8004/api/health; then
|
||||
echo "✗ PROD API nicht erreichbar — Backend-Logs:"
|
||||
docker compose logs backend --tail 150 || true
|
||||
exit 1
|
||||
fi
|
||||
echo "✓ PROD API /api/health OK"
|
||||
curl -sf http://localhost:3004/api/health && echo "✓ PROD Frontend-Proxy /api/health OK"
|
||||
echo "=== Kairo PROD Deploy complete ==="
|
||||
@@ -0,0 +1,231 @@
|
||||
name: Test Suite
|
||||
|
||||
# develop: push/PR → Tests gegen deployte Dev-Instanz (wartet auf Container).
|
||||
# main: push → Prod-Tests gegen kairo (8004/3004), parallel zu deploy-prod.yml.
|
||||
# workflow_run: optional (Gitea/act feuert oft nicht — push-Trigger ist maßgeblich).
|
||||
# Frontend-Build: deploy-dev/prod (docker compose build backend frontend), nicht hier.
|
||||
# compose-smoke (PR): eigener Stack auf CI-Ports 18197/13197 (kein Konflikt mit kairo-dev).
|
||||
on:
|
||||
push:
|
||||
branches: [develop, main]
|
||||
pull_request:
|
||||
branches: [develop]
|
||||
workflow_run:
|
||||
workflows: ["Deploy Development", "Deploy Production"]
|
||||
types: [completed]
|
||||
|
||||
jobs:
|
||||
pytest-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Backend pytest im deployten Container
|
||||
run: |
|
||||
set -e
|
||||
EVENT_NAME="${{ github.event_name }}"
|
||||
REF_NAME="${{ github.ref_name }}"
|
||||
BASE_REF="${{ github.base_ref }}"
|
||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
||||
APP_DIR="/home/lars/docker/kairo"
|
||||
COMPOSE_FILE="docker-compose.yml"
|
||||
|
||||
if [ "$EVENT_NAME" = "workflow_run" ]; then
|
||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
||||
APP_DIR="/home/lars/docker/kairo-dev"
|
||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||
fi
|
||||
elif [ "$REF_NAME" = "main" ]; then
|
||||
APP_DIR="/home/lars/docker/kairo"
|
||||
COMPOSE_FILE="docker-compose.yml"
|
||||
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||
APP_DIR="/home/lars/docker/kairo-dev"
|
||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||
fi
|
||||
|
||||
echo "pytest gegen ${APP_DIR} (${COMPOSE_FILE})"
|
||||
|
||||
cd "$APP_DIR"
|
||||
echo "Warte auf stabilen backend-Container …"
|
||||
for i in $(seq 1 60); do
|
||||
if docker compose -f "$COMPOSE_FILE" exec -T backend true 2>/dev/null; then
|
||||
echo "Backend bereit (Versuch $i)"
|
||||
break
|
||||
fi
|
||||
if [ "$i" -eq 60 ]; then
|
||||
echo "Timeout: backend-Container nicht bereit"
|
||||
docker compose -f "$COMPOSE_FILE" ps || true
|
||||
docker compose -f "$COMPOSE_FILE" logs backend --tail 80 || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
|
||||
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
|
||||
pip install -q -r requirements-dev.txt &&
|
||||
python -m pytest tests -ra -vv --tb=short &&
|
||||
python run_seeds.py --only seed_001_cleanup_pytest_artifacts --force
|
||||
"
|
||||
echo "✓ pytest OK"
|
||||
|
||||
lint-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
if: github.event_name != 'workflow_run'
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check backend syntax (Checkout)
|
||||
if: github.event_name != 'workflow_run'
|
||||
run: |
|
||||
python3 -m py_compile backend/main.py backend/run_migrations.py backend/db.py
|
||||
echo "✓ Backend syntax OK"
|
||||
|
||||
- name: Check backend syntax (Deploy-Pfad)
|
||||
if: github.event_name == 'workflow_run'
|
||||
run: |
|
||||
RUN_WORKFLOW="${{ github.event.workflow_run.name }}"
|
||||
if [ "$RUN_WORKFLOW" = "Deploy Development" ]; then
|
||||
APP_DIR="/home/lars/docker/kairo-dev"
|
||||
else
|
||||
APP_DIR="/home/lars/docker/kairo"
|
||||
fi
|
||||
python3 -m py_compile "$APP_DIR/backend/main.py"
|
||||
echo "✓ Backend syntax OK"
|
||||
|
||||
compose-smoke:
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
COMPOSE_PROJECT_NAME: kairo-ci-smoke
|
||||
DB_PASSWORD: ci_smoke_password
|
||||
KAIRO_BACKEND_PORT: 18197
|
||||
KAIRO_FRONTEND_PORT: 13197
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Isolierter Stack (CI-Ports, kein Konflikt mit kairo-dev)
|
||||
run: |
|
||||
set -e
|
||||
COMPOSE="docker-compose.dev-env.yml"
|
||||
API_PORT="${KAIRO_BACKEND_PORT}"
|
||||
UI_PORT="${KAIRO_FRONTEND_PORT}"
|
||||
echo "compose-smoke auf localhost:${API_PORT} / ${UI_PORT}"
|
||||
docker compose -f "$COMPOSE" up -d --build --wait
|
||||
curl -sf "http://localhost:${API_PORT}/api/health"
|
||||
curl -sf "http://localhost:${UI_PORT}/api/health"
|
||||
docker compose -f "$COMPOSE" exec -T backend pip install -q -r requirements-dev.txt
|
||||
docker compose -f "$COMPOSE" exec -T backend python -m pytest tests -ra -vv --tb=short
|
||||
docker compose -f "$COMPOSE" down -v
|
||||
echo "✓ compose-smoke OK"
|
||||
|
||||
k6-health-baseline:
|
||||
name: k6 /api/health Baseline
|
||||
needs: [pytest-backend]
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: k6-Ziel wählen
|
||||
id: k6
|
||||
run: |
|
||||
EVENT="${{ github.event_name }}"
|
||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||
REF="${{ github.ref_name }}"
|
||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||
echo "base_url=http://localhost:8004" >> $GITHUB_OUTPUT
|
||||
elif [ "$REF" = "main" ]; then
|
||||
echo "base_url=http://localhost:8004" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "base_url=http://localhost:8097" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: /api/health abwarten
|
||||
run: |
|
||||
BASE="${{ steps.k6.outputs.base_url }}"
|
||||
for i in $(seq 1 90); do
|
||||
if curl -sf "$BASE/api/health" >/dev/null 2>&1; then
|
||||
echo "Health OK (Versuch $i)"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
curl -v "$BASE/api/health" || true
|
||||
exit 1
|
||||
|
||||
- name: Install k6
|
||||
run: |
|
||||
set -e
|
||||
K6_VER="v0.55.0"
|
||||
ARCH=$(uname -m)
|
||||
case "$ARCH" in
|
||||
x86_64) K6_ARCH=amd64 ;;
|
||||
aarch64|arm64) K6_ARCH=arm64 ;;
|
||||
*) echo "k6: unbekannte Architektur: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
curl -sSL "https://github.com/grafana/k6/releases/download/${K6_VER}/k6-${K6_VER}-linux-${K6_ARCH}.tar.gz" -o /tmp/k6.tgz
|
||||
tar -xzf /tmp/k6.tgz -C /tmp
|
||||
sudo mv "/tmp/k6-${K6_VER}-linux-${K6_ARCH}/k6" /usr/local/bin/k6
|
||||
|
||||
- name: k6 Health-Baseline
|
||||
run: |
|
||||
set -e
|
||||
BASE_URL="${{ steps.k6.outputs.base_url }}"
|
||||
if [ -z "$BASE_URL" ]; then
|
||||
echo "BASE_URL leer — steps.k6.outputs.base_url prüfen"
|
||||
exit 1
|
||||
fi
|
||||
echo "k6 gegen BASE_URL=$BASE_URL (K6_CI=1, quiet)"
|
||||
BASE_URL="$BASE_URL" K6_CI=1 k6 run --quiet scripts/load/k6-health-baseline.js
|
||||
echo "✓ k6 Health-Baseline OK"
|
||||
|
||||
playwright-smoke:
|
||||
needs: [pytest-backend]
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Playwright-Ziel wählen
|
||||
id: pw
|
||||
run: |
|
||||
EVENT="${{ github.event_name }}"
|
||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||
REF="${{ github.ref_name }}"
|
||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||
echo "base_url=http://localhost:3004" >> $GITHUB_OUTPUT
|
||||
elif [ "$REF" = "main" ]; then
|
||||
echo "base_url=http://localhost:3004" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "base_url=http://localhost:3097" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: /api/health abwarten
|
||||
run: |
|
||||
BASE="${{ steps.pw.outputs.base_url }}"
|
||||
for i in $(seq 1 90); do
|
||||
if curl -sf "$BASE/api/health" >/dev/null 2>&1; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
exit 1
|
||||
|
||||
- name: Install Playwright
|
||||
run: |
|
||||
npm install
|
||||
npx playwright install --with-deps chromium
|
||||
|
||||
- name: Run Playwright smoke
|
||||
env:
|
||||
PLAYWRIGHT_BASE_URL: ${{ steps.pw.outputs.base_url }}
|
||||
run: npx playwright test tests/smoke-health.spec.js
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
# Environment
|
||||
.env
|
||||
.env.local
|
||||
.env.production
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
.Python
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# Build output
|
||||
frontend/dist/
|
||||
|
||||
# Data (NEVER commit database or user data)
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
data/
|
||||
photos/
|
||||
uploads/
|
||||
media/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# IDE
|
||||
.vscode/settings.json
|
||||
.idea/
|
||||
*.swp
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Docker overrides
|
||||
docker-compose.override.yml
|
||||
|
||||
# SSL certificates (never commit)
|
||||
nginx/ssl/
|
||||
nginx/certbot/
|
||||
*.pem
|
||||
*.key
|
||||
*.crt
|
||||
*.csr
|
||||
|
||||
# Pytest
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
coverage/
|
||||
|
||||
# Temp
|
||||
tmp/
|
||||
*.tmp
|
||||
*_alt.md
|
||||
|
||||
# Claude: nur ausgewählte Bereiche versionieren
|
||||
.claude/**
|
||||
!.claude/README.md
|
||||
!.claude/docs/
|
||||
!.claude/docs/**/*
|
||||
!.claude/rules/
|
||||
!.claude/rules/**/*
|
||||
!.claude/commands/
|
||||
!.claude/commands/**/*
|
||||
.claude/settings.local.json
|
||||
|
||||
# Cursor MCP
|
||||
.cursor/mcp.json
|
||||
frontend/package-lock.json
|
||||
@@ -0,0 +1,120 @@
|
||||
# CLAUDE.md – Jinkendo Kairo
|
||||
|
||||
Du arbeitest im Projekt **Jinkendo Kairo**.
|
||||
|
||||
Kairo ist der operative Program Director der Jinkendo-Produktfamilie.
|
||||
|
||||
## Leitfrage
|
||||
|
||||
Welcher nächste Schritt bringt ein Vorhaben aktuell am wirkungsvollsten voran?
|
||||
|
||||
---
|
||||
|
||||
## 1. Aktueller Entwicklungsstand
|
||||
|
||||
Sprint 0.
|
||||
|
||||
Es geht noch nicht um die vollständige Fachanwendung, sondern um das Fundament.
|
||||
|
||||
Sprint 0 baut:
|
||||
|
||||
- Tenant
|
||||
- User
|
||||
- Actor
|
||||
- TenantContext
|
||||
- Auth-Gates
|
||||
- Capability / Rights Registry
|
||||
- minimale Feature Registry
|
||||
- minimale Prompt Registry
|
||||
- Placeholder Validation
|
||||
- Configuration-Grundmodell
|
||||
- Audit
|
||||
- Migration/Deploy-Grundlage
|
||||
|
||||
---
|
||||
|
||||
## 2. Verbindliche Primärdokumente
|
||||
|
||||
Lies bei Projektstart in dieser Reihenfolge:
|
||||
|
||||
1. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
2. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
3. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
4. `docs/sprints/Sprint0_Vibe_Coder_Handover_v0.1.md`
|
||||
5. `docs/architecture/Kairo_Architecture_References_v0.1.md`
|
||||
6. `.cursor/rules/kairo-architecture.mdc`
|
||||
|
||||
---
|
||||
|
||||
## 3. Designprinzipien als Referenz
|
||||
|
||||
Die Designprinzipien aus Mitai und Shinkan liegen unter:
|
||||
|
||||
```text
|
||||
docs/reference/design-principles/
|
||||
mitai/
|
||||
shinkan/
|
||||
alignment/
|
||||
```
|
||||
|
||||
Diese Dokumente sind **Referenzmaterial**, nicht direkter Arbeitsauftrag.
|
||||
|
||||
Sie dienen dazu, Entscheidungen zu begründen und bekannte Anti-Patterns zu vermeiden.
|
||||
|
||||
Sie dürfen nicht dazu verwendet werden, Kairo mit Mitai- oder Shinkan-Domänenlogik zu überladen.
|
||||
|
||||
---
|
||||
|
||||
## 4. Auslegungsreihenfolge bei Konflikten
|
||||
|
||||
Bei Konflikten gilt:
|
||||
|
||||
1. `Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
2. `Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
3. `Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
4. `Jinkendo_Foundation_Minimum_Viable_Foundation_v0.2.md`
|
||||
5. `DESIGN_PRINCIPLES_ALIGNMENT.md`
|
||||
6. Mitai/Shinkan Einzelprinzipien
|
||||
|
||||
Mitai/Shinkan-Prinzipien dürfen Kairo nicht überstimmen.
|
||||
|
||||
---
|
||||
|
||||
## 5. Verbindliche Regeln
|
||||
|
||||
1. Kairo ist mandantenfähig.
|
||||
2. Alle operativen Zuweisungen laufen über Actors.
|
||||
3. User und Actor sind nicht dasselbe.
|
||||
4. Agenten sind Actors, keine Sonderlogik.
|
||||
5. Jeder geschützte Request soll über TenantContext aufgelöst werden.
|
||||
6. Auth, Capability, Feature und Governance sind getrennte Konzepte.
|
||||
7. Rechte und Capabilities werden nicht verstreut hardcodiert.
|
||||
8. Prompts werden nicht hardcodiert.
|
||||
9. Platzhalter werden validiert.
|
||||
10. Fachliche Konfiguration wird nicht hardcodiert.
|
||||
11. Admin- und Agentenaktionen werden auditiert.
|
||||
12. Migrationen sind nummeriert und reproduzierbar.
|
||||
|
||||
---
|
||||
|
||||
## 6. Nicht tun
|
||||
|
||||
- keine Mitai-Domänenlogik kopieren
|
||||
- keine Shinkan-Domänenlogik kopieren
|
||||
- keine Trainingsplanung bauen
|
||||
- keine Gesundheitslogik bauen
|
||||
- keine Lebensmanager-/Seichō-Logik in Kairo einbauen
|
||||
- keine Vorhaben-/Projektlogik in AP0.1 vorziehen
|
||||
- kein Billing oder SSO bauen
|
||||
- keine strategischen Produktentscheidungen eigenmächtig ändern
|
||||
- keine Designprinzipien aus `docs/reference/` ohne Principle-Gate oder Architecture Decision in Scope ziehen
|
||||
|
||||
---
|
||||
|
||||
## 7. Abweichungen
|
||||
|
||||
Bei notwendiger Abweichung erstelle ein Architecture Decision Proposal.
|
||||
|
||||
## 8. Aktueller erster Auftrag
|
||||
|
||||
AP0.1 – Projektgrundlage (Backend, Frontend minimal, Tests, Deploy).
|
||||
@@ -1,3 +1,216 @@
|
||||
# Kairo-Jinkendo
|
||||
# Jinkendo Kairo
|
||||
|
||||
Programmmanger für alles im Leben
|
||||
Operativer Program Director der Jinkendo-Produktfamilie.
|
||||
|
||||
Kairo steuert Vorhaben, Programme, Projekte, Meilensteine, Maßnahmen, Backlogs, Reviews, Nachweise und die Zusammenarbeit von Menschen, Arbeitsgruppen und KI-Agenten.
|
||||
|
||||
## Leitfrage
|
||||
|
||||
> Welcher nächste Schritt bringt ein Vorhaben aktuell am wirkungsvollsten voran?
|
||||
|
||||
## Startzustand
|
||||
|
||||
Dieses Repository startet mit einem reinen Spezifikations- und Sprint-0-Handover-Paket.
|
||||
|
||||
Noch nicht enthalten:
|
||||
|
||||
- produktiver Anwendungscode
|
||||
- endgültiger Technologie-Stack
|
||||
- vollständige Jinkendo-Foundation
|
||||
- Mitai- oder Shinkan-Code
|
||||
- Billing / SSO / zentrale Produktfamilien-Konvergenz
|
||||
|
||||
## Verbindliche Dokumente für Sprint 0
|
||||
|
||||
1. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
2. `docs/architecture/Jinkendo_Foundation_Minimum_Viable_Foundation_v0.2.md`
|
||||
3. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
4. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
5. `docs/sprints/Sprint0_Vibe_Coder_Handover_v0.1.md`
|
||||
6. `docs/sprints/Sprint0_AP0_1_Project_Setup_Assignment_v0.1.md`
|
||||
7. `CLAUDE.md`
|
||||
8. `.cursor/rules/kairo-architecture.mdc`
|
||||
|
||||
## Arbeitsmodus
|
||||
|
||||
Kairo wird iterativ entwickelt.
|
||||
|
||||
Sprint 0 baut nur das Fundament:
|
||||
|
||||
- Tenant
|
||||
- User
|
||||
- Actor
|
||||
- TenantContext
|
||||
- Auth-Gates
|
||||
- Capability/Rights Registry
|
||||
- minimale Feature Registry
|
||||
- minimale Prompt Registry
|
||||
- Platzhaltermodell
|
||||
- Audit
|
||||
- Migration/Deploy-Grundlage
|
||||
|
||||
Vorhaben, Projekte, Meilensteine und Maßnahmen kommen erst nach Sprint 0.
|
||||
|
||||
|
||||
## Designprinzipien-Referenzen
|
||||
|
||||
Die extrahierten Designprinzipien aus Mitai und Shinkan liegen im Repository unter:
|
||||
|
||||
```text
|
||||
docs/reference/design-principles/
|
||||
```
|
||||
|
||||
Diese Dokumente sind Referenzen, kein direkter Sprint-Scope.
|
||||
|
||||
Verbindlich ist nur, was über das Kairo Sprint-0 Principle Gate oder eine Architecture Decision übernommen wurde.
|
||||
|
||||
## Deployment & CI
|
||||
|
||||
Zwei getrennte Gitea-Workflows (wie Shinkan):
|
||||
|
||||
| Workflow | Branch |
|
||||
|----------|--------|
|
||||
| **Deploy Development** | `develop` |
|
||||
| **Deploy Production** | `main` |
|
||||
| **Test Suite** | nach Deploy + bei Push/PR `develop` |
|
||||
|
||||
Details: [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)
|
||||
|
||||
## Local Development
|
||||
|
||||
Voraussetzungen: Docker + Docker Compose.
|
||||
|
||||
```bash
|
||||
git clone http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git
|
||||
cd Kairo-Jinkendo
|
||||
git checkout develop
|
||||
|
||||
# Dev-Stack (PostgreSQL + Backend + Frontend)
|
||||
docker compose -f docker-compose.dev-env.yml up --build
|
||||
|
||||
# Health prüfen
|
||||
curl http://localhost:8097/api/health
|
||||
curl http://localhost:3097/api/health
|
||||
|
||||
# Tests im Backend-Container
|
||||
docker compose -f docker-compose.dev-env.yml exec backend pip install -r requirements-dev.txt
|
||||
docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests -ra -vv
|
||||
```
|
||||
|
||||
UI: http://localhost:3097 · API: http://localhost:8097
|
||||
|
||||
Interaktive API-Doku (Dev): http://localhost:8097/api/docs
|
||||
|
||||
### Auth (AP0.2)
|
||||
|
||||
**Ersteinrichtung Dev** (automatisch per Seed nach jedem Backend-Start):
|
||||
|
||||
| Feld | Wert |
|
||||
|------|------|
|
||||
| E-Mail | `lars@stommer.com` |
|
||||
| Passwort | `12345678` |
|
||||
|
||||
Alternativ: UI-Registrierung (nur wenn DB leer und Dev-Seed deaktiviert) oder Bootstrap per `.env`:
|
||||
|
||||
```env
|
||||
KAIRO_BOOTSTRAP_ADMIN_EMAIL=admin@kairo.local
|
||||
KAIRO_BOOTSTRAP_ADMIN_PASSWORD=…
|
||||
KAIRO_BOOTSTRAP_TENANT_SLUG=default
|
||||
```
|
||||
|
||||
Migrationen & idempotente Data-Seeds: [docs/MIGRATIONS.md](docs/MIGRATIONS.md)
|
||||
|
||||
| Endpoint | Methode | Auth | Beschreibung |
|
||||
|----------|---------|------|--------------|
|
||||
| `/api/auth/setup-status` | GET | — | Ob Erstregistrierung offen ist |
|
||||
| `/api/auth/register` | POST | — | Erster User → Portal-Admin + Tenant (nur wenn noch kein User) |
|
||||
| `/api/auth/login` | POST | — | E-Mail + Passwort → Session-Token |
|
||||
| `/api/auth/logout` | POST | `X-Auth-Token` | Session löschen |
|
||||
| `/api/me` | GET | `X-Auth-Token` | Aktueller User + Tenant-Liste |
|
||||
| `/api/me/context` | GET | `X-Auth-Token` | TenantContext (Tenant + Human Actor + Capabilities) |
|
||||
| `/api/me/entitlements` | GET | `X-Auth-Token` | Entitlements-Snapshot (Rollen, Capabilities, Features-Platzhalter) |
|
||||
| `/api/me/admin/demo` | GET | `X-Auth-Token` + `kairo.admin.access` | Beispiel-Endpoint mit `require_capability` |
|
||||
| `/api/me/tenant` | POST | `X-Auth-Token` | Aktiven Tenant wechseln (nur Memberships) |
|
||||
|
||||
### Registries (AP0.4)
|
||||
|
||||
Feature-, Prompt-, Placeholder- und Config-Registry analog zur Rights Registry: Code-Registrierung → Startup-Sync → DB.
|
||||
|
||||
| Endpoint | Methode | Capability | Beschreibung |
|
||||
|----------|---------|------------|--------------|
|
||||
| `/api/features` | GET | `kairo.feature.registry.read` | Feature-Katalog |
|
||||
| `/api/prompts` | GET | `kairo.prompt.registry.read` | Prompt-Definitionen |
|
||||
| `/api/prompts/{key}` | GET | `kairo.prompt.registry.read` | Definition + aktive Version |
|
||||
| `/api/prompts/{key}/render` | POST | `kairo.prompt.render` | Single-Mode Rendering (ohne LLM) |
|
||||
| `/api/config` | GET | `kairo.config.registry.read` | Konfiguration (global/tenant) |
|
||||
| `/api/config` | POST | `kairo.config.registry.manage` | Konfiguration setzen |
|
||||
|
||||
Startup: `sync_prompt_feature_config.py` nach Rights-Sync (`SKIP_REGISTRY_SYNC=1` zum Überspringen).
|
||||
|
||||
**Prompt-Modell:** `PromptDefinition` → `PromptVersion` → optional `PromptStep` (workflow-/pipeline-fähig; AP0.4 führt nur `execution_mode=single` aus).
|
||||
|
||||
**Beispiel-Prompts:** `kairo.system.health_summary`, `kairo.context.debug_summary`
|
||||
|
||||
**Features im Entitlements-Snapshot:** `kairo.prompt.registry`, `kairo.config.registry`, `kairo.feature.registry`
|
||||
|
||||
| Capability | Modul | Kurzbeschreibung |
|
||||
|------------|-------|------------------|
|
||||
| `kairo.feature.registry.read` | feature | Feature-Katalog lesen |
|
||||
| `kairo.feature.registry.manage` | feature | Feature-Metadaten verwalten |
|
||||
| `kairo.prompt.registry.read` | prompt | Prompt Registry lesen |
|
||||
| `kairo.prompt.registry.manage` | prompt | Prompt Registry verwalten |
|
||||
| `kairo.config.registry.read` | config | Config lesen |
|
||||
| `kairo.config.registry.manage` | config | Config schreiben |
|
||||
| `kairo.prompt.render` | prompt | Prompt rendern (Test/Preview) |
|
||||
|
||||
Zusätzlich AP0.3-Capabilities (siehe oben).
|
||||
|
||||
Enforcement: `CAPABILITY_ENFORCE=probe` (Default) oder `enforce`.
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:8097/api/me/entitlements -H "X-Auth-Token: TOKEN"
|
||||
curl -s -X POST http://localhost:8097/api/prompts/kairo.system.health_summary/render \
|
||||
-H "X-Auth-Token: TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"values":{"debug_message":"OK","debug_level":"info"},"use_context":false}'
|
||||
```
|
||||
|
||||
### Capabilities (AP0.3)
|
||||
|
||||
Registry-first: Capabilities werden in `backend/rights_registrations/` registriert und beim Start via `sync_rights_registry.py` in die DB synchronisiert.
|
||||
|
||||
| Capability | Modul | Kurzbeschreibung |
|
||||
|------------|-------|------------------|
|
||||
| `kairo.admin.access` | platform | Portal-Administration |
|
||||
| `kairo.tenant.manage` | tenant | Tenant-Verwaltung |
|
||||
| `kairo.actor.manage` | tenant | Actor-Verwaltung |
|
||||
| `kairo.context.read` | platform | TenantContext lesen |
|
||||
| `kairo.entitlements.read` | platform | Entitlements lesen |
|
||||
|
||||
Enforcement: `CAPABILITY_ENFORCE=probe` (Default, loggt Verweigerungen) oder `enforce` (HTTP 403).
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:8097/api/me/entitlements -H "X-Auth-Token: TOKEN"
|
||||
```
|
||||
|
||||
```bash
|
||||
# Login
|
||||
curl -s -X POST http://localhost:8097/api/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"email":"admin@kairo.local","password":"…"}'
|
||||
|
||||
# Geschützter Endpoint
|
||||
curl -s http://localhost:8097/api/me -H "X-Auth-Token: TOKEN"
|
||||
```
|
||||
|
||||
Regeln: `user_id` kommt aus der Session, nicht aus Client-Headern. Portalrolle (`portal_role`) und Tenantrolle (`tenant_role`) sind getrennt.
|
||||
|
||||
## AP0.1 – Stand Projektgrundlage
|
||||
|
||||
| Bereich | Status |
|
||||
|---------|--------|
|
||||
| Git + Gitea (`develop` / `main`) | erledigt |
|
||||
| Docker Compose (Prod + Dev) | erledigt |
|
||||
| Backend (FastAPI, Migrationen, `/api/health`) | erledigt |
|
||||
| Frontend minimal (React + nginx Proxy) | erledigt |
|
||||
| pytest (Health + Migrationen + Auth/Tenant/Actor) | erledigt (AP0.2) |
|
||||
| Gitea Actions (Deploy + Test) | erledigt |
|
||||
@@ -0,0 +1,18 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y postgresql-client \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
ENV PIP_DEFAULT_TIMEOUT=120
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
RUN chmod +x /app/entrypoint.sh
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
"""Authentication: bcrypt passwords, server-side sessions, FastAPI dependencies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Depends, Header, HTTPException
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
|
||||
AUTH_HEADER = "X-Auth-Token"
|
||||
SESSION_DAYS = int(os.getenv("SESSION_DAYS", "30"))
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(password: str, stored_hash: str) -> bool:
|
||||
if not stored_hash:
|
||||
return False
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def make_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def _session_expiry() -> datetime:
|
||||
return datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)
|
||||
|
||||
|
||||
def get_user_by_email(email: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, email, password_hash, display_name, portal_role, is_active
|
||||
FROM users
|
||||
WHERE LOWER(email) = LOWER(%s)
|
||||
""",
|
||||
(email.strip(),),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_user_by_id(user_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, portal_role, is_active, created_at
|
||||
FROM users
|
||||
WHERE id = %s
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return dict(row) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_session(token: str) -> Optional[dict[str, Any]]:
|
||||
if not token:
|
||||
return None
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
s.id AS session_id,
|
||||
s.token,
|
||||
s.user_id,
|
||||
s.active_tenant_id,
|
||||
s.expires_at,
|
||||
u.email,
|
||||
u.display_name,
|
||||
u.portal_role,
|
||||
u.is_active AS user_is_active
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token = %s AND s.expires_at > NOW()
|
||||
""",
|
||||
(token,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
session = dict(row)
|
||||
if not session.get("user_is_active"):
|
||||
return None
|
||||
return session
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _default_active_tenant(user_id: str) -> Optional[str]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT tm.tenant_id
|
||||
FROM tenant_memberships tm
|
||||
JOIN tenants t ON t.id = tm.tenant_id
|
||||
WHERE tm.user_id = %s
|
||||
AND tm.is_active = TRUE
|
||||
AND t.is_active = TRUE
|
||||
ORDER BY tm.created_at ASC
|
||||
LIMIT 1
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return str(row[0]) if row else None
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_session(user_id: str, active_tenant_id: Optional[str] = None) -> dict[str, Any]:
|
||||
token = make_token()
|
||||
tenant_id = active_tenant_id or _default_active_tenant(user_id)
|
||||
expires_at = _session_expiry()
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token, user_id, active_tenant_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING token, expires_at, active_tenant_id
|
||||
""",
|
||||
(token, user_id, tenant_id, expires_at),
|
||||
)
|
||||
row = dict(cur.fetchone())
|
||||
conn.commit()
|
||||
row["user_id"] = user_id
|
||||
return row
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete_session(token: str) -> None:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def set_session_active_tenant(token: str, tenant_id: str) -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE sessions s
|
||||
SET active_tenant_id = %s
|
||||
FROM users u
|
||||
WHERE s.token = %s
|
||||
AND s.user_id = u.id
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM tenant_memberships tm
|
||||
JOIN tenants t ON t.id = tm.tenant_id
|
||||
WHERE tm.user_id = s.user_id
|
||||
AND tm.tenant_id = %s
|
||||
AND tm.is_active = TRUE
|
||||
AND t.is_active = TRUE
|
||||
)
|
||||
""",
|
||||
(tenant_id, token, tenant_id),
|
||||
)
|
||||
updated = cur.rowcount > 0
|
||||
conn.commit()
|
||||
return updated
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def login(email: str, password: str) -> dict[str, Any]:
|
||||
user = get_user_by_email(email)
|
||||
if not user or not user.get("is_active"):
|
||||
log_audit("auth.login_failed", details={"email": email.strip().lower()})
|
||||
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||
|
||||
if not verify_password(password, user["password_hash"]):
|
||||
log_audit("auth.login_failed", user_id=str(user["id"]), details={"email": user["email"]})
|
||||
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||
|
||||
session = create_session(str(user["id"]))
|
||||
log_audit("auth.login", user_id=str(user["id"]), details={"email": user["email"]})
|
||||
return {
|
||||
"token": session["token"],
|
||||
"expires_at": session["expires_at"].isoformat(),
|
||||
"user": {
|
||||
"id": str(user["id"]),
|
||||
"email": user["email"],
|
||||
"display_name": user["display_name"],
|
||||
"portal_role": user["portal_role"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def logout(token: str) -> None:
|
||||
session = get_session(token)
|
||||
if session:
|
||||
log_audit(
|
||||
"auth.logout",
|
||||
user_id=str(session["user_id"]),
|
||||
tenant_id=str(session["active_tenant_id"]) if session.get("active_tenant_id") else None,
|
||||
)
|
||||
delete_session(token)
|
||||
|
||||
|
||||
def require_auth(x_auth_token: Optional[str] = Header(default=None, alias=AUTH_HEADER)) -> dict[str, Any]:
|
||||
session = get_session(x_auth_token or "")
|
||||
if not session:
|
||||
raise HTTPException(status_code=401, detail="Nicht eingeloggt")
|
||||
return session
|
||||
|
||||
|
||||
def require_portal_admin(session: dict[str, Any] = Depends(require_auth)) -> dict[str, Any]:
|
||||
if session.get("portal_role") != "admin":
|
||||
raise HTTPException(status_code=403, detail="Nur für Portal-Admins")
|
||||
return session
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Bootstrap first admin user from environment (optional alternative to UI registration)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from services.registration import provision_system_admin, user_count
|
||||
|
||||
|
||||
def _env(name: str) -> str:
|
||||
return os.getenv(name, "").strip()
|
||||
|
||||
|
||||
def bootstrap_admin_if_needed() -> None:
|
||||
if _env("SKIP_BOOTSTRAP").lower() in ("1", "true", "yes"):
|
||||
return
|
||||
|
||||
email = _env("KAIRO_BOOTSTRAP_ADMIN_EMAIL")
|
||||
password = _env("KAIRO_BOOTSTRAP_ADMIN_PASSWORD")
|
||||
if not email or not password:
|
||||
return
|
||||
|
||||
if user_count() > 0:
|
||||
return
|
||||
|
||||
tenant_slug = _env("KAIRO_BOOTSTRAP_TENANT_SLUG") or "default"
|
||||
tenant_name = _env("KAIRO_BOOTSTRAP_TENANT_NAME") or "Default Tenant"
|
||||
display_name = _env("KAIRO_BOOTSTRAP_ADMIN_NAME") or "Kairo Admin"
|
||||
|
||||
provision_system_admin(
|
||||
email=email,
|
||||
password=password,
|
||||
display_name=display_name,
|
||||
tenant_slug=tenant_slug,
|
||||
tenant_name=tenant_name,
|
||||
source="env_bootstrap",
|
||||
)
|
||||
print(f"[bootstrap] Systemadmin und Tenant '{tenant_slug}' angelegt")
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Central capability resolution and FastAPI enforcement dependencies."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Any, Callable
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
|
||||
from rights_registry import load_grants_for_roles
|
||||
from services.audit import log_audit
|
||||
from tenant_context import TenantContext, get_tenant_context, require_tenant_context
|
||||
|
||||
CAPABILITY_ENFORCE_ENV = "CAPABILITY_ENFORCE"
|
||||
|
||||
|
||||
def capability_enforcement_mode() -> str:
|
||||
raw = os.getenv(CAPABILITY_ENFORCE_ENV, "probe").strip().lower()
|
||||
return "enforce" if raw in ("1", "true", "enforce", "yes") else "probe"
|
||||
|
||||
|
||||
def resolve_capabilities(*, portal_role: str, tenant_role: str | None) -> frozenset[str]:
|
||||
return frozenset(load_grants_for_roles(portal_role=portal_role, tenant_role=tenant_role))
|
||||
|
||||
|
||||
def has_capability(ctx: TenantContext, capability_key: str) -> bool:
|
||||
return capability_key in ctx.capabilities
|
||||
|
||||
|
||||
def check_capability(ctx: TenantContext, capability_key: str) -> dict[str, Any]:
|
||||
allowed = has_capability(ctx, capability_key)
|
||||
return {
|
||||
"capability_key": capability_key,
|
||||
"allowed": allowed,
|
||||
"reason": None if allowed else "missing_grant",
|
||||
}
|
||||
|
||||
|
||||
def require_capability(capability_key: str) -> Callable[..., TenantContext]:
|
||||
"""FastAPI dependency — blocks in enforce mode, probes in probe mode."""
|
||||
|
||||
def _dependency(ctx: TenantContext = Depends(require_tenant_context)) -> TenantContext:
|
||||
return _enforce_capability(ctx, capability_key)
|
||||
|
||||
return _dependency
|
||||
|
||||
|
||||
def require_capability_ctx(capability_key: str) -> Callable[..., TenantContext]:
|
||||
"""Like require_capability but allows portal context without active tenant."""
|
||||
|
||||
def _dependency(ctx: TenantContext = Depends(get_tenant_context)) -> TenantContext:
|
||||
return _enforce_capability(ctx, capability_key)
|
||||
|
||||
return _dependency
|
||||
|
||||
|
||||
def _enforce_capability(ctx: TenantContext, capability_key: str) -> TenantContext:
|
||||
result = check_capability(ctx, capability_key)
|
||||
if result["allowed"]:
|
||||
return ctx
|
||||
|
||||
log_audit(
|
||||
"capability.denied",
|
||||
user_id=ctx.user_id,
|
||||
tenant_id=ctx.tenant_id,
|
||||
details={
|
||||
"capability_key": capability_key,
|
||||
"mode": capability_enforcement_mode(),
|
||||
"portal_role": ctx.portal_role,
|
||||
"tenant_role": ctx.tenant_role,
|
||||
},
|
||||
)
|
||||
|
||||
if capability_enforcement_mode() == "enforce":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"Capability fehlt: {capability_key}",
|
||||
)
|
||||
return ctx
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Central configuration service — no plaintext secrets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from db import get_connection
|
||||
from services.audit import log_audit
|
||||
|
||||
SECRET_VALUE_FORBIDDEN = (
|
||||
"Configuration entries with is_secret=true must not store plaintext values; "
|
||||
"use environment or secret management."
|
||||
)
|
||||
|
||||
|
||||
def _validate_secret_entry(*, is_secret: bool, value: Any) -> None:
|
||||
if not is_secret:
|
||||
return
|
||||
if value not in (None, {}, "", {"ref": "env"}):
|
||||
raise ValueError(SECRET_VALUE_FORBIDDEN)
|
||||
|
||||
|
||||
def get_config(
|
||||
config_key: str,
|
||||
*,
|
||||
scope: str = "global",
|
||||
tenant_id: str | None = None,
|
||||
) -> dict | None:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||
FROM configuration_entries
|
||||
WHERE config_key = %s AND scope = %s
|
||||
AND (
|
||||
(scope = 'global' AND tenant_id IS NULL)
|
||||
OR (scope = 'tenant' AND tenant_id = %s::uuid)
|
||||
)
|
||||
""",
|
||||
(config_key, scope, tenant_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"config_key": row[0],
|
||||
"scope": row[1],
|
||||
"tenant_id": str(row[2]) if row[2] else None,
|
||||
"value": row[3],
|
||||
"value_type": row[4],
|
||||
"description": row[5],
|
||||
"is_secret": row[6],
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_configs(*, scope: str | None = None, tenant_id: str | None = None) -> list[dict]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
if scope == "global":
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||
FROM configuration_entries
|
||||
WHERE scope = 'global' AND tenant_id IS NULL
|
||||
ORDER BY config_key
|
||||
"""
|
||||
)
|
||||
elif scope == "tenant" and tenant_id:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||
FROM configuration_entries
|
||||
WHERE scope = 'tenant' AND tenant_id = %s::uuid
|
||||
ORDER BY config_key
|
||||
""",
|
||||
(tenant_id,),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||
FROM configuration_entries
|
||||
ORDER BY scope, config_key
|
||||
"""
|
||||
)
|
||||
rows = []
|
||||
for row in cur.fetchall():
|
||||
item = {
|
||||
"config_key": row[0],
|
||||
"scope": row[1],
|
||||
"tenant_id": str(row[2]) if row[2] else None,
|
||||
"value_type": row[4],
|
||||
"description": row[5],
|
||||
"is_secret": row[6],
|
||||
}
|
||||
if row[6]:
|
||||
item["value"] = {"ref": "env"}
|
||||
else:
|
||||
item["value"] = row[3]
|
||||
rows.append(item)
|
||||
return rows
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_config(
|
||||
*,
|
||||
config_key: str,
|
||||
scope: str,
|
||||
value: Any,
|
||||
value_type: str = "string",
|
||||
description: str = "",
|
||||
is_secret: bool = False,
|
||||
tenant_id: str | None = None,
|
||||
user_id: str | None = None,
|
||||
) -> dict:
|
||||
_validate_secret_entry(is_secret=is_secret, value=value)
|
||||
if scope == "tenant" and not tenant_id:
|
||||
raise ValueError("tenant_id required for tenant-scoped config")
|
||||
if scope == "global":
|
||||
tenant_id = None
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
if scope == "global":
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO configuration_entries (
|
||||
config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||
)
|
||||
VALUES (%s, 'global', NULL, %s::jsonb, %s, %s, %s)
|
||||
ON CONFLICT (config_key) WHERE scope = 'global' DO UPDATE SET
|
||||
value = EXCLUDED.value,
|
||||
value_type = EXCLUDED.value_type,
|
||||
description = EXCLUDED.description,
|
||||
is_secret = EXCLUDED.is_secret,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
config_key,
|
||||
json.dumps(value if not is_secret else {"ref": "env"}),
|
||||
value_type,
|
||||
description,
|
||||
is_secret,
|
||||
),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO configuration_entries (
|
||||
config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||
)
|
||||
VALUES (%s, 'tenant', %s::uuid, %s::jsonb, %s, %s, %s)
|
||||
ON CONFLICT (config_key, tenant_id) WHERE scope = 'tenant' DO UPDATE SET
|
||||
value = EXCLUDED.value,
|
||||
value_type = EXCLUDED.value_type,
|
||||
description = EXCLUDED.description,
|
||||
is_secret = EXCLUDED.is_secret,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
config_key,
|
||||
tenant_id,
|
||||
json.dumps(value if not is_secret else {"ref": "env"}),
|
||||
value_type,
|
||||
description,
|
||||
is_secret,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
log_audit(
|
||||
"config.entry.changed",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"config_key": config_key, "scope": scope, "is_secret": is_secret},
|
||||
)
|
||||
result = get_config(config_key, scope=scope, tenant_id=tenant_id)
|
||||
assert result is not None
|
||||
return result
|
||||
|
||||
|
||||
def sync_default_configs(defaults: list[dict]) -> int:
|
||||
if not defaults:
|
||||
return 0
|
||||
for item in defaults:
|
||||
existing = get_config(item["config_key"], scope=item.get("scope", "global"))
|
||||
if existing:
|
||||
continue
|
||||
upsert_config(
|
||||
config_key=item["config_key"],
|
||||
scope=item.get("scope", "global"),
|
||||
value=item["value"],
|
||||
value_type=item.get("value_type", "string"),
|
||||
description=item.get("description", ""),
|
||||
is_secret=item.get("is_secret", False),
|
||||
)
|
||||
print(f"[config_service] Default configs ensured — {len(defaults)} item(s)")
|
||||
return 0
|
||||
@@ -0,0 +1,75 @@
|
||||
"""PostgreSQL connection helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
import psycopg2
|
||||
from psycopg2.extensions import connection
|
||||
|
||||
|
||||
def db_params() -> dict[str, str]:
|
||||
return {
|
||||
"host": os.getenv("DB_HOST", "localhost"),
|
||||
"port": os.getenv("DB_PORT", "5432"),
|
||||
"dbname": os.getenv("DB_NAME", "kairo_dev"),
|
||||
"user": os.getenv("DB_USER", "kairo_dev"),
|
||||
"password": os.getenv("DB_PASSWORD", "dev_password"),
|
||||
}
|
||||
|
||||
|
||||
def get_connection() -> connection:
|
||||
p = db_params()
|
||||
return psycopg2.connect(
|
||||
host=p["host"],
|
||||
port=p["port"],
|
||||
database=p["dbname"],
|
||||
user=p["user"],
|
||||
password=p["password"],
|
||||
)
|
||||
|
||||
|
||||
def is_retryable_db_error(exc: Exception) -> bool:
|
||||
"""Nur temporäre Verbindungsprobleme erneut versuchen (nicht Auth/Config)."""
|
||||
msg = str(exc).lower()
|
||||
if "password authentication failed" in msg:
|
||||
return False
|
||||
if "does not exist" in msg and any(token in msg for token in ("role", "database")):
|
||||
return False
|
||||
if "no pg_hba.conf entry" in msg:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def connect_with_retry(max_retries: int = 30, sleep_seconds: float = 2.0) -> connection:
|
||||
p = db_params()
|
||||
last_exc: Exception | None = None
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
conn = get_connection()
|
||||
conn.autocommit = False
|
||||
print(f"[OK] Connected to database: {p['dbname']}")
|
||||
return conn
|
||||
except psycopg2.OperationalError as exc:
|
||||
last_exc = exc
|
||||
if not is_retryable_db_error(exc):
|
||||
raise
|
||||
if attempt >= max_retries - 1:
|
||||
raise
|
||||
print(f"Waiting for database... ({attempt + 1}/{max_retries})")
|
||||
time.sleep(sleep_seconds)
|
||||
if last_exc:
|
||||
raise last_exc
|
||||
raise RuntimeError("database connection failed")
|
||||
|
||||
|
||||
def check_db() -> bool:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
return True
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Entitlements snapshot for GET /api/me/entitlements."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from capabilities import capability_enforcement_mode, check_capability
|
||||
from feature_registry import load_active_features
|
||||
from rights_registry import get_registered_capabilities
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def _capability_map(ctx: TenantContext) -> dict[str, dict[str, Any]]:
|
||||
registered = {reg.key for reg in get_registered_capabilities()}
|
||||
snapshot: dict[str, dict[str, Any]] = {}
|
||||
for key in sorted(registered):
|
||||
snapshot[key] = check_capability(ctx, key)
|
||||
return snapshot
|
||||
|
||||
|
||||
def _feature_snapshot() -> dict[str, dict[str, Any]]:
|
||||
features = load_active_features()
|
||||
return {
|
||||
key: {
|
||||
"enabled": meta["enabled"],
|
||||
"module": meta["module"],
|
||||
"name": meta["name"],
|
||||
}
|
||||
for key, meta in features.items()
|
||||
}
|
||||
|
||||
|
||||
def build_entitlements_snapshot(ctx: TenantContext) -> dict[str, Any]:
|
||||
features = _feature_snapshot()
|
||||
tenant_block = None
|
||||
if ctx.tenant_id:
|
||||
tenant_block = {
|
||||
"tenant_id": ctx.tenant_id,
|
||||
"slug": ctx.tenant_slug,
|
||||
"name": ctx.tenant_name,
|
||||
"role": ctx.tenant_role,
|
||||
"capabilities": {
|
||||
key: value
|
||||
for key, value in _capability_map(ctx).items()
|
||||
if key in ctx.capabilities
|
||||
},
|
||||
"features": features,
|
||||
}
|
||||
|
||||
return {
|
||||
"account": {
|
||||
"user_id": ctx.user_id,
|
||||
"email": ctx.email,
|
||||
"display_name": ctx.display_name,
|
||||
"portal_role": ctx.portal_role,
|
||||
"capabilities": _capability_map(ctx),
|
||||
"features": features,
|
||||
},
|
||||
"tenant": tenant_block,
|
||||
"actor": (
|
||||
{
|
||||
"actor_id": ctx.actor_id,
|
||||
"actor_type": ctx.actor_type,
|
||||
}
|
||||
if ctx.actor_id
|
||||
else None
|
||||
),
|
||||
"roles": {
|
||||
"portal": ctx.portal_role,
|
||||
"tenant": ctx.tenant_role,
|
||||
},
|
||||
"capabilities": sorted(ctx.capabilities),
|
||||
"features": features,
|
||||
"enforcement": {
|
||||
"capabilities": capability_enforcement_mode(),
|
||||
"features": "probe",
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
echo "=== Kairo Backend Startup ==="
|
||||
|
||||
if [ "${SKIP_DB_MIGRATE}" != "1" ] && [ "${SKIP_DB_MIGRATE}" != "true" ] && [ "${SKIP_DB_MIGRATE}" != "yes" ]; then
|
||||
python run_migrations.py
|
||||
else
|
||||
echo "[SKIP_DB_MIGRATE] Migrationen übersprungen"
|
||||
fi
|
||||
|
||||
if [ "${SKIP_SEEDS}" != "1" ] && [ "${SKIP_SEEDS}" != "true" ] && [ "${SKIP_SEEDS}" != "yes" ]; then
|
||||
python run_seeds.py
|
||||
else
|
||||
echo "[SKIP_SEEDS] Data-Seeds übersprungen"
|
||||
fi
|
||||
|
||||
if [ "${SKIP_RIGHTS_SYNC}" != "1" ] && [ "${SKIP_RIGHTS_SYNC}" != "true" ] && [ "${SKIP_RIGHTS_SYNC}" != "yes" ]; then
|
||||
python sync_rights_registry.py
|
||||
else
|
||||
echo "[SKIP_RIGHTS_SYNC] Rights-Registry-Sync übersprungen"
|
||||
fi
|
||||
|
||||
if [ "${SKIP_REGISTRY_SYNC}" != "1" ] && [ "${SKIP_REGISTRY_SYNC}" != "true" ] && [ "${SKIP_REGISTRY_SYNC}" != "yes" ]; then
|
||||
python sync_prompt_feature_config.py
|
||||
else
|
||||
echo "[SKIP_REGISTRY_SYNC] Feature/Prompt/Config-Sync übersprungen"
|
||||
fi
|
||||
|
||||
export KAIRO_DB_READY=1
|
||||
echo "=== Starte Anwendung: $* ==="
|
||||
exec "$@"
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Side-effect imports for feature registrations."""
|
||||
|
||||
from feature_registrations import platform, prompt_ops # noqa: F401
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Platform feature catalog entries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from feature_registry import FeatureRegistration, register_feature
|
||||
|
||||
register_feature(
|
||||
FeatureRegistration(
|
||||
key="kairo.feature.registry",
|
||||
module="platform",
|
||||
name="Feature Registry",
|
||||
description="Metadatenkatalog registrierter Kairo-Features",
|
||||
)
|
||||
)
|
||||
|
||||
register_feature(
|
||||
FeatureRegistration(
|
||||
key="kairo.config.registry",
|
||||
module="config",
|
||||
name="Configuration Registry",
|
||||
description="Zentrale fachliche Konfiguration (global/tenant)",
|
||||
)
|
||||
)
|
||||
|
||||
register_feature(
|
||||
FeatureRegistration(
|
||||
key="kairo.prompt.registry",
|
||||
module="prompt",
|
||||
name="Prompt Registry",
|
||||
description="Workflow-ready Prompt-Definitionen und Versionen",
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Prompt-related feature metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Reserved for future prompt-domain features beyond registry catalog.
|
||||
@@ -0,0 +1,108 @@
|
||||
"""In-memory feature registry with startup sync to PostgreSQL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from db import get_connection
|
||||
|
||||
VALID_CONTEXT_KINDS = frozenset(
|
||||
{
|
||||
"kairo.tenant_context",
|
||||
"kairo.actor_context",
|
||||
"kairo.debug_context",
|
||||
}
|
||||
)
|
||||
|
||||
VALID_EXECUTION_MODES = frozenset({"single", "pipeline", "workflow"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FeatureRegistration:
|
||||
key: str
|
||||
module: str
|
||||
name: str
|
||||
description: str
|
||||
|
||||
|
||||
_REGISTRY: dict[str, FeatureRegistration] = {}
|
||||
|
||||
|
||||
def register_feature(registration: FeatureRegistration) -> None:
|
||||
if not registration.key or not registration.key.strip():
|
||||
raise ValueError("Feature key is required")
|
||||
if not registration.module or not registration.module.strip():
|
||||
raise ValueError("Feature module is required")
|
||||
if not registration.name or not registration.name.strip():
|
||||
raise ValueError("Feature name is required")
|
||||
if not registration.description or not registration.description.strip():
|
||||
raise ValueError("Feature description is required")
|
||||
if registration.key in _REGISTRY:
|
||||
raise ValueError(f"Feature already registered: {registration.key}")
|
||||
_REGISTRY[registration.key] = registration
|
||||
|
||||
|
||||
def get_registered_features() -> tuple[FeatureRegistration, ...]:
|
||||
return tuple(_REGISTRY.values())
|
||||
|
||||
|
||||
def clear_feature_registry_for_tests() -> None:
|
||||
_REGISTRY.clear()
|
||||
|
||||
|
||||
def sync_features_to_db() -> int:
|
||||
if not _REGISTRY:
|
||||
print("[feature_registry] Keine Features registriert — Sync übersprungen")
|
||||
return 0
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
for reg in _REGISTRY.values():
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO features (feature_key, module, name, description, is_active)
|
||||
VALUES (%s, %s, %s, %s, TRUE)
|
||||
ON CONFLICT (feature_key) DO UPDATE SET
|
||||
module = EXCLUDED.module,
|
||||
name = EXCLUDED.name,
|
||||
description = EXCLUDED.description,
|
||||
is_active = TRUE,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(reg.key, reg.module, reg.name, reg.description),
|
||||
)
|
||||
conn.commit()
|
||||
print(f"[feature_registry] Sync OK — {len(_REGISTRY)} Feature(s)")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
print(f"[feature_registry] Sync FAIL: {exc}")
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def load_active_features() -> dict[str, dict]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT feature_key, module, name, description
|
||||
FROM features
|
||||
WHERE is_active = TRUE
|
||||
ORDER BY feature_key
|
||||
"""
|
||||
)
|
||||
return {
|
||||
row[0]: {
|
||||
"enabled": True,
|
||||
"module": row[1],
|
||||
"name": row[2],
|
||||
"description": row[3],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Jinkendo Kairo — FastAPI application entry point."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from db import check_db
|
||||
from version import APP_NAME, APP_VERSION, DB_SCHEMA_VERSION
|
||||
|
||||
if os.getenv("KAIRO_DB_READY") != "1":
|
||||
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() not in ("1", "true", "yes"):
|
||||
import run_migrations
|
||||
|
||||
exit_code = run_migrations.main()
|
||||
if exit_code != 0:
|
||||
print(f"[FAIL] Migrationen fehlgeschlagen (Exit {exit_code})")
|
||||
sys.exit(exit_code)
|
||||
else:
|
||||
print("[SKIP_DB_MIGRATE] Migrationen übersprungen")
|
||||
|
||||
if os.getenv("SKIP_SEEDS", "").strip().lower() not in ("1", "true", "yes"):
|
||||
import run_seeds
|
||||
|
||||
exit_code = run_seeds.main()
|
||||
if exit_code != 0:
|
||||
print(f"[FAIL] Seeds fehlgeschlagen (Exit {exit_code})")
|
||||
sys.exit(exit_code)
|
||||
else:
|
||||
print("[SKIP_SEEDS] Data-Seeds übersprungen")
|
||||
|
||||
allowed_origins = [
|
||||
origin.strip()
|
||||
for origin in os.getenv("ALLOWED_ORIGINS", "http://localhost:3097").split(",")
|
||||
if origin.strip()
|
||||
]
|
||||
|
||||
app = FastAPI(
|
||||
title="Jinkendo Kairo",
|
||||
version=APP_VERSION,
|
||||
docs_url="/api/docs" if os.getenv("ENVIRONMENT", "development") != "production" else None,
|
||||
redoc_url=None,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=allowed_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
from routers import auth, config, features, me, prompts # noqa: E402
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(me.router)
|
||||
app.include_router(features.router)
|
||||
app.include_router(prompts.router)
|
||||
app.include_router(config.router)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def api_health():
|
||||
db_status = "ok"
|
||||
try:
|
||||
if not check_db():
|
||||
db_status = "error"
|
||||
except Exception:
|
||||
db_status = "error"
|
||||
|
||||
status = "ok" if db_status == "ok" else "degraded"
|
||||
return {
|
||||
"status": status,
|
||||
"app": APP_NAME,
|
||||
"db": db_status,
|
||||
"version": APP_VERSION,
|
||||
"schema": DB_SCHEMA_VERSION,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/version")
|
||||
def api_version():
|
||||
return {
|
||||
"app": APP_NAME,
|
||||
"version": APP_VERSION,
|
||||
"schema": DB_SCHEMA_VERSION,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
-- AP0.1: minimale Schema-Vorbereitung (keine Tenant/User/Actor-Fachlogik)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS kairo_app_meta (
|
||||
id SERIAL PRIMARY KEY,
|
||||
key VARCHAR(128) UNIQUE NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
INSERT INTO kairo_app_meta (key, value)
|
||||
VALUES ('schema_phase', 'ap0.1')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
@@ -0,0 +1,81 @@
|
||||
-- AP0.2: Auth, Identity, Tenant & Actor Foundation
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
display_name VARCHAR(255) NOT NULL,
|
||||
portal_role VARCHAR(32) NOT NULL DEFAULT 'user'
|
||||
CHECK (portal_role IN ('user', 'admin')),
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE tenants (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
slug VARCHAR(64) NOT NULL UNIQUE,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE tenant_memberships (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
tenant_role VARCHAR(32) NOT NULL DEFAULT 'member'
|
||||
CHECK (tenant_role IN ('owner', 'admin', 'member')),
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (tenant_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_tenant_memberships_user ON tenant_memberships(user_id);
|
||||
|
||||
CREATE TABLE actors (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
actor_type VARCHAR(32) NOT NULL
|
||||
CHECK (actor_type IN ('human', 'agent', 'working_group', 'external_system')),
|
||||
name VARCHAR(255) NOT NULL,
|
||||
user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CHECK (
|
||||
(actor_type = 'human' AND user_id IS NOT NULL)
|
||||
OR (actor_type <> 'human' AND user_id IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX idx_actors_human_user_tenant
|
||||
ON actors(tenant_id, user_id)
|
||||
WHERE actor_type = 'human';
|
||||
|
||||
CREATE INDEX idx_actors_tenant ON actors(tenant_id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
token VARCHAR(128) NOT NULL UNIQUE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
active_tenant_id UUID NULL REFERENCES tenants(id) ON DELETE SET NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_sessions_token ON sessions(token);
|
||||
CREATE INDEX idx_sessions_user_id ON sessions(user_id);
|
||||
|
||||
CREATE TABLE audit_log (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
action VARCHAR(64) NOT NULL,
|
||||
user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||
tenant_id UUID NULL REFERENCES tenants(id) ON DELETE SET NULL,
|
||||
details JSONB NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_audit_log_created ON audit_log(created_at DESC);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Tracking für idempotente Data-Seeds (Checksum-basiert, bei Änderung erneut ausführbar)
|
||||
|
||||
CREATE TABLE IF NOT EXISTS data_seeds (
|
||||
seed_name VARCHAR(255) PRIMARY KEY,
|
||||
checksum VARCHAR(64) NOT NULL,
|
||||
executed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
last_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
-- AP0.3: Capability catalog and role → capability grants
|
||||
|
||||
CREATE TABLE capabilities (
|
||||
capability_key VARCHAR(128) PRIMARY KEY,
|
||||
module VARCHAR(64) NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE role_capability_grants (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
role_scope VARCHAR(16) NOT NULL
|
||||
CHECK (role_scope IN ('portal', 'tenant')),
|
||||
role_code VARCHAR(32) NOT NULL,
|
||||
capability_key VARCHAR(128) NOT NULL REFERENCES capabilities(capability_key) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (role_scope, role_code, capability_key)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_role_capability_grants_lookup
|
||||
ON role_capability_grants(role_scope, role_code);
|
||||
@@ -0,0 +1,121 @@
|
||||
-- AP0.4: Feature, Prompt, Placeholder and Configuration registries
|
||||
|
||||
CREATE TABLE features (
|
||||
feature_key VARCHAR(128) PRIMARY KEY,
|
||||
module VARCHAR(64) NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE prompt_definitions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
prompt_key VARCHAR(128) NOT NULL UNIQUE,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
purpose TEXT NOT NULL DEFAULT '',
|
||||
context_kind VARCHAR(64) NOT NULL,
|
||||
execution_mode VARCHAR(32) NOT NULL DEFAULT 'single'
|
||||
CHECK (execution_mode IN ('single', 'pipeline', 'workflow')),
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||
CHECK (status IN ('draft', 'active', 'archived')),
|
||||
active_version_id UUID,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE prompt_versions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
prompt_definition_id UUID NOT NULL REFERENCES prompt_definitions(id) ON DELETE CASCADE,
|
||||
version VARCHAR(64) NOT NULL,
|
||||
body TEXT NOT NULL DEFAULT '',
|
||||
input_schema JSONB,
|
||||
output_schema JSONB,
|
||||
model_policy_key VARCHAR(128),
|
||||
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
changelog TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE (prompt_definition_id, version)
|
||||
);
|
||||
|
||||
ALTER TABLE prompt_definitions
|
||||
ADD CONSTRAINT fk_prompt_definitions_active_version
|
||||
FOREIGN KEY (active_version_id) REFERENCES prompt_versions(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE TABLE prompt_steps (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
prompt_version_id UUID NOT NULL REFERENCES prompt_versions(id) ON DELETE CASCADE,
|
||||
step_key VARCHAR(128) NOT NULL,
|
||||
step_order INT NOT NULL DEFAULT 0,
|
||||
step_type VARCHAR(32) NOT NULL DEFAULT 'template'
|
||||
CHECK (step_type IN ('template', 'resolver', 'llm_call', 'postprocess', 'validation')),
|
||||
template_body TEXT NOT NULL DEFAULT '',
|
||||
input_mapping JSONB,
|
||||
output_mapping JSONB,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (prompt_version_id, step_key)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_prompt_steps_version_order
|
||||
ON prompt_steps(prompt_version_id, step_order);
|
||||
|
||||
CREATE TABLE placeholder_definitions (
|
||||
placeholder_key VARCHAR(128) NOT NULL,
|
||||
context_kind VARCHAR(64) NOT NULL,
|
||||
value_type VARCHAR(32) NOT NULL DEFAULT 'string'
|
||||
CHECK (value_type IN ('string', 'number', 'boolean', 'object', 'array', 'json')),
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
required BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
source VARCHAR(64) NOT NULL DEFAULT 'input',
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (placeholder_key, context_kind)
|
||||
);
|
||||
|
||||
CREATE TABLE configuration_entries (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
config_key VARCHAR(128) NOT NULL,
|
||||
scope VARCHAR(32) NOT NULL DEFAULT 'global'
|
||||
CHECK (scope IN ('global', 'tenant')),
|
||||
tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
value JSONB NOT NULL DEFAULT '{}',
|
||||
value_type VARCHAR(32) NOT NULL DEFAULT 'string'
|
||||
CHECK (value_type IN ('string', 'number', 'boolean', 'object', 'array', 'json')),
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
is_secret BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CHECK (
|
||||
(scope = 'global' AND tenant_id IS NULL)
|
||||
OR (scope = 'tenant' AND tenant_id IS NOT NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX uq_configuration_entries_global
|
||||
ON configuration_entries (config_key)
|
||||
WHERE scope = 'global';
|
||||
|
||||
CREATE UNIQUE INDEX uq_configuration_entries_tenant
|
||||
ON configuration_entries (config_key, tenant_id)
|
||||
WHERE scope = 'tenant';
|
||||
|
||||
CREATE TABLE prompt_execution_logs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
prompt_definition_id UUID REFERENCES prompt_definitions(id) ON DELETE SET NULL,
|
||||
prompt_version_id UUID REFERENCES prompt_versions(id) ON DELETE SET NULL,
|
||||
execution_mode VARCHAR(32) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL
|
||||
CHECK (status IN ('success', 'error', 'skipped')),
|
||||
rendered_preview TEXT,
|
||||
input_summary JSONB,
|
||||
error_message TEXT,
|
||||
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_prompt_execution_logs_created
|
||||
ON prompt_execution_logs(created_at DESC);
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Side-effect imports for placeholder registrations."""
|
||||
|
||||
from placeholder_registrations import actor_context, debug, tenant_context # noqa: F401
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Actor context placeholders."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||
|
||||
_CTX = "kairo.actor_context"
|
||||
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("actor_id", _CTX, "string", "UUID des Actors", required=True)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("actor_type", _CTX, "string", "Actor-Typ", required=True)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("tenant_id", _CTX, "string", "UUID des Tenants", required=True)
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Debug context placeholders."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||
|
||||
_CTX = "kairo.debug_context"
|
||||
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("debug_message", _CTX, "string", "Freier Debug-Text", required=True)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("debug_level", _CTX, "string", "Log-Level oder Kategorie", required=False)
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""TenantContext placeholders for prompt rendering."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||
|
||||
_CTX = "kairo.tenant_context"
|
||||
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("tenant_name", _CTX, "string", "Name des aktiven Tenants", required=True)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("tenant_id", _CTX, "string", "UUID des aktiven Tenants", required=True)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("actor_name", _CTX, "string", "Anzeigename des Human Actors", required=False)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("actor_id", _CTX, "string", "UUID des Human Actors", required=False)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("actor_type", _CTX, "string", "Actor-Typ (z. B. human)", required=False)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("portal_role", _CTX, "string", "Portal-Rolle des Users", required=True)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration("tenant_role", _CTX, "string", "Tenant-Rolle in der Membership", required=False)
|
||||
)
|
||||
register_placeholder(
|
||||
PlaceholderRegistration(
|
||||
"capabilities",
|
||||
_CTX,
|
||||
"json",
|
||||
"Aufgelöste Capability-Keys als JSON-Array",
|
||||
required=False,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Placeholder definitions registry with DB sync."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from db import get_connection
|
||||
from feature_registry import VALID_CONTEXT_KINDS
|
||||
|
||||
VALID_VALUE_TYPES = frozenset({"string", "number", "boolean", "object", "array", "json"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlaceholderRegistration:
|
||||
placeholder_key: str
|
||||
context_kind: str
|
||||
value_type: str
|
||||
description: str
|
||||
required: bool = False
|
||||
source: str = "input"
|
||||
|
||||
|
||||
_REGISTRY: list[PlaceholderRegistration] = []
|
||||
|
||||
|
||||
def register_placeholder(registration: PlaceholderRegistration) -> None:
|
||||
if not registration.placeholder_key or not registration.placeholder_key.strip():
|
||||
raise ValueError("Placeholder key is required")
|
||||
if registration.context_kind not in VALID_CONTEXT_KINDS:
|
||||
raise ValueError(f"Unknown context_kind: {registration.context_kind}")
|
||||
if registration.value_type not in VALID_VALUE_TYPES:
|
||||
raise ValueError(f"Unknown value_type: {registration.value_type}")
|
||||
if not registration.description or not registration.description.strip():
|
||||
raise ValueError("Placeholder description is required")
|
||||
key = (registration.placeholder_key, registration.context_kind)
|
||||
if any((r.placeholder_key, r.context_kind) == key for r in _REGISTRY):
|
||||
raise ValueError(f"Placeholder already registered: {key}")
|
||||
_REGISTRY.append(registration)
|
||||
|
||||
|
||||
def get_registered_placeholders() -> tuple[PlaceholderRegistration, ...]:
|
||||
return tuple(_REGISTRY)
|
||||
|
||||
|
||||
def clear_placeholder_registry_for_tests() -> None:
|
||||
_REGISTRY.clear()
|
||||
|
||||
|
||||
def sync_placeholders_to_db() -> int:
|
||||
if not _REGISTRY:
|
||||
print("[placeholder_registry] Keine Placeholder registriert — Sync übersprungen")
|
||||
return 0
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
for reg in _REGISTRY:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO placeholder_definitions (
|
||||
placeholder_key, context_kind, value_type, description,
|
||||
required, source, is_active
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, TRUE)
|
||||
ON CONFLICT (placeholder_key, context_kind) DO UPDATE SET
|
||||
value_type = EXCLUDED.value_type,
|
||||
description = EXCLUDED.description,
|
||||
required = EXCLUDED.required,
|
||||
source = EXCLUDED.source,
|
||||
is_active = TRUE,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
reg.placeholder_key,
|
||||
reg.context_kind,
|
||||
reg.value_type,
|
||||
reg.description,
|
||||
reg.required,
|
||||
reg.source,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
print(f"[placeholder_registry] Sync OK — {len(_REGISTRY)} Placeholder(s)")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
print(f"[placeholder_registry] Sync FAIL: {exc}")
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def load_placeholders_for_context(context_kind: str) -> list[dict]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT placeholder_key, value_type, description, required, source
|
||||
FROM placeholder_definitions
|
||||
WHERE context_kind = %s AND is_active = TRUE
|
||||
ORDER BY placeholder_key
|
||||
""",
|
||||
(context_kind,),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"placeholder_key": row[0],
|
||||
"value_type": row[1],
|
||||
"description": row[2],
|
||||
"required": row[3],
|
||||
"source": row[4],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Build placeholder value maps from TenantContext."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from tenant_context import TenantContext
|
||||
|
||||
|
||||
def build_tenant_context_values(ctx: TenantContext) -> dict[str, Any]:
|
||||
return {
|
||||
"tenant_name": ctx.tenant_name or "",
|
||||
"tenant_id": ctx.tenant_id or "",
|
||||
"actor_name": ctx.display_name,
|
||||
"actor_id": ctx.actor_id or "",
|
||||
"actor_type": ctx.actor_type or "",
|
||||
"portal_role": ctx.portal_role,
|
||||
"tenant_role": ctx.tenant_role or "",
|
||||
"capabilities": sorted(ctx.capabilities),
|
||||
}
|
||||
|
||||
|
||||
def build_actor_context_values(ctx: TenantContext) -> dict[str, Any]:
|
||||
return {
|
||||
"actor_id": ctx.actor_id or "",
|
||||
"actor_type": ctx.actor_type or "",
|
||||
"tenant_id": ctx.tenant_id or "",
|
||||
}
|
||||
|
||||
|
||||
def merge_context_values(ctx: TenantContext, context_kind: str, extra: dict[str, Any]) -> dict[str, Any]:
|
||||
base: dict[str, Any] = {}
|
||||
if context_kind == "kairo.tenant_context":
|
||||
base = build_tenant_context_values(ctx)
|
||||
elif context_kind == "kairo.actor_context":
|
||||
base = build_actor_context_values(ctx)
|
||||
merged = {**base, **extra}
|
||||
for key, value in merged.items():
|
||||
if key == "capabilities" and isinstance(value, list):
|
||||
merged[key] = value
|
||||
elif isinstance(value, (dict, list)) and key != "capabilities":
|
||||
continue
|
||||
return merged
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Side-effect imports for prompt registrations."""
|
||||
|
||||
from prompt_registrations import debug, platform # noqa: F401
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Debug prompts for actor context kind."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prompt_registry import PromptRegistration, PromptVersionRegistration, register_prompt
|
||||
|
||||
register_prompt(
|
||||
PromptRegistration(
|
||||
prompt_key="kairo.actor.debug_summary",
|
||||
name="Actor Context Debug",
|
||||
purpose="Minimaler Prompt für kairo.actor_context",
|
||||
context_kind="kairo.actor_context",
|
||||
execution_mode="single",
|
||||
active_version="1.0.0",
|
||||
versions=(
|
||||
PromptVersionRegistration(
|
||||
version="1.0.0",
|
||||
body="Actor {{actor_id}} ({{actor_type}}) in tenant {{tenant_id}}.",
|
||||
changelog="Actor context smoke",
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Technical smoke-test prompts — no product logic."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prompt_registry import (
|
||||
PromptRegistration,
|
||||
PromptStepRegistration,
|
||||
PromptVersionRegistration,
|
||||
register_prompt,
|
||||
)
|
||||
|
||||
register_prompt(
|
||||
PromptRegistration(
|
||||
prompt_key="kairo.system.health_summary",
|
||||
name="System Health Summary",
|
||||
purpose="Smoke-Test für Registry, Versionierung und Rendering",
|
||||
context_kind="kairo.debug_context",
|
||||
execution_mode="single",
|
||||
active_version="1.0.0",
|
||||
versions=(
|
||||
PromptVersionRegistration(
|
||||
version="1.0.0",
|
||||
body="",
|
||||
changelog="Initial smoke prompt",
|
||||
steps=(
|
||||
PromptStepRegistration(
|
||||
step_key="summary",
|
||||
step_order=0,
|
||||
step_type="template",
|
||||
template_body=(
|
||||
"Kairo Systemstatus: {{debug_message}} "
|
||||
"(Level: {{debug_level}})"
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
register_prompt(
|
||||
PromptRegistration(
|
||||
prompt_key="kairo.context.debug_summary",
|
||||
name="Tenant Context Debug Summary",
|
||||
purpose="Smoke-Test für TenantContext-Placeholder",
|
||||
context_kind="kairo.tenant_context",
|
||||
execution_mode="single",
|
||||
active_version="1.0.0",
|
||||
versions=(
|
||||
PromptVersionRegistration(
|
||||
version="1.0.0",
|
||||
body=(
|
||||
"Tenant {{tenant_name}} ({{tenant_id}}): "
|
||||
"Portal={{portal_role}}, Tenant-Rolle={{tenant_role}}, "
|
||||
"Actor={{actor_id}} ({{actor_type}})."
|
||||
),
|
||||
changelog="Initial tenant context prompt",
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
# Pipeline/workflow structural sample — not executed in AP0.4
|
||||
register_prompt(
|
||||
PromptRegistration(
|
||||
prompt_key="kairo.pipeline.placeholder",
|
||||
name="Pipeline Placeholder",
|
||||
purpose="Strukturelle Vorbereitung für pipeline execution_mode",
|
||||
context_kind="kairo.debug_context",
|
||||
execution_mode="pipeline",
|
||||
active_version="0.1.0",
|
||||
versions=(
|
||||
PromptVersionRegistration(
|
||||
version="0.1.0",
|
||||
body="Pipeline placeholder: {{debug_message}}",
|
||||
changelog="Not executed in AP0.4",
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,310 @@
|
||||
"""Prompt definition registry with versioning and optional steps."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
|
||||
from db import get_connection
|
||||
from feature_registry import VALID_CONTEXT_KINDS, VALID_EXECUTION_MODES
|
||||
|
||||
VALID_STEP_TYPES = frozenset(
|
||||
{"template", "resolver", "llm_call", "postprocess", "validation"}
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromptStepRegistration:
|
||||
step_key: str
|
||||
step_order: int
|
||||
step_type: str
|
||||
template_body: str
|
||||
input_mapping: dict | None = None
|
||||
output_mapping: dict | None = None
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromptVersionRegistration:
|
||||
version: str
|
||||
body: str
|
||||
input_schema: dict | None = None
|
||||
output_schema: dict | None = None
|
||||
model_policy_key: str | None = None
|
||||
changelog: str = ""
|
||||
steps: tuple[PromptStepRegistration, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromptRegistration:
|
||||
prompt_key: str
|
||||
name: str
|
||||
purpose: str
|
||||
context_kind: str
|
||||
execution_mode: str
|
||||
active_version: str
|
||||
versions: tuple[PromptVersionRegistration, ...]
|
||||
|
||||
|
||||
_REGISTRY: dict[str, PromptRegistration] = {}
|
||||
|
||||
|
||||
def register_prompt(registration: PromptRegistration) -> None:
|
||||
if not registration.prompt_key or not registration.prompt_key.strip():
|
||||
raise ValueError("Prompt key is required")
|
||||
if registration.context_kind not in VALID_CONTEXT_KINDS:
|
||||
raise ValueError(f"Unknown context_kind: {registration.context_kind}")
|
||||
if registration.execution_mode not in VALID_EXECUTION_MODES:
|
||||
raise ValueError(f"Unknown execution_mode: {registration.execution_mode}")
|
||||
if not registration.versions:
|
||||
raise ValueError("At least one prompt version is required")
|
||||
version_ids = {v.version for v in registration.versions}
|
||||
if registration.active_version not in version_ids:
|
||||
raise ValueError(f"active_version not found in versions: {registration.active_version}")
|
||||
for step in _iter_steps(registration):
|
||||
if step.step_type not in VALID_STEP_TYPES:
|
||||
raise ValueError(f"Unknown step_type: {step.step_type}")
|
||||
if registration.prompt_key in _REGISTRY:
|
||||
raise ValueError(f"Prompt already registered: {registration.prompt_key}")
|
||||
_REGISTRY[registration.prompt_key] = registration
|
||||
|
||||
|
||||
def _iter_steps(registration: PromptRegistration):
|
||||
for version in registration.versions:
|
||||
yield from version.steps
|
||||
|
||||
|
||||
def get_registered_prompts() -> tuple[PromptRegistration, ...]:
|
||||
return tuple(_REGISTRY.values())
|
||||
|
||||
|
||||
def clear_prompt_registry_for_tests() -> None:
|
||||
_REGISTRY.clear()
|
||||
|
||||
|
||||
def sync_prompts_to_db() -> int:
|
||||
if not _REGISTRY:
|
||||
print("[prompt_registry] Keine Prompts registriert — Sync übersprungen")
|
||||
return 0
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
for reg in _REGISTRY.values():
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO prompt_definitions (
|
||||
prompt_key, name, purpose, context_kind, execution_mode, status
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, 'active')
|
||||
ON CONFLICT (prompt_key) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
purpose = EXCLUDED.purpose,
|
||||
context_kind = EXCLUDED.context_kind,
|
||||
execution_mode = EXCLUDED.execution_mode,
|
||||
status = 'active',
|
||||
updated_at = NOW()
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
reg.prompt_key,
|
||||
reg.name,
|
||||
reg.purpose,
|
||||
reg.context_kind,
|
||||
reg.execution_mode,
|
||||
),
|
||||
)
|
||||
definition_id = cur.fetchone()[0]
|
||||
|
||||
active_version_id = None
|
||||
for version in reg.versions:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO prompt_versions (
|
||||
prompt_definition_id, version, body,
|
||||
input_schema, output_schema, model_policy_key, changelog
|
||||
)
|
||||
VALUES (%s, %s, %s, %s::jsonb, %s::jsonb, %s, %s)
|
||||
ON CONFLICT (prompt_definition_id, version) DO UPDATE SET
|
||||
body = EXCLUDED.body,
|
||||
input_schema = EXCLUDED.input_schema,
|
||||
output_schema = EXCLUDED.output_schema,
|
||||
model_policy_key = EXCLUDED.model_policy_key,
|
||||
changelog = EXCLUDED.changelog
|
||||
RETURNING id
|
||||
""",
|
||||
(
|
||||
definition_id,
|
||||
version.version,
|
||||
version.body,
|
||||
json.dumps(version.input_schema) if version.input_schema else None,
|
||||
json.dumps(version.output_schema) if version.output_schema else None,
|
||||
version.model_policy_key,
|
||||
version.changelog,
|
||||
),
|
||||
)
|
||||
version_id = cur.fetchone()[0]
|
||||
if version.version == reg.active_version:
|
||||
active_version_id = version_id
|
||||
|
||||
for step in version.steps:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO prompt_steps (
|
||||
prompt_version_id, step_key, step_order, step_type,
|
||||
template_body, input_mapping, output_mapping, enabled
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s::jsonb, %s)
|
||||
ON CONFLICT (prompt_version_id, step_key) DO UPDATE SET
|
||||
step_order = EXCLUDED.step_order,
|
||||
step_type = EXCLUDED.step_type,
|
||||
template_body = EXCLUDED.template_body,
|
||||
input_mapping = EXCLUDED.input_mapping,
|
||||
output_mapping = EXCLUDED.output_mapping,
|
||||
enabled = EXCLUDED.enabled,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(
|
||||
version_id,
|
||||
step.step_key,
|
||||
step.step_order,
|
||||
step.step_type,
|
||||
step.template_body,
|
||||
json.dumps(step.input_mapping) if step.input_mapping else None,
|
||||
json.dumps(step.output_mapping) if step.output_mapping else None,
|
||||
step.enabled,
|
||||
),
|
||||
)
|
||||
|
||||
if active_version_id:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE prompt_definitions
|
||||
SET active_version_id = %s, updated_at = NOW()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(active_version_id, definition_id),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
print(f"[prompt_registry] Sync OK — {len(_REGISTRY)} Prompt(s)")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
print(f"[prompt_registry] Sync FAIL: {exc}")
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def load_prompt_definition(prompt_key: str) -> dict | None:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, prompt_key, name, purpose, context_kind, execution_mode,
|
||||
status, active_version_id
|
||||
FROM prompt_definitions
|
||||
WHERE prompt_key = %s
|
||||
""",
|
||||
(prompt_key,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"id": str(row[0]),
|
||||
"prompt_key": row[1],
|
||||
"name": row[2],
|
||||
"purpose": row[3],
|
||||
"context_kind": row[4],
|
||||
"execution_mode": row[5],
|
||||
"status": row[6],
|
||||
"active_version_id": str(row[7]) if row[7] else None,
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def load_active_prompt_version(definition: dict) -> dict | None:
|
||||
version_id = definition.get("active_version_id")
|
||||
if not version_id:
|
||||
return None
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, version, body, input_schema, output_schema, model_policy_key
|
||||
FROM prompt_versions
|
||||
WHERE id = %s
|
||||
""",
|
||||
(version_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"id": str(row[0]),
|
||||
"version": row[1],
|
||||
"body": row[2],
|
||||
"input_schema": row[3],
|
||||
"output_schema": row[4],
|
||||
"model_policy_key": row[5],
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def load_template_steps(version_id: str) -> list[dict]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT step_key, step_order, step_type, template_body, enabled
|
||||
FROM prompt_steps
|
||||
WHERE prompt_version_id = %s AND enabled = TRUE
|
||||
ORDER BY step_order, step_key
|
||||
""",
|
||||
(version_id,),
|
||||
)
|
||||
return [
|
||||
{
|
||||
"step_key": row[0],
|
||||
"step_order": row[1],
|
||||
"step_type": row[2],
|
||||
"template_body": row[3],
|
||||
"enabled": row[4],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_prompt_definitions() -> list[dict]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT prompt_key, name, purpose, context_kind, execution_mode, status
|
||||
FROM prompt_definitions
|
||||
ORDER BY prompt_key
|
||||
"""
|
||||
)
|
||||
return [
|
||||
{
|
||||
"prompt_key": row[0],
|
||||
"name": row[1],
|
||||
"purpose": row[2],
|
||||
"context_kind": row[3],
|
||||
"execution_mode": row[4],
|
||||
"status": row[5],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Single-mode prompt rendering without LLM execution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from db import get_connection
|
||||
from prompt_registry import load_active_prompt_version, load_prompt_definition, load_template_steps
|
||||
from prompt_validation import PLACEHOLDER_PATTERN, PlaceholderValidationError, validate_placeholder_input
|
||||
from services.audit import log_audit
|
||||
|
||||
PLACEHOLDER_SUB = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")
|
||||
|
||||
|
||||
class PromptRenderError(Exception):
|
||||
def __init__(self, message: str, *, code: str = "render_error"):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def _render_template(template: str, values: dict[str, Any]) -> str:
|
||||
def replacer(match: re.Match[str]) -> str:
|
||||
key = match.group(1)
|
||||
if key not in values:
|
||||
return match.group(0)
|
||||
value = values[key]
|
||||
if isinstance(value, (dict, list)):
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
return str(value)
|
||||
|
||||
return PLACEHOLDER_SUB.sub(replacer, template)
|
||||
|
||||
|
||||
def _resolve_template_body(version: dict) -> tuple[str, str]:
|
||||
"""Return (template_body, source) where source is 'body' or 'step'."""
|
||||
steps = load_template_steps(version["id"])
|
||||
template_steps = [s for s in steps if s["step_type"] == "template" and s["template_body"]]
|
||||
if template_steps:
|
||||
step = template_steps[0]
|
||||
return step["template_body"], f"step:{step['step_key']}"
|
||||
if version.get("body"):
|
||||
return version["body"], "body"
|
||||
raise PromptRenderError("No template body or template step found", code="no_template")
|
||||
|
||||
|
||||
def _write_execution_log(
|
||||
*,
|
||||
definition: dict,
|
||||
version: dict,
|
||||
status: str,
|
||||
rendered_preview: str | None,
|
||||
input_summary: dict | None,
|
||||
error_message: str | None,
|
||||
user_id: str | None,
|
||||
) -> None:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO prompt_execution_logs (
|
||||
prompt_definition_id, prompt_version_id, execution_mode,
|
||||
status, rendered_preview, input_summary, error_message, created_by
|
||||
)
|
||||
VALUES (%s::uuid, %s::uuid, %s, %s, %s, %s::jsonb, %s, %s::uuid)
|
||||
""",
|
||||
(
|
||||
definition["id"],
|
||||
version["id"],
|
||||
definition["execution_mode"],
|
||||
status,
|
||||
rendered_preview,
|
||||
json.dumps(input_summary) if input_summary else None,
|
||||
error_message,
|
||||
user_id,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def render_prompt_single(
|
||||
prompt_key: str,
|
||||
*,
|
||||
values: dict[str, Any],
|
||||
user_id: str | None = None,
|
||||
log_execution: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
definition = load_prompt_definition(prompt_key)
|
||||
if not definition:
|
||||
raise PromptRenderError(f"Unknown prompt: {prompt_key}", code="not_found")
|
||||
if definition["status"] != "active":
|
||||
raise PromptRenderError(f"Prompt not active: {prompt_key}", code="inactive")
|
||||
|
||||
execution_mode = definition["execution_mode"]
|
||||
if execution_mode in ("pipeline", "workflow"):
|
||||
raise PromptRenderError(
|
||||
f"execution_mode '{execution_mode}' is not implemented in AP0.4",
|
||||
code="mode_not_implemented",
|
||||
)
|
||||
|
||||
version = load_active_prompt_version(definition)
|
||||
if not version:
|
||||
raise PromptRenderError("No active prompt version", code="no_version")
|
||||
|
||||
template_body, template_source = _resolve_template_body(version)
|
||||
|
||||
try:
|
||||
validation = validate_placeholder_input(
|
||||
template=template_body,
|
||||
context_kind=definition["context_kind"],
|
||||
values=values,
|
||||
)
|
||||
rendered = _render_template(template_body, values)
|
||||
result = {
|
||||
"prompt_key": prompt_key,
|
||||
"version": version["version"],
|
||||
"execution_mode": execution_mode,
|
||||
"template_source": template_source,
|
||||
"rendered_text": rendered,
|
||||
"validation": validation,
|
||||
}
|
||||
if log_execution:
|
||||
_write_execution_log(
|
||||
definition=definition,
|
||||
version=version,
|
||||
status="success",
|
||||
rendered_preview=rendered[:2000],
|
||||
input_summary={"keys": sorted(values.keys())},
|
||||
error_message=None,
|
||||
user_id=user_id,
|
||||
)
|
||||
return result
|
||||
except PlaceholderValidationError as exc:
|
||||
if log_execution:
|
||||
_write_execution_log(
|
||||
definition=definition,
|
||||
version=version,
|
||||
status="error",
|
||||
rendered_preview=None,
|
||||
input_summary={"keys": sorted(values.keys())},
|
||||
error_message=str(exc),
|
||||
user_id=user_id,
|
||||
)
|
||||
log_audit(
|
||||
"prompt.render.failed",
|
||||
user_id=user_id,
|
||||
details={
|
||||
"prompt_key": prompt_key,
|
||||
"missing": exc.missing,
|
||||
"type_errors": exc.type_errors,
|
||||
"unknown": exc.unknown,
|
||||
},
|
||||
)
|
||||
raise PromptRenderError(str(exc), code="validation_failed") from exc
|
||||
except PromptRenderError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if log_execution:
|
||||
_write_execution_log(
|
||||
definition=definition,
|
||||
version=version,
|
||||
status="error",
|
||||
rendered_preview=None,
|
||||
input_summary={"keys": sorted(values.keys())},
|
||||
error_message=str(exc),
|
||||
user_id=user_id,
|
||||
)
|
||||
raise PromptRenderError(str(exc), code="render_error") from exc
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Placeholder extraction and validation for prompt templates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from placeholder_registry import load_placeholders_for_context
|
||||
|
||||
PLACEHOLDER_PATTERN = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")
|
||||
|
||||
|
||||
class PlaceholderValidationError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
missing: list[str] | None = None,
|
||||
type_errors: list[str] | None = None,
|
||||
unknown: list[str] | None = None,
|
||||
):
|
||||
super().__init__(message)
|
||||
self.missing = missing or []
|
||||
self.type_errors = type_errors or []
|
||||
self.unknown = unknown or []
|
||||
|
||||
|
||||
def extract_placeholders(template: str) -> set[str]:
|
||||
return set(PLACEHOLDER_PATTERN.findall(template))
|
||||
|
||||
|
||||
def _check_value_type(value: Any, value_type: str) -> bool:
|
||||
if value_type == "string":
|
||||
return isinstance(value, str)
|
||||
if value_type == "number":
|
||||
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||
if value_type == "boolean":
|
||||
return isinstance(value, bool)
|
||||
if value_type == "object":
|
||||
return isinstance(value, dict)
|
||||
if value_type == "array":
|
||||
return isinstance(value, list)
|
||||
if value_type == "json":
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def validate_placeholder_input(
|
||||
*,
|
||||
template: str,
|
||||
context_kind: str,
|
||||
values: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Validate input values against registry; return metadata including unknown placeholders."""
|
||||
registry = {p["placeholder_key"]: p for p in load_placeholders_for_context(context_kind)}
|
||||
used = extract_placeholders(template)
|
||||
missing: list[str] = []
|
||||
type_errors: list[str] = []
|
||||
unknown = sorted(key for key in used if key not in registry)
|
||||
|
||||
for key, meta in registry.items():
|
||||
if meta["required"] and key not in values:
|
||||
missing.append(key)
|
||||
if key in values and not _check_value_type(values[key], meta["value_type"]):
|
||||
type_errors.append(f"{key}: expected {meta['value_type']}")
|
||||
|
||||
if missing or type_errors:
|
||||
raise PlaceholderValidationError(
|
||||
"Placeholder validation failed",
|
||||
missing=missing,
|
||||
type_errors=type_errors,
|
||||
unknown=unknown,
|
||||
)
|
||||
|
||||
return {
|
||||
"used_placeholders": sorted(used),
|
||||
"unknown_placeholders": unknown,
|
||||
"optional_missing": sorted(
|
||||
key for key in registry if not registry[key]["required"] and key not in values
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
-r requirements.txt
|
||||
pytest==8.3.4
|
||||
httpx==0.27.2
|
||||
@@ -0,0 +1,7 @@
|
||||
fastapi==0.111.0
|
||||
uvicorn[standard]==0.29.0
|
||||
psycopg2-binary==2.9.9
|
||||
sqlparse>=0.5.0
|
||||
pydantic==2.7.1
|
||||
email-validator>=2.1.0
|
||||
bcrypt>=4.1.0
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Import all module registrations — side effect registers capabilities."""
|
||||
|
||||
from . import platform, registry_ops, tenant_ops # noqa: F401
|
||||
|
||||
__all__ = ["platform", "registry_ops", "tenant_ops"]
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Platform-level Kairo capabilities."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from rights_registry import CapabilityRegistration, register_capability
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.admin.access",
|
||||
module="platform",
|
||||
description="Zugriff auf Portal-Administration und Admin-Endpunkte",
|
||||
default_grants=(("portal", "admin"),),
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.context.read",
|
||||
module="platform",
|
||||
description="TenantContext und Session-Kontext lesen",
|
||||
default_grants=(
|
||||
("portal", "admin"),
|
||||
("portal", "user"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
("tenant", "member"),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.entitlements.read",
|
||||
module="platform",
|
||||
description="Entitlements-Snapshot lesen",
|
||||
default_grants=(
|
||||
("portal", "admin"),
|
||||
("portal", "user"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
("tenant", "member"),
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""AP0.4 registry and prompt capabilities."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from rights_registry import CapabilityRegistration, register_capability
|
||||
|
||||
_TENANT_READ = (
|
||||
("portal", "admin"),
|
||||
("portal", "user"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
("tenant", "member"),
|
||||
)
|
||||
|
||||
_TENANT_ADMIN = (
|
||||
("portal", "admin"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.feature.registry.read",
|
||||
module="feature",
|
||||
description="Feature Registry lesen",
|
||||
default_grants=_TENANT_READ,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.feature.registry.manage",
|
||||
module="feature",
|
||||
description="Feature Registry verwalten (Sync/Metadaten)",
|
||||
default_grants=(("portal", "admin"),),
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.prompt.registry.read",
|
||||
module="prompt",
|
||||
description="Prompt Registry lesen",
|
||||
default_grants=_TENANT_READ,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.prompt.registry.manage",
|
||||
module="prompt",
|
||||
description="Prompt Registry verwalten",
|
||||
default_grants=(("portal", "admin"),),
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.config.registry.read",
|
||||
module="config",
|
||||
description="Configuration Registry lesen",
|
||||
default_grants=_TENANT_ADMIN,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.config.registry.manage",
|
||||
module="config",
|
||||
description="Configuration Registry schreiben",
|
||||
default_grants=_TENANT_ADMIN,
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.prompt.render",
|
||||
module="prompt",
|
||||
description="Prompts rendern (ohne LLM)",
|
||||
default_grants=_TENANT_READ,
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Tenant and actor management capabilities."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from rights_registry import CapabilityRegistration, register_capability
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.tenant.manage",
|
||||
module="tenant",
|
||||
description="Tenant-Einstellungen und Mandantenverwaltung",
|
||||
default_grants=(
|
||||
("portal", "admin"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
register_capability(
|
||||
CapabilityRegistration(
|
||||
key="kairo.actor.manage",
|
||||
module="tenant",
|
||||
description="Actors im aktiven Tenant verwalten",
|
||||
default_grants=(
|
||||
("portal", "admin"),
|
||||
("tenant", "owner"),
|
||||
("tenant", "admin"),
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""In-memory capability registry with startup sync to PostgreSQL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from db import get_connection
|
||||
|
||||
RoleGrant = tuple[str, str] # (role_scope, role_code)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapabilityRegistration:
|
||||
key: str
|
||||
module: str
|
||||
description: str
|
||||
default_grants: tuple[RoleGrant, ...] = ()
|
||||
|
||||
|
||||
_REGISTRY: dict[str, CapabilityRegistration] = {}
|
||||
|
||||
|
||||
def register_capability(registration: CapabilityRegistration) -> None:
|
||||
if not registration.key or not registration.key.strip():
|
||||
raise ValueError("Capability key is required")
|
||||
if not registration.module or not registration.module.strip():
|
||||
raise ValueError("Capability module is required")
|
||||
if not registration.description or not registration.description.strip():
|
||||
raise ValueError("Capability description is required")
|
||||
if registration.key in _REGISTRY:
|
||||
raise ValueError(f"Capability already registered: {registration.key}")
|
||||
_REGISTRY[registration.key] = registration
|
||||
|
||||
|
||||
def get_registered_capabilities() -> tuple[CapabilityRegistration, ...]:
|
||||
return tuple(_REGISTRY.values())
|
||||
|
||||
|
||||
def clear_registry_for_tests() -> None:
|
||||
"""Test helper — reset in-memory registry."""
|
||||
_REGISTRY.clear()
|
||||
|
||||
|
||||
def sync_rights_registry_to_db() -> int:
|
||||
"""Upsert capabilities and ensure default grants from registry."""
|
||||
if not _REGISTRY:
|
||||
print("[rights_registry] Keine Capabilities registriert — Sync übersprungen")
|
||||
return 0
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
for reg in _REGISTRY.values():
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO capabilities (capability_key, module, description, is_active)
|
||||
VALUES (%s, %s, %s, TRUE)
|
||||
ON CONFLICT (capability_key) DO UPDATE SET
|
||||
module = EXCLUDED.module,
|
||||
description = EXCLUDED.description,
|
||||
is_active = TRUE,
|
||||
updated_at = NOW()
|
||||
""",
|
||||
(reg.key, reg.module, reg.description),
|
||||
)
|
||||
for role_scope, role_code in reg.default_grants:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO role_capability_grants (role_scope, role_code, capability_key)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (role_scope, role_code, capability_key) DO NOTHING
|
||||
""",
|
||||
(role_scope, role_code, reg.key),
|
||||
)
|
||||
conn.commit()
|
||||
print(f"[rights_registry] Sync OK — {len(_REGISTRY)} Capability(s)")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
print(f"[rights_registry] Sync FAIL: {exc}")
|
||||
return 1
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def load_grants_for_roles(
|
||||
*,
|
||||
portal_role: str,
|
||||
tenant_role: str | None,
|
||||
) -> set[str]:
|
||||
"""Resolve capability keys granted by portal and optional tenant role."""
|
||||
conn = get_connection()
|
||||
try:
|
||||
keys: set[str] = set()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT c.capability_key
|
||||
FROM role_capability_grants g
|
||||
JOIN capabilities c ON c.capability_key = g.capability_key
|
||||
WHERE g.role_scope = 'portal'
|
||||
AND g.role_code = %s
|
||||
AND c.is_active = TRUE
|
||||
""",
|
||||
(portal_role,),
|
||||
)
|
||||
keys.update(row[0] for row in cur.fetchall())
|
||||
|
||||
if tenant_role:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT c.capability_key
|
||||
FROM role_capability_grants g
|
||||
JOIN capabilities c ON c.capability_key = g.capability_key
|
||||
WHERE g.role_scope = 'tenant'
|
||||
AND g.role_code = %s
|
||||
AND c.is_active = TRUE
|
||||
""",
|
||||
(tenant_role,),
|
||||
)
|
||||
keys.update(row[0] for row in cur.fetchall())
|
||||
return keys
|
||||
finally:
|
||||
conn.close()
|
||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
||||
"""Auth endpoints: login, logout, registration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from auth import login, logout, require_auth
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
from services.registration import register_system_admin, setup_status
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: str = Field(min_length=3, max_length=255)
|
||||
password: str = Field(min_length=8, max_length=256)
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
email: str = Field(min_length=3, max_length=255)
|
||||
password: str = Field(min_length=8, max_length=256)
|
||||
display_name: str = Field(min_length=1, max_length=255)
|
||||
organization_name: str | None = Field(default=None, max_length=255)
|
||||
|
||||
|
||||
@router.get("/setup-status")
|
||||
def auth_setup_status():
|
||||
return setup_status()
|
||||
|
||||
|
||||
@router.post("/register")
|
||||
def auth_register(body: RegisterRequest):
|
||||
"""Erster User wird Portal-Systemadmin inkl. Default-Tenant."""
|
||||
return register_system_admin(
|
||||
email=body.email,
|
||||
password=body.password,
|
||||
display_name=body.display_name,
|
||||
organization_name=body.organization_name,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def auth_login(body: LoginRequest):
|
||||
return login(body.email, body.password)
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def auth_logout(session: dict = Depends(require_auth)):
|
||||
token = session.get("token")
|
||||
if token:
|
||||
logout(token)
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Configuration registry API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from capabilities import require_capability_ctx
|
||||
from config_service import SECRET_VALUE_FORBIDDEN, list_configs, upsert_config
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/config", tags=["config"])
|
||||
|
||||
|
||||
class ConfigUpsertRequest(BaseModel):
|
||||
config_key: str
|
||||
scope: str = "global"
|
||||
value: Any = None
|
||||
value_type: str = "string"
|
||||
description: str = ""
|
||||
is_secret: bool = False
|
||||
tenant_id: str | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def get_configs(
|
||||
scope: str | None = None,
|
||||
ctx: TenantContext = Depends(require_capability_ctx("kairo.config.registry.read")),
|
||||
):
|
||||
tenant_id = ctx.tenant_id if scope == "tenant" else None
|
||||
if scope == "tenant" and not tenant_id:
|
||||
raise HTTPException(status_code=400, detail="Aktiver Tenant erforderlich für tenant-scope")
|
||||
return list_configs(scope=scope, tenant_id=tenant_id)
|
||||
|
||||
|
||||
@router.post("")
|
||||
def post_config(
|
||||
body: ConfigUpsertRequest,
|
||||
ctx: TenantContext = Depends(require_capability_ctx("kairo.config.registry.manage")),
|
||||
):
|
||||
tenant_id = body.tenant_id
|
||||
if body.scope == "tenant":
|
||||
tenant_id = tenant_id or ctx.tenant_id
|
||||
if not tenant_id:
|
||||
raise HTTPException(status_code=400, detail="tenant_id erforderlich")
|
||||
try:
|
||||
return upsert_config(
|
||||
config_key=body.config_key,
|
||||
scope=body.scope,
|
||||
value=body.value,
|
||||
value_type=body.value_type,
|
||||
description=body.description,
|
||||
is_secret=body.is_secret,
|
||||
tenant_id=tenant_id,
|
||||
user_id=ctx.user_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
if str(exc) == SECRET_VALUE_FORBIDDEN:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Feature registry API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from capabilities import require_capability_ctx
|
||||
from db import get_connection
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
router = APIRouter(prefix="/api/features", tags=["features"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_features(_ctx=Depends(require_capability_ctx("kairo.feature.registry.read"))):
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT feature_key, module, name, description, is_active
|
||||
FROM features
|
||||
ORDER BY feature_key
|
||||
"""
|
||||
)
|
||||
return [
|
||||
{
|
||||
"feature_key": row[0],
|
||||
"module": row[1],
|
||||
"name": row[2],
|
||||
"description": row[3],
|
||||
"is_active": row[4],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Current user, tenant context and entitlements endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from auth import get_session, require_auth, set_session_active_tenant
|
||||
from capabilities import require_capability
|
||||
from entitlements import build_entitlements_snapshot
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from tenant_context import TenantContext, get_tenant_context, list_user_tenants, require_tenant_context, resolve_tenant_context
|
||||
|
||||
router = APIRouter(prefix="/api/me", tags=["me"])
|
||||
|
||||
|
||||
class SwitchTenantRequest(BaseModel):
|
||||
tenant_id: str
|
||||
|
||||
|
||||
@router.get("")
|
||||
def get_me(session: dict = Depends(require_auth)):
|
||||
tenants = list_user_tenants(str(session["user_id"]))
|
||||
return {
|
||||
"id": str(session["user_id"]),
|
||||
"email": session["email"],
|
||||
"display_name": session["display_name"],
|
||||
"portal_role": session["portal_role"],
|
||||
"active_tenant_id": str(session["active_tenant_id"]) if session.get("active_tenant_id") else None,
|
||||
"tenants": tenants,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/context")
|
||||
def get_my_context(ctx: TenantContext = Depends(get_tenant_context)):
|
||||
return ctx.to_dict()
|
||||
|
||||
|
||||
@router.get("/context/required")
|
||||
def get_my_context_with_tenant(ctx: TenantContext = Depends(require_tenant_context)):
|
||||
"""Endpoint requiring an active tenant."""
|
||||
return ctx.to_dict()
|
||||
|
||||
|
||||
@router.get("/entitlements")
|
||||
def get_my_entitlements(ctx: TenantContext = Depends(get_tenant_context)):
|
||||
return build_entitlements_snapshot(ctx)
|
||||
|
||||
|
||||
@router.get("/admin/demo")
|
||||
def admin_demo(ctx: TenantContext = Depends(require_capability("kairo.admin.access"))):
|
||||
"""Example endpoint protected by require_capability."""
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "Portal-Admin Capability bestätigt",
|
||||
"user_id": ctx.user_id,
|
||||
"tenant_id": ctx.tenant_id,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/tenant")
|
||||
def switch_tenant(body: SwitchTenantRequest, session: dict = Depends(require_auth)):
|
||||
ok = set_session_active_tenant(session["token"], body.tenant_id)
|
||||
if not ok:
|
||||
raise HTTPException(status_code=403, detail="Tenant nicht erlaubt")
|
||||
fresh = get_session(session["token"])
|
||||
if not fresh:
|
||||
raise HTTPException(status_code=401, detail="Session ungültig")
|
||||
return resolve_tenant_context(fresh).to_dict()
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Prompt registry and rendering API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from capabilities import require_capability_ctx
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from prompt_context import merge_context_values
|
||||
from prompt_registry import list_prompt_definitions, load_active_prompt_version, load_prompt_definition
|
||||
from prompt_rendering import PromptRenderError, render_prompt_single
|
||||
from pydantic import BaseModel, Field
|
||||
from tenant_context import TenantContext
|
||||
|
||||
router = APIRouter(prefix="/api/prompts", tags=["prompts"])
|
||||
|
||||
|
||||
class RenderPromptRequest(BaseModel):
|
||||
values: dict[str, Any] = Field(default_factory=dict)
|
||||
use_context: bool = True
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_prompts(_ctx=Depends(require_capability_ctx("kairo.prompt.registry.read"))):
|
||||
return list_prompt_definitions()
|
||||
|
||||
|
||||
@router.get("/{prompt_key}")
|
||||
def get_prompt(prompt_key: str, _ctx=Depends(require_capability_ctx("kairo.prompt.registry.read"))):
|
||||
definition = load_prompt_definition(prompt_key)
|
||||
if not definition:
|
||||
raise HTTPException(status_code=404, detail="Prompt nicht gefunden")
|
||||
version = load_active_prompt_version(definition)
|
||||
return {
|
||||
"definition": definition,
|
||||
"active_version": version,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{prompt_key}/render")
|
||||
def render_prompt(
|
||||
prompt_key: str,
|
||||
body: RenderPromptRequest,
|
||||
ctx: TenantContext = Depends(require_capability_ctx("kairo.prompt.render")),
|
||||
):
|
||||
definition = load_prompt_definition(prompt_key)
|
||||
if not definition:
|
||||
raise HTTPException(status_code=404, detail="Prompt nicht gefunden")
|
||||
|
||||
if body.use_context and definition["context_kind"] in (
|
||||
"kairo.tenant_context",
|
||||
"kairo.actor_context",
|
||||
):
|
||||
if not ctx.tenant_id:
|
||||
raise HTTPException(status_code=403, detail="Aktiver Tenant erforderlich für diesen Prompt")
|
||||
|
||||
values = body.values
|
||||
if body.use_context:
|
||||
values = merge_context_values(ctx, definition["context_kind"], body.values)
|
||||
|
||||
try:
|
||||
return render_prompt_single(
|
||||
prompt_key,
|
||||
values=values,
|
||||
user_id=ctx.user_id,
|
||||
log_execution=True,
|
||||
)
|
||||
except PromptRenderError as exc:
|
||||
status = 400
|
||||
if exc.code == "not_found":
|
||||
status = 404
|
||||
elif exc.code == "mode_not_implemented":
|
||||
status = 501
|
||||
raise HTTPException(status_code=status, detail=str(exc)) from exc
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply numbered SQL migrations with schema_migrations tracking."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import List, Tuple
|
||||
|
||||
import psycopg2
|
||||
import sqlparse
|
||||
|
||||
from db import check_db, connect_with_retry, db_params, get_connection
|
||||
|
||||
_LEADING_DIGITS = re.compile(r"^(\d+)")
|
||||
|
||||
|
||||
def init_migrations_table(conn) -> None:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
migration VARCHAR(255) UNIQUE NOT NULL,
|
||||
executed_at TIMESTAMP DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _migration_sort_key(stem: str) -> Tuple[int, str]:
|
||||
match = _LEADING_DIGITS.match(stem)
|
||||
return (int(match.group(1)) if match else 0, stem)
|
||||
|
||||
|
||||
def migration_files(migrations_dir: str) -> List[Tuple[str, str]]:
|
||||
rows: List[Tuple[str, str]] = []
|
||||
for filename in os.listdir(migrations_dir):
|
||||
if not filename.endswith(".sql") or not filename[0].isdigit():
|
||||
continue
|
||||
stem = filename[:-4]
|
||||
rows.append((stem, os.path.join(migrations_dir, filename)))
|
||||
rows.sort(key=lambda item: _migration_sort_key(item[0]))
|
||||
return rows
|
||||
|
||||
|
||||
def executed_migrations(conn) -> set[str]:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT migration FROM schema_migrations")
|
||||
return {row[0] for row in cur.fetchall()}
|
||||
|
||||
|
||||
def pending_migrations(conn, migrations_dir: str) -> List[Tuple[str, str]]:
|
||||
done = executed_migrations(conn)
|
||||
return [(name, path) for name, path in migration_files(migrations_dir) if name not in done]
|
||||
|
||||
|
||||
def _split_statements(sql_text: str) -> List[str]:
|
||||
parts = sqlparse.split(sql_text.strip())
|
||||
return [part.strip() for part in parts if part and part.strip()]
|
||||
|
||||
|
||||
def _run_with_psql(filepath: str) -> tuple[bool, str]:
|
||||
psql = shutil.which("psql")
|
||||
if not psql:
|
||||
return False, ""
|
||||
|
||||
p = db_params()
|
||||
env = os.environ.copy()
|
||||
env["PGPASSWORD"] = str(p["password"])
|
||||
cmd = [
|
||||
psql,
|
||||
"-h",
|
||||
p["host"],
|
||||
"-p",
|
||||
str(p["port"]),
|
||||
"-U",
|
||||
p["user"],
|
||||
"-d",
|
||||
p["dbname"],
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-1",
|
||||
"-f",
|
||||
filepath,
|
||||
]
|
||||
proc = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=7200)
|
||||
if proc.returncode != 0:
|
||||
tail = ((proc.stderr or "") + "\n" + (proc.stdout or "")).strip()
|
||||
return False, tail[:8000] or f"exit {proc.returncode}"
|
||||
return True, (proc.stdout or "").strip()
|
||||
|
||||
|
||||
def _record_migration(conn, migration_name: str) -> None:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO schema_migrations (migration)
|
||||
VALUES (%s)
|
||||
ON CONFLICT (migration) DO NOTHING
|
||||
""",
|
||||
(migration_name,),
|
||||
)
|
||||
|
||||
|
||||
def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
||||
print(f"Running migration: {migration_name}")
|
||||
try:
|
||||
if shutil.which("psql"):
|
||||
ok, diag = _run_with_psql(filepath)
|
||||
if not ok:
|
||||
print(f" [FAIL] psql:\n{diag or '(kein Output)'}")
|
||||
conn.rollback()
|
||||
return False
|
||||
else:
|
||||
with open(filepath, "r", encoding="utf-8") as handle:
|
||||
body = handle.read()
|
||||
statements = _split_statements(body)
|
||||
with conn.cursor() as cur:
|
||||
for stmt in statements:
|
||||
cur.execute(stmt)
|
||||
|
||||
_record_migration(conn, migration_name)
|
||||
conn.commit()
|
||||
print(f" [OK] {migration_name}")
|
||||
return True
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
print(f" [FAIL] {migration_name}: {exc}")
|
||||
return False
|
||||
|
||||
|
||||
def migrations_directory() -> str:
|
||||
docker_path = "/app/migrations"
|
||||
if os.path.isdir(docker_path):
|
||||
return docker_path
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "migrations")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print("=" * 60)
|
||||
print("Jinkendo Kairo — Database Migrations")
|
||||
print("=" * 60)
|
||||
|
||||
migrations_dir = migrations_directory()
|
||||
if not os.path.isdir(migrations_dir):
|
||||
print(f"[FAIL] migrations directory missing: {migrations_dir}")
|
||||
return 1
|
||||
|
||||
try:
|
||||
conn = connect_with_retry()
|
||||
init_migrations_table(conn)
|
||||
pending = pending_migrations(conn, migrations_dir)
|
||||
|
||||
if not pending:
|
||||
print("[OK] Keine ausstehenden Migrationen.")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
print(f"{len(pending)} ausstehende Migration(en):")
|
||||
for name, _ in pending:
|
||||
print(f" - {name}")
|
||||
|
||||
for migration_name, filepath in pending:
|
||||
if not run_migration(conn, migration_name, filepath):
|
||||
conn.close()
|
||||
return 1
|
||||
|
||||
conn.close()
|
||||
print("[OK] Migrationen abgeschlossen.")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(f"[FAIL] {exc}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,260 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply idempotent data seeds with checksum-based tracking and re-run on change."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from typing import Callable, List, Optional, Tuple
|
||||
|
||||
import psycopg2
|
||||
import sqlparse
|
||||
|
||||
from db import connect_with_retry, db_params, get_connection
|
||||
|
||||
_SEED_PREFIX = re.compile(r"^seed_(\d+)_(.+)$")
|
||||
_DEV_MARKER = ".dev."
|
||||
|
||||
|
||||
def is_production() -> bool:
|
||||
return os.getenv("ENVIRONMENT", "development").strip().lower() == "production"
|
||||
|
||||
|
||||
def seeds_directory() -> str:
|
||||
docker_path = "/app/seeds"
|
||||
if os.path.isdir(docker_path):
|
||||
return docker_path
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "seeds")
|
||||
|
||||
|
||||
def init_data_seeds_table(conn) -> None:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS data_seeds (
|
||||
seed_name VARCHAR(255) PRIMARY KEY,
|
||||
checksum VARCHAR(64) NOT NULL,
|
||||
executed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
last_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _seed_sort_key(filename: str) -> Tuple[int, str]:
|
||||
stem = filename
|
||||
for suffix in (".sql", ".py"):
|
||||
if stem.endswith(suffix):
|
||||
stem = stem[: -len(suffix)]
|
||||
break
|
||||
match = _SEED_PREFIX.match(stem)
|
||||
if match:
|
||||
return (int(match.group(1)), stem)
|
||||
return (0, stem)
|
||||
|
||||
|
||||
def _seed_stem(filename: str) -> str:
|
||||
if filename.endswith(".dev.sql"):
|
||||
return filename[: -len(".dev.sql")]
|
||||
if filename.endswith(".sql"):
|
||||
return filename[: -len(".sql")]
|
||||
if filename.endswith(".py"):
|
||||
return filename[: -len(".py")]
|
||||
return filename
|
||||
|
||||
|
||||
def seed_files(seeds_dir: str) -> List[Tuple[str, str, str]]:
|
||||
"""Return (seed_name, filepath, kind) sorted by numeric prefix."""
|
||||
rows: List[Tuple[str, str, str]] = []
|
||||
if not os.path.isdir(seeds_dir):
|
||||
return rows
|
||||
|
||||
for filename in os.listdir(seeds_dir):
|
||||
if filename.startswith("_") or not filename.startswith("seed_"):
|
||||
continue
|
||||
if filename.endswith(".sql"):
|
||||
kind = "sql"
|
||||
elif filename.endswith(".py"):
|
||||
kind = "py"
|
||||
else:
|
||||
continue
|
||||
stem = _seed_stem(filename)
|
||||
rows.append((stem, os.path.join(seeds_dir, filename), kind))
|
||||
|
||||
rows.sort(key=lambda item: _seed_sort_key(item[0]))
|
||||
return rows
|
||||
|
||||
|
||||
def seed_applies_in_environment(filename: str) -> bool:
|
||||
if _DEV_MARKER in filename and is_production():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def file_checksum(filepath: str) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with open(filepath, "rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(65536), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def applied_seed_checksum(conn, seed_name: str) -> Optional[str]:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT checksum FROM data_seeds WHERE seed_name = %s", (seed_name,))
|
||||
row = cur.fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
def record_seed(conn, seed_name: str, checksum: str) -> None:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO data_seeds (seed_name, checksum, executed_at, last_run_at)
|
||||
VALUES (%s, %s, NOW(), NOW())
|
||||
ON CONFLICT (seed_name) DO UPDATE SET
|
||||
checksum = EXCLUDED.checksum,
|
||||
last_run_at = NOW()
|
||||
""",
|
||||
(seed_name, checksum),
|
||||
)
|
||||
|
||||
|
||||
def _split_statements(sql_text: str) -> List[str]:
|
||||
parts = sqlparse.split(sql_text.strip())
|
||||
return [part.strip() for part in parts if part and part.strip()]
|
||||
|
||||
|
||||
def run_sql_seed(conn, filepath: str) -> None:
|
||||
with open(filepath, "r", encoding="utf-8") as handle:
|
||||
body = handle.read()
|
||||
statements = _split_statements(body)
|
||||
with conn.cursor() as cur:
|
||||
for stmt in statements:
|
||||
cur.execute(stmt)
|
||||
|
||||
|
||||
def run_python_seed(filepath: str) -> None:
|
||||
module_name = f"kairo_seed_{hashlib.md5(filepath.encode()).hexdigest()[:12]}"
|
||||
spec = importlib.util.spec_from_file_location(module_name, filepath)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f"Seed-Modul nicht ladbar: {filepath}")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
run_fn: Callable[[], None] | None = getattr(module, "run", None)
|
||||
if run_fn is None:
|
||||
raise RuntimeError(f"Seed {filepath} hat keine run()-Funktion")
|
||||
run_fn()
|
||||
|
||||
|
||||
def run_seed(conn, seed_name: str, filepath: str, kind: str) -> tuple[bool, object]:
|
||||
print(f"Running seed: {seed_name}")
|
||||
try:
|
||||
if kind == "sql":
|
||||
run_sql_seed(conn, filepath)
|
||||
else:
|
||||
conn.commit()
|
||||
conn.close()
|
||||
run_python_seed(filepath)
|
||||
conn = connect_with_retry(max_retries=5)
|
||||
|
||||
checksum = file_checksum(filepath)
|
||||
record_seed(conn, seed_name, checksum)
|
||||
conn.commit()
|
||||
print(f" [OK] {seed_name}")
|
||||
return True, conn
|
||||
except Exception as exc:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
print(f" [FAIL] {seed_name}: {exc}")
|
||||
return False, conn
|
||||
|
||||
|
||||
def pending_seeds(
|
||||
conn,
|
||||
seeds_dir: str,
|
||||
*,
|
||||
only: Optional[List[str]] = None,
|
||||
force: bool = False,
|
||||
) -> List[Tuple[str, str, str]]:
|
||||
selected: List[Tuple[str, str, str]] = []
|
||||
for seed_name, filepath, kind in seed_files(seeds_dir):
|
||||
filename = os.path.basename(filepath)
|
||||
if not seed_applies_in_environment(filename):
|
||||
print(f" [SKIP] {seed_name} (nur Nicht-Prod)")
|
||||
continue
|
||||
if only and seed_name not in only:
|
||||
continue
|
||||
checksum = file_checksum(filepath)
|
||||
is_dev_seed = _DEV_MARKER in filename
|
||||
always_run = is_dev_seed and not is_production()
|
||||
if force or always_run or applied_seed_checksum(conn, seed_name) != checksum:
|
||||
selected.append((seed_name, filepath, kind))
|
||||
return selected
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
argv = argv if argv is not None else sys.argv[1:]
|
||||
only: Optional[List[str]] = None
|
||||
force = False
|
||||
|
||||
idx = 0
|
||||
while idx < len(argv):
|
||||
arg = argv[idx]
|
||||
if arg == "--only" and idx + 1 < len(argv):
|
||||
only = [part.strip() for part in argv[idx + 1].split(",") if part.strip()]
|
||||
idx += 2
|
||||
continue
|
||||
if arg == "--force":
|
||||
force = True
|
||||
idx += 1
|
||||
continue
|
||||
print(f"[FAIL] Unbekanntes Argument: {arg}")
|
||||
return 1
|
||||
|
||||
print("=" * 60)
|
||||
print("Jinkendo Kairo — Data Seeds")
|
||||
print("=" * 60)
|
||||
|
||||
seeds_dir = seeds_directory()
|
||||
if not os.path.isdir(seeds_dir):
|
||||
print(f"[OK] Kein seeds-Verzeichnis ({seeds_dir}) — nichts zu tun.")
|
||||
return 0
|
||||
|
||||
try:
|
||||
conn = connect_with_retry()
|
||||
init_data_seeds_table(conn)
|
||||
to_run = pending_seeds(conn, seeds_dir, only=only, force=force)
|
||||
|
||||
if not to_run:
|
||||
print("[OK] Alle Seeds aktuell — nichts auszuführen.")
|
||||
conn.close()
|
||||
return 0
|
||||
|
||||
print(f"{len(to_run)} Seed(s) ausstehend:")
|
||||
for seed_name, _, _ in to_run:
|
||||
print(f" - {seed_name}")
|
||||
|
||||
for seed_name, filepath, kind in to_run:
|
||||
ok, conn = run_seed(conn, seed_name, filepath, kind)
|
||||
if not ok:
|
||||
conn.close()
|
||||
return 1
|
||||
|
||||
conn.close()
|
||||
print("[OK] Seeds abgeschlossen.")
|
||||
return 0
|
||||
except Exception as exc:
|
||||
print(f"[FAIL] {exc}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,35 @@
|
||||
-- Dev/CI: pytest-Artefakte entfernen (idempotent, sicher mehrfach ausführbar).
|
||||
-- Nur in Nicht-Prod-Umgebungen (Dateiname *.dev.sql).
|
||||
|
||||
-- Reparatur: ungültige Human-Actors (user_id NULL verletzt CHECK constraint)
|
||||
DELETE FROM actors WHERE actor_type = 'human' AND user_id IS NULL;
|
||||
|
||||
-- Abhängigkeiten vor User-Löschung (human actors: user_id NOT NULL constraint)
|
||||
DELETE FROM actors
|
||||
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||
|
||||
DELETE FROM tenant_memberships
|
||||
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||
|
||||
DELETE FROM sessions
|
||||
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||
|
||||
DELETE FROM audit_log
|
||||
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||
|
||||
DELETE FROM users WHERE email ~* '@example\.com$';
|
||||
|
||||
-- Verwaiste pytest-Tenants (Factory-Slug t-{10 hex}), ohne Memberships
|
||||
DELETE FROM actors a
|
||||
USING tenants t
|
||||
WHERE a.tenant_id = t.id
|
||||
AND t.slug ~ '^t-[a-f0-9]{10}$'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM tenant_memberships tm WHERE tm.tenant_id = t.id
|
||||
);
|
||||
|
||||
DELETE FROM tenants t
|
||||
WHERE t.slug ~ '^t-[a-f0-9]{10}$'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM tenant_memberships tm WHERE tm.tenant_id = t.id
|
||||
);
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Bootstrap portal admin from KAIRO_BOOTSTRAP_* when no users exist."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def run() -> None:
|
||||
from bootstrap import bootstrap_admin_if_needed
|
||||
|
||||
bootstrap_admin_if_needed()
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Dev: Portal-Admin lars@stommer.com sicherstellen (läuft bei jedem Start in Dev)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def run() -> None:
|
||||
from services.dev_admin import ensure_dev_admin
|
||||
|
||||
ensure_dev_admin()
|
||||
Whitespace-only changes.
@@ -0,0 +1,68 @@
|
||||
"""Actor creation helpers — User and Actor remain separate concepts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from db import get_connection
|
||||
|
||||
ActorType = Literal["human", "agent", "working_group", "external_system"]
|
||||
|
||||
|
||||
def create_actor(
|
||||
*,
|
||||
tenant_id: str,
|
||||
actor_type: ActorType,
|
||||
name: str,
|
||||
user_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
if actor_type == "human" and not user_id:
|
||||
raise ValueError("Human actors require user_id")
|
||||
if actor_type != "human" and user_id:
|
||||
raise ValueError("Non-human actors must not have user_id")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO actors (tenant_id, actor_type, name, user_id)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, tenant_id, actor_type, name, user_id, is_active, created_at
|
||||
""",
|
||||
(tenant_id, actor_type, name, user_id),
|
||||
)
|
||||
row = dict(cur.fetchone())
|
||||
conn.commit()
|
||||
for key in ("id", "tenant_id", "user_id"):
|
||||
if row.get(key):
|
||||
row[key] = str(row[key])
|
||||
return row
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_human_actor(tenant_id: str, user_id: str) -> Optional[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, tenant_id, actor_type, name, user_id, is_active, created_at
|
||||
FROM actors
|
||||
WHERE tenant_id = %s AND user_id = %s AND actor_type = 'human'
|
||||
""",
|
||||
(tenant_id, user_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = dict(row)
|
||||
for key in ("id", "tenant_id", "user_id"):
|
||||
if result.get(key):
|
||||
result[key] = str(result[key])
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Minimal audit logging for critical auth actions (AP0.2)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
|
||||
from db import get_connection
|
||||
|
||||
|
||||
def log_audit(
|
||||
action: str,
|
||||
*,
|
||||
user_id: Optional[str] = None,
|
||||
tenant_id: Optional[str] = None,
|
||||
details: Optional[dict[str, Any]] = None,
|
||||
) -> None:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO audit_log (action, user_id, tenant_id, details)
|
||||
VALUES (%s, %s, %s, %s::jsonb)
|
||||
""",
|
||||
(action, user_id, tenant_id, json.dumps(details or {})),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Dev-only admin seed — ensures a known portal admin exists."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Iterable
|
||||
|
||||
from auth import hash_password
|
||||
from db import get_connection
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from services.actors import create_actor, get_human_actor
|
||||
from services.audit import log_audit
|
||||
from services.registration import provision_system_admin, user_count
|
||||
|
||||
DEV_ADMIN_EMAIL = "lars@stommer.com"
|
||||
DEV_ADMIN_PASSWORD = "12345678"
|
||||
DEV_ADMIN_NAME = "Lars Stommer"
|
||||
DEV_TENANT_SLUG = "stommer"
|
||||
DEV_TENANT_NAME = "Stommer"
|
||||
|
||||
|
||||
def _normalize_emails(emails: Iterable[str]) -> tuple[str, ...]:
|
||||
return tuple(sorted({email.strip().lower() for email in emails if email.strip()}))
|
||||
|
||||
|
||||
def delete_users_except(keep_emails: Iterable[str]) -> int:
|
||||
"""Remove all users not in keep_emails (with FK-safe order). Returns deleted count."""
|
||||
keep = _normalize_emails(keep_emails)
|
||||
if not keep:
|
||||
raise ValueError("keep_emails must not be empty")
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM actors WHERE actor_type = 'human' AND user_id IS NULL")
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM actors
|
||||
WHERE user_id IN (
|
||||
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||
)
|
||||
""",
|
||||
(list(keep),),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM tenant_memberships
|
||||
WHERE user_id IN (
|
||||
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||
)
|
||||
""",
|
||||
(list(keep),),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM sessions
|
||||
WHERE user_id IN (
|
||||
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||
)
|
||||
""",
|
||||
(list(keep),),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
DELETE FROM audit_log
|
||||
WHERE user_id IN (
|
||||
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||
)
|
||||
""",
|
||||
(list(keep),),
|
||||
)
|
||||
cur.execute(
|
||||
"DELETE FROM users WHERE lower(email) <> ALL(%s) RETURNING email",
|
||||
(list(keep),),
|
||||
)
|
||||
removed = cur.fetchall()
|
||||
conn.commit()
|
||||
return len(removed)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _ensure_tenant(conn, *, slug: str, name: str) -> dict:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO tenants (slug, name)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT (slug) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id, slug, name
|
||||
""",
|
||||
(slug, name),
|
||||
)
|
||||
return dict(cur.fetchone())
|
||||
|
||||
|
||||
def ensure_dev_admin(
|
||||
*,
|
||||
email: str = DEV_ADMIN_EMAIL,
|
||||
password: str = DEV_ADMIN_PASSWORD,
|
||||
display_name: str = DEV_ADMIN_NAME,
|
||||
tenant_slug: str = DEV_TENANT_SLUG,
|
||||
tenant_name: str = DEV_TENANT_NAME,
|
||||
) -> dict:
|
||||
"""Dev seed: remove other users, ensure portal admin + tenant + human actor."""
|
||||
if os.getenv("ENVIRONMENT", "development").strip().lower() == "production":
|
||||
raise RuntimeError("ensure_dev_admin darf nicht in Production laufen")
|
||||
|
||||
normalized_email = email.strip().lower()
|
||||
removed = delete_users_except([normalized_email])
|
||||
if removed:
|
||||
print(f"[dev_admin] {removed} fremde User entfernt")
|
||||
|
||||
if user_count() == 0:
|
||||
result = provision_system_admin(
|
||||
email=normalized_email,
|
||||
password=password,
|
||||
display_name=display_name,
|
||||
tenant_slug=tenant_slug,
|
||||
tenant_name=tenant_name,
|
||||
source="dev_seed",
|
||||
)
|
||||
print(f"[dev_admin] Portal-Admin angelegt: {normalized_email}")
|
||||
return result
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
tenant = _ensure_tenant(conn, slug=tenant_slug, name=tenant_name)
|
||||
tenant_id = str(tenant["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET password_hash = %s,
|
||||
display_name = %s,
|
||||
portal_role = 'admin',
|
||||
updated_at = NOW()
|
||||
WHERE lower(email) = %s
|
||||
RETURNING id, email, display_name, portal_role
|
||||
""",
|
||||
(hash_password(password), display_name.strip(), normalized_email),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise RuntimeError(f"Dev-Admin {normalized_email} fehlt nach Bereinigung")
|
||||
user = dict(row)
|
||||
user_id = str(user["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO tenant_memberships (tenant_id, user_id, tenant_role)
|
||||
VALUES (%s, %s, 'owner')
|
||||
ON CONFLICT (tenant_id, user_id) DO UPDATE SET tenant_role = 'owner'
|
||||
""",
|
||||
(tenant_id, user_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if not get_human_actor(tenant_id, user_id):
|
||||
create_actor(
|
||||
tenant_id=tenant_id,
|
||||
actor_type="human",
|
||||
name=display_name.strip(),
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
log_audit(
|
||||
"auth.dev_admin_ensure",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"email": normalized_email, "removed_users": removed},
|
||||
)
|
||||
print(f"[dev_admin] Portal-Admin bestätigt: {normalized_email}")
|
||||
return {
|
||||
"user": {
|
||||
"id": user_id,
|
||||
"email": user["email"],
|
||||
"display_name": user["display_name"],
|
||||
"portal_role": user["portal_role"],
|
||||
},
|
||||
"tenant": {"id": tenant_id, "slug": tenant["slug"], "name": tenant["name"]},
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
"""First-user / system-admin provisioning (bootstrap + registration)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from auth import create_session, get_user_by_email, hash_password
|
||||
from db import get_connection
|
||||
from psycopg2.extras import RealDictCursor
|
||||
from fastapi import HTTPException
|
||||
from services.actors import create_actor
|
||||
from services.audit import log_audit
|
||||
|
||||
|
||||
def user_count() -> int:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM users")
|
||||
return int(cur.fetchone()[0])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def registration_open() -> bool:
|
||||
return user_count() == 0
|
||||
|
||||
|
||||
def setup_status() -> dict[str, Any]:
|
||||
count = user_count()
|
||||
return {
|
||||
"has_users": count > 0,
|
||||
"registration_open": count == 0,
|
||||
"user_count": count,
|
||||
}
|
||||
|
||||
|
||||
def _slugify(value: str) -> str:
|
||||
slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
|
||||
return (slug[:48] or "default")
|
||||
|
||||
|
||||
def provision_system_admin(
|
||||
*,
|
||||
email: str,
|
||||
password: str,
|
||||
display_name: str,
|
||||
tenant_slug: str | None = None,
|
||||
tenant_name: str | None = None,
|
||||
source: str = "bootstrap",
|
||||
) -> dict[str, Any]:
|
||||
"""Create portal admin, default tenant, owner membership and human actor."""
|
||||
if user_count() > 0:
|
||||
raise ValueError("users_already_exist")
|
||||
|
||||
normalized_email = email.strip().lower()
|
||||
slug = tenant_slug or os.getenv("KAIRO_BOOTSTRAP_TENANT_SLUG") or "default"
|
||||
name = tenant_name or os.getenv("KAIRO_BOOTSTRAP_TENANT_NAME") or "Default Tenant"
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO tenants (slug, name)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT (slug) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id, slug, name
|
||||
""",
|
||||
(slug, name),
|
||||
)
|
||||
tenant = dict(cur.fetchone())
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO users (email, password_hash, display_name, portal_role)
|
||||
VALUES (%s, %s, %s, 'admin')
|
||||
RETURNING id, email, display_name, portal_role
|
||||
""",
|
||||
(normalized_email, hash_password(password), display_name.strip()),
|
||||
)
|
||||
user = dict(cur.fetchone())
|
||||
user_id = str(user["id"])
|
||||
tenant_id = str(tenant["id"])
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO tenant_memberships (tenant_id, user_id, tenant_role)
|
||||
VALUES (%s, %s, 'owner')
|
||||
""",
|
||||
(tenant_id, user_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
create_actor(
|
||||
tenant_id=tenant_id,
|
||||
actor_type="human",
|
||||
name=display_name.strip(),
|
||||
user_id=user_id,
|
||||
)
|
||||
log_audit(
|
||||
"auth.register_system_admin",
|
||||
user_id=user_id,
|
||||
tenant_id=tenant_id,
|
||||
details={"email": normalized_email, "source": source, "tenant_slug": slug},
|
||||
)
|
||||
|
||||
session = create_session(user_id, tenant_id)
|
||||
return {
|
||||
"token": session["token"],
|
||||
"expires_at": session["expires_at"].isoformat(),
|
||||
"user": {
|
||||
"id": user_id,
|
||||
"email": user["email"],
|
||||
"display_name": user["display_name"],
|
||||
"portal_role": user["portal_role"],
|
||||
},
|
||||
"tenant": {"id": tenant_id, "slug": tenant["slug"], "name": tenant["name"]},
|
||||
}
|
||||
|
||||
|
||||
def register_system_admin(
|
||||
*,
|
||||
email: str,
|
||||
password: str,
|
||||
display_name: str,
|
||||
organization_name: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if get_user_by_email(email):
|
||||
raise HTTPException(status_code=409, detail="E-Mail bereits registriert")
|
||||
|
||||
if not registration_open():
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Registrierung geschlossen — Systemadministrator ist bereits eingerichtet",
|
||||
)
|
||||
|
||||
org = (organization_name or display_name or "Default Tenant").strip()
|
||||
slug = _slugify(org)
|
||||
|
||||
return provision_system_admin(
|
||||
email=email,
|
||||
password=password,
|
||||
display_name=display_name.strip(),
|
||||
tenant_slug=slug,
|
||||
tenant_name=org,
|
||||
source="registration",
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Startup sync for feature, prompt, placeholder and default config registries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import feature_registrations # noqa: F401
|
||||
import placeholder_registrations # noqa: F401
|
||||
import prompt_registrations # noqa: F401
|
||||
from config_service import sync_default_configs
|
||||
from feature_registry import sync_features_to_db
|
||||
from placeholder_registry import sync_placeholders_to_db
|
||||
from prompt_registry import sync_prompts_to_db
|
||||
from services.audit import log_audit
|
||||
|
||||
DEFAULT_CONFIGS = [
|
||||
{
|
||||
"config_key": "prompt.default_execution_mode",
|
||||
"scope": "global",
|
||||
"value": "single",
|
||||
"value_type": "string",
|
||||
"description": "Default execution mode for prompt rendering",
|
||||
},
|
||||
{
|
||||
"config_key": "prompt.render_logging_enabled",
|
||||
"scope": "global",
|
||||
"value": True,
|
||||
"value_type": "boolean",
|
||||
"description": "Write prompt_execution_logs on render",
|
||||
},
|
||||
{
|
||||
"config_key": "features.registry_sync_enabled",
|
||||
"scope": "global",
|
||||
"value": True,
|
||||
"value_type": "boolean",
|
||||
"description": "Enable registry sync on startup",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
results = [
|
||||
sync_features_to_db(),
|
||||
sync_placeholders_to_db(),
|
||||
sync_prompts_to_db(),
|
||||
]
|
||||
sync_default_configs(DEFAULT_CONFIGS)
|
||||
log_audit(
|
||||
"registry.sync.completed",
|
||||
details={
|
||||
"features": results[0] == 0,
|
||||
"placeholders": results[1] == 0,
|
||||
"prompts": results[2] == 0,
|
||||
},
|
||||
)
|
||||
return 0 if all(code == 0 for code in results) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sync in-memory rights registry to PostgreSQL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def main() -> int:
|
||||
import rights_registrations # noqa: F401 — side-effect registration
|
||||
from rights_registry import sync_rights_registry_to_db
|
||||
|
||||
return sync_rights_registry_to_db()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,162 @@
|
||||
"""TenantContext resolution — single layer, not scattered header logic in routers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from psycopg2.extras import RealDictCursor
|
||||
|
||||
from auth import require_auth
|
||||
from db import get_connection
|
||||
from rights_registry import load_grants_for_roles
|
||||
from services.actors import get_human_actor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TenantContext:
|
||||
user_id: str
|
||||
email: str
|
||||
display_name: str
|
||||
portal_role: str
|
||||
tenant_id: Optional[str]
|
||||
tenant_slug: Optional[str]
|
||||
tenant_name: Optional[str]
|
||||
tenant_role: Optional[str]
|
||||
actor_id: Optional[str]
|
||||
actor_type: Optional[str]
|
||||
session_token: str
|
||||
capabilities: frozenset[str]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"user_id": self.user_id,
|
||||
"email": self.email,
|
||||
"display_name": self.display_name,
|
||||
"portal_role": self.portal_role,
|
||||
"capabilities": sorted(self.capabilities),
|
||||
"tenant": (
|
||||
{
|
||||
"id": self.tenant_id,
|
||||
"slug": self.tenant_slug,
|
||||
"name": self.tenant_name,
|
||||
"role": self.tenant_role,
|
||||
}
|
||||
if self.tenant_id
|
||||
else None
|
||||
),
|
||||
"actor": (
|
||||
{
|
||||
"id": self.actor_id,
|
||||
"type": self.actor_type,
|
||||
}
|
||||
if self.actor_id
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def list_user_tenants(user_id: str) -> list[dict[str, Any]]:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
t.id,
|
||||
t.slug,
|
||||
t.name,
|
||||
tm.tenant_role,
|
||||
tm.is_active AS membership_active
|
||||
FROM tenant_memberships tm
|
||||
JOIN tenants t ON t.id = tm.tenant_id
|
||||
WHERE tm.user_id = %s AND tm.is_active = TRUE AND t.is_active = TRUE
|
||||
ORDER BY t.name
|
||||
""",
|
||||
(user_id,),
|
||||
)
|
||||
rows = []
|
||||
for row in cur.fetchall():
|
||||
item = dict(row)
|
||||
item["id"] = str(item["id"])
|
||||
rows.append(item)
|
||||
return rows
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def resolve_tenant_context(session: dict[str, Any]) -> TenantContext:
|
||||
user_id = str(session["user_id"])
|
||||
tenant_id = session.get("active_tenant_id")
|
||||
portal_role = session["portal_role"]
|
||||
|
||||
if not tenant_id:
|
||||
caps = frozenset(load_grants_for_roles(portal_role=portal_role, tenant_role=None))
|
||||
return TenantContext(
|
||||
user_id=user_id,
|
||||
email=session["email"],
|
||||
display_name=session["display_name"],
|
||||
portal_role=portal_role,
|
||||
tenant_id=None,
|
||||
tenant_slug=None,
|
||||
tenant_name=None,
|
||||
tenant_role=None,
|
||||
actor_id=None,
|
||||
actor_type=None,
|
||||
session_token=session["token"],
|
||||
capabilities=caps,
|
||||
)
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT t.id, t.slug, t.name, tm.tenant_role
|
||||
FROM tenant_memberships tm
|
||||
JOIN tenants t ON t.id = tm.tenant_id
|
||||
WHERE tm.user_id = %s
|
||||
AND tm.tenant_id = %s
|
||||
AND tm.is_active = TRUE
|
||||
AND t.is_active = TRUE
|
||||
""",
|
||||
(user_id, tenant_id),
|
||||
)
|
||||
membership = cur.fetchone()
|
||||
if not membership:
|
||||
raise HTTPException(status_code=403, detail="Keine gültige Tenant-Mitgliedschaft")
|
||||
|
||||
tenant_id_str = str(membership["id"])
|
||||
tenant_role = membership["tenant_role"]
|
||||
human = get_human_actor(tenant_id_str, user_id)
|
||||
caps = frozenset(
|
||||
load_grants_for_roles(portal_role=portal_role, tenant_role=tenant_role)
|
||||
)
|
||||
return TenantContext(
|
||||
user_id=user_id,
|
||||
email=session["email"],
|
||||
display_name=session["display_name"],
|
||||
portal_role=portal_role,
|
||||
tenant_id=tenant_id_str,
|
||||
tenant_slug=membership["slug"],
|
||||
tenant_name=membership["name"],
|
||||
tenant_role=tenant_role,
|
||||
actor_id=human["id"] if human else None,
|
||||
actor_type=human["actor_type"] if human else None,
|
||||
session_token=session["token"],
|
||||
capabilities=caps,
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_tenant_context(session: dict[str, Any] = Depends(require_auth)) -> TenantContext:
|
||||
return resolve_tenant_context(session)
|
||||
|
||||
|
||||
def require_tenant_context(session: dict[str, Any] = Depends(require_auth)) -> TenantContext:
|
||||
ctx = resolve_tenant_context(session)
|
||||
if not ctx.tenant_id:
|
||||
raise HTTPException(status_code=403, detail="Kein aktiver Tenant — Tenant wählen")
|
||||
return ctx
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Shared pytest fixtures for AP0.2 auth tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
os.environ.setdefault("SKIP_SEEDS", "1")
|
||||
os.environ.setdefault("SKIP_BOOTSTRAP", "1")
|
||||
os.environ.setdefault("SKIP_RIGHTS_SYNC", "1")
|
||||
os.environ.setdefault("SKIP_REGISTRY_SYNC", "1")
|
||||
|
||||
|
||||
def _db_available() -> bool:
|
||||
try:
|
||||
import psycopg2
|
||||
|
||||
conn = psycopg2.connect(
|
||||
host=os.getenv("DB_HOST", "localhost"),
|
||||
port=os.getenv("DB_PORT", "5432"),
|
||||
dbname=os.getenv("DB_NAME", "kairo_dev"),
|
||||
user=os.getenv("DB_USER", "kairo_dev"),
|
||||
password=os.getenv("DB_PASSWORD", "dev_password"),
|
||||
)
|
||||
conn.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(not _db_available(), reason="PostgreSQL nicht erreichbar")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _run_migrations():
|
||||
import run_migrations
|
||||
|
||||
assert run_migrations.main() == 0
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _seed_hygiene():
|
||||
"""Vor/nach Tests pytest-Artefakte aus der geteilten Dev-DB entfernen."""
|
||||
import run_seeds
|
||||
|
||||
run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"])
|
||||
yield
|
||||
run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"])
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _sync_rights_registry():
|
||||
import rights_registrations # noqa: F401
|
||||
from rights_registry import sync_rights_registry_to_db
|
||||
|
||||
assert sync_rights_registry_to_db() == 0
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _sync_prompt_feature_config():
|
||||
import feature_registrations # noqa: F401
|
||||
import placeholder_registrations # noqa: F401
|
||||
import prompt_registrations # noqa: F401
|
||||
from sync_prompt_feature_config import main as sync_registries
|
||||
|
||||
assert sync_registries() == 0
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
import importlib
|
||||
|
||||
import main as main_module
|
||||
|
||||
importlib.reload(main_module)
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
return TestClient(main_module.app)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Test data factories (PostgreSQL required)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from auth import hash_password
|
||||
from db import get_connection
|
||||
from services.actors import create_actor
|
||||
|
||||
|
||||
def create_tenant(*, slug: str | None = None, name: str = "Test Tenant") -> str:
|
||||
slug = slug or f"t-{uuid.uuid4().hex[:10]}"
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO tenants (slug, name) VALUES (%s, %s) RETURNING id",
|
||||
(slug, name),
|
||||
)
|
||||
tenant_id = str(cur.fetchone()[0])
|
||||
conn.commit()
|
||||
return tenant_id
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_user(
|
||||
*,
|
||||
email: str | None = None,
|
||||
password: str = "test-password-123",
|
||||
display_name: str = "Test User",
|
||||
portal_role: str = "user",
|
||||
) -> dict:
|
||||
email = email or f"user-{uuid.uuid4().hex[:8]}@example.com"
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO users (email, password_hash, display_name, portal_role)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, email, display_name, portal_role
|
||||
""",
|
||||
(email, hash_password(password), display_name, portal_role),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {
|
||||
"id": str(row[0]),
|
||||
"email": row[1],
|
||||
"display_name": row[2],
|
||||
"portal_role": row[3],
|
||||
"password": password,
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def add_membership(*, tenant_id: str, user_id: str, tenant_role: str = "member") -> None:
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO tenant_memberships (tenant_id, user_id, tenant_role)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (tenant_id, user_id) DO UPDATE SET tenant_role = EXCLUDED.tenant_role
|
||||
""",
|
||||
(tenant_id, user_id, tenant_role),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def provision_user_in_tenant(
|
||||
*,
|
||||
tenant_role: str = "member",
|
||||
portal_role: str = "user",
|
||||
) -> dict:
|
||||
tenant_id = create_tenant()
|
||||
user = create_user(portal_role=portal_role)
|
||||
add_membership(tenant_id=tenant_id, user_id=user["id"], tenant_role=tenant_role)
|
||||
actor = create_actor(
|
||||
tenant_id=tenant_id,
|
||||
actor_type="human",
|
||||
name=user["display_name"],
|
||||
user_id=user["id"],
|
||||
)
|
||||
return {**user, "tenant_id": tenant_id, "actor_id": actor["id"]}
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Auth endpoint and session tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from auth import AUTH_HEADER, get_session
|
||||
from tests.factories import provision_user_in_tenant
|
||||
|
||||
|
||||
def test_login_logout_and_session(client):
|
||||
user = provision_user_in_tenant()
|
||||
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
assert login.status_code == 200
|
||||
payload = login.json()
|
||||
assert "token" in payload
|
||||
assert payload["user"]["email"] == user["email"]
|
||||
token = payload["token"]
|
||||
|
||||
me = client.get("/api/me", headers={AUTH_HEADER: token})
|
||||
assert me.status_code == 200
|
||||
assert me.json()["email"] == user["email"]
|
||||
assert me.json()["active_tenant_id"] == user["tenant_id"]
|
||||
|
||||
logout = client.post("/api/auth/logout", headers={AUTH_HEADER: token})
|
||||
assert logout.status_code == 200
|
||||
assert get_session(token) is None
|
||||
|
||||
me_after = client.get("/api/me", headers={AUTH_HEADER: token})
|
||||
assert me_after.status_code == 401
|
||||
|
||||
|
||||
def test_login_invalid_password(client):
|
||||
user = provision_user_in_tenant()
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": "wrong-password"},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_me_requires_auth(client):
|
||||
assert client.get("/api/me").status_code == 401
|
||||
|
||||
|
||||
def test_me_context_returns_tenant_and_actor(client):
|
||||
user = provision_user_in_tenant(tenant_role="admin")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
|
||||
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token})
|
||||
assert ctx.status_code == 200
|
||||
body = ctx.json()
|
||||
assert body["tenant"]["id"] == user["tenant_id"]
|
||||
assert body["tenant"]["role"] == "admin"
|
||||
assert body["actor"]["id"] == user["actor_id"]
|
||||
assert body["actor"]["type"] == "human"
|
||||
|
||||
|
||||
def test_tenant_switch_rejects_invalid_membership(client):
|
||||
user = provision_user_in_tenant()
|
||||
other = provision_user_in_tenant()
|
||||
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
|
||||
switch = client.post(
|
||||
"/api/me/tenant",
|
||||
headers={AUTH_HEADER: token},
|
||||
json={"tenant_id": other["tenant_id"]},
|
||||
)
|
||||
assert switch.status_code == 403
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Capability resolution and require_capability tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from auth import AUTH_HEADER
|
||||
from tests.factories import provision_user_in_tenant
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def enforce_capabilities(monkeypatch):
|
||||
monkeypatch.setenv("CAPABILITY_ENFORCE", "enforce")
|
||||
|
||||
|
||||
def test_portal_admin_has_admin_capability(client, enforce_capabilities):
|
||||
admin = provision_user_in_tenant(tenant_role="member", portal_role="admin")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": admin["email"], "password": admin["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
|
||||
res = client.get("/api/me/admin/demo", headers={AUTH_HEADER: token})
|
||||
assert res.status_code == 200
|
||||
assert res.json()["ok"] is True
|
||||
|
||||
|
||||
def test_tenant_member_denied_admin_capability(client, enforce_capabilities):
|
||||
member = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": member["email"], "password": member["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
|
||||
res = client.get("/api/me/admin/demo", headers={AUTH_HEADER: token})
|
||||
assert res.status_code == 403
|
||||
|
||||
|
||||
def test_tenant_owner_has_manage_capabilities(client, enforce_capabilities):
|
||||
owner = provision_user_in_tenant(tenant_role="owner", portal_role="user")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": owner["email"], "password": owner["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token}).json()
|
||||
|
||||
assert "kairo.tenant.manage" in ctx["capabilities"]
|
||||
assert "kairo.actor.manage" in ctx["capabilities"]
|
||||
assert "kairo.admin.access" not in ctx["capabilities"]
|
||||
|
||||
|
||||
def test_probe_mode_allows_without_capability(client, monkeypatch):
|
||||
monkeypatch.setenv("CAPABILITY_ENFORCE", "probe")
|
||||
member = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": member["email"], "password": member["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
|
||||
res = client.get("/api/me/admin/demo", headers={AUTH_HEADER: token})
|
||||
assert res.status_code == 200
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Configuration registry tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from auth import AUTH_HEADER
|
||||
from config_service import SECRET_VALUE_FORBIDDEN, get_config, list_configs, upsert_config
|
||||
from tests.factories import provision_user_in_tenant
|
||||
|
||||
|
||||
def test_global_config_upsert_and_read():
|
||||
upsert_config(
|
||||
config_key="test.ap0.config",
|
||||
scope="global",
|
||||
value="enabled",
|
||||
value_type="string",
|
||||
description="pytest config",
|
||||
)
|
||||
item = get_config("test.ap0.config", scope="global")
|
||||
assert item is not None
|
||||
assert item["value"] == "enabled"
|
||||
|
||||
|
||||
def test_secret_config_rejects_plaintext():
|
||||
with pytest.raises(ValueError, match=SECRET_VALUE_FORBIDDEN):
|
||||
upsert_config(
|
||||
config_key="test.secret",
|
||||
scope="global",
|
||||
value="super-secret-token",
|
||||
is_secret=True,
|
||||
)
|
||||
|
||||
|
||||
def test_config_api(client):
|
||||
user = provision_user_in_tenant(portal_role="admin", tenant_role="owner")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
res = client.get("/api/config", headers={AUTH_HEADER: token})
|
||||
assert res.status_code == 200
|
||||
keys = {item["config_key"] for item in res.json()}
|
||||
assert "prompt.default_execution_mode" in keys
|
||||
|
||||
|
||||
def test_config_post_api(client):
|
||||
user = provision_user_in_tenant(portal_role="admin", tenant_role="owner")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
res = client.post(
|
||||
"/api/config",
|
||||
json={
|
||||
"config_key": "test.api.config",
|
||||
"scope": "global",
|
||||
"value": True,
|
||||
"value_type": "boolean",
|
||||
"description": "via api",
|
||||
},
|
||||
headers={AUTH_HEADER: token},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.json()["config_key"] == "test.api.config"
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Entitlements snapshot tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from auth import AUTH_HEADER
|
||||
from tests.factories import provision_user_in_tenant
|
||||
|
||||
|
||||
def test_entitlements_snapshot_shape(client):
|
||||
user = provision_user_in_tenant(tenant_role="owner", portal_role="admin")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
|
||||
res = client.get("/api/me/entitlements", headers={AUTH_HEADER: token})
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
|
||||
assert "account" in body
|
||||
assert body["account"]["portal_role"] == "admin"
|
||||
assert "capabilities" in body["account"]
|
||||
assert body["tenant"]["tenant_id"] == user["tenant_id"]
|
||||
assert body["actor"]["actor_id"] == user["actor_id"]
|
||||
assert body["roles"]["portal"] == "admin"
|
||||
assert body["roles"]["tenant"] == "owner"
|
||||
assert "kairo.admin.access" in body["capabilities"]
|
||||
assert body["enforcement"]["capabilities"] in ("probe", "enforce")
|
||||
assert body["enforcement"]["features"] == "probe"
|
||||
assert "kairo.prompt.registry" in body["features"]
|
||||
assert body["features"]["kairo.prompt.registry"]["enabled"] is True
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Feature registry tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import feature_registrations # noqa: F401
|
||||
from auth import AUTH_HEADER
|
||||
from db import get_connection
|
||||
from feature_registry import get_registered_features, sync_features_to_db
|
||||
from tests.factories import provision_user_in_tenant
|
||||
|
||||
|
||||
def test_feature_registration_required_fields():
|
||||
keys = {f.key for f in get_registered_features()}
|
||||
assert keys == {
|
||||
"kairo.feature.registry",
|
||||
"kairo.config.registry",
|
||||
"kairo.prompt.registry",
|
||||
}
|
||||
|
||||
|
||||
def test_feature_sync_idempotent():
|
||||
assert sync_features_to_db() == 0
|
||||
assert sync_features_to_db() == 0
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM features WHERE is_active = TRUE")
|
||||
assert cur.fetchone()[0] == 3
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_features_in_entitlements(client):
|
||||
user = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
res = client.get("/api/me/entitlements", headers={AUTH_HEADER: token})
|
||||
features = res.json()["features"]
|
||||
assert "kairo.prompt.registry" in features
|
||||
assert features["kairo.prompt.registry"]["enabled"] is True
|
||||
assert features["kairo.prompt.registry"]["module"] == "prompt"
|
||||
|
||||
|
||||
def test_features_api_requires_auth(client):
|
||||
assert client.get("/api/features").status_code == 401
|
||||
@@ -0,0 +1,31 @@
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setenv("SKIP_DB_MIGRATE", "1")
|
||||
monkeypatch.setenv("SKIP_BOOTSTRAP", "1")
|
||||
import importlib
|
||||
|
||||
import main as main_module
|
||||
|
||||
importlib.reload(main_module)
|
||||
return TestClient(main_module.app)
|
||||
|
||||
|
||||
def test_app_importable():
|
||||
import main
|
||||
|
||||
assert main.app is not None
|
||||
|
||||
|
||||
def test_health_endpoint(client):
|
||||
response = client.get("/api/health")
|
||||
assert response.status_code == 200
|
||||
payload = response.json()
|
||||
assert payload["app"] == "jinkendo-kairo"
|
||||
assert payload["status"] in {"ok", "degraded"}
|
||||
assert payload["db"] in {"ok", "error"}
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Migration runner tests (require PostgreSQL)."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg2
|
||||
import pytest
|
||||
|
||||
import run_migrations
|
||||
|
||||
|
||||
def _db_available() -> bool:
|
||||
try:
|
||||
conn = psycopg2.connect(
|
||||
host=os.getenv("DB_HOST", "localhost"),
|
||||
port=os.getenv("DB_PORT", "5432"),
|
||||
dbname=os.getenv("DB_NAME", "kairo_dev"),
|
||||
user=os.getenv("DB_USER", "kairo_dev"),
|
||||
password=os.getenv("DB_PASSWORD", "dev_password"),
|
||||
)
|
||||
conn.close()
|
||||
return True
|
||||
except psycopg2.OperationalError:
|
||||
return False
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(not _db_available(), reason="PostgreSQL nicht erreichbar")
|
||||
|
||||
|
||||
def test_migration_runner_finds_migrations():
|
||||
migrations_dir = run_migrations.migrations_directory()
|
||||
files = run_migrations.migration_files(migrations_dir)
|
||||
names = [name for name, _ in files]
|
||||
assert "001_init_core" in names
|
||||
assert "002_auth_identity_tenant_actor" in names
|
||||
assert "003_data_seeds_tracking" in names
|
||||
assert "004_capabilities_registry" in names
|
||||
assert "005_prompt_feature_config_registry" in names
|
||||
|
||||
|
||||
def test_migration_runner_is_idempotent():
|
||||
assert run_migrations.main() == 0
|
||||
assert run_migrations.main() == 0
|
||||
|
||||
conn = run_migrations.connect_with_retry(max_retries=5)
|
||||
executed = run_migrations.executed_migrations(conn)
|
||||
conn.close()
|
||||
assert "001_init_core" in executed
|
||||
assert "002_auth_identity_tenant_actor" in executed
|
||||
assert "003_data_seeds_tracking" in executed
|
||||
assert "004_capabilities_registry" in executed
|
||||
assert "005_prompt_feature_config_registry" in executed
|
||||
|
||||
|
||||
def test_core_table_exists():
|
||||
conn = run_migrations.connect_with_retry(max_retries=5)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COUNT(*) FROM information_schema.tables
|
||||
WHERE table_schema = 'public' AND table_name = 'kairo_app_meta'
|
||||
"""
|
||||
)
|
||||
assert cur.fetchone()[0] == 1
|
||||
conn.close()
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Prompt registry and rendering tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import prompt_registrations # noqa: F401
|
||||
from auth import AUTH_HEADER
|
||||
from db import get_connection
|
||||
from prompt_registry import get_registered_prompts, sync_prompts_to_db
|
||||
from prompt_rendering import PromptRenderError, render_prompt_single
|
||||
from prompt_validation import PlaceholderValidationError, validate_placeholder_input
|
||||
from tests.factories import provision_user_in_tenant
|
||||
|
||||
|
||||
def test_prompt_registry_contains_smoke_prompts():
|
||||
keys = {p.prompt_key for p in get_registered_prompts()}
|
||||
assert "kairo.system.health_summary" in keys
|
||||
assert "kairo.context.debug_summary" in keys
|
||||
assert "kairo.pipeline.placeholder" in keys
|
||||
|
||||
|
||||
def test_prompt_sync_idempotent():
|
||||
assert sync_prompts_to_db() == 0
|
||||
assert sync_prompts_to_db() == 0
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM prompt_definitions")
|
||||
assert cur.fetchone()[0] >= 4
|
||||
cur.execute("SELECT COUNT(*) FROM prompt_steps")
|
||||
assert cur.fetchone()[0] >= 1
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_placeholder_required_missing():
|
||||
try:
|
||||
validate_placeholder_input(
|
||||
template="Hello {{debug_message}}",
|
||||
context_kind="kairo.debug_context",
|
||||
values={},
|
||||
)
|
||||
assert False, "expected validation error"
|
||||
except PlaceholderValidationError as exc:
|
||||
assert "debug_message" in exc.missing
|
||||
|
||||
|
||||
def test_placeholder_optional_ok():
|
||||
meta = validate_placeholder_input(
|
||||
template="Level {{debug_level}}",
|
||||
context_kind="kairo.debug_context",
|
||||
values={"debug_message": "ok"},
|
||||
)
|
||||
assert "debug_level" in meta["optional_missing"]
|
||||
|
||||
|
||||
def test_render_debug_prompt():
|
||||
result = render_prompt_single(
|
||||
"kairo.system.health_summary",
|
||||
values={"debug_message": "All systems nominal", "debug_level": "info"},
|
||||
log_execution=False,
|
||||
)
|
||||
assert "All systems nominal" in result["rendered_text"]
|
||||
assert result["template_source"].startswith("step:")
|
||||
|
||||
|
||||
def test_render_pipeline_mode_rejected():
|
||||
try:
|
||||
render_prompt_single(
|
||||
"kairo.pipeline.placeholder",
|
||||
values={"debug_message": "x"},
|
||||
log_execution=False,
|
||||
)
|
||||
assert False, "expected error"
|
||||
except PromptRenderError as exc:
|
||||
assert exc.code == "mode_not_implemented"
|
||||
|
||||
|
||||
def test_render_api(client):
|
||||
user = provision_user_in_tenant(tenant_role="owner", portal_role="admin")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
client.post(
|
||||
"/api/me/tenant",
|
||||
json={"tenant_id": user["tenant_id"]},
|
||||
headers={AUTH_HEADER: token},
|
||||
)
|
||||
res = client.post(
|
||||
"/api/prompts/kairo.context.debug_summary/render",
|
||||
json={"values": {}, "use_context": True},
|
||||
headers={AUTH_HEADER: token},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert user["tenant_id"] in res.json()["rendered_text"]
|
||||
|
||||
|
||||
def test_prompts_list_api(client):
|
||||
user = provision_user_in_tenant(portal_role="admin", tenant_role="owner")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
res = client.get("/api/prompts", headers={AUTH_HEADER: token})
|
||||
assert res.status_code == 200
|
||||
keys = {item["prompt_key"] for item in res.json()}
|
||||
assert "kairo.system.health_summary" in keys
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Registration and first system-admin tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from auth import AUTH_HEADER, get_session
|
||||
from db import get_connection
|
||||
from services.registration import user_count
|
||||
|
||||
|
||||
def test_setup_status_open_without_users(client):
|
||||
if user_count() > 0:
|
||||
return
|
||||
res = client.get("/api/auth/setup-status")
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["registration_open"] is True
|
||||
assert body["has_users"] is False
|
||||
|
||||
|
||||
def test_register_first_user_becomes_portal_admin(client):
|
||||
if user_count() > 0:
|
||||
return
|
||||
|
||||
suffix = uuid.uuid4().hex[:8]
|
||||
email = f"admin-{suffix}@example.com"
|
||||
res = client.post(
|
||||
"/api/auth/register",
|
||||
json={
|
||||
"email": email,
|
||||
"password": "secure-pass-123",
|
||||
"display_name": "System Admin",
|
||||
"organization_name": "Kairo Org",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
body = res.json()
|
||||
assert body["user"]["portal_role"] == "admin"
|
||||
assert body["token"]
|
||||
assert get_session(body["token"]) is not None
|
||||
|
||||
me = client.get("/api/me", headers={AUTH_HEADER: body["token"]})
|
||||
assert me.status_code == 200
|
||||
assert me.json()["portal_role"] == "admin"
|
||||
|
||||
ctx = client.get("/api/me/context", headers={AUTH_HEADER: body["token"]})
|
||||
assert ctx.status_code == 200
|
||||
assert ctx.json()["tenant"]["role"] == "owner"
|
||||
assert ctx.json()["actor"]["type"] == "human"
|
||||
|
||||
# cleanup: allow re-run in isolated env — skip delete in shared CI DB
|
||||
closed = client.get("/api/auth/setup-status")
|
||||
assert closed.json()["registration_open"] is False
|
||||
|
||||
|
||||
def test_register_closed_when_users_exist(client):
|
||||
if user_count() == 0:
|
||||
return
|
||||
|
||||
res = client.post(
|
||||
"/api/auth/register",
|
||||
json={
|
||||
"email": f"other-{uuid.uuid4().hex[:8]}@example.com",
|
||||
"password": "secure-pass-123",
|
||||
"display_name": "Other User",
|
||||
},
|
||||
)
|
||||
assert res.status_code == 403
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Rights registry and DB sync tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import rights_registrations # noqa: F401
|
||||
from db import get_connection
|
||||
from rights_registry import get_registered_capabilities, sync_rights_registry_to_db
|
||||
|
||||
|
||||
def test_registry_contains_initial_capabilities():
|
||||
keys = {reg.key for reg in get_registered_capabilities()}
|
||||
assert keys == {
|
||||
"kairo.admin.access",
|
||||
"kairo.tenant.manage",
|
||||
"kairo.actor.manage",
|
||||
"kairo.context.read",
|
||||
"kairo.entitlements.read",
|
||||
"kairo.feature.registry.read",
|
||||
"kairo.feature.registry.manage",
|
||||
"kairo.prompt.registry.read",
|
||||
"kairo.prompt.registry.manage",
|
||||
"kairo.config.registry.read",
|
||||
"kairo.config.registry.manage",
|
||||
"kairo.prompt.render",
|
||||
}
|
||||
|
||||
|
||||
def test_sync_is_idempotent():
|
||||
assert sync_rights_registry_to_db() == 0
|
||||
assert sync_rights_registry_to_db() == 0
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM capabilities")
|
||||
assert cur.fetchone()[0] == 12
|
||||
cur.execute("SELECT COUNT(*) FROM role_capability_grants")
|
||||
assert cur.fetchone()[0] >= 5
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Data seed runner tests (require PostgreSQL)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import run_seeds
|
||||
from tests.factories import create_user
|
||||
|
||||
|
||||
def test_seed_runner_finds_seeds():
|
||||
seeds_dir = run_seeds.seeds_directory()
|
||||
names = [name for name, _, _ in run_seeds.seed_files(seeds_dir)]
|
||||
assert "seed_001_cleanup_pytest_artifacts" in names
|
||||
assert "seed_002_bootstrap_admin" in names
|
||||
|
||||
|
||||
def test_cleanup_seed_removes_example_com_users():
|
||||
suffix = uuid.uuid4().hex[:8]
|
||||
user = create_user(email=f"seed-test-{suffix}@example.com")
|
||||
|
||||
assert run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts", "--force"]) == 0
|
||||
|
||||
from db import get_connection
|
||||
|
||||
conn = get_connection()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM users WHERE id = %s", (user["id"],))
|
||||
assert cur.fetchone()[0] == 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_cleanup_seed_is_idempotent():
|
||||
assert run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"]) == 0
|
||||
assert run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"]) == 0
|
||||
|
||||
|
||||
def test_dev_admin_seed_ensures_lars():
|
||||
import os
|
||||
|
||||
if os.getenv("ENVIRONMENT", "development").strip().lower() == "production":
|
||||
return
|
||||
|
||||
from auth import get_user_by_email, verify_password
|
||||
from services.dev_admin import DEV_ADMIN_EMAIL, DEV_ADMIN_PASSWORD
|
||||
|
||||
assert run_seeds.main(["--only", "seed_003_ensure_dev_admin"]) == 0
|
||||
|
||||
user = get_user_by_email(DEV_ADMIN_EMAIL)
|
||||
assert user is not None
|
||||
assert user["portal_role"] == "admin"
|
||||
assert verify_password(DEV_ADMIN_PASSWORD, user["password_hash"])
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Actor and TenantContext tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from auth import AUTH_HEADER
|
||||
from services.actors import create_actor
|
||||
from tests.factories import create_tenant, provision_user_in_tenant
|
||||
|
||||
|
||||
def test_human_actor_linked_to_user(client):
|
||||
user = provision_user_in_tenant()
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token}).json()
|
||||
assert ctx["actor"]["type"] == "human"
|
||||
assert ctx["actor"]["id"] == user["actor_id"]
|
||||
|
||||
|
||||
def test_agent_actor_without_user(client):
|
||||
tenant_id = create_tenant()
|
||||
agent = create_actor(tenant_id=tenant_id, actor_type="agent", name="Planner Agent")
|
||||
assert agent["user_id"] is None
|
||||
assert agent["actor_type"] == "agent"
|
||||
|
||||
|
||||
def test_working_group_and_external_system_actors(client):
|
||||
tenant_id = create_tenant()
|
||||
wg = create_actor(tenant_id=tenant_id, actor_type="working_group", name="Steering Group")
|
||||
ext = create_actor(tenant_id=tenant_id, actor_type="external_system", name="Jira")
|
||||
assert wg["actor_type"] == "working_group"
|
||||
assert ext["actor_type"] == "external_system"
|
||||
|
||||
|
||||
def test_portal_role_separate_from_tenant_role(client):
|
||||
user = provision_user_in_tenant(tenant_role="member", portal_role="admin")
|
||||
login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": user["email"], "password": user["password"]},
|
||||
)
|
||||
token = login.json()["token"]
|
||||
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token}).json()
|
||||
assert ctx["portal_role"] == "admin"
|
||||
assert ctx["tenant"]["role"] == "member"
|
||||
@@ -0,0 +1,3 @@
|
||||
APP_VERSION = "0.4.0-ap0.4"
|
||||
DB_SCHEMA_VERSION = "005"
|
||||
APP_NAME = "jinkendo-kairo"
|
||||
@@ -0,0 +1,83 @@
|
||||
# Keine festen container_name — Compose-Namen haben Projektprefix (<projekt>-postgres-1).
|
||||
# Host-Ports: KAIRO_BACKEND_PORT (Default 8097), KAIRO_FRONTEND_PORT (Default 3097).
|
||||
# CI compose-smoke: 18197/13197 — siehe infra/ci-smoke.env.example
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: "${DB_NAME:-kairo_dev}"
|
||||
POSTGRES_USER: "${DB_USER:-kairo_dev}"
|
||||
POSTGRES_PASSWORD: "${DB_PASSWORD:-dev_password}"
|
||||
volumes:
|
||||
- dev-kairo-db-data:/var/lib/postgresql/data
|
||||
# Kein Host-Port: DB nur im Compose-Netz (vermeidet Konflikte mit kairo-dev + CI)
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-kairo_dev} -d ${DB_NAME:-kairo_dev}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- dev-kairo-network
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
DB_HOST: postgres
|
||||
DB_PORT: 5432
|
||||
DB_NAME: "${DB_NAME:-kairo_dev}"
|
||||
DB_USER: "${DB_USER:-kairo_dev}"
|
||||
DB_PASSWORD: "${DB_PASSWORD:-dev_password}"
|
||||
APP_URL: "${APP_URL:-https://dev.kairo.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.kairo.jinkendo.de,http://192.168.2.49:3097,http://localhost:3097}"
|
||||
ENVIRONMENT: "${ENVIRONMENT:-development}"
|
||||
SESSION_DAYS: "${SESSION_DAYS:-30}"
|
||||
KAIRO_BOOTSTRAP_ADMIN_EMAIL: "${KAIRO_BOOTSTRAP_ADMIN_EMAIL:-}"
|
||||
KAIRO_BOOTSTRAP_ADMIN_PASSWORD: "${KAIRO_BOOTSTRAP_ADMIN_PASSWORD:-}"
|
||||
KAIRO_BOOTSTRAP_TENANT_SLUG: "${KAIRO_BOOTSTRAP_TENANT_SLUG:-default}"
|
||||
KAIRO_BOOTSTRAP_TENANT_NAME: "${KAIRO_BOOTSTRAP_TENANT_NAME:-Default Tenant}"
|
||||
ports:
|
||||
- "${KAIRO_BACKEND_PORT:-8097}:8000"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"python",
|
||||
"-c",
|
||||
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health')",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 18
|
||||
start_period: 90s
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- dev-kairo-network
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_API_URL: ""
|
||||
ports:
|
||||
- "${KAIRO_FRONTEND_PORT:-3097}:80"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- dev-kairo-network
|
||||
|
||||
volumes:
|
||||
dev-kairo-db-data:
|
||||
|
||||
networks:
|
||||
dev-kairo-network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,83 @@
|
||||
# Medien: aktuell nicht vorgesehen. Bei Bedarf NAS-Mount + docker-compose.override.yml (siehe docs/DEPLOYMENT.md).
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: kairo-db-prod
|
||||
environment:
|
||||
POSTGRES_DB: "${DB_NAME:-kairo}"
|
||||
POSTGRES_USER: "${DB_USER:-kairo_user}"
|
||||
POSTGRES_PASSWORD: "${DB_PASSWORD:-change_me}"
|
||||
volumes:
|
||||
- kairo-db-data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "127.0.0.1:5436:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-kairo_user} -d ${DB_NAME:-kairo}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- kairo-network
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: kairo-api
|
||||
environment:
|
||||
DB_HOST: postgres
|
||||
DB_PORT: 5432
|
||||
DB_NAME: "${DB_NAME:-kairo}"
|
||||
DB_USER: "${DB_USER:-kairo_user}"
|
||||
DB_PASSWORD: "${DB_PASSWORD:-change_me}"
|
||||
APP_URL: "${APP_URL:-https://kairo.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://kairo.jinkendo.de}"
|
||||
ENVIRONMENT: "${ENVIRONMENT:-production}"
|
||||
SESSION_DAYS: "${SESSION_DAYS:-30}"
|
||||
KAIRO_BOOTSTRAP_ADMIN_EMAIL: "${KAIRO_BOOTSTRAP_ADMIN_EMAIL:-}"
|
||||
KAIRO_BOOTSTRAP_ADMIN_PASSWORD: "${KAIRO_BOOTSTRAP_ADMIN_PASSWORD:-}"
|
||||
ports:
|
||||
- "${KAIRO_BACKEND_PORT:-8004}:8000"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"python",
|
||||
"-c",
|
||||
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health')",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- kairo-network
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_API_URL: ""
|
||||
container_name: kairo-ui
|
||||
ports:
|
||||
- "${KAIRO_FRONTEND_PORT:-3004}:80"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- kairo-network
|
||||
|
||||
volumes:
|
||||
kairo-db-data:
|
||||
|
||||
networks:
|
||||
kairo-network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,125 @@
|
||||
# Deployment – Kairo Jinkendo
|
||||
|
||||
**Stand:** 2026-07-04 (AP0.1)
|
||||
**Server:** Raspberry Pi 5 (`192.168.2.49`) — gleicher Host wie Shinkan/Mitai
|
||||
**Runner:** Gitea Actions (`/home/lars/gitea-runner/`)
|
||||
|
||||
---
|
||||
|
||||
## Port- und Pfad-Übersicht
|
||||
|
||||
| | Production | Development |
|
||||
|---|------------|-------------|
|
||||
| **Git-Branch** | `main` | `develop` |
|
||||
| **Server-Verzeichnis** | `/home/lars/docker/kairo` | `/home/lars/docker/kairo-dev` |
|
||||
| **Frontend-Port** | 3004 | 3097 |
|
||||
| **Backend-Port** | 8004 | 8097 |
|
||||
| **PostgreSQL** | nur im Container-Netz (Prod optional localhost:5436) | nur im Container-Netz |
|
||||
| **Domain** | kairo.jinkendo.de | dev.kairo.jinkendo.de |
|
||||
|
||||
---
|
||||
|
||||
## Einmalige Server-Einrichtung
|
||||
|
||||
```bash
|
||||
mkdir -p /home/lars/docker/kairo /home/lars/docker/kairo-dev
|
||||
|
||||
cd /home/lars/docker/kairo-dev
|
||||
git clone http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git .
|
||||
git checkout develop
|
||||
cp .env.example .env
|
||||
# DB_PASSWORD setzen
|
||||
|
||||
cd /home/lars/docker/kairo
|
||||
git clone http://192.168.2.144:3000/Lars/Kairo-Jinkendo.git .
|
||||
git checkout main
|
||||
cp .env.example .env
|
||||
# Prod-DB_PASSWORD setzen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Gitea Actions – Checkliste
|
||||
|
||||
1. **Actions aktiviert** (Repository → Settings → Actions)
|
||||
2. **Pi-Runner registriert** — derselbe wie Shinkan/Mitai (`ubuntu-latest`)
|
||||
3. Push `develop` → `deploy-dev.yml` → `curl http://localhost:8097/api/health`
|
||||
4. Merge `main` → `deploy-prod.yml` → `curl http://localhost:8004/api/health`
|
||||
5. Push `main` → `deploy-prod.yml` + `test.yml` (Prod pytest/k6/Playwright auf localhost 8004/3004)
|
||||
|
||||
| Workflow | Trigger | Zweck |
|
||||
|----------|---------|--------|
|
||||
| `deploy-dev.yml` | Push `develop` | Deploy nach `/home/lars/docker/kairo-dev` |
|
||||
| `deploy-prod.yml` | Push `main` | Deploy nach `/home/lars/docker/kairo` |
|
||||
| `test.yml` | Push `develop`/`main`, PR `develop` | lint, pytest, k6, Playwright gegen deployte Instanz |
|
||||
| `test.yml` → `compose-smoke` | Pull Request | Eigener Stack auf **CI-Ports 18197/13197** |
|
||||
|
||||
Struktur wie Shinkan: **Deploy** und **Test Suite** sind getrennte Workflows in Gitea.
|
||||
|
||||
Bei Push auf `develop` oder `main` starten Deploy und Test Suite parallel; pytest wartet auf den Backend-Container (Dev: 8097/3097, Prod: 8004/3004).
|
||||
|
||||
---
|
||||
|
||||
## Medien (optional)
|
||||
|
||||
Aktuell keine Medien-Speicherung. Bei Bedarf: NAS-Mount + `docker-compose.override.yml` (siehe frühere Doku-Version im Git-Verlauf).
|
||||
|
||||
---
|
||||
|
||||
## Reverse Proxy (optional)
|
||||
|
||||
| Hostname | Ziel (Pi) |
|
||||
|----------|-----------|
|
||||
| `kairo.jinkendo.de` | `http://192.168.2.49:3004` |
|
||||
| `dev.kairo.jinkendo.de` | `http://192.168.2.49:3097` |
|
||||
|
||||
---
|
||||
|
||||
## Datenbank-Passwort (Dev & Prod)
|
||||
|
||||
PostgreSQL im Compose-Stack initialisiert User/Passwort **nur beim ersten Start** des Volumes.
|
||||
Wenn `DB_PASSWORD` in `.env` nicht mehr zum Volume passt, scheitert das Backend mit
|
||||
`password authentication failed for user "kairo_user"` — der Container bleibt `unhealthy`.
|
||||
|
||||
**Prod (Daten behalten):** Passwort in der laufenden DB an `.env` anpassen:
|
||||
|
||||
```bash
|
||||
cd /home/lars/docker/kairo
|
||||
set -a && source .env && set +a
|
||||
docker compose exec -T postgres psql -U kairo_user -d kairo \
|
||||
-c "ALTER USER kairo_user WITH PASSWORD '${DB_PASSWORD}';"
|
||||
docker compose restart backend
|
||||
curl -sf http://localhost:8004/api/health
|
||||
```
|
||||
|
||||
**Dev (Volume neu, inkl. Testdaten):** Volume löschen und neu starten (`dev-kairo-db-data`).
|
||||
Wenn du `DB_NAME`, `DB_USER` oder `DB_PASSWORD` in `.env` änderst, muss das Volume neu angelegt werden:
|
||||
|
||||
```bash
|
||||
cd /home/lars/docker/kairo-dev
|
||||
docker compose -f docker-compose.dev-env.yml down -v
|
||||
docker compose -f docker-compose.dev-env.yml up -d --wait
|
||||
curl -sf http://localhost:8097/api/health
|
||||
```
|
||||
|
||||
Danach laufen Migrationen und Dev-Seeds automatisch (u. a. `lars@stommer.com`).
|
||||
|
||||
---
|
||||
|
||||
## Manuelles Deploy
|
||||
|
||||
```bash
|
||||
# Development
|
||||
cd /home/lars/docker/kairo-dev
|
||||
git fetch origin develop && git reset --hard origin/develop
|
||||
docker compose -f docker-compose.dev-env.yml build --no-cache
|
||||
docker compose -f docker-compose.dev-env.yml up -d
|
||||
|
||||
# Production
|
||||
cd /home/lars/docker/kairo
|
||||
git fetch origin main && git reset --hard origin/main
|
||||
docker compose build --no-cache
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Health: `curl http://localhost:8097/api/health` (Dev) bzw. `http://localhost:8004/api/health` (Prod)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Migrationen & Data-Seeds
|
||||
|
||||
Kairo trennt **Schema-Migrationen** (einmalig) von **Data-Seeds** (idempotent, bei Änderung erneut ausführbar).
|
||||
|
||||
## Schema-Migrationen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Pfad** | `backend/migrations/NNN_beschreibung.sql` |
|
||||
| **Tracking** | Tabelle `schema_migrations` |
|
||||
| **Ausführung** | Beim Backend-Start (`run_migrations.py`), überspringbar via `SKIP_DB_MIGRATE=1` |
|
||||
| **Regel** | Jede Datei wird **genau einmal** angewendet. Änderungen → neue nummerierte Datei. |
|
||||
|
||||
## Data-Seeds
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Pfad** | `backend/seeds/seed_NNN_beschreibung.sql` oder `.py` |
|
||||
| **Tracking** | Tabelle `data_seeds` (Name + SHA256-Checksum) |
|
||||
| **Ausführung** | Nach Schema-Migrationen (`run_seeds.py`), überspringbar via `SKIP_SEEDS=1` |
|
||||
| **Regel** | Seed läuft erneut, wenn die Datei **geändert** wurde (Checksum abweicht) oder `--force` gesetzt ist. |
|
||||
|
||||
### Umgebungsfilter
|
||||
|
||||
Dateien mit **`.dev.`** im Namen (z. B. `seed_001_….dev.sql`) laufen **nicht in Production** (`ENVIRONMENT=production`).
|
||||
|
||||
### Seeds manuell ausführen
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.dev-env.yml exec backend python run_seeds.py
|
||||
docker compose -f docker-compose.dev-env.yml exec backend python run_seeds.py --only seed_001_cleanup_pytest_artifacts --force
|
||||
```
|
||||
|
||||
## Aktuelle Seeds
|
||||
|
||||
| Seed | Typ | Zweck |
|
||||
|------|-----|--------|
|
||||
| `seed_001_cleanup_pytest_artifacts` | SQL (dev) | Entfernt pytest/CI-User (`*@example.com`) und verwaiste Test-Tenants |
|
||||
| `seed_002_bootstrap_admin` | Python | Legt Systemadmin aus `KAIRO_BOOTSTRAP_*` an, wenn noch kein User existiert |
|
||||
| `seed_003_ensure_dev_admin` | Python (dev) | Entfernt fremde Dev-User, stellt `lars@stommer.com` als Portal-Admin sicher (jeder Start) |
|
||||
|
||||
Dev-Seeds (`.dev.*`) werden in Nicht-Prod-Umgebungen **bei jedem Backend-Start** erneut ausgeführt.
|
||||
|
||||
## Neuen Seed anlegen
|
||||
|
||||
1. Datei `backend/seeds/seed_NNN_kurzname.sql` oder `.py` anlegen (Python: `def run() -> None:`).
|
||||
2. SQL idempotent halten (`DELETE … WHERE …`, `INSERT … ON CONFLICT`, etc.).
|
||||
3. Nur Dev/CI: `.dev.sql` / `.dev.py` Suffix verwenden.
|
||||
4. Nach Deploy prüfen: `python run_seeds.py` — bei geänderter Datei wird der Seed automatisch erneut ausgeführt.
|
||||
|
||||
## Tests & CI
|
||||
|
||||
- pytest setzt `SKIP_SEEDS=1` beim App-Import; Cleanup läuft über Fixture + nach CI-pytest.
|
||||
- Geteilte Dev-DB wird nach jedem Test-Lauf bereinigt (`run_seeds.py --only seed_001_cleanup_pytest_artifacts --force`).
|
||||
@@ -0,0 +1,38 @@
|
||||
# Architecture Decision Proposal
|
||||
|
||||
Status: Entwurf
|
||||
Stand: YYYY-MM-DD
|
||||
Autor:
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
Was ist die konkrete Entscheidungssituation?
|
||||
|
||||
## Betroffene Regel
|
||||
|
||||
Welches verbindliche Dokument oder Prinzip (Gate, Foundation, Spec) ist betroffen?
|
||||
|
||||
## Optionen
|
||||
|
||||
| Option | Kurzbeschreibung | Pro | Contra |
|
||||
|--------|------------------|-----|--------|
|
||||
| A | | | |
|
||||
| B | | | |
|
||||
|
||||
## Empfehlung
|
||||
|
||||
Welche Option und warum?
|
||||
|
||||
## Risiko
|
||||
|
||||
Was kann schiefgehen?
|
||||
|
||||
## Rückbaubarkeit
|
||||
|
||||
Wie lässt sich die Entscheidung rückgängig machen oder später verfeinern?
|
||||
|
||||
## Auswirkung auf Sprint 0
|
||||
|
||||
Betrifft das den Sprint-0-Scope oder nur spätere Arbeitspakete?
|
||||
@@ -0,0 +1,200 @@
|
||||
# Jinkendo Foundation
|
||||
## Minimum Viable Foundation v0.2
|
||||
|
||||
Status: Arbeitsfassung
|
||||
Stand: 2026-07-04
|
||||
Zweck: Minimale produktübergreifende Grundlage, soweit sie für Jinkendo Kairo Sprint 0 zwingend relevant ist.
|
||||
|
||||
---
|
||||
|
||||
## 1. Zweck
|
||||
|
||||
Diese Minimum Viable Foundation beschreibt nur die produktübergreifenden Prinzipien, die Kairo von Anfang an korrekt berücksichtigen muss.
|
||||
|
||||
Sie ist keine vollständige Zielarchitektur der Jinkendo-Produktfamilie.
|
||||
|
||||
Sie erzwingt keine Konvergenz von Mitai und Shinkan.
|
||||
|
||||
Sie verhindert nur, dass Kairo grundlegende Plattformkonzepte falsch oder isoliert implementiert.
|
||||
|
||||
---
|
||||
|
||||
## 2. Geltungsbereich
|
||||
|
||||
Gilt für Kairo Sprint 0 und spätere neue Jinkendo-Produkte, soweit dieselben Prinzipien relevant sind.
|
||||
|
||||
Nicht Gegenstand:
|
||||
|
||||
- Umbau von Mitai
|
||||
- Umbau von Shinkan
|
||||
- zentrale Familienarchitektur
|
||||
- Billing
|
||||
- SSO
|
||||
- vollständige Shared Packages
|
||||
|
||||
---
|
||||
|
||||
## 3. Drift-Schutz
|
||||
|
||||
Ein Prinzip wird nur Sprint-0-verbindlich, wenn alle drei Fragen mit „Ja“ beantwortet werden:
|
||||
|
||||
1. Verhindert es später teures strukturelles Refactoring in Kairo?
|
||||
2. Ist es für Sprint 0 zwingend erforderlich?
|
||||
3. Kann es minimal umgesetzt werden, ohne Kairo zu überladen?
|
||||
|
||||
Alles andere kommt ins Architektur-Backlog.
|
||||
|
||||
---
|
||||
|
||||
## 4. Verbindliche Foundation-Prinzipien für Kairo Sprint 0
|
||||
|
||||
### F-01 Tenant-first
|
||||
|
||||
Kairo ist mandantenfähig zu modellieren.
|
||||
|
||||
Alle fachlichen Objekte benötigen Tenant-Bezug oder einen expliziten globalen Scope.
|
||||
|
||||
### F-02 Actor-first
|
||||
|
||||
Operative Verantwortung wird Actors zugeordnet.
|
||||
|
||||
Actors können Menschen, KI-Agenten, Arbeitsgruppen oder externe Systeme sein.
|
||||
|
||||
### F-03 TenantContext pro Request
|
||||
|
||||
Jeder geschützte Request muss einen aufgelösten Kontext besitzen:
|
||||
|
||||
- User
|
||||
- Tenant
|
||||
- Actor
|
||||
- Rollen
|
||||
- Capabilities
|
||||
|
||||
### F-04 Auth, Capability, Feature und Governance trennen
|
||||
|
||||
Kairo vermischt nicht:
|
||||
|
||||
- Auth: Wer ist eingeloggt?
|
||||
- Capability: Darf diese Funktion genutzt werden?
|
||||
- Feature: Welche Produktfunktion ist betroffen?
|
||||
- Governance: Darf dieses Objekt gesehen oder verändert werden?
|
||||
|
||||
Feature-Limits und Billing werden nur vorbereitet, nicht in Sprint 0 vollständig gebaut.
|
||||
|
||||
### F-05 Registry-first
|
||||
|
||||
Neue steuerungsrelevante Funktionen registrieren sich an zentralen Registries.
|
||||
|
||||
Mindestens:
|
||||
|
||||
- Rights / Capability Registry
|
||||
- Feature Registry
|
||||
- Prompt Registry
|
||||
- Configuration Registry
|
||||
|
||||
### F-06 Prompts nicht hardcoden
|
||||
|
||||
Produktive interne Prompts liegen nicht hart im Code.
|
||||
|
||||
Sprint 0 benötigt:
|
||||
|
||||
- Prompt Template
|
||||
- Prompt Version
|
||||
- Placeholder
|
||||
- Kontextart
|
||||
- Admin-Scope
|
||||
|
||||
### F-07 Platzhalter kontrollieren
|
||||
|
||||
Platzhalter sind typisiert, dokumentiert und werden validiert.
|
||||
|
||||
Fehlende Pflichtplatzhalter führen zu kontrollierten Fehlern.
|
||||
|
||||
### F-08 Keine hardcodierte fachliche Konfiguration
|
||||
|
||||
Nicht hardcodieren:
|
||||
|
||||
- Rollen
|
||||
- Rechte
|
||||
- Prompts
|
||||
- fachliche Statuslisten
|
||||
- Feature-Flags mit fachlicher Bedeutung
|
||||
- Workflowparameter
|
||||
- AI-Modellzuordnung
|
||||
|
||||
Technische Defaults sind erlaubt, müssen aber dokumentiert und später überschreibbar sein.
|
||||
|
||||
### F-09 Audit für Admin- und Agentenaktionen
|
||||
|
||||
Administrative und agentenbezogene Aktionen müssen auditierbar sein.
|
||||
|
||||
Sprint 0 benötigt ein einfaches AuditLog-Modell.
|
||||
|
||||
### F-10 Nummerierte Migrationen und Fail-Fast-Startup
|
||||
|
||||
Schemaänderungen laufen über nummerierte Migrationen.
|
||||
|
||||
Fehlgeschlagene Migrationen dürfen den App-Start blockieren.
|
||||
|
||||
---
|
||||
|
||||
## 5. Bewusst nicht Sprint-0-verbindlich
|
||||
|
||||
Nicht in Sprint 0:
|
||||
|
||||
- vollständige Entitlement-/Billing-Engine
|
||||
- Usage-Zähler
|
||||
- Tiers
|
||||
- Pläne
|
||||
- Coupons
|
||||
- SSO
|
||||
- vollständige Mitai Prompt Engine
|
||||
- Shinkan Access Layer mit Vereinslogik
|
||||
- Widget Dashboard
|
||||
- Data Layer nach Mitai-Vorbild
|
||||
- Import-Framework
|
||||
- Media Assets
|
||||
- Content Reports
|
||||
- Maturity Models
|
||||
|
||||
---
|
||||
|
||||
## 6. Referenzprinzipien
|
||||
|
||||
### Aus Mitai relevant
|
||||
|
||||
- Prompt Templates nicht hardcoden
|
||||
- zentrale Prompt-Ausführung als Zielbild
|
||||
- Registry-Muster
|
||||
- Feature-Registry als Konzept
|
||||
- Migration/Deploy-Standard
|
||||
- Auth-Session-Basis
|
||||
|
||||
### Aus Shinkan relevant
|
||||
|
||||
- TenantContext
|
||||
- Trennung von Portalrolle und fachlicher Rolle
|
||||
- Rights Registry
|
||||
- Capabilities vs. Features
|
||||
- Entitlements-Snapshot als API-Idee
|
||||
- schmale AI Prompt Runtime als Sprint-0-kompatibles Vorbild
|
||||
|
||||
---
|
||||
|
||||
## 7. Kairo-spezifische Entscheidung
|
||||
|
||||
Kairo übernimmt keine allgemeine Familienarchitektur.
|
||||
|
||||
Kairo übernimmt nur:
|
||||
|
||||
```text
|
||||
Tenant + Actor + TenantContext
|
||||
Capability Registry
|
||||
Feature Registry minimal
|
||||
Prompt Registry minimal
|
||||
Placeholder validiert
|
||||
Audit
|
||||
Migration/Deploy
|
||||
```
|
||||
|
||||
Alles andere ist späteres Architektur-Backlog.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Kairo Architecture References v0.1
|
||||
|
||||
Status: verbindliche Referenzliste für Coding-Agenten
|
||||
Stand: 2026-07-04
|
||||
|
||||
## Primäre Kairo-Dokumente
|
||||
|
||||
1. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
2. `docs/architecture/Jinkendo_Foundation_Minimum_Viable_Foundation_v0.2.md`
|
||||
3. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
4. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
5. `docs/sprints/Sprint0_Vibe_Coder_Handover_v0.1.md`
|
||||
6. `CLAUDE.md`
|
||||
7. `.cursor/rules/kairo-architecture.mdc`
|
||||
8. `docs/sprints/Sprint0_AP0_1_Project_Setup_Assignment_v0.1.md`
|
||||
|
||||
## Hilfsdokumente
|
||||
|
||||
- `docs/architecture/ARCHITECTURE_DECISION_PROPOSAL_TEMPLATE.md`
|
||||
- `infra/README.md` — Platzhalter für serverseitige Infra-Ergänzungen
|
||||
|
||||
## Referenzdokumente
|
||||
|
||||
### Alignment
|
||||
|
||||
- `docs/reference/design-principles/alignment/DESIGN_PRINCIPLES_ALIGNMENT.md`
|
||||
- `docs/reference/design-principles/alignment/FAMILY_ENTITLEMENT_MODEL.md`
|
||||
|
||||
### Mitai
|
||||
|
||||
- `docs/reference/design-principles/mitai/PROMPT_ENGINE_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/mitai/REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/mitai/FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/mitai/AUTH_SESSION_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/mitai/MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md`
|
||||
|
||||
### Shinkan
|
||||
|
||||
- `docs/reference/design-principles/shinkan/ACCESS_LAYER_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/shinkan/RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/shinkan/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/shinkan/AI_PROMPT_RUNTIME_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/shinkan/AUTH_SESSION_DESIGN_PRINCIPLES.md`
|
||||
- `docs/reference/design-principles/shinkan/MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md`
|
||||
|
||||
## Auslegungsregel
|
||||
|
||||
Bei Konflikten gilt diese Reihenfolge:
|
||||
|
||||
1. Kairo Sprint-0 Principle Gate
|
||||
2. Sprint-0 Foundation v0.3
|
||||
3. Kairo Product Spec
|
||||
4. Kairo Foundation v0.2
|
||||
5. Alignment-Dokumente
|
||||
6. Mitai/Shinkan Einzelprinzipien
|
||||
|
||||
Mitai/Shinkan-Dokumente dürfen Kairo nicht überstimmen.
|
||||
|
||||
## Drift-Regel
|
||||
|
||||
Ein Agent darf Designprinzipien nur als Begründung verwenden, nicht als Erweiterungsauftrag.
|
||||
|
||||
Erlaubt:
|
||||
> Shinkan Rights Registry begründet, warum Kairo eine Capability Registry braucht.
|
||||
|
||||
Nicht erlaubt:
|
||||
> Shinkan hat Club Features, also bauen wir Club Features in Kairo.
|
||||
@@ -0,0 +1,105 @@
|
||||
# Jinkendo Kairo
|
||||
## Sprint-0 Principle Gate v0.1
|
||||
|
||||
Status: verbindlicher Scope-Filter für Sprint 0
|
||||
Stand: 2026-07-04
|
||||
|
||||
---
|
||||
|
||||
## 1. Zweck
|
||||
|
||||
Dieses Dokument verhindert Drift.
|
||||
|
||||
Es legt fest, welche Prinzipien aus Mitai/Shinkan/Family-Alignment für Kairo Sprint 0 verbindlich sind und welche ausdrücklich nicht umgesetzt werden.
|
||||
|
||||
---
|
||||
|
||||
## 2. Entscheidungsregel
|
||||
|
||||
Ein Prinzip ist nur dann Sprint-0-verbindlich, wenn alle drei Fragen mit Ja beantwortet werden:
|
||||
|
||||
1. Verhindert es später teures strukturelles Refactoring?
|
||||
2. Ist es für Sprint 0 zwingend erforderlich?
|
||||
3. Kann es minimal umgesetzt werden, ohne Kairo zu überladen?
|
||||
|
||||
---
|
||||
|
||||
## 3. Sprint-0-verbindliche Prinzipien
|
||||
|
||||
| ID | Prinzip | Sprint-0-Konsequenz |
|
||||
|---|---|---|
|
||||
| G-01 | Tenant-first | Tenant ist Kernobjekt; keine Single-User-Architektur |
|
||||
| G-02 | Actor-first | Assignments gehen an Actors, nicht direkt an User |
|
||||
| G-03 | TenantContext pro Request | Auth-Kontext wird zentral aufgelöst |
|
||||
| G-04 | Auth / Capability / Feature / Governance trennen | Keine Vermischung von Login, Rollen, Limits und Objektzugriff |
|
||||
| G-05 | Rights Registry | Rechte/Capabilities werden registriert, nicht verstreut hardcodiert |
|
||||
| G-06 | Feature Registry minimal | Features sind bekannt und benannt, auch wenn Limits später kommen |
|
||||
| G-07 | Prompt Registry minimal | Prompts sind administrierbare Templates, nicht Code-Strings |
|
||||
| G-08 | Platzhalter validieren | Pflichtplatzhalter dürfen nicht stillschweigend fehlen |
|
||||
| G-09 | Config statt Hardcoding | Fachliche Konfiguration nicht im Code verdrahten |
|
||||
| G-10 | Audit | Admin- und Agentenaktionen werden protokolliert |
|
||||
| G-11 | Migration Standard | Nummerierte SQL-Migrationen + Tracking |
|
||||
| G-12 | Fail-Fast Startup | App startet nicht mit fehlerhaftem Schema |
|
||||
|
||||
---
|
||||
|
||||
## 4. Nur vorbereiten, nicht vollständig bauen
|
||||
|
||||
| Thema | Sprint-0-Umfang |
|
||||
|---|---|
|
||||
| Entitlements | Minimaler `/me/entitlements` Snapshot: tenant, actor, roles, capabilities |
|
||||
| Feature Limits | Datenmodell optional vorbereiten; keine Usage-Zähler |
|
||||
| Prompt Engine | Templates, Versionen, Platzhalter; keine Workflows/Pipelines |
|
||||
| Admin UI | Minimal prüfbar; keine ausgereifte Oberfläche |
|
||||
| MCP | Schnittstellen später; keine MCP-Implementierung in Sprint 0 |
|
||||
| AI Agenten | Actor Type Agent vorbereiten; keine vollständige Agentensteuerung |
|
||||
|
||||
---
|
||||
|
||||
## 5. Explizit nicht Sprint 0
|
||||
|
||||
- Billing
|
||||
- Tiers
|
||||
- Pläne
|
||||
- Coupons
|
||||
- Usage-Zähler
|
||||
- SSO
|
||||
- Mitai Data Layer
|
||||
- Mitai Widget Dashboard
|
||||
- Universal Import
|
||||
- Shinkan Exercise Catalog
|
||||
- Shinkan Training Planning
|
||||
- Shinkan Media Assets
|
||||
- Shinkan Content Reports
|
||||
- Shinkan Maturity Models
|
||||
- vollständige Familien-Konvergenz
|
||||
- Lebensmanager-/Seichō-Fachlogik
|
||||
|
||||
---
|
||||
|
||||
## 6. Review-Regel
|
||||
|
||||
Jeder neue Vorschlag im Sprint wird mit einer Kategorie versehen:
|
||||
|
||||
```text
|
||||
A – Sprint-0-verbindlich
|
||||
B – Architektur-Backlog
|
||||
C – Produktspezifisch / ignorieren
|
||||
```
|
||||
|
||||
Nur Kategorie A darf in Sprint 0 umgesetzt werden.
|
||||
|
||||
---
|
||||
|
||||
## 7. Abweichungsregel
|
||||
|
||||
Ein Coding-Agent darf nicht eigenmächtig von diesem Gate abweichen.
|
||||
|
||||
Bei notwendiger Abweichung erstellt er ein Architecture Decision Proposal mit:
|
||||
|
||||
- Problem
|
||||
- betroffene Regel
|
||||
- vorgeschlagene Änderung
|
||||
- Risiko
|
||||
- Alternative
|
||||
- Empfehlung
|
||||
@@ -0,0 +1,448 @@
|
||||
# Jinkendo Kairo
|
||||
## Product Spec v0.2
|
||||
|
||||
Status: Arbeitsfassung
|
||||
Stand: 2026-07-04
|
||||
Zweck: Konsolidierte Produktspezifikation für den Start des neuen Kairo-Repositories.
|
||||
|
||||
---
|
||||
|
||||
## 1. Produktidentität
|
||||
|
||||
**Jinkendo Kairo** ist der operative Program Director der Jinkendo-Produktfamilie.
|
||||
|
||||
Kairo steuert Vorhaben, Programme, Projekte, Meilensteine, Maßnahmen, Backlogs, Reviews, Nachweise und die Zusammenarbeit von Menschen, Arbeitsgruppen und KI-Agenten.
|
||||
|
||||
**Leitfrage:**
|
||||
|
||||
> Welcher nächste Schritt bringt ein Vorhaben aktuell am wirkungsvollsten voran?
|
||||
|
||||
---
|
||||
|
||||
## 2. Produktgrenze
|
||||
|
||||
Kairo ist kein klassischer Projektmanager, keine reine ToDo-App und kein reines Softwareentwicklungstool.
|
||||
|
||||
Kairo ist auch kein Lebenssinn-, Identitäts- oder Gesundheitsprodukt.
|
||||
|
||||
### Kairo verantwortet
|
||||
|
||||
- Vorhaben
|
||||
- Programme
|
||||
- Projekte
|
||||
- Meilensteine
|
||||
- Maßnahmen
|
||||
- Backlog Items
|
||||
- Nachweise
|
||||
- Reviews
|
||||
- Entscheidungen
|
||||
- Blocker
|
||||
- Actor-Zuweisungen
|
||||
- Arbeitsgruppen
|
||||
- KI-Agenten
|
||||
- operative Priorisierung
|
||||
- Umsetzungstransparenz
|
||||
|
||||
### Kairo verantwortet nicht
|
||||
|
||||
- persönliche Identität
|
||||
- Lebensvisionen
|
||||
- persönliche Entwicklungsmodelle
|
||||
- Gesundheitsdaten
|
||||
- Trainingsfachlogik
|
||||
- Wissensmanagement
|
||||
- Ernährungslogik
|
||||
- Skill- oder Reifegradmodelle aus Shinkan
|
||||
|
||||
Diese Domänen gehören zu anderen Jinkendo-Produkten wie mindnet, Mitai, Shinkan und perspektivisch Seichō.
|
||||
|
||||
---
|
||||
|
||||
## 3. Abgrenzung zu Seichō
|
||||
|
||||
**Seichō** verantwortet persönliche Entwicklung.
|
||||
|
||||
**Kairo** verantwortet operative Umsetzung.
|
||||
|
||||
Beispiel:
|
||||
|
||||
- Seichō: „Ich möchte als Vater präsenter werden.“
|
||||
- Kairo: „Welche konkreten Vorhaben, Meilensteine und Maßnahmen setzen das um?“
|
||||
|
||||
Kairo darf persönliche Entwicklungsziele aus Seichō operativ unterstützen, aber nicht die persönliche Entwicklungslogik selbst übernehmen.
|
||||
|
||||
---
|
||||
|
||||
## 4. Stable Core und Agile Edge
|
||||
|
||||
### Stable Core
|
||||
|
||||
Der Stable Core wird nur bewusst und selten geändert.
|
||||
|
||||
Er umfasst:
|
||||
|
||||
- Fachsprache
|
||||
- Kernobjekte
|
||||
- Produktgrenzen
|
||||
- Actor-Modell
|
||||
- Tenant-Modell
|
||||
- Backlog-Modell
|
||||
- Meilensteinmodell
|
||||
- Rechte-/Capability-Grundmodell
|
||||
- Prompt-/Registry-Grundmodell
|
||||
- Änderungsregeln
|
||||
- Agentenregeln
|
||||
|
||||
### Agile Edge
|
||||
|
||||
Der Agile Edge darf iterativ wachsen.
|
||||
|
||||
Er umfasst:
|
||||
|
||||
- UI
|
||||
- Dashboards
|
||||
- Reports
|
||||
- MCP-Tools
|
||||
- Integrationen
|
||||
- Automationen
|
||||
- Priorisierungsstrategien
|
||||
- Visualisierungen
|
||||
- Komfortfunktionen
|
||||
|
||||
---
|
||||
|
||||
## 5. Ubiquitous Language
|
||||
|
||||
| Begriff | Bedeutung |
|
||||
|---|---|
|
||||
| Vision | Langfristig gewünschter Zustand; primär außerhalb Kairo |
|
||||
| Vorhaben | Aktiv verfolgte Veränderung oder angestrebtes Ergebnis |
|
||||
| Programm | Bündel zusammengehöriger Projekte |
|
||||
| Projekt | Zeitlich begrenzte Ergebniserzeugung |
|
||||
| Meilenstein | Überprüfbarer Zielzustand, keine Aufgabe |
|
||||
| Maßnahme | Kleinste operative Arbeitseinheit mit eindeutigem Ergebnis |
|
||||
| Backlog Item | Noch nicht verbindlich priorisierter Handlungsbedarf |
|
||||
| Review | Strukturierte Bewertung eines Scopes |
|
||||
| Nachweis | Beleg für Fortschritt, Abschluss oder Entscheidung |
|
||||
| Entscheidung | Festgehaltene Auswahl zwischen Optionen |
|
||||
| Blocker | Hindernis, das Fortschritt verhindert oder stark erschwert |
|
||||
| Actor | Mensch, KI-Agent, Arbeitsgruppe oder externes System |
|
||||
| Assignment | Zuweisung einer Maßnahme an einen oder mehrere Actors |
|
||||
| Tenant | Abgegrenzter Nutzungsraum, z. B. Person, Familie, Team, Organisation |
|
||||
| TenantContext | Aufgelöster Request-Kontext mit User, Tenant, Actor, Rollen und Capabilities |
|
||||
| Capability | Funktionale Erlaubnis: „Darf Actor X diese Funktion nutzen?“ |
|
||||
| Feature | Registrierte Produktfunktion, optional später mit Limit/Kontingent |
|
||||
| Governance | Objektbezogene Zugriffslogik: „Darf Actor X dieses Objekt sehen/ändern?“ |
|
||||
|
||||
Neue Begriffe werden nur eingeführt, wenn bestehende Begriffe fachlich nicht ausreichen.
|
||||
|
||||
---
|
||||
|
||||
## 6. Grundstruktur
|
||||
|
||||
```text
|
||||
Tenant
|
||||
└── Actor
|
||||
└── Vorhaben
|
||||
├── Programm
|
||||
│ └── Projekt
|
||||
│ ├── Meilenstein
|
||||
│ ├── Maßnahme
|
||||
│ └── Backlog Item
|
||||
├── Meilenstein
|
||||
├── Maßnahme
|
||||
├── Backlog Item
|
||||
├── Nachweis
|
||||
└── Review
|
||||
```
|
||||
|
||||
Nicht jedes Vorhaben benötigt Programme oder Projekte.
|
||||
|
||||
Kleine Vorhaben können direkt Meilensteine, Maßnahmen und Backlog Items besitzen.
|
||||
|
||||
---
|
||||
|
||||
## 7. Kernobjekte
|
||||
|
||||
### Tenant
|
||||
|
||||
Ein Tenant ist ein abgegrenzter Nutzungsraum.
|
||||
|
||||
Beispiele:
|
||||
|
||||
- persönlicher Arbeitsraum
|
||||
- Familie
|
||||
- Verein
|
||||
- Team
|
||||
- Organisation
|
||||
- Projektverbund
|
||||
|
||||
### User
|
||||
|
||||
Ein User ist ein authentifizierter Account.
|
||||
|
||||
Ein User kann Mitglied mehrerer Tenants sein.
|
||||
|
||||
### Actor
|
||||
|
||||
Ein Actor ist die operative Zurechnungseinheit.
|
||||
|
||||
Actor Types:
|
||||
|
||||
- Human
|
||||
- Agent
|
||||
- WorkingGroup
|
||||
- ExternalSystem
|
||||
|
||||
Alle Assignments erfolgen an Actors, nicht direkt an User.
|
||||
|
||||
### Vorhaben
|
||||
|
||||
Ein Vorhaben beschreibt eine aktiv verfolgte Veränderung oder ein angestrebtes Ergebnis.
|
||||
|
||||
Es besitzt mindestens:
|
||||
|
||||
- Titel
|
||||
- Zielzustand
|
||||
- Status
|
||||
- Priorität
|
||||
- verantwortliche Actors
|
||||
- Bezug zu Maßnahmen, Meilensteinen, Backlog und Reviews
|
||||
|
||||
### Programm
|
||||
|
||||
Ein Programm bündelt zusammengehörige Projekte oder Vorhabenanteile.
|
||||
|
||||
Programme sind optional.
|
||||
|
||||
### Projekt
|
||||
|
||||
Ein Projekt erzeugt ein konkretes Ergebnis innerhalb eines Vorhabens oder Programms.
|
||||
|
||||
### Meilenstein
|
||||
|
||||
Ein Meilenstein beschreibt einen überprüfbaren Zielzustand.
|
||||
|
||||
Er ist keine Aufgabe.
|
||||
|
||||
Mögliche Status:
|
||||
|
||||
- geplant
|
||||
- aktiv
|
||||
- gefährdet
|
||||
- erreicht
|
||||
- verschoben
|
||||
- verworfen
|
||||
|
||||
### Maßnahme
|
||||
|
||||
Eine Maßnahme ist die kleinste operative Arbeitseinheit.
|
||||
|
||||
Mögliche Status:
|
||||
|
||||
- offen
|
||||
- bereit
|
||||
- in Arbeit
|
||||
- blockiert
|
||||
- Review erforderlich
|
||||
- erledigt
|
||||
- verworfen
|
||||
|
||||
### Backlog Item
|
||||
|
||||
Backlog Items entstehen aus Ideen, Bugs, Risiken, Verbesserungen oder Agentenvorschlägen.
|
||||
|
||||
Sie verpflichten nicht automatisch zur Umsetzung.
|
||||
|
||||
### Nachweis
|
||||
|
||||
Nachweise belegen Fortschritt oder Abschluss.
|
||||
|
||||
Beispiele:
|
||||
|
||||
- Commit
|
||||
- Dokument
|
||||
- Link
|
||||
- Datei
|
||||
- Messwert
|
||||
- Foto
|
||||
- Review-Ergebnis
|
||||
- externe Bestätigung
|
||||
|
||||
### Review
|
||||
|
||||
Ein Review bewertet einen Scope und erzeugt ggf. Entscheidungen, Maßnahmen oder Backlog Items.
|
||||
|
||||
### Blocker
|
||||
|
||||
Ein Blocker verhindert oder gefährdet Fortschritt.
|
||||
|
||||
Blocker müssen sichtbar, zugeordnet und reviewbar sein.
|
||||
|
||||
---
|
||||
|
||||
## 8. Actor- und Assignment-Modell
|
||||
|
||||
Actors können Menschen, KI-Agenten, Arbeitsgruppen oder externe Systeme sein.
|
||||
|
||||
Unterstützte Assignment-Modi:
|
||||
|
||||
- Exclusive: genau ein verantwortlicher Actor
|
||||
- Collaborative: mehrere Actors arbeiten gemeinsam
|
||||
- Pool: eine Arbeitsgruppe oder ein Pool kann übernehmen
|
||||
- Proposed: Zuweisungsvorschlag, noch nicht angenommen
|
||||
- Auction: Actors bewerben sich oder übernehmen bewusst
|
||||
|
||||
Agenten sind keine Sonderfälle außerhalb des Modells.
|
||||
|
||||
---
|
||||
|
||||
## 9. Multiuser und Mandantenfähigkeit
|
||||
|
||||
Multiuser ist Kernfunktion, keine spätere Erweiterung.
|
||||
|
||||
Kairo unterstützt:
|
||||
|
||||
- private Vorhaben
|
||||
- Familienvorhaben
|
||||
- Teamvorhaben
|
||||
- Organisationsvorhaben
|
||||
- Arbeitsgruppen
|
||||
- KI-Agenten innerhalb eines Tenants
|
||||
- objektbezogene Sichtbarkeit und Bearbeitbarkeit
|
||||
|
||||
Jede fachliche Entität ist tenantfähig zu modellieren.
|
||||
|
||||
---
|
||||
|
||||
## 10. Rechte, Capabilities und Governance
|
||||
|
||||
Kairo trennt:
|
||||
|
||||
```text
|
||||
Auth = Wer ist eingeloggt?
|
||||
Capability = Darf Actor diese Funktion nutzen?
|
||||
Feature = Welche Produktfunktion ist betroffen?
|
||||
Governance = Darf Actor dieses konkrete Objekt sehen/ändern?
|
||||
```
|
||||
|
||||
Feature-Limits, Usage-Zähler, Billing, Tiers und Pläne sind nicht Bestandteil von Sprint 0, werden aber im Modell nicht verbaut.
|
||||
|
||||
---
|
||||
|
||||
## 11. Prompt- und AI-Grundmodell
|
||||
|
||||
Kairo nutzt intern keine hardcodierten Produktionsprompts.
|
||||
|
||||
Mindestmodell:
|
||||
|
||||
- Prompt Templates in DB oder konfigurierbarer Persistenz
|
||||
- Prompt Versions
|
||||
- typisierte Platzhalter
|
||||
- Kontextarten
|
||||
- Adminbarkeit
|
||||
- Preview/Testmöglichkeit später
|
||||
- zentrale Prompt-Ausführung als Fassade
|
||||
|
||||
Sprint 0 baut keine komplexe Workflow- oder Pipeline-Engine.
|
||||
|
||||
---
|
||||
|
||||
## 12. Registry-Grundmodell
|
||||
|
||||
Neue Funktionen registrieren sich an zentralen Steuerungsschichten.
|
||||
|
||||
Mindestens vorgesehen:
|
||||
|
||||
- Rights / Capability Registry
|
||||
- Feature Registry
|
||||
- Prompt Registry
|
||||
- Configuration Registry
|
||||
- Audit Events
|
||||
|
||||
Ziel: keine verstreuten, unsichtbaren Sonderlogiken.
|
||||
|
||||
---
|
||||
|
||||
## 13. Agentenregeln
|
||||
|
||||
Agenten dürfen:
|
||||
|
||||
- Kontext anfragen
|
||||
- nächste Maßnahme abfragen
|
||||
- Maßnahmen claimen
|
||||
- Fortschritt melden
|
||||
- Blocker melden
|
||||
- Backlog Items vorschlagen
|
||||
- Nachweise einreichen
|
||||
- Reviews anfordern
|
||||
|
||||
Agenten dürfen nicht ohne Freigabe:
|
||||
|
||||
- strategische Ziele ändern
|
||||
- Vorhaben löschen
|
||||
- Meilensteine verschieben
|
||||
- Rechte oder Rollen ändern
|
||||
- Prompts produktiv ändern
|
||||
- Admin-Konfiguration ändern
|
||||
- private Daten anderer Actors auswerten
|
||||
|
||||
---
|
||||
|
||||
## 14. Änderungsregime
|
||||
|
||||
Änderungen werden klassifiziert als:
|
||||
|
||||
| Ebene | Bedeutung |
|
||||
|---|---|
|
||||
| Operativ | Maßnahmen, Status, Nachweise, Kommentare |
|
||||
| Taktisch | Prioritäten, Meilensteinzuschnitt, Assignment-Modus |
|
||||
| Strategisch | Produktgrenze, Stable Core, grundlegende Ziele oder Rechte |
|
||||
|
||||
Strategische Änderungen benötigen menschliche Freigabe.
|
||||
|
||||
---
|
||||
|
||||
## 15. MVP-Zielbild
|
||||
|
||||
Der MVP umfasst nach Sprint 0 schrittweise:
|
||||
|
||||
- Tenant/User/Actor
|
||||
- Vorhaben
|
||||
- Projekte
|
||||
- Meilensteine
|
||||
- Maßnahmen
|
||||
- Backlog
|
||||
- Assignments
|
||||
- Arbeitsgruppen
|
||||
- Agentenstatus
|
||||
- Reviews
|
||||
- Nachweise
|
||||
- Blocker
|
||||
- Vorschlag der nächsten sinnvollen Maßnahme
|
||||
- MCP-Minimalintegration für Coding-Agenten
|
||||
|
||||
---
|
||||
|
||||
## 16. Nicht-Ziele des MVP
|
||||
|
||||
Nicht Teil des MVP:
|
||||
|
||||
- vollständige Mitai-Integration
|
||||
- vollständige Shinkan-Integration
|
||||
- vollständige mindnet-Integration
|
||||
- vollständige Seichō-Integration
|
||||
- vollständiges Billing
|
||||
- zentrales SSO
|
||||
- komplexe Prompt-Workflows
|
||||
- KI-Autopilot für strategische Entscheidungen
|
||||
- vollständiger Lebensmanager
|
||||
- Gesundheits- oder Trainingsdomänenlogik
|
||||
|
||||
---
|
||||
|
||||
## 17. Leitregel
|
||||
|
||||
Kairo steuert Umsetzung.
|
||||
|
||||
Sinn, Identität und persönliche Entwicklung verbleiben außerhalb seiner fachlichen Verantwortung.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Designprinzipien – Referenzpaket für Kairo
|
||||
|
||||
Status: Referenz / nicht automatisch verbindlich
|
||||
Stand: 2026-07-04
|
||||
|
||||
Dieses Verzeichnis enthält die extrahierten Designprinzipien aus Mitai und Shinkan sowie den Abgleich.
|
||||
|
||||
Diese Dokumente sind **Referenzmaterial**, kein direkter Sprint-Scope.
|
||||
|
||||
Verbindlich für Kairo ist nur, was in folgenden Dokumenten steht:
|
||||
|
||||
1. `docs/architecture/Kairo_Sprint0_Principle_Gate_v0.1.md`
|
||||
2. `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`
|
||||
3. `docs/product/Jinkendo_Kairo_Product_Spec_v0.2.md`
|
||||
4. eine spätere explizite Architecture Decision
|
||||
|
||||
## Struktur
|
||||
|
||||
```text
|
||||
docs/reference/design-principles/
|
||||
mitai/
|
||||
shinkan/
|
||||
alignment/
|
||||
```
|
||||
|
||||
## Für Kairo Sprint 0 relevant
|
||||
|
||||
- TenantContext / mandantenfähiger Request-Kontext
|
||||
- Actor-first statt User-first
|
||||
- Auth, Capability, Feature und Governance trennen
|
||||
- Rights / Capability Registry
|
||||
- minimale Feature Registry
|
||||
- minimale Prompt Registry
|
||||
- Prompt Templates nicht hardcoden
|
||||
- Template und Kontext trennen
|
||||
- typisierte und validierte Platzhalter
|
||||
- nummerierte Migrationen und Fail-Fast
|
||||
|
||||
## Nicht automatisch übernehmen
|
||||
|
||||
- Mitai Data Layer
|
||||
- Mitai Widget Dashboard
|
||||
- Mitai Universal Import
|
||||
- vollständige Mitai Prompt Engine
|
||||
- Shinkan Exercise Catalog
|
||||
- Shinkan Training Planning
|
||||
- Shinkan Skill Scoring
|
||||
- Shinkan Media Assets
|
||||
- Shinkan Content Reports
|
||||
- Shinkan Maturity Models
|
||||
- Billing, Tiers, Coupons, Usage-Limits
|
||||
- zentrale Familien-Konvergenz
|
||||
|
||||
## Regel
|
||||
|
||||
Wenn ein Agent ein Prinzip aus diesem Referenzpaket übernehmen möchte, das nicht im Sprint-0-Gate steht, muss er ein Architecture Decision Proposal erstellen.
|
||||
@@ -0,0 +1,358 @@
|
||||
# Designprinzipien – Abgleich Mitai ↔ Shinkan
|
||||
|
||||
**Status:** Review / Entscheidungsgrundlage
|
||||
**Stand:** 2026-07-04
|
||||
**Zweck:** Widersprüche, bewusste Abweichungen und Implementierungslücken zwischen den Designprinzipien-Serien identifizieren — Basis für **Familien-Entscheidungen** und langfristige Konvergenz von Mitai und Shinkan.
|
||||
|
||||
**Quellen:**
|
||||
|
||||
| App | Index |
|
||||
|-----|--------|
|
||||
| Mitai (Foundation) | [mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/README.md) — 9 Module |
|
||||
| Shinkan | [design-principles/DESIGN_PRINCIPLES_INDEX.md](./design-principles/DESIGN_PRINCIPLES_INDEX.md) — 15 Module |
|
||||
|
||||
---
|
||||
|
||||
## 1. Kurzfassung
|
||||
|
||||
| Kategorie | Anzahl | Bedeutung |
|
||||
|-----------|--------|-----------|
|
||||
| **Familien-Konsens** | 12 Muster | In beiden Serien gleich oder kompatibel — **verbindlich für neue Apps** |
|
||||
| **Bewusste Produkt-Abweichung** | 8 | Fachlich/Architektur begründet — **nicht angleichen**, aber im Familienmodell verankern |
|
||||
| **Konzeptuelle Spannung** | 6 | Widersprüche oder gegenläufige Defaults — **Familien-Entscheidung nötig** |
|
||||
| **Ist vs. Prinzip (Schuld)** | 14+ | Mindestens eine App verletzt eigene oder Schwester-Prinzipien — **Remediation** |
|
||||
| **Nur Shinkan** | 6 Module | Mandanten-/Domänen-Bausteine ohne Mitai-Pendant |
|
||||
| **Nur Mitai (reifer)** | 3 Muster | Data Layer, Widget-Dashboard, Universal Import — Shinkan vereinfacht oder fehlt |
|
||||
|
||||
**Kernbefund:** Mitai und Shinkan teilen dieselbe **technische Basis** (Auth, Migration, Nav-SSoT, Registry-Denken, Probe→Enforce), divergieren aber strukturell bei **Entitlement-Subjekt** (Profil vs. Verein), **Berechnungsarchitektur** (generischer Data Layer vs. domänenspezifisches Scoring) und **KI-Reife** (Unified Executor vs. schmale Laufzeit).
|
||||
|
||||
---
|
||||
|
||||
## 2. Familien-Konsens (für neue Produkte übernehmen)
|
||||
|
||||
Diese Muster sind in beiden Serien explizit oder implizit tragfähig:
|
||||
|
||||
| # | Muster | Mitai | Shinkan |
|
||||
|---|--------|-------|---------|
|
||||
| F1 | Server-Sessions + `Depends(require_auth)` | Auth #1–3 | Auth #1–2 |
|
||||
| F2 | `profile_id` aus Session, nie aus Client-Header | Auth #3 | Auth #3 |
|
||||
| F3 | Auth getrennt von Authorization/Entitlements | Auth #10 | Capabilities + Access Layer |
|
||||
| F4 | Nummerierte SQL-Migrationen + Tracking beim Container-Start | Migration #1–5 | Migration #1–3 |
|
||||
| F5 | Fail-fast, kein Auto-Rollback | Migration #5 | Migration #2 |
|
||||
| F6 | `appNav` / zentrale Nav-Config als SSoT | Navigation #1 | Navigation #1 |
|
||||
| F7 | Admin als eigener Hub/Realm | Navigation #6–7 | Navigation #2 |
|
||||
| F8 | DB-konfigurierbare KI-Prompts (nicht hardcoded Prod) | Prompt #2 | AI Runtime #2 |
|
||||
| F9 | Template vs. Kontext/Daten trennen | Prompt #5 | AI Runtime #4 |
|
||||
| F10 | Ingest ≠ Interpretation beim Import | Import #2 | Wiki Import #1 |
|
||||
| F11 | Preview/Dry-Run vor Massenimport | Import #3+ | Wiki Import #2 |
|
||||
| F12 | 4-Phasen-Rollout Entitlements (Log → Enforce) | Feature #8 | Capability #2 |
|
||||
|
||||
**Empfehlung:** Als **`JINKENDO_FOUNDATION_CHECKLIST`** in künftigen Apps verpflichtend; Details pro Modul in den Einzeldokumenten.
|
||||
|
||||
---
|
||||
|
||||
## 3. Modul-Abgleich (9 vergleichbare Paare)
|
||||
|
||||
Legende **Bewertung:**
|
||||
|
||||
| Symbol | Bedeutung |
|
||||
|--------|-----------|
|
||||
| ✅ | Prinzipien aligned / kompatibel |
|
||||
| ⚠️ | Teilweise aligned; Lücken in Implementierung oder Doku |
|
||||
| 🔀 | Bewusste Produkt-Divergenz (kein Bug) |
|
||||
| ❌ | Widerspruch oder gegenläufiges Konzept — Entscheidung nötig |
|
||||
| 🏗️ | Ist-Stand verletzt dokumentierte Prinzipien (Architekturschuld) |
|
||||
|
||||
---
|
||||
|
||||
### 3.1 Prompt Engine (Mitai #1) ↔ AI Prompt Runtime (Shinkan #5)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| Single Entry Point | `execute_prompt` / Unified System | `ai_prompt_runtime` + verteilte Orchestratoren | ❌ Konzept |
|
||||
| Prompt-Typen | base / pipeline / workflow | nur slug + Mustache | 🔀 Shinkan bewusst schlanker |
|
||||
| Platzhalter-Registry | zentral, API-Verträge | Kontext-Arten (`AiPromptContextKind`), kein Registry-Katalog | ⚠️ |
|
||||
| Data Layer-Anbindung | Layer 1 → Resolver | Domänen-Builder ad hoc | ⚠️ |
|
||||
| Debug/Preview | ausgereift | Admin-Vorschau, weniger Runtime-Transparenz | ⚠️ |
|
||||
| Feature-Gating an Execute | teils fehlend (Legacy) | Capability geplant, teils Probe | 🏗️ beide |
|
||||
|
||||
**Widersprüche / gegenläufig:**
|
||||
|
||||
- Mitai: **Ein Executor** ist Kernprinzip. Shinkan: **kein** vergleichbarer Executor — Planungs-KI umgeht teils die Laufzeit.
|
||||
- Beide warnen vor **parallelen KI-Pfaden**; beide haben sie noch (Mitai `insights.py`, Shinkan Router-OpenRouter).
|
||||
|
||||
**Familien-Entscheidung (Vorschlag):**
|
||||
|
||||
| Option | Inhalt |
|
||||
|--------|--------|
|
||||
| **Zielbild** | Gemeinsame **`prompt_executor`-Fassade** (Package oder Copy mit Namespace); Shinkan-Kontext-Builder als Plugins |
|
||||
| **Shinkan-Roadmap** | Planungs-Orchestrierung in Laufzeit ziehen; keine Workflow-Graphs vor Planungs-Kontext-Reife |
|
||||
| **Nicht kopieren** | Mitai: doppelte Pipeline-Modelle, PLACEHOLDER_MAP-Duplikat, Roh-SQL im Executor |
|
||||
|
||||
---
|
||||
|
||||
### 3.2 Data Layer (Mitai #2) ↔ Skill Scoring (Shinkan #8)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| Berechnungs-SSoT | `data_layer/` Layer 0→1→2 | nur `skill_scoring.py` | ❌ Abdeckung |
|
||||
| Router delegieren | explizites Prinzip #13 | Skill-Router ja; Planung teils nicht | ⚠️ |
|
||||
| Confidence / data_points | Pflicht-Metadaten | nicht analog | 🔀 Domäne anders |
|
||||
| Chart/KPI-Anbindung | Layer 2b Adapter | KPI-Dashboard ruft Router-Helfer | ⚠️ |
|
||||
| Import-Grenze | keine Scores beim Insert | Wiki: explizit kein Scoring beim Insert | ✅ |
|
||||
|
||||
**Widerspruch:**
|
||||
|
||||
- Mitai postuliert **generische Berechnungsschicht** für die ganze App. Shinkan hat **kein** Data Layer — nur ein **domänenspezifisches** Scoring-Modul. Das ist keine Implementierungslücke allein, sondern **unterschiedliche Architektur-Tiefe**.
|
||||
|
||||
**Familien-Entscheidung (Vorschlag):**
|
||||
|
||||
| Option | Inhalt |
|
||||
|--------|--------|
|
||||
| **Familien-Prinzip** | „Berechnungen in benannter Schicht, nicht in Router/React“ — **Ja** |
|
||||
| **Implementierung** | Mitai: `data_layer/` bleibt Referenz. Shinkan: Skill Scoring **ist** Layer-1-Vorbild; langfristig **`planning_metrics/`** o. ä. statt Router-SQL |
|
||||
| **Nicht verallgemeinern** | Mitai-Formeln (TDEE, WHR) — nur Schichtenmodell übernehmen |
|
||||
|
||||
---
|
||||
|
||||
### 3.3 Feature & Entitlement (Mitai #3) ↔ Capability & Club Features (Shinkan #2)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| Subjekt | **Profil** + Tier | **Verein** (`club_id`) + Plan | ❌ Scope |
|
||||
| Auflösungs-API | `check_feature_access` | `check_capability` + `club_features` + `/me/entitlements` | 🔀 |
|
||||
| Rollout 4 Phasen | ja | ja (Env-Flags) | ✅ |
|
||||
| Registry | DB `features` + Tiers | Code-Registry → DB Sync | ⚠️ |
|
||||
| Capabilities vs. Features | Features only | Capabilities **und** Kontingente getrennt | 🔀 Shinkan feiner |
|
||||
| Widget/Layout-Gating | zentral | Entitlements-API, kein Widget-Layout | ⚠️ |
|
||||
|
||||
**Größter Familien-Konflikt:**
|
||||
|
||||
Mitai-Dokument #3 „Nicht übernehmen“ Punkt 10: *„Profile as Entitlement-Subject — Multi-App-Familie braucht separates Identity/Subscription-Boundary.“*
|
||||
Shinkan **ist** die Antwort mit Verein als Subjekt — aber es gibt **kein gemeinsames Familienmodell**, das Profil-Tier **und** Org-Limits kombiniert.
|
||||
|
||||
**Familien-Entscheidung (Vorschlag):**
|
||||
|
||||
```
|
||||
Entitlement-Subjekt (familie):
|
||||
├── account (profile_id) → Tier, persönliche Limits (Mitai)
|
||||
└── tenant (club_id?) → Org-Plan, Capabilities (Shinkan, optional null)
|
||||
|
||||
API: GET /me/entitlements?tenant_id=
|
||||
Enforcement: eine resolve_entitlement(subject, capability|feature)
|
||||
```
|
||||
|
||||
| App | Remediation |
|
||||
|-----|-------------|
|
||||
| Mitai | Org-Scope reservieren; Tier-Drift (#3 Schuld) bereinigen |
|
||||
| Shinkan | `CLUB_FEATURE_ENFORCE=1` produktiv; Mitai-Legacy `check_feature_access` nicht nutzen (bereits Regel) |
|
||||
|
||||
---
|
||||
|
||||
### 3.4 Registry / Plugin (Mitai #4) ↔ Rights Registry (Shinkan #3)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| Registry-first | Platzhalter, Widgets, CSV-Module | Capabilities + Features only | ⚠️ Abdeckung |
|
||||
| Validierung an Grenze | ja | ja (`register_*` wirft) | ✅ |
|
||||
| Runtime + DB | Dual (Katalog + DB-Overrides) | Code → DB Upsert | ✅ |
|
||||
| Dual Registry FE/BE | Widgets + `registerDashboardWidgets` | nicht vorhanden | 🔀 |
|
||||
| Metadaten-Tiefe | nach Risiko (Matrix in Doc) | schlankere Dataclasses | ✅ |
|
||||
|
||||
**Kein Widerspruch** — Shinkan Rights Registry ist **Teilmenge** des Mitai-Meta-Musters.
|
||||
|
||||
**Familien-Entscheidung:** Mitai-Registry-Matrix (Platzhalter / UI-Plugin / Import-Modul / Rechte) als **Familien-Taxonomie**; Shinkan erweitert um Import-/Prompt-Registry wenn Wiki-Import generisch wird.
|
||||
|
||||
---
|
||||
|
||||
### 3.5 Auth & Session (Mitai #5 ↔ Shinkan #4)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| Session-Modell | opaque token | gleich (shared `auth.py`) | ✅ |
|
||||
| Depends-Pattern | ja | ja (+ TenantContext) | ✅ |
|
||||
| IDOR Profile-Header | dokumentierte Schwäche | Shinkan: Session-only betont | ⚠️ prüfen |
|
||||
| RBAC | `role` admin/user | Portal-Rolle **+** Vereinsrollen | 🔀 |
|
||||
| Rate Limiting | ja | (Mitai-spezifisch in Router) | ⚠️ |
|
||||
| Feature-Flags in Session | Legacy-Spalten | Account-Lifecycle separat | 🏗️ Mitai |
|
||||
|
||||
**Gegenläufig:** Shinkan **erweitert** Auth um Mandanten — darf Mandantenlogik **nicht** in `auth.py` legen (Shinkan-Prinzip „Nicht übernehmen“).
|
||||
|
||||
**Familien-Entscheidung:** Gemeinsames Auth-Modul; **TenantContext** als optionales Add-on-Pattern für mandantenfähige Apps.
|
||||
|
||||
---
|
||||
|
||||
### 3.6 Universal Import (Mitai #6) ↔ Wiki Import (Shinkan #11)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| Ingest ≠ Interpretation | ✅ | ✅ | ✅ |
|
||||
| Modul-Registry | zentral | fehlt (wiki-hardcoded) | ⚠️ |
|
||||
| SAVEPOINT pro Zeile | ja | nicht dokumentiert | ⚠️ |
|
||||
| Vorlagen/Mappings | generisch | SMW-Kategorien via Env | 🔀 |
|
||||
| Feature-Limits | an Import gebunden | Admin-only | ⚠️ |
|
||||
|
||||
**Kein Konflikt** — unterschiedliche Reife. Shinkan ist **Spezialfall** des Mitai-Musters.
|
||||
|
||||
**Familien-Entscheidung:** Neue Import-Quellen über **Universal-Import-Gerüst** (Mitai); Wiki als `import_type=mediawiki` registrieren.
|
||||
|
||||
---
|
||||
|
||||
### 3.7 Dashboard Widgets (Mitai #7) ↔ Dashboard KPIs (Shinkan #14)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| UX-Modell | konfigurierbares Widget-Layout | festes KPI-Aggregat | ❌ UX-Konzept |
|
||||
| Chatty Client vermeiden | via Widget-Daten | via `/dashboard/kpis` | ✅ Ziel |
|
||||
| Entitlements | `allowed` pro Widget | TenantContext auf KPIs | ✅ |
|
||||
| Data Layer | Widgets konsumieren Layer 1 | intern Router-Helfer | ⚠️ |
|
||||
|
||||
**Gegenläufig:** Mitai: **Nutzer konfiguriert Dashboard**. Shinkan: **Produkt definiert feste Kacheln** — bewusste MVP-Vereinfachung.
|
||||
|
||||
**Familien-Entscheidung:**
|
||||
|
||||
| App-Typ | Dashboard-Pattern |
|
||||
|---------|-------------------|
|
||||
| Personal Tracking (Mitai) | Widget-Katalog + Layout-JSON |
|
||||
| Trainer/Verein (Shinkan) | Aggregierte KPI-Endpoints ausreichend; Widget-System optional Phase 2 |
|
||||
| Neue App | Aggregat-Endpoint **mindestens**; Widget-System wenn Personalisierung nötig |
|
||||
|
||||
---
|
||||
|
||||
### 3.8 Navigation / IA (Mitai #8 ↔ Shinkan #12)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| appNav SSoT | ja | ja | ✅ |
|
||||
| Admin-Hub | Shell + Hub-Gruppen | horizontale `AdminPageNav` | ⚠️ |
|
||||
| Breakpoint 1024px | explizit | „prüfen“ | ⚠️ |
|
||||
| Onboarding-Nav | — | reduziert ohne Verein | 🔀 Shinkan |
|
||||
| adminNav.js SSoT | empfohlen | hardcoded Array in JSX | 🏗️ Shinkan |
|
||||
| Safe Area PWA | ja | Design-System, weniger explizit | ⚠️ |
|
||||
|
||||
**Familien-Entscheidung:** `appNav.js` + **`adminNav.js`** als Pflicht; Shinkan `AdminPageNav` refactoren.
|
||||
|
||||
---
|
||||
|
||||
### 3.9 Migration & Deploy (Mitai #9 ↔ Shinkan #13)
|
||||
|
||||
| Aspekt | Mitai | Shinkan | Bewertung |
|
||||
|--------|-------|---------|-----------|
|
||||
| XXX_*.sql + schema_migrations | ✅ | ✅ | ✅ |
|
||||
| Startup vor App | ✅ | ✅ | ✅ |
|
||||
| develop/main | ✅ | ✅ | ✅ |
|
||||
| Feste Ports | ✅ | ✅ | ✅ |
|
||||
| Immutabler Docker-Build | dokumentiert | nicht im Shinkan-Doc | ⚠️ Doku |
|
||||
| Health-Check / PG wait | ausführlich | kürzer | ⚠️ Doku |
|
||||
|
||||
**Aligned** — Shinkan-Dokument ist **Untermenge**; Implementierung vermutlich gleich (shared Infra).
|
||||
|
||||
---
|
||||
|
||||
## 4. Nur Shinkan (6 Module) — Einordnung für die Familie
|
||||
|
||||
| Modul | Familien-Relevanz | Mitai-Bezug |
|
||||
|-------|-------------------|------------|
|
||||
| **Access Layer & Tenant** | **Pflicht** für mandantenfähige Apps | Mitai #3 fordert Org-Boundary — hier ausformuliert |
|
||||
| **Media Assets & Archiv** | Optional (Content-Apps) | — |
|
||||
| **Exercise Catalog** | Shinkan-Domäne | — |
|
||||
| **Training Planning** | Shinkan-Domäne | — |
|
||||
| **Content Reports (P-13)** | Empfohlen für UGC/Plattform | — |
|
||||
| **Maturity Models** | Optional (Kompetenz-Apps) | — |
|
||||
|
||||
**Kein Widerspruch zu Mitai** — ergänzen das Familienmodell um **Mandant + Content-Governance**.
|
||||
|
||||
---
|
||||
|
||||
## 5. Querschnitt: Ist-Stand vs. dokumentierte Prinzipien
|
||||
|
||||
Gemeinsame **Architekturschuld** (beide Apps verletzen teils eigene „Nicht übernehmen“-Listen):
|
||||
|
||||
| Thema | Mitai | Shinkan |
|
||||
|-------|-------|---------|
|
||||
| Parallele KI-Pfade | `insights.py` Legacy | OpenRouter direkt in Routern |
|
||||
| Entitlement Enforcement | teils UI-only / Legacy-Spalten | Env Probe-only |
|
||||
| Registry-Sync / Duplikat | PLACEHOLDER_MAP + Registry | Capabilities-Sync, kein Prompt-Registry |
|
||||
| Frontend ohne Backend-Gate | teils | Capabilities Probe |
|
||||
| Dokumentations-Drift | Tier vs. Enforcement-Docs | Endpoint-Audit unvollständig |
|
||||
| Monolithische Pages/Client | God Pages, api.js | God Pages, api.js (Roadmap Phase 4) |
|
||||
| Fehlende JSON-Schema-KI | TODO | TODO (explizit vermeiden) |
|
||||
|
||||
---
|
||||
|
||||
## 6. Entscheidungs-Matrix (Priorisiert)
|
||||
|
||||
| Prio | Entscheidung | Betroffene Apps | Empfohlene Familien-Regel |
|
||||
|------|--------------|-----------------|---------------------------|
|
||||
| **P0** | Entitlement-Subjekt: Profil **und** optional Tenant | Mitai, Shinkan, neu | Ein API-Shape `/me/entitlements`; zwei Subjekt-Ebenen |
|
||||
| **P0** | Kein Client-`profile_id` für AuthZ | alle | Session-only; Tenant via Header + Membership |
|
||||
| **P1** | KI: ein Executor pro App | Mitai (fertig), Shinkan (Ziel) | `execute_prompt(slug, context_dto)` |
|
||||
| **P1** | Berechnungs-SSoT-Schicht | Shinkan erweitern | Mindestens ein `*/metrics.py` pro Domäne mit KPIs |
|
||||
| **P1** | Enforcement produktiv | beide | Phase 4 Enforce in Prod für kritische Features |
|
||||
| **P2** | Registry-Taxonomie vereinheitlichen | beide | Rechte / Platzhalter / Import / UI-Plugin |
|
||||
| **P2** | Admin-Nav SSoT | Shinkan | `adminNav.js` wie Mitai |
|
||||
| **P2** | Import: Universal + Spezialmodule | Shinkan | Wiki als registriertes Modul |
|
||||
| **P3** | Dashboard: Aggregat vs. Widgets | produktabhängig | Entscheidungsbaum §3.7 |
|
||||
| **P3** | Shared `auth.py` / `db_init` | beide | Monorepo-Package oder Sync-Disziplin |
|
||||
|
||||
---
|
||||
|
||||
## 7. Konvergenz-Roadmap (langfristig)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph foundation [Familien-Foundation]
|
||||
M9[Migration]
|
||||
M5[Auth]
|
||||
F3[Entitlements 2-Ebenen]
|
||||
R4[Registry Meta]
|
||||
end
|
||||
|
||||
subgraph mitai [Mitai]
|
||||
DL[Data Layer]
|
||||
PE[Prompt Engine]
|
||||
DW[Dashboard Widgets]
|
||||
end
|
||||
|
||||
subgraph shinkan [Shinkan]
|
||||
AL[Access Layer]
|
||||
AR[AI Runtime → Executor]
|
||||
SS[Skill Scoring → Layer 1]
|
||||
end
|
||||
|
||||
M9 --> mitai
|
||||
M9 --> shinkan
|
||||
M5 --> mitai
|
||||
M5 --> shinkan
|
||||
F3 --> mitai
|
||||
F3 --> shinkan
|
||||
R4 --> mitai
|
||||
R4 --> shinkan
|
||||
AL -.->|Mandanten-Apps| foundation
|
||||
PE -.->|Konvergenz| AR
|
||||
DL -.->|Schichtenmodell| SS
|
||||
```
|
||||
|
||||
| Phase | Mitai | Shinkan |
|
||||
|-------|-------|---------|
|
||||
| **Kurz** | Legacy KI-Pfade entfernen; Enforcement-Doku vereinheitlichen | Access-Layer-Audit abschließen; `CAPABILITY_ENFORCE` |
|
||||
| **Mittel** | Org-Scope in Entitlements vorbereiten | `ai_prompt_runtime` → Unified Executor; Router-Helfer statt KPI-Duplikat |
|
||||
| **Lang** | SSO/Identity (Vision) | Data-Layer-ähnliche Module für Planung; optional Widget-Dashboard |
|
||||
|
||||
---
|
||||
|
||||
## 8. Nächste Schritte
|
||||
|
||||
1. **Review-Workshop:** Tabelle §6 P0–P1 durchgehen und Familien-Regeln verbindlich markieren.
|
||||
2. ~~**`FAMILY_ENTITLEMENT_MODEL.md`** anlegen (P0)~~ → [FAMILY_ENTITLEMENT_MODEL.md](./FAMILY_ENTITLEMENT_MODEL.md) (Entwurf 2026-07-04)
|
||||
3. **Shinkan-Index** und **Mitai-Foundation-README** auf dieses Dokument verlinken.
|
||||
4. **`FAMILY_ENTITLEMENT_MODEL.md`** — Entwurf angelegt (§6 Produkt-Abweichungen, §8 Regeln neue Apps).
|
||||
5. Pro **P1-Punkt** Issue/Remediation-Eintrag in jeweiliger `SCHULDEN_UND_REMEDIATION` / Mitai-Äquivalent.
|
||||
|
||||
---
|
||||
|
||||
## 9. Changelog
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-07-04 | Erstfassung Abgleich Mitai Foundation (9) ↔ Shinkan (15) |
|
||||
@@ -0,0 +1,316 @@
|
||||
# Familien-Modell: Entitlements & Limits
|
||||
|
||||
**Status:** Entwurf / verbindliche Zielrichtung (mit bewussten Produkt-Ausnahmen)
|
||||
**Stand:** 2026-07-04
|
||||
**Bezüge:**
|
||||
|
||||
- [DESIGN_PRINCIPLES_ALIGNMENT.md](./DESIGN_PRINCIPLES_ALIGNMENT.md) — Abgleich Mitai ↔ Shinkan
|
||||
- Mitai: [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](file:///c:/Dev/mitai-jinkendo/.claude/docs/jinkendo-foundation/design-principles/FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
- Shinkan: [CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md](./design-principles/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
|
||||
---
|
||||
|
||||
## 1. Zweck
|
||||
|
||||
Dieses Dokument definiert das **gemeinsame Entitlement-Modell** der Jinkendo-Produktfamilie:
|
||||
|
||||
- **Was** für neue Apps und Refactors **Standard** ist
|
||||
- **Welche Produkt-Profile** welche Scopes nutzen (Account, Tenant, beides, keins)
|
||||
- **Wie** bewusste Abweichungen dokumentiert werden — Abweichung ist erlaubt, **Undokumentiertheit** nicht
|
||||
|
||||
**Nicht enthalten:** Stripe/SSO (`auth.jinkendo.de`), vollständige Billing-Implementierung, app-spezifische Feature-IDs.
|
||||
|
||||
---
|
||||
|
||||
## 2. Leitgedanke: Vier getrennte Fragen
|
||||
|
||||
Jede geschützte Aktion durchläuft konzeptionell **vier unabhängige Prüfungen**. Nicht jede App implementiert alle vier — siehe §6.
|
||||
|
||||
| # | Frage | Familien-Begriff | Typische Quelle |
|
||||
|---|--------|------------------|-----------------|
|
||||
| **A** | Wer ist eingeloggt? | **Auth** (Identität) | Session → `profile_id` |
|
||||
| **B** | Darf diese Rolle die **Funktion** ausführen? | **Capability** (Permission) | Rollen-Matrix, `min_account_state` |
|
||||
| **C** | Ist das **Kontingent** erschöpft? | **Feature / Limit** (Quota) | Plan, Tier, Usage-Zähler |
|
||||
| **D** | Darf ich **dieses Objekt** lesen/ändern? | **Governance** (Object ACL) | `visibility`, `club_id`, Owner |
|
||||
|
||||
```
|
||||
Request → Auth (A) → [Capability (B)] → [Feature-Limit (C)] → [Governance (D)] → Handler
|
||||
```
|
||||
|
||||
**Familien-Regel:** B, C und D **nicht** in React-Widgets oder Router-Inline-Logik vermischen — jeweils eine Auflösungsfunktion pro Ebene.
|
||||
|
||||
**Shinkan-Ergänzung:** Governance ist dort ausgebaut (`TenantContext`, Access Layer); Mitai fokussiert A+B+C auf Profil-Ebene.
|
||||
|
||||
---
|
||||
|
||||
## 3. Familien-Standard: Zwei Subjekt-Ebenen
|
||||
|
||||
Limits und Pläne können an **zwei Subjekte** hängen. Beide sind im Familienmodell **first-class** — Apps wählen, welche sie nutzen (§6).
|
||||
|
||||
| Subjekt | ID | Typische Frage | Beispiel |
|
||||
|---------|-----|----------------|----------|
|
||||
| **Account** | `profile_id` | Was darf **ich** als Nutzer (Tarif)? | Mitai Free vs. Premium |
|
||||
| **Tenant** | `tenant_id` (z. B. `club_id`) | Was darf **meine Organisation**? | Shinkan Vereinsplan, KI-Kontingent |
|
||||
|
||||
### 3.1 Auflösungs-Reihenfolge (wenn beide Ebenen aktiv)
|
||||
|
||||
Für eine Aktion mit Capability `X` und Feature `Y`:
|
||||
|
||||
1. **Account-Lifecycle** — z. B. E-Mail verifiziert, Onboarding abgeschlossen
|
||||
2. **Capability(B)** — Rolle darf Funktion (Account- und/oder Tenant-Rollen)
|
||||
3. **Feature(C)** — Kontingent am **primären Billing-Subjekt** der App (siehe Produkt-Profil)
|
||||
4. **Governance(D)** — Objekt sichtbar/bearbeitbar
|
||||
|
||||
**AND-Verknüpfung:** Alle aktiven Ebenen müssen passieren. Ausnahmen nur in §6.3 dokumentiert.
|
||||
|
||||
### 3.2 Primäres Billing-Subjekt pro App
|
||||
|
||||
| Profil | Primäres Subjekt für Limits | Capability-Subjekt |
|
||||
|--------|----------------------------|-------------------|
|
||||
| Personal App (Mitai) | **Account** | Account |
|
||||
| Mandanten-App (Shinkan) | **Tenant** | Account + Tenant-Rolle |
|
||||
| Hybrid (Zukunft) | konfigurierbar | beide |
|
||||
|
||||
---
|
||||
|
||||
## 4. Familien-Standard: Capabilities vs. Features
|
||||
|
||||
| Konzept | Familien-Definition | Subjekt | Beispiel |
|
||||
|---------|---------------------|---------|----------|
|
||||
| **Capability** | Binäre oder rollenbasierte **Erlaubnis** („darf ich?“) | meist Account + Tenant-Kontext | `exercises.ai.suggest` |
|
||||
| **Feature** | **Kontingent** oder Boolean-Limit („wie oft/noch?“) | Account **oder** Tenant | `ai_calls` / Monat |
|
||||
| **Verknüpfung** | Capability kann `linked_feature_id` haben | — | KI-Capability → KI-Kontingent |
|
||||
|
||||
**Familien-Regel:**
|
||||
|
||||
- Capabilities **registry-first** registrieren (Code → DB-Sync, Shinkan-Muster).
|
||||
- Feature-IDs **nicht** in UI hardcoden — nur aus Entitlements-Response.
|
||||
- `NULL` Limit = unbegrenzt; `0` = deaktiviert (Mitai-Semantik, familienweit).
|
||||
|
||||
---
|
||||
|
||||
## 5. Familien-Standard: API & Enforcement
|
||||
|
||||
### 5.1 Ziel-API (neue Apps)
|
||||
|
||||
Ein **einheitlicher Snapshot** für das Frontend:
|
||||
|
||||
```
|
||||
GET /api/me/entitlements
|
||||
?tenant_id=<optional>
|
||||
|
||||
Response (skizziert):
|
||||
{
|
||||
"account": {
|
||||
"profile_id": 1,
|
||||
"account_state": "active_member",
|
||||
"tier_id": "premium", // optional, Account-Apps
|
||||
"features": { "ai_calls": { "allowed", "used", "limit", "remaining", "reset_at" } },
|
||||
"capabilities": { "analysis.run": { "allowed": true, "reason": null } }
|
||||
},
|
||||
"tenant": { // null wenn App keinen Tenant kennt
|
||||
"tenant_id": 42,
|
||||
"tenant_type": "club",
|
||||
"plan_id": "pro",
|
||||
"features": { ... },
|
||||
"capabilities": { ... },
|
||||
"roles": ["trainer"]
|
||||
},
|
||||
"enforcement": {
|
||||
"capabilities": "enforce|probe",
|
||||
"features": "enforce|probe"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Familien-Regel:** UI liest **nur** diesen Snapshot (oder domänenspezifische Teilmenge) — keine parallelen `/subscription/me` + `/features/usage` + Ad-hoc-Checks in neuen Apps.
|
||||
|
||||
### 5.2 Ist-API (bestehende Apps — Abweichung dokumentiert)
|
||||
|
||||
| App | Endpoint heute | Familien-Ziel |
|
||||
|-----|----------------|---------------|
|
||||
| **Mitai** | `/subscription/me`, `/features/usage`, `check_feature_access` | Snapshot schrittweise; Account-Block reicht |
|
||||
| **Shinkan** | `GET /api/me/entitlements?club_id=` | Tenant-Block + Capabilities; Account-Tier fehlt bewusst |
|
||||
|
||||
Migration: **kein Big-Bang** — alte Endpoints als Facade auf Snapshot mappen.
|
||||
|
||||
### 5.3 Vier-Phasen-Rollout (familienweit verbindlich)
|
||||
|
||||
| Phase | Verhalten | Env-Beispiel |
|
||||
|-------|-----------|--------------|
|
||||
| **1** | Cleanup Legacy-Flags | — |
|
||||
| **2** | **Probe** — JSON-Log, HTTP 200 | `*_ENFORCE=0` |
|
||||
| **3** | Frontend-Gates aus Entitlements | — |
|
||||
| **4** | **Enforce** — HTTP 403 | `*_ENFORCE=1` |
|
||||
|
||||
**Familien-Regel:** Phase 4 für **neue** kritische Features von Anfang an planbar; Bestands-Apps dürfen in Phase 2–3 bleiben bis kalibriert.
|
||||
|
||||
### 5.4 Enforcement-Priorität
|
||||
|
||||
1. **API** — autoritativ (`403`)
|
||||
2. **Frontend** — UX (Badges, disabled Buttons)
|
||||
3. **Niemals** — nur UI ohne API-Gate
|
||||
|
||||
---
|
||||
|
||||
## 6. Produkt-Profile & bewusste Abweichungen
|
||||
|
||||
Abweichungen vom Familien-Standard sind **zulässig**, wenn sie in der Tabelle **§6.2** stehen und begründet sind.
|
||||
|
||||
### 6.1 Profil-Matrix (Soll)
|
||||
|
||||
| Profil | Apps | Account-Limits | Tenant-Limits | Capabilities | Governance (Objekt) |
|
||||
|--------|------|----------------|---------------|--------------|---------------------|
|
||||
| **P1 Personal** | Mitai | ✅ primär | ❌ | ✅ Account | minimal / privat |
|
||||
| **P2 Mandant** | Shinkan | ⚠️ Lifecycle only | ✅ primär | ✅ Account + Tenant-Rollen | ✅ Access Layer |
|
||||
| **P3 Minimal** | Miken, Ikigai (geplant) | optional | ❌ | optional | minimal |
|
||||
| **P4 Hybrid** | (Reserve) | ✅ | ✅ | ✅ beide | ✅ |
|
||||
|
||||
### 6.2 Registrierter Abweichungs-Katalog
|
||||
|
||||
| ID | App | Abweichung vom Familien-Standard | Begründung | Review |
|
||||
|----|-----|----------------------------------|------------|--------|
|
||||
| **DEV-01** | Mitai | Kein `tenant`-Block in Entitlements | Persönliche Tracking-App; kein Verein | Beibehalten (P1) |
|
||||
| **DEV-02** | Mitai | Kein Capability-Katalog (nur Features+Tier) | RBAC = admin/user ausreichend | Optional später `account.*` Capabilities |
|
||||
| **DEV-03** | Mitai | Mehrere Nutzer-APIs statt einem Snapshot | Historisch gewachsen | Facade → Snapshot (mittelfristig) |
|
||||
| **DEV-04** | Mitai | Legacy Session-Spalten (`ai_enabled`, …) parallel Features | Migrationsschuld | Bereinigen, nicht in neue Apps |
|
||||
| **DEV-05** | Shinkan | Kein Account-Tier / `profiles.tier` | Verein zahlt, nicht Trainer | Beibehalten (P2) |
|
||||
| **DEV-06** | Shinkan | Capabilities **und** Governance (zwei Achsen) | Trainer vs. Objekt-Rechte | Familien-Vorbild für P2/P4 |
|
||||
| **DEV-07** | Shinkan | `check_feature_access` (Mitai-Legacy) explizit verboten | Falsches Subjekt | Beibehalten |
|
||||
| **DEV-08** | Shinkan | Enforcement oft Probe-only | Rollout-Sicherheit | → Phase 4 bis Datum X |
|
||||
| **DEV-09** | Shinkan | Inventar-Features live gezählt | Drift-Vermeidung | Abweichung OK; in P2 dokumentieren |
|
||||
| **DEV-10** | Beide | Kein atomares Check+Increment | Race bei Parallel-Requests | Familien-Backlog; Workaround dokumentieren |
|
||||
| **DEV-11** | Neue Apps | dürfen **nur** Account **oder** nur Tenant wählen | MVP | Eintrag hier anlegen vor Launch |
|
||||
|
||||
**Neue Abweichung:** Zeile in §6.2 + ggf. ein Satz im App-`CLAUDE.md`.
|
||||
|
||||
### 6.3 Dokumentierte Ausnahmen (Bypass)
|
||||
|
||||
| Ausnahme | Apps | Regel |
|
||||
|----------|------|-------|
|
||||
| Plattform-Admin Audit | Shinkan | Quota-Bypass über Grants, nicht pauschal superadmin |
|
||||
| Admin ohne Auto-Bypass | Mitai | Admins unterliegen Limits (Produktentscheid) |
|
||||
| Öffentliche Routen ohne Auth | alle | Kein Entitlement-Check |
|
||||
|
||||
---
|
||||
|
||||
## 7. Mapping: Familien-Begriff ↔ Implementierung
|
||||
|
||||
### 7.1 Mitai (Profil P1)
|
||||
|
||||
| Familien | Mitai-Implementierung |
|
||||
|----------|----------------------|
|
||||
| Account-Features | `features`, `tier_limits`, `user_feature_usage` |
|
||||
| Account-Tier | `get_effective_tier()`, `access_grants` |
|
||||
| Check | `check_feature_access(profile_id, feature_id)` |
|
||||
| Increment | `increment_feature_usage(profile_id, …)` |
|
||||
| UI | `UsageBadge`, Widget `allowed` |
|
||||
|
||||
### 7.2 Shinkan (Profil P2)
|
||||
|
||||
| Familien | Shinkan-Implementierung |
|
||||
|----------|-------------------------|
|
||||
| Tenant-Features | `club_plan_limits`, `club_feature_usage`, `club_features.py` |
|
||||
| Tenant-Plan | `get_effective_club_plan(club_id)` |
|
||||
| Capabilities | `check_capability`, `capabilities` + `rights_registry` |
|
||||
| Snapshot | `build_me_entitlements()` → `GET /me/entitlements` |
|
||||
| Governance | `TenantContext`, `club_tenancy` — **kein** Ersatz für Capabilities |
|
||||
|
||||
### 7.3 Gemeinsame Muster (copy-ready)
|
||||
|
||||
| Muster | Mitai | Shinkan |
|
||||
|--------|-------|---------|
|
||||
| Feature-Registry in DB | ✅ | ✅ (`app='shinkan'`) |
|
||||
| Plan × Feature Matrix | `tier_limits` | `club_plan_limits` |
|
||||
| Admin-Override | `user_feature_restrictions` | `club_feature_overrides` |
|
||||
| Promo/Trial | `access_grants` | `club_access_grants` |
|
||||
| 4-Phasen-Rollout | ✅ | ✅ |
|
||||
| Registry-first neue IDs | ⚠️ teils hardcoded | ✅ `rights_registrations/` |
|
||||
|
||||
---
|
||||
|
||||
## 8. Entscheidungsregeln für neue Produkte
|
||||
|
||||
### 8.1 Pflicht (alle Apps mit Auth)
|
||||
|
||||
- [ ] Session → `profile_id`; kein Client-Header als Autorität
|
||||
- [ ] Entitlements-Auflösung **eine Funktion pro Ebene** (Capability, Feature)
|
||||
- [ ] API-Enforcement vor UI-Gate
|
||||
- [ ] 4-Phasen-Rollout dokumentiert
|
||||
- [ ] Produkt-Profil (P1–P4) gewählt + Abweichungen in §6.2
|
||||
|
||||
### 8.2 Wenn Personal App (P1)
|
||||
|
||||
- [ ] Primäres Subjekt = Account
|
||||
- [ ] `tenant`-Block in API = `null` (DEV-01-Analog)
|
||||
- [ ] Feature-Registry + Tier-Matrix
|
||||
|
||||
### 8.3 Wenn Mandanten-App (P2)
|
||||
|
||||
- [ ] Primäres Subjekt = Tenant
|
||||
- [ ] `TenantContext` + Governance getrennt von Capabilities
|
||||
- [ ] Capabilities registry-first
|
||||
- [ ] Account nur Lifecycle (verified, member) — kein Tier nötig (DEV-05-Analog erlaubt)
|
||||
|
||||
### 8.4 Wenn Minimal App (P3)
|
||||
|
||||
- [ ] Explizit: „keine Limits“ oder nur Boolean-Features — in §6.2 eintragen
|
||||
- [ ] Kein halbes Mitai-v9c kopieren
|
||||
|
||||
---
|
||||
|
||||
## 9. Konvergenz-Roadmap (optional, nicht blockierend)
|
||||
|
||||
| Schritt | Mitai | Shinkan | Familie |
|
||||
|---------|-------|---------|---------|
|
||||
| **Kurz** | Legacy Session-Flags entfernen | `CAPABILITY_ENFORCE` / `CLUB_FEATURE_ENFORCE` Prod | DEV-04, DEV-08 schließen |
|
||||
| **Mittel** | `/me/entitlements` Account-Block | Snapshot um `tenant`-Typ metadata erweitern | Facade alte APIs |
|
||||
| **Lang** | Optional `tenant_id` reservieren (null) | Optional Account-Tier für Cross-Sell | Shared package `jinkendo_entitlements` |
|
||||
| **Vision** | SSO + zentraler Billing | Vereins-Abo Stripe | `CENTRAL_SUBSCRIPTION_SYSTEM` |
|
||||
|
||||
**Wichtig:** Konvergenz ist **empfohlen**, nicht Pflicht — solange §6.2 aktuell bleibt.
|
||||
|
||||
---
|
||||
|
||||
## 10. Anti-Patterns (familienweit verboten)
|
||||
|
||||
1. Tier- oder Plan-Namen in React-Komponenten hardcoden
|
||||
2. Limit-Logik nur im Frontend
|
||||
3. Shinkan-Vereinslimits über Mitai `check_feature_access(profile_id)`
|
||||
4. Capability-Check durch Governance ersetzen (oder umgekehrt)
|
||||
5. Neue Feature-IDs nur in SQL-Migration ohne Registry
|
||||
6. Enforcement Phase 4 „vergessen“ bei paid Features ohne dokumentierte Probe-Phase
|
||||
7. Undokumentierte Produkt-Abweichung (nicht in §6.2)
|
||||
|
||||
---
|
||||
|
||||
## 11. Offene Familien-Entscheidungen (Backlog)
|
||||
|
||||
| ID | Frage | Optionen | Default wenn unentschieden |
|
||||
|----|-------|----------|----------------------------|
|
||||
| **FD-01** | Atomares check+increment | DB-Lock / Transaction / Queue | Status quo + Retry-Hinweis in Doku |
|
||||
| **FD-02** | Shared Python-Modul | Monorepo-Paket vs. Copy+Sync | Copy+Sync mit gleicher API-Shape |
|
||||
| **FD-03** | Capability-Namespace global | `jinkendo.*` vs. app-prefix | `{app}.{domain}.{action}` |
|
||||
| **FD-04** | Mitai bekommt Capability-Layer? | ja/nein/später | nein (DEV-02) bis Bedarf |
|
||||
| **FD-05** | Ein `features.app` für alle Apps | gemeinsame DB vs. pro Deploy | pro Deploy (heute) |
|
||||
|
||||
---
|
||||
|
||||
## 12. Verwandte Dokumente
|
||||
|
||||
| Dokument | Inhalt |
|
||||
|----------|--------|
|
||||
| [DESIGN_PRINCIPLES_ALIGNMENT.md](./DESIGN_PRINCIPLES_ALIGNMENT.md) | Vollständiger Mitai ↔ Shinkan Abgleich |
|
||||
| [design-principles/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md](./design-principles/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md) | Shinkan Ist-Prinzipien |
|
||||
| [ACCESS_LAYER_DESIGN_PRINCIPLES.md](./design-principles/ACCESS_LAYER_DESIGN_PRINCIPLES.md) | Governance (Ebene D) |
|
||||
| Mitai Foundation #3 | Feature & Entitlement Ist Mitai |
|
||||
| Shinkan `CLUB_MEMBERSHIP_AND_FEATURES.v1.md` | Vereins-Abo Detail |
|
||||
| Shinkan `CAPABILITY_CATALOG.v1.md` | Capability-IDs |
|
||||
|
||||
---
|
||||
|
||||
## 13. Changelog
|
||||
|
||||
| Datum | Änderung |
|
||||
|-------|----------|
|
||||
| 2026-07-04 | Entwurf: Familien-Standard, Produkt-Profile P1–P4, Abweichungs-Katalog DEV-01–11 |
|
||||
@@ -0,0 +1,326 @@
|
||||
# Auth & Session – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** Authentifizierung, Session-Management, rollenbasierte API-Zugriffe — kein Mandanten-/SSO-System, keine Zahlungs-Auth
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 5 von n
|
||||
**Vorgänger:** [REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md](./REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| Auth-Kern | `backend/auth.py` |
|
||||
| Auth-Endpoints | `backend/routers/auth.py` |
|
||||
| Profile | `backend/routers/profiles.py` |
|
||||
| Frontend | `frontend/src/context/AuthContext.jsx`, `ProfileContext.jsx`, `utils/api.js` |
|
||||
| DB | `profiles`, `sessions` |
|
||||
| Architektur-Regeln | `.claude/rules/ARCHITECTURE.md`, `CLAUDE.md` § Auth |
|
||||
| Vision (nicht implementiert) | `CENTRAL_SUBSCRIPTION_SYSTEM.md` (SSO/JWT) |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Auth & Session**
|
||||
|
||||
Server-seitige, token-basierte Authentifizierung mit FastAPI-Dependencies — **Identität und Rolle**, getrennt von Feature-Entitlements und fachlicher Logik.
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Das Modul übernimmt:
|
||||
|
||||
1. **Identität** — Wer ist eingeloggt? (`profiles` + Passwort/bcrypt)
|
||||
2. **Session** — Opaque Token in `sessions`, Ablaufzeit, Logout
|
||||
3. **API-Gate** — `require_auth`, `require_admin`, `require_auth_flexible`
|
||||
4. **Passwort-Lifecycle** — Hash, Verify, Reset, Registrierung, E-Mail-Verifizierung
|
||||
5. **Rollen** — `profiles.role`: `user` \| `admin` (grobbinsenartig)
|
||||
|
||||
Es übernimmt **nicht**:
|
||||
|
||||
- Feature-Limits / Tier (→ Feature & Entitlement System, gleiche `auth.py`-Datei aber logisch getrennt)
|
||||
- Mandanten-Isolation / Org-Workspaces
|
||||
- OAuth/SSO/JWT (nur Vision)
|
||||
- Authorization auf Datensatzebene (Row-Level Security)
|
||||
|
||||
### Was Mitai **ist** vs. **nicht ist**
|
||||
|
||||
| Mitai | Produktfamilien-Muster |
|
||||
|-------|------------------------|
|
||||
| 1 Login = 1 Profil (E-Mail) | ✅ Account-Modell |
|
||||
| Historisch Multi-Profil auf einer Instanz | ⚠️ Legacy (`/profiles`, `X-Profile-Id`) |
|
||||
| Self-hosted Einzelinstanz | ✅ Kein Multi-Tenant-SaaS |
|
||||
| Session-Token in DB | ✅ Server-side Session Store |
|
||||
| Zentrale Jinkendo-Auth (Vision) | ❌ nicht gebaut |
|
||||
|
||||
---
|
||||
|
||||
## Administrierte vs. code-definierte Konfiguration
|
||||
|
||||
| Konfiguration | Speicherort | Administrierbar? |
|
||||
|---------------|-------------|------------------|
|
||||
| Nutzer-Stammdaten, Rolle | `profiles` | Admin (User-Verwaltung) / Self-Service |
|
||||
| Session-Laufzeit | `profiles.session_days` (Default 30) | Profil/Admin |
|
||||
| Passwort-Hash | `profiles.pin_hash` | Nutzer (change pin) |
|
||||
| E-Mail-Verifizierung | `email_verified`, Token-Felder | System |
|
||||
| Trial-Ende | `trial_ends_at` | System bei Registrierung |
|
||||
| SMTP | Env (`SMTP_*`, `APP_URL`) | Deploy |
|
||||
| Rate Limits Login/Register | Code (`5/min`, `3/hour`) | Code |
|
||||
|
||||
**Hardcodiert:** bcrypt, Token-Länge (`secrets.token_urlsafe(32)`), Rollen-Enum (`user`/`admin`), Header-Name `X-Auth-Token`.
|
||||
|
||||
---
|
||||
|
||||
## Session- und Auth-Flow
|
||||
|
||||
```
|
||||
Login (email + password)
|
||||
→ verify_pin (bcrypt | legacy SHA256)
|
||||
→ optional bcrypt upgrade
|
||||
→ INSERT sessions (token, profile_id, expires_at)
|
||||
→ Client: localStorage bodytrack_token
|
||||
|
||||
Request
|
||||
→ Header X-Auth-Token (api.js / AuthContext)
|
||||
→ get_session(token) JOIN profiles
|
||||
→ require_auth → session dict (profile_id, role, …)
|
||||
|
||||
Logout
|
||||
→ DELETE sessions WHERE token=…
|
||||
→ Client: localStorage clear
|
||||
```
|
||||
|
||||
**Sonderfall:** `require_auth_flexible` — Token via Header **oder** Query `ssetoken` (SSE, `<img>`, Downloads).
|
||||
|
||||
---
|
||||
|
||||
## Rollen
|
||||
|
||||
| Rolle | Mechanismus | Typische Rechte |
|
||||
|-------|-------------|-----------------|
|
||||
| **user** | `profiles.role = 'user'` | Eigene Daten, Features nach Tier |
|
||||
| **admin** | `require_admin` | Admin-Shell, Prompts, User, System |
|
||||
|
||||
Kein feingranulares RBAC (keine Permission-Matrix). Admin ist Binär-Schalter.
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. FastAPI-Dependencies als Auth-Gate
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jeder geschützte Endpoint nutzt `session: dict = Depends(require_auth)` als **separaten** Parameter — nie in `Header()` eingebettet. |
|
||||
| **Begründung** | Verhindert ungeschützte Endpoints durch falsche Parameter-Signatur. |
|
||||
| **Quelle** | `CLAUDE.md` § Kritische Regeln; `auth.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht linter-erzwungen; Legacy-Endpoints existieren. |
|
||||
|
||||
### 2. Server-side opaque Sessions
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Token ist zufällig, in DB gespeichert; Validierung über `sessions` + Ablauf — kein JWT mit Client-Claims. |
|
||||
| **Begründung** | Revocation (Logout), kein Trust in Client-Payload; einfaches Modell für Self-Hosted. |
|
||||
| **Quelle** | `sessions` Tabelle; `make_token()`, `get_session()` |
|
||||
| **Tragfähigkeit** | **hoch** (Single-App, Self-Hosted) |
|
||||
| **Einschränkung** | Skalierung multi-node braucht shared session store; SSO-Familie braucht anderes Modell. |
|
||||
|
||||
### 3. profile_id aus Session, nicht aus Client
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Autoritative Identität für neue Endpoints: `session['profile_id']` — Client darf Profil nicht wählen. |
|
||||
| **Begründung** | Verhindert IDOR (Zugriff auf fremde Profile). |
|
||||
| **Quelle** | `routers/goals.py`, `routers/prompts.py`; Architektur-Intent in `CLAUDE.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy `get_pid(x_profile_id)` akzeptiert `X-Profile-Id` **ohne** Session-Abgleich — siehe Nicht übernehmen. |
|
||||
|
||||
### 4. bcrypt mit Legacy-Migration
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Passwörter mit bcrypt; SHA256-Legacy beim Login erkannt und transparent auf bcrypt upgraded. |
|
||||
| **Begründung** | Kein Big-Bang-Migration; sichere Hashes ohne Nutzer-Zwangs-Reset. |
|
||||
| **Quelle** | `verify_pin()`, Login in `routers/auth.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Upgrade nur bei erfolgreichem Login. |
|
||||
|
||||
### 5. Rate Limiting auf Auth-Endpoints
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Login, Register, Forgot-Password, Resend-Verification mit `slowapi`-Limits (IP-basiert). |
|
||||
| **Begründung** | Brute-Force- und Abuse-Schutz. |
|
||||
| **Quelle** | `routers/auth.py` (`5/minute`, `3/hour`); `main.py` Limiter |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | IP-only; kein account-based lockout. |
|
||||
|
||||
### 6. Keine E-Mail-Enumeration bei sensiblen Flows
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Forgot-Password und Resend-Verification liefern generische Erfolgsmeldung, auch wenn E-Mail unbekannt. |
|
||||
| **Begründung** | Privacy; erschwert Account-Scraping. |
|
||||
| **Quelle** | `password_reset_request`, `resend_verification` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Register sagt „E-Mail bereits registriert“ (Enumeration möglich). |
|
||||
|
||||
### 7. E-Mail-Verifizierung vor voller Nutzung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Self-Register setzt `email_verified=FALSE`; Verify-Endpoint aktiviert + Auto-Login-Session. |
|
||||
| **Begründung** | Valide Kontaktadresse; Spam-Reduktion. |
|
||||
| **Quelle** | `register`, `verify_email` in `routers/auth.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht überall im Backend erzwungen (Login ohne verified check?). |
|
||||
|
||||
### 8. Flexible Auth für technische Clients
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `require_auth_flexible`: gleiche Session-Validierung via Header oder `?ssetoken=` für SSE/Bilder. |
|
||||
| **Begründung** | Browser-APIs ohne Custom Headers. |
|
||||
| **Quelle** | `auth.py`; Prompt SSE `/execute-stream` |
|
||||
| **Tragfähigkeit** | **mittel–hoch** |
|
||||
| **Einschränkung** | Token in URL kann in Logs/Referrer leaken — kurze Sessions / HTTPS Pflicht. |
|
||||
|
||||
### 9. Zentraler API-Client mit Token-Injektion
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Frontend: `api.js` injiziert `X-Auth-Token` automatisch — kein scattered `fetch` ohne Auth. |
|
||||
| **Begründung** | Konsistenz; eine Stelle für Token-Handling. |
|
||||
| **Quelle** | `utils/api.js` → `hdrs()`; `getToken()` aus AuthContext |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Einzelne Komponenten umgehen noch `api.js` (SettingsPage, EmailSettings). |
|
||||
|
||||
### 10. Auth getrennt von Authorization (Features)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `require_auth` = identifiziert; `check_feature_access` = berechtigt für Aktion — nacheinander im Router. |
|
||||
| **Begründung** | Klare Schichten; Auth-Modul nicht mit Tier-Logik vermischen (auch wenn Datei `auth.py` beides enthält). |
|
||||
| **Quelle** | `FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md`; Router-Muster |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy Profil-Flags `ai_enabled`, `export_enabled` parallel zum Feature-System. |
|
||||
|
||||
### 11. Admin-Gate im Frontend und Backend
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Backend: `require_admin`; Frontend: `RequireAdmin` + `isAdmin` aus Session-Rolle. |
|
||||
| **Begründung** | UX-Navigation + API-Sicherheit (Frontend allein reicht nicht). |
|
||||
| **Quelle** | `RequireAdmin.jsx`; `require_admin()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Einzelne Routen (Workflow-Editor) ohne Frontend-Admin-Gate. |
|
||||
|
||||
### 12. Session-Kontext im Frontend
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `AuthProvider` hält `{ token, profile_id, role, profile }`; App setzt `setProfileId(session.profile_id)` für API. |
|
||||
| **Begründung** | Single React-Tree für Login-State; Re-Validate via `/auth/me` beim Start. |
|
||||
| **Quelle** | `AuthContext.jsx`; `App.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `ProfileContext` lädt alle Profile — Multi-Profil-UX Rest; Session-Profil ist Kanon. |
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
1. **`get_pid(X-Profile-Id)` ohne Session-Bindung** — Client kann fremde `profile_id` senden; IDOR-Risiko. Kanon: immer `session['profile_id']` oder explizite Admin-Impersonation mit Audit.
|
||||
|
||||
2. **Profile-CRUD nur mit `require_auth`** — `/profiles` listet alle Nutzer für jeden Authentifizierten (Kommentar „admin“, kein `require_admin`). Für Familien-Architektur: strikte Admin-Gates.
|
||||
|
||||
3. **Dual-System Profil-Flags vs. Features** — `ai_enabled`, `export_enabled`, `ai_limit_day` in Session-Query neben v9c Feature-Registry.
|
||||
|
||||
4. **localStorage-Key-Inkonsistenz** — `bodytrack_token` vs. `mitai-jinkendo_active_profile` (historischer App-Name).
|
||||
|
||||
5. **Direktes `fetch` ohne `api.js`** — umgeht Token-/Error-Konvention.
|
||||
|
||||
6. **Reset-Token in `sessions`-Tabelle** — `reset_{token}` mischt Session-Typen in einer Tabelle; OK für MVP, für Familie: getrennte Token-Typen/Tabellen.
|
||||
|
||||
7. **Kein JWT/SSO trotz Produktfamilien-Vision** — `CENTRAL_SUBSCRIPTION_SYSTEM.md` beschreibt `auth.jinkendo.de` — Mitai-Implementierung ist **nicht** das Zielbild für Cross-App-SSO.
|
||||
|
||||
8. **Multi-Profil-Haushalt ohne klares Modell** — Legacy Multi-Profile auf einer Instanz vs. 1 Account = 1 Profil; für neue Apps Modell explizit wählen.
|
||||
|
||||
9. **Role als einziges RBAC** — reicht für Admin/User, nicht für feingranulare Permissions.
|
||||
|
||||
10. **Session-Query mit veralteten Profil-Spalten** — `get_session` SELECT enthält Legacy-Felder statt nur Identität + Rolle.
|
||||
|
||||
11. **Fehlende erzwungene E-Mail-Verified-Prüfung** — Registrierung setzt Flag, Login prüft es nicht offensichtlich.
|
||||
|
||||
12. **Debug-Print in Auth-Modul** — `print("[AUTH.PY] Module loaded…")` in Produktionscode.
|
||||
|
||||
---
|
||||
|
||||
## Abgrenzung zu anderen Serien-Dokumenten
|
||||
|
||||
| Thema | Dokument |
|
||||
|-------|----------|
|
||||
| Tier, Limits, Quotas | [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md) |
|
||||
| Zentrale SSO/Abo-Vision | [CENTRAL_SUBSCRIPTION_SYSTEM.md](../../technical/CENTRAL_SUBSCRIPTION_SYSTEM.md) |
|
||||
| API-First / Router | `ARCHITECTURE.md` §1 |
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Ist-Stand)
|
||||
|
||||
```
|
||||
backend/
|
||||
├── auth.py # Session, require_*, Feature-Access (v9c)
|
||||
└── routers/
|
||||
├── auth.py # login, logout, register, verify, reset
|
||||
└── profiles.py # CRUD, get_pid (Legacy)
|
||||
|
||||
frontend/src/
|
||||
├── context/AuthContext.jsx
|
||||
├── context/ProfileContext.jsx
|
||||
├── layouts/RequireAdmin.jsx
|
||||
└── utils/api.js # Token-Injektion
|
||||
|
||||
DB:
|
||||
├── profiles # Identität, Rolle, Hash, Tier, Trial
|
||||
└── sessions # token → profile_id, expires_at
|
||||
```
|
||||
|
||||
**Endpoints (Auswahl):**
|
||||
|
||||
| Endpoint | Auth |
|
||||
|----------|------|
|
||||
| `POST /api/auth/login` | Public + Rate limit |
|
||||
| `POST /api/auth/logout` | Token optional |
|
||||
| `GET /api/auth/me` | require_auth |
|
||||
| `POST /api/auth/register` | Public + Rate limit |
|
||||
| `GET /api/auth/verify/{token}` | Public |
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Feature-Entitlements: [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
- Architektur-Regeln Auth: `CLAUDE.md`, `.claude/rules/ARCHITECTURE.md`
|
||||
- GUI Admin-Guard: `docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`
|
||||
- SSO-Vision: [CENTRAL_SUBSCRIPTION_SYSTEM.md](../../technical/CENTRAL_SUBSCRIPTION_SYSTEM.md)
|
||||
|
||||
---
|
||||
|
||||
## Geplante Folgedokumente (Serie)
|
||||
|
||||
| # | Modul | Status |
|
||||
|---|-------|--------|
|
||||
| 1 | Prompt Engine | ✅ |
|
||||
| 2 | Data Layer | ✅ |
|
||||
| 3 | Feature & Entitlement | ✅ |
|
||||
| 4 | Registry-/Plugin-Muster | ✅ |
|
||||
| 5 | Auth & Session | ✅ dieses Dokument |
|
||||
| 6 | Universal Import | ✅ `UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md` |
|
||||
| 7 | Dashboard Widgets | ✅ |
|
||||
| 8 | Navigation / IA | ✅ `NAVIGATION_IA_DESIGN_PRINCIPLES.md` |
|
||||
| 9 | Migration & Deploy | ✅ |
|
||||
@@ -0,0 +1,363 @@
|
||||
# Dashboard Widgets – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** Konfigurierbare Übersicht (Widget-Katalog, Layout, Entitlements, Frontend-Registry) — keine Chart-/Metrik-Berechnung
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 7 von n
|
||||
**Vorgänger:** [UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md](./UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| Katalog (SSoT) | `backend/widget_catalog.py` |
|
||||
| Layout-Schema | `backend/dashboard_layout_schema.py` |
|
||||
| Config-Validierung | `backend/dashboard_widget_config.py` |
|
||||
| Entitlements | `backend/dashboard_widget_entitlements.py`, `widget_feature_requirements_db.py` |
|
||||
| Produkt-Standard | `backend/system_dashboard_product_default.py` |
|
||||
| HTTP | `backend/routers/app_dashboard.py` |
|
||||
| Frontend-Registry | `frontend/src/widgetSystem/dashboardWidgetRegistry.jsx` |
|
||||
| Registrierung | `frontend/src/widgetSystem/registerDashboardWidgets.js` |
|
||||
| Layout-Editor | `frontend/src/pages/DashboardConfigurePage.jsx` |
|
||||
| Fehler-Isolation | `frontend/src/widgetSystem/WidgetErrorBoundary.jsx` |
|
||||
| Leitfaden | `DASHBOARD_WIDGETS_AGENT_GUIDE.md` |
|
||||
| Registry-Meta | [REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md](./REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md) |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Dashboard Widgets**
|
||||
|
||||
Erweiterbares System für **konfigurierbare Startübersicht**: Backend-Katalog definiert erlaubte Widget-IDs; Nutzer speichern Reihenfolge, Ein/Aus und optionale `config` pro Profil; Frontend rendert über eine lokale Komponenten-Registry.
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Das Modul übernimmt:
|
||||
|
||||
1. **Widget-Katalog** — IDs, Titel, Beschreibung, optionale Feature-Anforderung (`requires_feature`).
|
||||
2. **Layout-Persistenz** — `profiles.dashboard_layout` (JSON v1: `{ version, widgets[] }`).
|
||||
3. **Validierung** — Erlaubte IDs, keine Duplikate, max. 32 Widgets, mindestens eines aktiv.
|
||||
4. **Pro-Widget-Config** — Whitelist pro Widget-ID; Normalisierung beim Speichern.
|
||||
5. **Standard-Layouts** — Code-Fallback (`DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS`), Admin-Override (`system_config`), Lab-Template (`DEFAULT_LAB_WIDGET_IDS`).
|
||||
6. **Entitlements** — `allowed` im Katalog; Layout bereinigt bei fehlender Berechtigung.
|
||||
7. **Frontend-Rendering** — Registry mappt Katalog-ID → React-Komponente + Props aus `layoutEntry.config`.
|
||||
8. **Nutzer-Konfigurator** — „Übersicht anpassen“ (Sortieren, Toggle, Config-Editoren).
|
||||
|
||||
Es übernimmt **nicht**:
|
||||
|
||||
- Berechnung von KPIs, Charts, Scores (→ Data Layer + Chart-Endpoints, siehe [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md))
|
||||
- Tier-/Subscription-Logik in Widgets (→ Feature System, siehe [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md))
|
||||
- Prompt-/KI-Ausführung (Widget zeigt nur UI; Pipeline läuft über eigene API)
|
||||
|
||||
### Datenfluss (Happy Path)
|
||||
|
||||
```
|
||||
WIDGET_CATALOG (Backend)
|
||||
→ GET /api/app/widgets/catalog (+ allowed via check_feature_access)
|
||||
→ GET /api/app/dashboard-layout
|
||||
→ coalesce_effective_layout (Profil oder Standard)
|
||||
→ merge_missing_catalog_widgets (neue IDs anhängen)
|
||||
→ apply_entitlements_to_layout_dict
|
||||
→ Frontend: ensureDashboardWidgetsRegistered()
|
||||
→ WidgetRenderer: enabled widgets → mapProps(layoutEntry.config) → Component
|
||||
→ PUT /api/app/dashboard-layout (Pydantic + Entitlements + speichern)
|
||||
```
|
||||
|
||||
### Layout-Eintrag (Struktur)
|
||||
|
||||
| Feld | Bedeutung |
|
||||
|------|-----------|
|
||||
| `id` | Muss in `WIDGET_CATALOG` existieren |
|
||||
| `enabled` | Sichtbar auf der Übersicht |
|
||||
| `config` | Optional; nur für whitelisted Widgets mit Inhalt erlaubt |
|
||||
|
||||
---
|
||||
|
||||
## Administrierte vs. code-definierte Konfiguration
|
||||
|
||||
| Konfiguration | Speicherort | Wer pflegt? |
|
||||
|---------------|-------------|-------------|
|
||||
| Widget-IDs, Metadaten, Default-Aktivierung | `widget_catalog.py` | Entwickler |
|
||||
| Produkt-Standard-Layout (live) | `system_config.dashboard_product_default` | Admin |
|
||||
| Produkt-Standard (Fallback) | `DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS` | Entwickler |
|
||||
| Lab-/Editor-Standard | `DEFAULT_LAB_WIDGET_IDS` | Entwickler |
|
||||
| Nutzer-Layout | `profiles.dashboard_layout` | Nutzer |
|
||||
| Feature-Gate (Katalog) | `requires_feature` pro Eintrag | Entwickler |
|
||||
| Feature-Gate (Override) | `widget_feature_requirements` + Marker | Admin |
|
||||
| Config-Schema pro Widget | `dashboard_widget_config.py` | Entwickler |
|
||||
| React-Komponente | `registerDashboardWidgets.js` | Entwickler |
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. Backend-Katalog als Single Source of Truth für IDs
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `WIDGET_CATALOG` ist die einzige autoritative Liste erlaubter Widget-IDs; `ALLOWED_WIDGET_IDS` wird daraus abgeleitet — nicht manuell duplizieren. |
|
||||
| **Begründung** | Layout-Validator, API und Default-Layouts bleiben synchron; unbekannte IDs werden beim PUT abgewiesen. |
|
||||
| **Quelle** | `widget_catalog.py`; Agent-Guide §4 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Frontend-Registry ist zweite manuelle Bindung (kein Build-Time-Gate). |
|
||||
|
||||
### 2. Dual Registry: Backend-Kanon + Frontend-Komponentenbindung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jede Katalog-ID braucht einen Eintrag in `registerDashboardWidget({ id, Component, mapProps })`; idempotent via `ensureDashboardWidgetsRegistered()`. |
|
||||
| **Begründung** | React-Komponenten können nicht im Python-Katalog leben; explizite Zuordnung hält Bundle tree-shakeable. |
|
||||
| **Quelle** | `registerDashboardWidgets.js`, `dashboardWidgetRegistry.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Fehlende Registrierung → Laufzeit „Unbekanntes Widget“, kein CI-Fail. |
|
||||
|
||||
### 3. Layout als versioniertes Profil-JSON
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Nutzer-Layout in `profiles.dashboard_layout`; Schema `version: 1`, Liste `{ id, enabled, config? }`. |
|
||||
| **Begründung** | Pro Profil anpassbar; Reset auf NULL → System-Standard. |
|
||||
| **Quelle** | `DashboardLayoutPayload`, `app_dashboard.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nur v1; Schema-Evolution braucht Migrationspfad. |
|
||||
|
||||
### 4. Validierung an der API-Grenze (Pydantic)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jeder GET/PUT-Pfad normalisiert über `DashboardLayoutPayload`: Duplikat-IDs, unbekannte IDs, leeres Layout (kein enabled) → Fehler. |
|
||||
| **Begründung** | Keine korrupten Layouts in der DB; Frontend kann auf gültige Struktur vertrauen. |
|
||||
| **Quelle** | `dashboard_layout_schema.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Ungültiges gespeichertes Layout → Fallback auf Standard (`coalesce_effective_layout`). |
|
||||
|
||||
### 5. Config nur für explizit whitelisted Widgets
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `WIDGETS_ALLOWING_CONFIG`: Widgets **ohne** Eintrag dürfen nur leere `config` haben; sonst Validierungsfehler. |
|
||||
| **Begründung** | Verhindert unkontrollierte JSON-Blobs und stille Ignorierung unbekannter Keys. |
|
||||
| **Quelle** | `dashboard_widget_config.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Pro Widget heterogene Schemas (chart_days vs. KPI-Tiles vs. show_*-Booleans). |
|
||||
|
||||
### 6. Strikte Config-Keys (Whitelist, Normalisierung)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Unbekannte Keys in `config` werden abgelehnt; bekannte Keys typgeprüft und normalisiert (z. B. `chart_days` 7–90, KPI max. 9 Kacheln). |
|
||||
| **Begründung** | Vorhersagbares Verhalten; Editor und Backend stimmen überein. |
|
||||
| **Quelle** | `_validate_chart_days_only`, `_validate_kpi_board_config`, History-Viz-Defaults |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Frontend-Normalizer (`bodyChartDays.js`, `*VizConfig.js`) teils parallel — Abweichungsrisiko. |
|
||||
|
||||
### 7. Config-Größenlimit
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `MAX_WIDGET_CONFIG_JSON_BYTES` (3072) — keine großen Blobs in Layout-JSON. |
|
||||
| **Begründung** | DB-Spalte und API-Payload bleiben schlank; Config = Präferenzen, nicht Datenspeicher. |
|
||||
| **Quelle** | `dashboard_widget_config.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | — |
|
||||
|
||||
### 8. Katalog-Erweiterung ohne Layout-Reset
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `merge_missing_catalog_widgets` hängt neue Katalog-IDs ans bestehende Layout an (`enabled: false`). |
|
||||
| **Begründung** | Nutzer müssen nach Deploy nicht resetten; „Übersicht anpassen“ zeigt neue Optionen. |
|
||||
| **Quelle** | `dashboard_layout_schema.py`; Agent-Guide |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Reihenfolge neuer Widgets immer am Ende. |
|
||||
|
||||
### 9. Mehrere Standard-Layouts (Produkt vs. Lab vs. Admin)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | **Produkt:** `get_product_default_base_dict` (DB-Override oder `DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS`). **Lab:** `lab_default_layout_dict` für Editor/Reset. **Nutzer:** eigenes JSON oder NULL. |
|
||||
| **Begründung** | Onboarding-Default getrennt von Entwickler-/Lab-Template; Admin kann Produkt-Standard ohne Deploy ändern. |
|
||||
| **Quelle** | `system_dashboard_product_default.py`, `widget_catalog.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Feldname `lab_default_layout` historisch irreführend (Servertemplate, nicht nur Lab). |
|
||||
|
||||
### 10. Entitlements zentral, Widgets konsumieren nur `allowed`
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Sichtbarkeit über `check_feature_access` in `widget_id_allowed`; Katalog liefert `allowed` pro Zeile. Widgets/React duplizieren **keine** Tier-Logik. |
|
||||
| **Begründung** | Eine Wahrheit für „darf angezeigt werden“; spätere Feature-Cluster ohne Widget-Refactor. |
|
||||
| **Quelle** | `dashboard_widget_entitlements.py`; Agent-Guide §0 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Inhalts-Endpoints (Charts, KI) brauchen **eigenes** Feature-Gate (Defense in Depth). |
|
||||
|
||||
### 11. Layout-Persistenz bereinigt nicht erlaubte Widgets
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `apply_entitlements_to_layout_dict`: bei fehlender Berechtigung `enabled: false`; mindestens `welcome` bleibt aktiv. GET und PUT wenden an. |
|
||||
| **Begründung** | Keine „gespeichert aber nie sichtbar“-Zombies; Downgrade/Tier-Wechsel degradieren gracefully. |
|
||||
| **Quelle** | `dashboard_widget_entitlements.py`, `app_dashboard.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Policy ist deaktivieren, nicht entfernen — IDs bleiben im JSON. |
|
||||
|
||||
### 12. DB-Override für Widget-Feature-Anforderungen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Katalog-`requires_feature` ist Default; Admin kann per `dashboard_widget_requirement_custom` + `widget_feature_requirements` überschreiben (AND-Semantik). |
|
||||
| **Begründung** | Runtime-Anpassung ohne Code-Deploy; Marker-Zeile trennt Custom von Fallback. |
|
||||
| **Quelle** | `widget_feature_requirements_db.py`, Migration 041 |
|
||||
| **Tragfähigkeit** | **mittel–hoch** |
|
||||
| **Einschränkung** | Zwei Quellen (Code + DB) — Dokumentation und Admin-UI nötig. |
|
||||
|
||||
### 13. mapProps: Layout-Config → Komponenten-Props
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Registry-Eintrag mappt `ctx.layoutEntry.config` auf typisierte Props (`chartDays`, `kpiConfig`, `bodyHistoryVizConfig`, …). |
|
||||
| **Begründung** | Widget-Komponenten bleiben layout-agnostisch; Normalisierung an einer Stelle pro ID. |
|
||||
| **Quelle** | `registerDashboardWidgets.js` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Teilweise Normalisierung in Widget statt in `mapProps` (inkonsistent, aber dokumentiert). |
|
||||
|
||||
### 14. Refresh-Koordination über Context
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `refreshTick` + `requestRefresh()` im Render-Context; Widgets laden Daten bei Tick-Änderung neu; Aktionen (z. B. Schnelleingabe) rufen `requestRefresh`. |
|
||||
| **Begründung** | Kein globales State-Monster; gezielte Invalidierung nach Capture. |
|
||||
| **Quelle** | `dashboardWidgetRegistry.jsx`, Widget-Implementierungen |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Kein feingranulares Cache pro Widget. |
|
||||
|
||||
### 15. Fehler-Isolation pro Widget
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `WidgetErrorBoundary` um jede Instanz — Render-Fehler crashen nicht die ganze Übersicht. |
|
||||
| **Begründung** | Robuste PWA; ein defektes Chart blockiert nicht Gewicht-Eingabe. |
|
||||
| **Quelle** | `WidgetErrorBoundary.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Kein automatisches Retry/Reporting. |
|
||||
|
||||
### 16. Konfigurator filtert nach `allowed`
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `DashboardConfigurePage` blendet Widgets mit `allowed === false` aus der bearbeitbaren Liste aus. |
|
||||
| **Begründung** | Nutzer sehen keine Optionen, die sie nicht nutzen dürfen (Agent-Guide A2). |
|
||||
| **Quelle** | `DashboardConfigurePage.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Bereits gespeicherte disabled Einträge können im JSON verbleiben. |
|
||||
|
||||
### 17. Widgets konsumieren Data Layer, duplizieren keine Logik
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Chart-/KPI-Widgets rufen Chart-Endpoints bzw. API-Fassaden auf; Berechnungen leben in `data_layer/`, nicht in Widget-JS. |
|
||||
| **Begründung** | Gleiche Zahlen wie Verlauf, KI-Platzhalter und Export. |
|
||||
| **Quelle** | Layer-2b `*_history_viz`-Widgets; [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md) |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy-Widgets unter `dashboard-widgets-legacy/` teils ältere Fetch-Pfade. |
|
||||
|
||||
### 18. Dedizierte Config-Editoren für komplexe Widgets
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Einfache `chart_days`: Set `CHART_DAYS_WIDGET_IDS` im Layout-Editor; komplexe Config: eigene Editor-Komponenten (`KpiBoardConfigEditor`, `*VizConfigEditor`). |
|
||||
| **Begründung** | UX skaliert mit Config-Komplexität; Backend-Schema und Editor bleiben parallel pflegbar. |
|
||||
| **Quelle** | `widgetSystem/*ConfigEditor.jsx`, Agent-Guide §3.4 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Jedes neue komplexe Widget = Editor + Validator + Tests. |
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
1. **Tier-Logik in React-Widgets** — nur `allowed` aus API; keine hardcodierten Plan-Namen.
|
||||
|
||||
2. **`ALLOWED_WIDGET_IDS` manuell pflegen** — immer aus Katalog ableiten.
|
||||
|
||||
3. **Config ohne Backend-Whitelist** — stille Ignorierung unbekannter Keys in Widgets.
|
||||
|
||||
4. **Nur UI-Gating ohne API-Absicherung** — Chart-/KI-/Export-Endpoints weiterhin `check_feature_access` (403).
|
||||
|
||||
5. **Frontend-Registry vergessen** — Katalog-Eintrag ohne `registerDashboardWidget` → Laufzeitfehler statt Build-Fail.
|
||||
|
||||
6. **Große Daten in `config`** — Layout ist Präferenzspeicher, kein Blob-Store (>3072 Bytes).
|
||||
|
||||
7. **Doppelte Widget-IDs im Layout** — Validator verbietet; Editor muss dasselbe erzwingen.
|
||||
|
||||
8. **Neue Katalog-IDs ohne `merge_missing_catalog_widgets`-Pfad** — Nutzer-Layouts veralten unsichtbar.
|
||||
|
||||
9. **Kompletter Katalog nur in DB** — schwer testbar; Code-Katalog + optionale Feature-Overrides ist das Muster.
|
||||
|
||||
10. **Evidence-Pflicht à la Placeholder-Registry** — 22 Metadatenfelder pro Widget wären Overkill; Tiefe an Risiko anpassen ([REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md](./REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md)).
|
||||
|
||||
11. **Ein Default für alles** — Produkt-Onboarding, Lab-Template und Admin-Override haben unterschiedliche Zwecke; nicht vermischen.
|
||||
|
||||
12. **Fehlender Cross-Check Backend ↔ Frontend IDs** — empfohener Test/Gate fehlt im Ist-Stand; nicht als „optional“ ignorieren.
|
||||
|
||||
13. **Berechnungslogik im Widget** — KPIs/Scores gehören in Data Layer, nicht in `useEffect`-Mathe.
|
||||
|
||||
14. **Entitlements beim Speichern ablehnen statt deaktivieren** — Mitai wählt deaktivieren; Policy bewusst festlegen und dokumentieren.
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Ist-Stand)
|
||||
|
||||
```
|
||||
backend/
|
||||
├── widget_catalog.py # WIDGET_CATALOG, DEFAULT_*_IDS
|
||||
├── dashboard_layout_schema.py # Pydantic, merge_missing, defaults
|
||||
├── dashboard_widget_config.py # WIDGETS_ALLOWING_CONFIG, Validatoren
|
||||
├── dashboard_widget_entitlements.py # allowed, layout cleanup
|
||||
├── widget_feature_requirements_db.py # Admin-Override
|
||||
├── system_dashboard_product_default.py
|
||||
└── routers/app_dashboard.py
|
||||
|
||||
frontend/src/
|
||||
├── widgetSystem/
|
||||
│ ├── dashboardWidgetRegistry.jsx
|
||||
│ ├── registerDashboardWidgets.js
|
||||
│ ├── layoutEditor.js
|
||||
│ ├── bodyChartDays.js, *VizConfig.js
|
||||
│ └── *ConfigEditor.jsx
|
||||
├── components/dashboard-widgets/ # Produkt-Widgets
|
||||
├── components/dashboard-widgets-legacy/ # ältere Kern-Widgets
|
||||
└── pages/DashboardConfigurePage.jsx
|
||||
|
||||
DB:
|
||||
├── profiles.dashboard_layout
|
||||
├── system_config.dashboard_product_default
|
||||
├── dashboard_widget_requirement_custom
|
||||
└── widget_feature_requirements
|
||||
```
|
||||
|
||||
**Katalog-Umfang:** ~24 Widget-IDs (Stand `widget_catalog.py`); ~13 mit konfigurierbarer `config`.
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Agent-Guide (normativ): [DASHBOARD_WIDGETS_AGENT_GUIDE.md](../../technical/DASHBOARD_WIDGETS_AGENT_GUIDE.md)
|
||||
- Registry-Meta: [REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md](./REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md)
|
||||
- Feature-Gates: [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
- Datenberechnung: [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md)
|
||||
- Architektur §9: `.claude/rules/ARCHITECTURE.md`
|
||||
|
||||
---
|
||||
|
||||
## Geplante Folgedokumente (Serie)
|
||||
|
||||
| # | Modul | Status |
|
||||
|---|-------|--------|
|
||||
| 1–6 | … | ✅ |
|
||||
| 7 | Dashboard Widgets | ✅ dieses Dokument |
|
||||
| 8 | Navigation / IA | ✅ |
|
||||
| 9 | Migration & Deploy | ✅ |
|
||||
@@ -0,0 +1,359 @@
|
||||
# Data Layer – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** Multi-Layer Data Architecture (Phase 0c, Issue #53) — keine Mitai-Gesamtarchitektur, keine konkrete Gesundheits-/Ernährungsfachlogik als Produktinhalt
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 2 von n
|
||||
**Vorgänger:** [PROMPT_ENGINE_DESIGN_PRINCIPLES.md](./PROMPT_ENGINE_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| Metriken (Layer 1) | `backend/data_layer/*_metrics.py`, `scores.py`, `correlations.py` |
|
||||
| Utilities | `backend/data_layer/utils.py` |
|
||||
| Visualisierung (Layer 2b) | `*_chart_payloads.py`, `*_viz.py` |
|
||||
| KI-Formatierung (Layer 2a-Hilfe) | `prompt_output_compact.py` |
|
||||
| Persistenz-Orchestrierung | `activity_persistence_orchestrator.py`, `activity_session_metrics.py` |
|
||||
| Konsumenten | `routers/charts.py`, `placeholder_resolver.py`, `routers/exportdata.py` |
|
||||
| Leitfäden | `DATA_LAYER_EXTENSION_GUIDE.md`, `docs/issues/issue-53-phase-0c-multi-layer-architecture.md` |
|
||||
| Architektur-Regel Import-Grenze | `.claude/rules/ARCHITECTURE.md` §8 |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Data Layer** (Phase 0c Multi-Layer Architecture, Issue #53)
|
||||
|
||||
Zentrale Schicht für **Datenabruf, Berechnung und strukturierte Aufbereitung** — ohne UI-Formatierung, ohne Prompt-Texte, ohne Chart.js-spezifische Ausgabe in den Kern-Metrik-Modulen.
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Der Data Layer ist die **Single Source of Truth für alle abgeleiteten Messwerte und Metriken**. Er übernimmt:
|
||||
|
||||
1. **Datenabruf** — Lesen aus PostgreSQL (profile-scoped), optional mit Quality-Filter.
|
||||
2. **Berechnung** — Trends, Scores, Korrelationen, Aggregationen, Projektionen.
|
||||
3. **Strukturierte Rückgabe** — Dicts/Listen mit numerischen Werten, Datumsfeldern, Metadaten (`confidence`, `data_points`).
|
||||
4. **Konsumenten-Bereitstellung** — Charts (Layer 2b), KI-Platzhalter (Layer 2a via Resolver), Export, Router-Anreicherung.
|
||||
|
||||
Er übernimmt **nicht**:
|
||||
|
||||
- CSV-Parsing und Feld-Mapping (Import-Schicht)
|
||||
- Prompt-Template-Auflösung (Prompt Engine)
|
||||
- React-Rendering oder Frontend-Berechnungen
|
||||
- Autorisierung / Feature-Limits (Auth-Schicht)
|
||||
|
||||
### Schichtenmodell (Multi-Layer)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Layer 0: Persistenz (PostgreSQL) │
|
||||
│ weight_log, nutrition_log, activity_log, sleep_log, … │
|
||||
└──────────────────────────┬──────────────────────────────┘
|
||||
│
|
||||
┌──────────────────────────▼──────────────────────────────┐
|
||||
│ Layer 1: DATA LAYER (Metriken) │
|
||||
│ Strukturierte Daten · confidence · data_points │
|
||||
│ KEINE formatierten Strings · KEINE Chart.js-Objekte │
|
||||
└──────────────┬───────────────────────┬──────────────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────────────────────┐ ┌────────────────────────────┐
|
||||
│ Layer 2a: KI / Prompts │ │ Layer 2b: Visualisierung │
|
||||
│ placeholder_resolver │ │ *_chart_payloads, *_viz │
|
||||
│ prompt_output_compact │ │ routers/charts.py │
|
||||
└──────────────────────────┘ └────────────────────────────┘
|
||||
```
|
||||
|
||||
### Administrierte vs. code-definierte Konfiguration
|
||||
|
||||
| Was | Wo | Administrierbar? |
|
||||
|-----|-----|------------------|
|
||||
| Berechnungslogik (Formeln, Fenster) | `data_layer/*.py` | ❌ Code + Review |
|
||||
| Confidence-Schwellen | `data_layer/utils.py` | ❌ Code |
|
||||
| Goal Mode / Focus Weights | DB (`profiles`, `user_focus_area_weights`) | ✅ Nutzer/Admin |
|
||||
| Quality Filter (Profil) | DB (`profiles`) | ✅ Admin |
|
||||
| Chart-Zeitfenster | Query-Parameter an API | ✅ Request |
|
||||
| Referenzwerte (persönlich) | DB + `reference_values.py` | ✅ Nutzer |
|
||||
| EAV Session Metrics | DB (`training_*_parameter`) | ✅ Admin |
|
||||
|
||||
**Bewusst nicht hardcodiert in Routern:** Metrik-Berechnungen — Router delegieren an Data Layer.
|
||||
|
||||
**Hardcodiert (Code):** Domänen-Module, Confidence-Regeln, Schwellen pro Metrik-Typ, TDEE-Fallback-Logik, Chart-Payload-Struktur.
|
||||
|
||||
### Trennung: Metriken · Chart-Payloads · KI-Formatierung · Persistenz
|
||||
|
||||
| Schicht | Module | Verantwortung |
|
||||
|---------|--------|---------------|
|
||||
| **Metriken** | `body_metrics.py`, `nutrition_metrics.py`, … | Reine Berechnung, strukturierte Dicts |
|
||||
| **Chart-Payloads** | `nutrition_chart_payloads.py`, `correlation_chart_payloads.py`, … | Chart.js-kompatible `{ labels, datasets, metadata }` aus Layer-1-Daten |
|
||||
| **Viz-Bundles** | `body_viz.py`, `fitness_viz.py`, … | Zusammengesetzte Dashboard-/History-Pakete für Frontend |
|
||||
| **KI-Kompaktierung** | `prompt_output_compact.py` | Token-sparende Zahlen/JSON für Platzhalter |
|
||||
| **Interpretation** | `*_interpretation.py`, `vital_signs_assessment.py` | Textliche Einordnung (WHO-Klassen etc.) — Grenze zu Layer 2a |
|
||||
| **Persistenz-Orchestrator** | `activity_persistence_orchestrator.py` | Schreibpfade REST/CSV → DB + Nebenwirkungen (EAV, Eval) |
|
||||
|
||||
### Konsumenten (wer ruft den Data Layer auf?)
|
||||
|
||||
| Konsument | Muster |
|
||||
|-----------|--------|
|
||||
| `routers/charts.py` | Layer-1-Funktion + Chart-Payload-Builder |
|
||||
| `placeholder_resolver.py` | Layer-1 → Formatierung/JSON für `{{placeholders}}` |
|
||||
| `routers/exportdata.py` | `enrich_sessions_with_metrics`, `serialize_dates` |
|
||||
| `routers/activity.py`, `csv_import.py` | `activity_persistence_orchestrator` (Schreiben) |
|
||||
| `prompt_executor.execute_prompt_with_data` | ⚠️ teils Roh-SQL parallel zum Data Layer (Legacy) |
|
||||
|
||||
### Rollen
|
||||
|
||||
Der Data Layer hat **keine eigene Admin-UI**. Konfiguration erfolgt indirekt:
|
||||
|
||||
- **Admin:** Training-Parameter, Attributprofile, Referenzwert-Typen, Quality-Filter
|
||||
- **Nutzer:** Profildaten, Referenzwerte, Focus-Area-Gewichte (beeinflussen Scores)
|
||||
- **Entwickler:** Neue Funktionen in `data_layer/` nach Extension Guide
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. Single Source of Truth für Berechnungen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jede Metrik wird **einmal** in `data_layer/` berechnet; Charts, KI und Export konsumieren dieselbe Funktion. |
|
||||
| **Begründung** | Verhindert divergierende Zahlen zwischen Dashboard, Analyse und KI-Ausgabe. |
|
||||
| **Quelle** | Issue #53 Executive Summary; `nutrition_chart_payloads.py` Kommentar „identisch zu GET /api/charts/energy-balance“ |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht alle Pfade migriert (`insights._prepare_template_vars`, `execute_prompt_with_data` Roh-SQL). |
|
||||
|
||||
### 2. Layer 1 liefert strukturierte Daten, keine formatierten Strings
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Kern-Metrik-Funktionen geben Dicts mit `float`/`int`/`date` zurück — **keine** Strings mit Einheiten („86,1 kg“). |
|
||||
| **Begründung** | Formatierung ist konsumentenspezifisch (DE-Locale, Chart-Achsen, KI-Token). |
|
||||
| **Quelle** | `data_layer/__init__.py` Docstring: „NO FORMATTING. NO STRINGS WITH UNITS.“ |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `placeholder_resolver` und `*_interpretation` Module formatieren teils direkt — Grenze Layer 1/2a nicht überall scharf. |
|
||||
|
||||
### 3. Pflicht-Metadaten: confidence + data_points
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jede Metrik-Funktion liefert mindestens `confidence` (`high`\|`medium`\|`low`\|`insufficient`) und `data_points`. |
|
||||
| **Begründung** | UI/KI können Datenqualität kommunizieren; Debugging und Monitoring vereinfacht. |
|
||||
| **Quelle** | `DATA_LAYER_EXTENSION_GUIDE.md` § Pflicht-Felder; `calculate_confidence()` in `utils.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht runtime-validiert; Disziplin per Code-Review. |
|
||||
|
||||
### 4. Confidence nach Metrik-Typ und Zeitfenster
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Schwellen unterscheiden `general`, `correlation`, `trend` und Fensterlänge (7d / 28d / 90d). |
|
||||
| **Begründung** | Korrelationen brauchen mehr Paare; Trends messen Abdeckung (% der Tage). |
|
||||
| **Quelle** | `data_layer/utils.py` → `calculate_confidence()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Schwellen global hardcodiert, nicht pro Metrik konfigurierbar. |
|
||||
|
||||
### 5. Domänen-Module statt Monolith
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Ein Python-Modul pro fachlichem Bereich (`body_metrics`, `nutrition_metrics`, …), max. ~500 Zeilen, dann Split. |
|
||||
| **Begründung** | Wartbarkeit, klare Ownership, parallele Entwicklung. |
|
||||
| **Quelle** | `DATA_LAYER_EXTENSION_GUIDE.md` § Modul-Struktur |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Einige Module deutlich >500 Zeilen (Phase-0c-Wachstum). |
|
||||
|
||||
### 6. Layer 2b: Chart-Payloads als Adapter
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Chart.js-Strukturen leben in dedizierten `*_chart_payloads.py` / `*_viz.py`, nicht in Metrik-Modulen. |
|
||||
| **Begründung** | Gleiche Metrik, verschiedene Visualisierungen; API-Endpoints bleiben dünn. |
|
||||
| **Quelle** | `nutrition_chart_payloads.py`; `routers/charts.py` Imports |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Teilweise noch SQL-Duplikation in Payload-Buildern neben Layer-1-Aufruf. |
|
||||
|
||||
### 7. Layer 2a-Hilfe: KI-spezifische Kompaktierung getrennt
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Token-Reduktion für LLM-Kontext (`compact_float_for_prompt`, `compact_json_payload_for_prompts`) ist eigenes Modul, nicht in Metrik-Kern. |
|
||||
| **Begründung** | KI hat andere Anforderungen als Charts (Präzision vs. Token-Kosten). |
|
||||
| **Quelle** | `prompt_output_compact.py`; Tests in `tests/test_prompt_output_compact.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nur für KI-Pfad; Charts nutzen eigene Rundung. |
|
||||
|
||||
### 8. Import-Grenze: Ingest vs. Interpretation
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | CSV-Import macht Mapping + Typkonvertierung + Duplikatlogik — **keine** fachliche Auswertung beim Insert. |
|
||||
| **Begründung** | Semantik gehört in Layer 1+, sonst versteckte Business-Logik in Import-Adaptern. |
|
||||
| **Quelle** | `ARCHITECTURE.md` §8; Issue #53 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy-Adapter (Apple-Schlaf-Aggregat, dedizierte Import-Endpoints) noch aktiv. |
|
||||
|
||||
### 9. Persistenz-Orchestrator für Schreibpfade
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Alle Schreibwege eines Domänenobjekts (REST, CSV, Legacy) laufen durch **einen** Orchestrator mit Nebenwirkungen (EAV, Evaluation). |
|
||||
| **Begründung** | Konsistente Duplikat-Erkennung, Registry-Felder, keine divergierenden Insert-Logiken. |
|
||||
| **Quelle** | `activity_persistence_orchestrator.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Bisher vor allem Aktivität; andere Domänen noch direkt in Routern. |
|
||||
|
||||
### 10. Registry als Feld-Kanon (Activity)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Erlaubte persistierbare Felder für CSV/REST leiten sich aus `module_registry` ab, nicht aus Router-Hardcoding. |
|
||||
| **Begründung** | Single Source of Truth für Import-Mappings und DB-Updates. |
|
||||
| **Quelle** | `activity_data_canon.py`, `activity_persistence_orchestrator.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nur Activity vollständig; andere Module noch klassische Spalten-CRUD. |
|
||||
|
||||
### 11. EAV-Anreicherung als Read-Layer
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Session-Metriken (EAV) werden beim **Lesen** angereichert (`enrich_sessions_with_metrics`), nicht pro Consumer dupliziert. |
|
||||
| **Begründung** | Ein Merge-Kanon für Liste, Detail, Export, Platzhalter. |
|
||||
| **Quelle** | `activity_session_metrics.py`; `ACTIVITY_SESSION_METRICS_EAV_AGENT_GUIDE.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Domänenspezifisch (Training); Muster übertragbar. |
|
||||
|
||||
### 12. Scores als composable Layer
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Composite Scores (`scores.py`) kombinieren Domänen-Metriken mit nutzer-spezifischen Focus Weights — keine Score-Logik in Routern. |
|
||||
| **Begründung** | Goal-Mode-/Focus-abhängige Gewichtung zentral, für KI und Dashboard gleich. |
|
||||
| **Quelle** | `data_layer/scores.py`; Phase-0b-Fokus-System |
|
||||
| **Tragfähigkeit** | **mittel–hoch** |
|
||||
| **Einschränkung** | Eng an Mitai-Zielsystem gekoppelt; Muster „gewichtete Composite Scores“ ist generisch. |
|
||||
|
||||
### 13. API-First: Router delegieren, rechnen nicht
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `routers/charts.py` und ähnliche Endpoints rufen Data-Layer-Funktionen auf und mappen auf HTTP — keine Trend-Berechnung im Router. |
|
||||
| **Begründung** | Testbarkeit; Frontend ohne Business-Logik. |
|
||||
| **Quelle** | `ARCHITECTURE.md` §1.2 API-First |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `charts.py` ist groß (2246+ Zeilen) — viel Adapter-Code, aber Berechnung delegiert. |
|
||||
|
||||
### 14. serialize_dates / safe_float als Querschnitt
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | JSON/API-Serialisierung (Dates, Decimal) zentral in `utils.py`, nicht pro Modul neu erfunden. |
|
||||
| **Begründung** | PostgreSQL-Typen (DATE, DECIMAL) konsistent für API und Export. |
|
||||
| **Quelle** | `data_layer/utils.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | — |
|
||||
|
||||
### 15. Extension Guide als verbindlicher Entwicklungsvertrag
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Neue Metriken folgen Template (Retrieve → Confidence → Early Return → Calculate → Return) und werden in `__init__.py` exportiert. |
|
||||
| **Begründung** | Einheitliche Struktur für 97+ Funktionen und wachsende Codebase. |
|
||||
| **Quelle** | `DATA_LAYER_EXTENSION_GUIDE.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Guide und Ist-Code divergieren teils (Modulgröße, `goals.py` noch nicht in `__init__`). |
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
Muster, die sich nicht bewährt haben oder zu produktspezifisch sind:
|
||||
|
||||
1. **Berechnungslogik in `placeholder_resolver.py`** — Phase-0b-Legacy; Resolver soll nur formatieren/aggregieren, nicht rechnen.
|
||||
|
||||
2. **Paralleler Roh-SQL-Kontext in `prompt_executor.execute_prompt_with_data`** — lädt Modul-Rohdaten per SQL, obwohl Layer 1 existiert; zweite Wahrheit.
|
||||
|
||||
3. **Legacy Insights-Pfad (`insights._prepare_template_vars`)** — eigene Variablen-Vorbereitung ohne Data Layer.
|
||||
|
||||
4. **Import mit fachlicher Interpretation** — Apple-Schlaf-Aggregat und ähnliche Adapter verstecken Semantik im Ingest (Gitea #69).
|
||||
|
||||
5. **Monolithische Router mit Inline-Berechnung** — vor Phase 0c; gelegentlich noch Reste in nicht migrierten Pfaden.
|
||||
|
||||
6. **Interpretation vermischt mit Layer 1** — `*_interpretation.py` liefert teils fertige Texte; für Familien-Architektur klar als Layer 2a/2b markieren oder auslagern.
|
||||
|
||||
7. **SQL-Duplikation in Chart-Payloads** — manche Payload-Builder führen eigene Queries statt ausschließlich Layer-1-Ergebnisse zu visualisieren.
|
||||
|
||||
8. **Hardcodierte Confidence global** — funktioniert, aber nicht pro Metrik/Domäne konfigurierbar; Skalierung in Multi-Tenant-Produktfamilie prüfen.
|
||||
|
||||
9. **Domänen-Module als Produktinhalt** — `body_metrics`, TDEE, WHR etc. sind Mitai-spezifisch; **Schichtenmodell** übernehmen, **Formeln** nicht blind kopieren.
|
||||
|
||||
10. **Fehlende runtime-Validierung des Return-Schemas** — `confidence`/`data_points` per Konvention, nicht per TypedDict/Pydantic erzwungen.
|
||||
|
||||
11. **Uneinheitliche Schreib-Orchestrierung** — nur Activity hat `persistence_orchestrator`; andere Domänen noch fragmentiert.
|
||||
|
||||
12. **Riesige Einzeldateien** — einige Metrik-Module >>500 Zeilen widersprechen eigenem Extension Guide.
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Ist-Stand)
|
||||
|
||||
```
|
||||
backend/data_layer/
|
||||
├── Kern-Metriken (Layer 1)
|
||||
│ ├── body_metrics.py
|
||||
│ ├── nutrition_metrics.py
|
||||
│ ├── activity_metrics.py
|
||||
│ ├── recovery_metrics.py
|
||||
│ ├── health_metrics.py
|
||||
│ ├── scores.py
|
||||
│ └── correlations.py
|
||||
├── Visualisierung (Layer 2b)
|
||||
│ ├── *_chart_payloads.py (nutrition, recovery, correlation)
|
||||
│ └── *_viz.py (body, nutrition, fitness, recovery, history_overview)
|
||||
├── KI / Format (Layer 2a-Nähe)
|
||||
│ ├── prompt_output_compact.py
|
||||
│ └── *_interpretation.py
|
||||
├── Persistenz / EAV
|
||||
│ ├── activity_persistence_orchestrator.py
|
||||
│ ├── activity_session_metrics.py
|
||||
│ └── activity_data_canon.py
|
||||
├── Querschnitt
|
||||
│ ├── utils.py
|
||||
│ ├── reference_values.py
|
||||
│ └── nutrition_body_merge.py
|
||||
└── __init__.py (Exports)
|
||||
```
|
||||
|
||||
**Konsumenten-Endpoints (Auswahl):** 20+ Chart-Endpoints in `routers/charts.py` (E1–E5, A1–A8, R1–R5, C1–C4).
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Issue #53 Abschluss: [issue-53-phase-0c-multi-layer-architecture.md](../../../../docs/issues/issue-53-phase-0c-multi-layer-architecture.md)
|
||||
- Extension Guide: [DATA_LAYER_EXTENSION_GUIDE.md](../../technical/DATA_LAYER_EXTENSION_GUIDE.md)
|
||||
- Fachliche Datenarchitektur: [DATA_ARCHITECTURE.md](../../functional/DATA_ARCHITECTURE.md)
|
||||
- Import-Grenze: [ARCHITECTURE.md](../../../rules/ARCHITECTURE.md) §8
|
||||
- Platzhalter-Anbindung: [PLACEHOLDER_REGISTRY_FRAMEWORK.md](../../technical/PLACEHOLDER_REGISTRY_FRAMEWORK.md)
|
||||
- Prompt Engine (Konsument Layer 2a): [PROMPT_ENGINE_DESIGN_PRINCIPLES.md](./PROMPT_ENGINE_DESIGN_PRINCIPLES.md)
|
||||
- Feature & Entitlement: [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
|
||||
---
|
||||
|
||||
## Geplante Folgedokumente (Serie)
|
||||
|
||||
| # | Modul | Datei (geplant) |
|
||||
|---|-------|-----------------|
|
||||
| 1 | Prompt Engine | ✅ `PROMPT_ENGINE_DESIGN_PRINCIPLES.md` |
|
||||
| 2 | Data Layer | ✅ dieses Dokument |
|
||||
| 3 | Feature & Entitlement System | ✅ `FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md` |
|
||||
| 4 | Registry-/Plugin-Muster | ✅ `REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md` |
|
||||
| 5 | Auth & Session | ✅ `AUTH_SESSION_DESIGN_PRINCIPLES.md` |
|
||||
| 6 | Universal Import | ✅ `UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md` |
|
||||
| 7 | Dashboard Widgets | ✅ `DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md` |
|
||||
| 8 | Navigation / IA | ✅ `NAVIGATION_IA_DESIGN_PRINCIPLES.md` |
|
||||
| 9 | Migration & Deploy | ✅ `MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md` |
|
||||
@@ -0,0 +1,370 @@
|
||||
# Feature & Entitlement System – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** Membership-, Tier- und Feature-Limit-System (v9c) — keine Mitai-Domänenlogik, kein zentrales SSO/Stripe (Vision)
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 3 von n
|
||||
**Vorgänger:** [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| Entitlement-Auflösung | `backend/auth.py` (`get_effective_tier`, `check_feature_access`, `increment_feature_usage`) |
|
||||
| Monitoring | `backend/feature_logger.py` |
|
||||
| Nutzer-API | `backend/routers/subscription.py`, `backend/routers/features.py` |
|
||||
| Admin | `routers/tiers_mgmt.py`, `tier_limits.py`, `coupons.py`, `access_grants.py`, `user_restrictions.py` |
|
||||
| Widget-Gating | `backend/dashboard_widget_entitlements.py`, `widget_feature_requirements_db.py` |
|
||||
| Frontend | `UsageBadge.jsx`, Feature-Usage in Seiten (z. B. `Analysis.jsx`, `WeightPage`) |
|
||||
| Doku | `MEMBERSHIP_SYSTEM.md`, `FEATURE_ENFORCEMENT.md`, `CENTRAL_SUBSCRIPTION_SYSTEM.md` (Vision) |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Feature & Entitlement System** (Membership v9c)
|
||||
|
||||
Zentrale Schicht für **„Darf dieser Nutzer diese Funktion wie oft nutzen?“** — unabhängig von Auth (Identität) und unabhängig von fachlicher Business-Logik in Routern.
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Das System übernimmt:
|
||||
|
||||
1. **Feature-Registry** — Deklarative Liste aller limitierbaren Produktfunktionen mit Metadaten.
|
||||
2. **Tier-Auflösung** — Effektiver Tarif eines Profils (Basis-Tier + zeitliche Grants).
|
||||
3. **Limit-Auflösung** — Pro Feature: Override → Tier-Limit → Feature-Default.
|
||||
4. **Usage-Tracking** — Zähler für Count-Features mit optionalem Reset (daily/monthly/never).
|
||||
5. **Enforcement** — HTTP 403 bei Überschreitung; Frontend-Vorschaum via Badges.
|
||||
6. **Beobachtbarkeit** — Strukturiertes JSON-Logging aller Access-Checks.
|
||||
7. **Promotionen** — Coupons → Access Grants (temporäre Tier-Elevation, Pause/Resume).
|
||||
|
||||
Es übernimmt **nicht**:
|
||||
|
||||
- Login, Session, Passwort (Auth-Modul)
|
||||
- Zahlungsabwicklung / Stripe (geplant, `CENTRAL_SUBSCRIPTION_SYSTEM.md`)
|
||||
- Mandanten-Isolation (Org/Workspace) — Entitlements sind **profile-scoped**
|
||||
- Inhaltliche Berechtigung pro Datensatz (nur Feature-Gates)
|
||||
|
||||
### Zwei Entscheidungsebenen
|
||||
|
||||
| Ebene | Frage | Funktion |
|
||||
|-------|--------|----------|
|
||||
| **Tier** | Welcher Tarif gilt? | `get_effective_tier()` |
|
||||
| **Feature** | Darf Feature X genutzt werden (wie oft)? | `check_feature_access()` |
|
||||
|
||||
Tier beeinflusst Feature-Limits über `tier_limits`; User-Overrides können Limits unabhängig vom Tier setzen.
|
||||
|
||||
### Administrierte Konfigurationen
|
||||
|
||||
| Konfiguration | Speicherort | Admin-UI |
|
||||
|---------------|-------------|----------|
|
||||
| Feature-Definitionen | `features` | Admin Features |
|
||||
| Tier-Stufen | `tiers` | Admin Tiers |
|
||||
| Tier × Feature Matrix | `tier_limits` | Admin Tier Limits |
|
||||
| User-Overrides | `user_feature_restrictions` | Admin User Restrictions |
|
||||
| Coupons | `coupons`, `coupon_redemptions` | Admin Coupons |
|
||||
| Temporäre Tier-Grants | `access_grants` | (via Coupon/Admin) |
|
||||
| Widget → Feature Mapping | `widget_feature_requirements`, Katalog | Admin Widget Features |
|
||||
| Usage-Zähler | `user_feature_usage` | (automatisch) |
|
||||
|
||||
**Nicht hardcodiert:** Limits pro Tier, Feature-Metadaten, Coupon-Parameter, User-Overrides.
|
||||
|
||||
**Hardcodiert (Code):** Feature-IDs in Routern (`'ai_calls'`, `'weight_entries'`, …), Reset-Berechnung, 4-Phasen-Muster, 11 initial registrierte Features.
|
||||
|
||||
### Auflösungs-Hierarchien
|
||||
|
||||
**Effektiver Tier** (`get_effective_tier`):
|
||||
|
||||
1. Aktiver `access_grants`-Eintrag (`is_active`, `valid_from`/`valid_until`)
|
||||
2. Fallback: `profiles.tier`
|
||||
|
||||
**Feature-Limit** (`check_feature_access` → `_check_impl`):
|
||||
|
||||
1. `user_feature_restrictions.limit_value` (höchste Priorität)
|
||||
2. `tier_limits` für effektiven Tier
|
||||
3. `features.default_limit`
|
||||
|
||||
**Limit-Semantik:**
|
||||
|
||||
| `limit_type` | Bedeutung |
|
||||
|--------------|-----------|
|
||||
| `count` | Zählbares Kontingent; `used < limit` |
|
||||
| `boolean` | An/Aus; `limit == 1` erlaubt, `0` gesperrt |
|
||||
|
||||
| `limit_value` | Bedeutung |
|
||||
|---------------|-----------|
|
||||
| `NULL` | Unbegrenzt |
|
||||
| `0` | Deaktiviert |
|
||||
| `> 0` | Kontingent oder Boolean „an“ |
|
||||
|
||||
### Rollen
|
||||
|
||||
| Rolle | Darf |
|
||||
|-------|------|
|
||||
| **Admin** | Features/Tiers/Limits/Coupons/Restrictions CRUD; alle Nutzer-Overrides |
|
||||
| **Nutzer** | Eigene Subscription/Usage lesen (`/subscription/me`, `/features/usage`); keine Limit-Änderung |
|
||||
|
||||
Enforcement gilt für alle authentifizierten Nutzer gleich — Admins haben keine automatische Bypass-Logik in `check_feature_access`.
|
||||
|
||||
### Versionierung, Freigabe, Test
|
||||
|
||||
| Mechanismus | Status |
|
||||
|-------------|--------|
|
||||
| 4-Phasen-Rollout (Monitor → UI → Enforce) | ✅ dokumentiert & angewendet |
|
||||
| JSON-Log `feature-usage.log` | ✅ Phase 2 Monitoring |
|
||||
| DB-Migration v9c für Schema | ✅ |
|
||||
| Automatisierte Enforcement-Tests pro Router | ⚠️ teilweise (Widgets getestet) |
|
||||
| Zentrale Policy „jeder Endpoint muss checken“ | ❌ nicht erzwungen |
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. Feature-Registry statt hardcodierter Limits
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jedes limitierbare Produkt-Feature ist Zeile in `features` — neue Features ohne Schema-Migration für Limits. |
|
||||
| **Begründung** | Admin-UI, Usage-API und Backend-Checks teilen dieselbe ID und Metadaten. |
|
||||
| **Quelle** | `MEMBERSHIP_SYSTEM.md` § Feature-Registry; `routers/features.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Feature-IDs müssen trotzdem in Router-Code referenziert werden. |
|
||||
|
||||
### 2. Eine Auflösungsfunktion für Entitlements
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Alle Backend- und Widget-Checks rufen `check_feature_access(profile_id, feature_id)` auf. |
|
||||
| **Begründung** | Keine duplizierte Tier/Limit-Logik in Routern, Widgets oder Frontend. |
|
||||
| **Quelle** | `auth.py`; `dashboard_widget_entitlements.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht alle Endpoints nutzen es (z. B. `/prompts/execute` fehlt). |
|
||||
|
||||
### 3. Getrennte Tier- und Feature-Auflösung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `get_effective_tier()` für Tarif; `check_feature_access()` für konkretes Feature — Tier ist Input, nicht Output der Feature-Prüfung. |
|
||||
| **Begründung** | Temporäre Grants heben Tier an; User-Override kann einzelnes Feature unabhängig anpassen. |
|
||||
| **Quelle** | `auth.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `get_effective_tier` im Code einfacher als in `MEMBERSHIP_SYSTEM.md` (kein `tier_locked`, Trial nicht in Tier-Funktion). |
|
||||
|
||||
### 4. Prioritäts-Kette für Limits
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | User-Override > Tier-Limit > Feature-Default — explizit und dokumentiert. |
|
||||
| **Begründung** | Support/Beta-Fälle ohne Tier-Wechsel; vorhersehbares Verhalten. |
|
||||
| **Quelle** | `_check_impl()` in `auth.py`; `MEMBERSHIP_SYSTEM.md` § Zugriffs-Hierarchie |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `user_feature_restrictions.enabled` im Schema, aber nicht in `_check_impl` ausgewertet. |
|
||||
|
||||
### 5. Count vs. Boolean als zwei Feature-Klassen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Zählbare Aktionen (`count` + Usage) vs. Schalter-Features (`boolean`, kein Counter). |
|
||||
| **Begründung** | Pipeline-An/Aus vs. monatliche KI-Calls — unterschiedliche UX und Backend-Logik. |
|
||||
| **Quelle** | `features.limit_type`; `FEATURE_ENFORCEMENT.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Boolean-Features nutzen `limit_value` 0/1 — leicht mit Count zu verwechseln. |
|
||||
|
||||
### 6. Reset-Perioden für Count-Features
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `reset_period`: `never` \| `daily` \| `monthly` — Counter-Reset in `check_feature_access` bei abgelaufenem `reset_at`. |
|
||||
| **Begründung** | Monats-Kontingente vs. Lifetime-Limits in einem Modell. |
|
||||
| **Quelle** | `auth.py` → `_calculate_next_reset()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Reset beim Check, nicht per Cron — Edge Cases bei seltenem Zugriff. |
|
||||
|
||||
### 7. Usage nur bei neuen Entitäten incrementieren
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `increment_feature_usage()` nur nach **INSERT**, nicht nach UPDATE/Upsert-Deduplikat. |
|
||||
| **Begründung** | Limits messen „neue Nutzung“, nicht Bearbeitung bestehender Daten. |
|
||||
| **Quelle** | `FEATURE_ENFORCEMENT.md` § Wichtige Regeln |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Bulk-Import muss explizit zählen; Fehler anfällig. |
|
||||
|
||||
### 8. Vier-Phasen-Rollout (Observe before Enforce)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Phase 1 Cleanup → 2 Logging → 3 Frontend-Badges → 4 HTTP 403. |
|
||||
| **Begründung** | Limits einführen ohne blind Nutzer zu blockieren; Daten für Limit-Kalibrierung. |
|
||||
| **Quelle** | `FEATURE_ENFORCEMENT.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Disziplin pro Feature; kein zentraler Feature-Flag pro Endpoint-Phase. |
|
||||
|
||||
### 9. Strukturiertes Feature-Logging
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jeder Check: `log_feature_usage(profile_id, feature_id, access, action)` → JSON in `feature-usage.log`. |
|
||||
| **Begründung** | Audit, Debugging, Kalibrierung — auch wenn noch nicht enforced. |
|
||||
| **Quelle** | `feature_logger.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Log-Pfad `/app/logs` container-spezifisch. |
|
||||
|
||||
### 10. Defense in Depth: API 403 + Frontend-Gate
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Backend blockiert autoritativ; Frontend zeigt `UsageBadge`, deaktiviert Buttons, Tooltip bei Limit. |
|
||||
| **Begründung** | UX (frühes Feedback) + Sicherheit (API nicht umgehbar via curl). |
|
||||
| **Quelle** | `FEATURE_ENFORCEMENT.md`; `UsageBadge.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Frontend-Gate optional pro Seite; nicht generisch erzwungen. |
|
||||
|
||||
### 11. Nutzer-Usage-API ohne Code-Änderung bei neuen Features
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `GET /features/usage` iteriert alle aktiven `features` und ruft `check_feature_access` pro Zeile. |
|
||||
| **Begründung** | Neues DB-Feature erscheint automatisch in Quota-Übersicht. |
|
||||
| **Quelle** | `routers/features.py` → `get_feature_usage()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Frontend muss Feature-ID kennen, um Badge zu binden. |
|
||||
|
||||
### 12. Access Grants für temporäre Tier-Elevation
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Coupons/Admin erzeugen `access_grants`; effektiver Tier steigt zeitlich begrenzt. |
|
||||
| **Begründung** | Promotions, Partner (Wellpass), Trials ohne permanente Tier-Änderung. |
|
||||
| **Quelle** | `access_grants`; `routers/coupons.py` (Pause/Resume) |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Coupon-Stacking-Logik komplex; dokumentiert vs. Code prüfen bei Neuentwicklung. |
|
||||
|
||||
### 13. Entitlements als Querschnitt für UI-Module (Widgets)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Dashboard-Widgets mappen auf `features.id`; Katalog liefert `allowed` pro Profil. |
|
||||
| **Begründung** | Tier-Logik nicht in React-Widgets duplizieren (`DASHBOARD_WIDGETS_AGENT_GUIDE` §0). |
|
||||
| **Quelle** | `dashboard_widget_entitlements.py`; `ARCHITECTURE.md` §9 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Widget-Sichtbarkeit ≠ API-Schutz — Chart-Endpoints brauchen eigenes Gating (A4). |
|
||||
|
||||
### 14. Admin-konfigurierbare Tier × Feature Matrix
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `tier_limits` trennt Tier-Definition von Limits; Tiers ohne hardcodierte Spalten pro Feature. |
|
||||
| **Begründung** | Neue Tiers/Preise ohne Code-Deploy der Limit-Logik. |
|
||||
| **Quelle** | `MEMBERSHIP_SYSTEM.md` § Tier-System; `tier_limits` Tabelle |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Tier-Namen in Seed-Daten (`free`, `premium`, …) — erweiterbar, aber Konvention. |
|
||||
|
||||
### 15. NULL = unlimited, 0 = disabled
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Einheitliche Semantik für Limit-Werte in allen Schichten. |
|
||||
| **Begründung** | Vermeidet Sonderfälle „-1 means unlimited“; klare Admin-UI. |
|
||||
| **Quelle** | `_check_impl()` in `auth.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | SQL NULL vs. Python None — konsistent, aber in UI erklärungsbedürftig. |
|
||||
|
||||
---
|
||||
|
||||
## Registrierte Features (Referenz)
|
||||
|
||||
| Feature ID | Typ | Reset | Typische Aktion |
|
||||
|------------|-----|-------|-----------------|
|
||||
| `weight_entries` | count | never | Gewicht anlegen |
|
||||
| `circumference_entries` | count | never | Umfang anlegen |
|
||||
| `caliper_entries` | count | never | Caliper anlegen |
|
||||
| `activity_entries` | count | monthly | Training anlegen/import |
|
||||
| `nutrition_entries` | count | monthly | Ernährung anlegen/import |
|
||||
| `photos` | count | monthly | Foto hochladen |
|
||||
| `ai_calls` | count | monthly | KI-Analyse |
|
||||
| `ai_pipeline` | boolean | — | Pipeline-Analyse |
|
||||
| `data_export` | count | monthly | Export/PDF |
|
||||
| `data_import` | count | monthly | ZIP/Universal-Import |
|
||||
|
||||
**Enforcement-Lücken (Ist):** `routers/prompts.py` (`/execute`, `/execute-stream`) ohne `check_feature_access` — Legacy `insights.py` hat Enforcement für `ai_calls`/`ai_pipeline`.
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
1. **Dokumentations-Drift** — `MEMBERSHIP_SYSTEM.md` („Enforcement deaktiviert“) vs. `FEATURE_ENFORCEMENT.md` (Phase 4 komplett) vs. Ist-Code; bei Neuentwicklung einen Kanon festlegen.
|
||||
|
||||
2. **Unvollständige Tier-Auflösung** — Doku beschreibt `tier_locked`, Trial-in-Tier; Code nutzt primär Grants + `profiles.tier`. Trial (`trial_ends_at`) eher UI-Banner als Tier-Engine.
|
||||
|
||||
3. **Feature-IDs in Routern verstreut** — kein zentraler Endpoint-Registry-Eintrag „welcher Router prüft welches Feature“.
|
||||
|
||||
4. **Check und Increment nicht atomar** — Race bei parallelen Requests möglich; kein DB-Level Locking.
|
||||
|
||||
5. **Legacy Profil-Spalten parallel** — `ai_enabled`, `ai_limit_day`, `export_enabled` in Sessions-Query neben Feature-System.
|
||||
|
||||
6. **Frontend ohne Backend-Gate** — reine UI-Deaktivierung ohne 403 ist unsicher (manche Seiten nur teilweise umgesetzt).
|
||||
|
||||
7. **Boolean via limit_value 0/1** — funktioniert, aber für Familien-Architektur explizites `enabled`-Flag oder Capability-Tokens erwägen.
|
||||
|
||||
8. **Unused Schema-Felder** — `user_feature_restrictions.enabled` nicht in Auflösung eingebunden.
|
||||
|
||||
9. **App-lokales Abo ohne Zahlungsanbindung** — Stripe/SSO nur Vision (`CENTRAL_SUBSCRIPTION_SYSTEM.md`); nicht als fertiges Familien-Muster übernehmen.
|
||||
|
||||
10. **Profile als Entitlement-Subject** — kein Org/Mandant; Multi-App-Familie braucht separates Identity/Subscription-Boundary.
|
||||
|
||||
11. **Self-hosted Tier als Sonderfall** — `selfhosted` ist Deploy-Modell, kein generisches SaaS-Tier-Muster.
|
||||
|
||||
12. **Increment-Schleifen bei Bulk** — `for _ in range(new_entries): increment_feature_usage()` — ineffizient; batch-Inkrement besser.
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Ist-Stand)
|
||||
|
||||
```
|
||||
backend/
|
||||
├── auth.py # get_effective_tier, check_feature_access, increment_feature_usage
|
||||
├── feature_logger.py # JSON-Logging
|
||||
├── dashboard_widget_entitlements.py # Widget allowed + Layout-Sanitisierung
|
||||
├── widget_feature_requirements_db.py
|
||||
└── routers/
|
||||
├── subscription.py # /me, /usage, /limits (Nutzer)
|
||||
├── features.py # Admin CRUD + /usage, /check-access
|
||||
├── tiers_mgmt.py, tier_limits.py
|
||||
├── coupons.py, access_grants.py
|
||||
└── user_restrictions.py
|
||||
|
||||
frontend/src/components/
|
||||
└── UsageBadge.jsx # Quota-Anzeige (Phase 3)
|
||||
```
|
||||
|
||||
**DB (v9c):** `features`, `tiers`, `tier_limits`, `user_feature_restrictions`, `user_feature_usage`, `coupons`, `coupon_redemptions`, `access_grants`, `user_activity_log`
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Membership-Detail: [MEMBERSHIP_SYSTEM.md](../../technical/MEMBERSHIP_SYSTEM.md)
|
||||
- Enforcement-Howto: [FEATURE_ENFORCEMENT.md](../../architecture/FEATURE_ENFORCEMENT.md)
|
||||
- Vision Produktfamilie: [CENTRAL_SUBSCRIPTION_SYSTEM.md](../../technical/CENTRAL_SUBSCRIPTION_SYSTEM.md)
|
||||
- Widget-Gating: [DASHBOARD_WIDGETS_AGENT_GUIDE.md](../../technical/DASHBOARD_WIDGETS_AGENT_GUIDE.md) §0
|
||||
- Prompt Engine (Enforcement-Lücke): [PROMPT_ENGINE_DESIGN_PRINCIPLES.md](./PROMPT_ENGINE_DESIGN_PRINCIPLES.md)
|
||||
|
||||
---
|
||||
|
||||
## Geplante Folgedokumente (Serie)
|
||||
|
||||
| # | Modul | Status |
|
||||
|---|-------|--------|
|
||||
| 1 | Prompt Engine | ✅ |
|
||||
| 2 | Data Layer | ✅ |
|
||||
| 3 | Feature & Entitlement | ✅ dieses Dokument |
|
||||
| 4 | Registry-/Plugin-Muster | ✅ |
|
||||
| 5 | Auth & Session | ✅ |
|
||||
| 6 | Universal Import | ✅ |
|
||||
| 7 | Dashboard Widgets | ✅ |
|
||||
| 8 | Navigation / IA | ✅ |
|
||||
| 9 | Migration & Deploy | ✅ `MIGRATION_DEPLOY_DESIGN_PRINCIPLES.md` |
|
||||
@@ -0,0 +1,369 @@
|
||||
# Migration & Deploy – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** DB-Migrationen, Container-Startup, CI/CD-Deploy — keine Anwendungsdomäne
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 9 von n (Abschluss)
|
||||
**Vorgänger:** [NAVIGATION_IA_DESIGN_PRINCIPLES.md](./NAVIGATION_IA_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| DB-Init & Migrationen | `backend/db_init.py`, `backend/startup.sh` |
|
||||
| Migrationen | `backend/migrations/XXX_*.sql` |
|
||||
| Basis-Schema (Greenfield) | `backend/schema.sql` |
|
||||
| Tracking | Tabelle `schema_migrations` |
|
||||
| Compose Prod/Dev | `docker-compose.yml`, `docker-compose.dev-env.yml` |
|
||||
| CI/CD | `.gitea/workflows/deploy-dev.yml`, `deploy-prod.yml`, `test.yml` |
|
||||
| Versionierung | `backend/version.py` (`APP_VERSION`, `DB_SCHEMA_VERSION`, `MODULE_VERSIONS`) |
|
||||
| Doku (operativ) | `MIGRATIONS.md` |
|
||||
| Architektur-Regeln | `.claude/rules/ARCHITECTURE.md` §2, §7 |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Migration & Deploy**
|
||||
|
||||
Automatische **PostgreSQL-Schema-Evolution** beim Container-Start plus **Git-getriebene Deploy-Pipeline** (develop → Dev, main → Prod) auf selbst-gehosteter Infrastruktur (Docker auf Raspberry Pi).
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Das Modul übernimmt:
|
||||
|
||||
1. **Schema-Migrationen** — Nummerierte SQL-Dateien, idempotent wo möglich, getrackt in `schema_migrations`.
|
||||
2. **Startup-Orchestrierung** — Postgres ready → Schema/Migrationen → optional SQLite-Import → Uvicorn.
|
||||
3. **Umgebungstrennung** — Dev (`3099`/`8099`) vs. Prod (`3002`/`8002`), getrennte DBs/Volumes.
|
||||
4. **Deploy-Automatisierung** — Push auf Branch → Runner → `git reset --hard` → `docker compose build --no-cache` → Health-Check.
|
||||
5. **Post-Deploy-Tests** — Pytest/Lint/Frontend-Build gegen **deployed** Container auf dem Runner.
|
||||
6. **Versions-Metadaten** — App-/Modul-Version und dokumentierte `DB_SCHEMA_VERSION`.
|
||||
|
||||
Es übernimmt **nicht**:
|
||||
|
||||
- Fachliche Datenberechnungen (→ Data Layer)
|
||||
- Automatisches Downgrade/Rollback von Schema
|
||||
- Blue-Green oder Multi-Region-Deploy
|
||||
|
||||
### Deploy-Pipeline (Happy Path)
|
||||
|
||||
```
|
||||
Entwickler: commit → push develop
|
||||
→ Gitea Runner: deploy-dev.yml
|
||||
→ cd /home/lars/docker/bodytrack-dev
|
||||
→ git fetch + reset --hard origin/develop
|
||||
→ docker compose -f docker-compose.dev-env.yml build --no-cache && up -d
|
||||
→ backend startup.sh → db_init.py (Migrationen)
|
||||
→ curl localhost:8099/api/auth/status
|
||||
→ test.yml (push + nach Deploy): pytest im Container, py_compile, npm run build
|
||||
|
||||
Prod: PR develop → main → deploy-prod.yml (Port 8002, bodytrack/)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Administrierte vs. code-definierte Konfiguration
|
||||
|
||||
| Konfiguration | Speicherort | Wer pflegt? |
|
||||
|---------------|-------------|-------------|
|
||||
| Migration-SQL | `backend/migrations/` | Entwickler |
|
||||
| Welche Migrationen angewendet | `schema_migrations` (DB) | Automatisch |
|
||||
| Greenfield-Basis | `schema.sql` | Entwickler (selten) |
|
||||
| Compose/Ports/Env | `docker-compose*.yml`, `.env` auf Server | Betrieb |
|
||||
| Deploy-Workflow | `.gitea/workflows/*.yml` | Entwickler |
|
||||
| App-Version / Changelog | `backend/version.py` | Entwickler (pro Release) |
|
||||
| Prod-Geheimnisse | Server-`.env`, nicht im Repo | Betrieb |
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. Migrationen beim Container-Start ( nicht manuell in Prod)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `startup.sh` ruft `db_init.py` auf **bevor** Uvicorn startet; pending Migrationen werden automatisch angewendet. |
|
||||
| **Begründung** | Kein vergessenes Schema-Update; Deploy und DB-Stand bleiben gekoppelt. |
|
||||
| **Quelle** | `startup.sh`, `db_init.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Fehlgeschlagene Migration blockiert API-Start (`sys.exit(1)`). |
|
||||
|
||||
### 2. Nummeriertes Datei-Pattern als Gate
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Nur `\d{3}_*.sql` wird ausgeführt (z. B. `054_activity_session_metrics_eav.sql`); alles andere wird ignoriert. |
|
||||
| **Begründung** | Sortierbare Reihenfolge; Ad-hoc-Skripte (`check_features.sql`, `v9c_*.sql`) verunreinigen nicht den Lauf. |
|
||||
| **Quelle** | `run_migrations()` Regex |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy-Dateien ohne Nummer liegen noch im Ordner (historischer Ballast). |
|
||||
|
||||
### 3. Tracking-Tabelle als Single Source of „applied“
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `schema_migrations(filename)` — jede erfolgreiche Datei genau einmal eingetragen; Pending = Dateien minus Applied. |
|
||||
| **Begründung** | Idempotenter Startup; wiederholter Container-Start wendet nichts doppelt an. |
|
||||
| **Quelle** | `ensure_migration_table`, `apply_migration` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Kein checksum — geänderte Datei nach Apply wird nicht erneut ausgeführt. |
|
||||
|
||||
### 4. Alphabetische Reihenfolge = Migrations-Reihenfolge
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `sorted(glob)` — dreistellige Präfixe (`001`, `054`, `061`) definieren die Apply-Order. |
|
||||
| **Begründung** | Einfach, git-freundlich, keine separate Migrations-Registry. |
|
||||
| **Quelle** | `run_migrations()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nummern-Kollisionen oder nachträgliches Einfügen erfordern Disziplin (immer nächste freie Nummer). |
|
||||
|
||||
### 5. Fail-Fast bei Migrationsfehler
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Schlägt eine Migration fehl → kein Commit in Tracking (bei Exception vor INSERT), Prozess exit 1, Container unhealthy. |
|
||||
| **Begründung** | API läuft nicht mit halb angewendetem Schema. |
|
||||
| **Quelle** | `apply_migration`, `main` in `db_init.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Manueller Recovery-Prozess nötig (siehe MIGRATIONS.md Rollback). |
|
||||
|
||||
### 6. Greenfield: schema.sql, Bestand: nur Migrationen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Existiert `profiles` nicht → einmalig `schema.sql` laden; danach nur noch nummerierte Migrationen. |
|
||||
| **Begründung** | Frische Instanz schnell bootstrapped; langlebige DBs evolvieren incremental. |
|
||||
| **Quelle** | `check_table_exists`, `load_schema` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `schema.sql` kann hinter Migrationen zurückfallen wenn nicht gepflegt. |
|
||||
|
||||
### 7. Idempotente DDL bevorzugen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, defensive UPDATEs — Migration soll mehrfach ausführbar sein ohne Schaden. |
|
||||
| **Begründung** | Recovery nach partiellem Apply; manuelles Re-Run sicherer. |
|
||||
| **Quelle** | `MIGRATIONS.md` Best Practices |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht alle Änderungen sind idempotent (DROP, irreversible Datenmigration). |
|
||||
|
||||
### 8. Kein psql-Meta in Migrationsdateien
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Nur SQL — kein `\echo`, `\i`, `\connect`; Ausführung via psycopg2, nicht interaktiv. |
|
||||
| **Begründung** | Parser/Runner versteht nur SQL-Statements. |
|
||||
| **Quelle** | `MIGRATIONS.md`, `apply_migration` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | — |
|
||||
|
||||
### 9. Schema-Änderung = nummerierte Migration (nie ad-hoc in Prod)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Neue Tabellen/Spalten **nur** via `backend/migrations/XXX_*.sql`; nicht direkt in laufender Prod-DB editieren. |
|
||||
| **Begründung** | Reproduzierbarkeit Dev→Prod; Review im Git-Diff. |
|
||||
| **Quelle** | ARCHITECTURE.md, CLAUDE.md |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Agent-Regel — technisch nicht erzwungen. |
|
||||
|
||||
### 10. DB_SCHEMA_VERSION als dokumentierter Marker
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `backend/version.py` → `DB_SCHEMA_VERSION` bei Schema-Änderung manuell bumpen (Format z. B. `YYYYMMDD` + Suffix). |
|
||||
| **Begründung** | API `/api/version` und Changelog zeigen Schema-Stand unabhängig von App-Minor. |
|
||||
| **Quelle** | ARCHITECTURE.md §2.6 |
|
||||
| **Tragfähigkeit** | **mittel–hoch** |
|
||||
| **Einschränkung** | Nicht automatisch aus `schema_migrations` abgeleitet — Drift möglich. |
|
||||
|
||||
### 11. Branch → Umgebung (develop / main)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `develop` → Dev-Deploy automatisch; `main` → Prod-Deploy automatisch; Prod nur nach expliziter Freigabe/Merge. |
|
||||
| **Begründung** | Klare Promotion; Dev als Integrationsumgebung. |
|
||||
| **Quelle** | Workflows, CLAUDE.md Deployment |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Kein Staging-Branch zwischen Dev und Prod. |
|
||||
|
||||
### 12. Deploy-Arbeitskopie = exakt Remote-Branch
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Runner: `git fetch` + `git reset --hard origin/<branch>` — keine `pull`-Merge-Konflikte, kein schmutziger `package-lock` auf dem Pi. |
|
||||
| **Begründung** | Reproduzierbarer Deploy-Baum; Fix aus GUI-IA-Abnahme 2026-04-05. |
|
||||
| **Quelle** | `deploy-prod.yml`, `deploy-dev.yml` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Lokale Hotfixes auf dem Server werden beim Deploy überschrieben. |
|
||||
|
||||
### 13. Immutabler Build pro Deploy (`--no-cache`)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `docker compose build --no-cache` bei jedem Deploy — frisches Image aus Dockerfile + Repo-Stand. |
|
||||
| **Begründung** | Keine veralteten Layer; Migrationen und Code garantiert im Image. |
|
||||
| **Quelle** | Deploy-Workflows |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Langsamere Deploys; kein Registry-basiertes Image-Promotion. |
|
||||
|
||||
### 14. Health-Check nach Deploy
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Nach `up -d`: kurz warten, dann `curl -sf …/api/auth/status` (8099 Dev / 8002 Prod). |
|
||||
| **Begründung** | Minimale Smoke-Verification dass API antwortet (inkl. DB-Init durchlaufen). |
|
||||
| **Quelle** | Deploy-Workflows |
|
||||
| **Tragfähigkeit** | **mittel–hoch** |
|
||||
| **Einschränkung** | Prüft nicht fachliche Endpoints oder Migration-Inhalt. |
|
||||
|
||||
### 15. Persistente Volumes für Daten und Fotos
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Postgres-Daten, `/app/data`, `/app/photos` in benannten/external Volumes — überleben Container-Rebuild. |
|
||||
| **Begründung** | Deploy = neues Image, nicht Datenverlust. |
|
||||
| **Quelle** | `docker-compose*.yml` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Volume-Backup/Restore ist Betriebsaufgabe außerhalb Repo. |
|
||||
|
||||
### 16. Postgres Healthcheck vor Backend-Start
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `depends_on: condition: service_healthy` — Backend startet erst wenn DB `pg_isready`. |
|
||||
| **Begründung** | `wait_for_postgres` in db_init ist zweite Absicherung; reduziert Race beim ersten Start. |
|
||||
| **Quelle** | Compose-Files |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | — |
|
||||
|
||||
### 17. Tests gegen deployed Stack (Self-Hosted Runner)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `test.yml` führt pytest **im laufenden Backend-Container** auf dem Pi aus, nicht in isolierter GitHub-Cloud. |
|
||||
| **Begründung** | Tests laufen gegen echte Dev/Prod-Compose-Umgebung des Projekts. |
|
||||
| **Quelle** | `.gitea/workflows/test.yml` |
|
||||
| **Tragfähigkeit** | **mittel** |
|
||||
| **Einschränkung** | Prod-Deploy triggert Tests auf Prod-Pfad — Risiko wenn Tests schreibend; `-m 'not slow'` begrenzt Laufzeit. |
|
||||
|
||||
### 18. Feste Ports pro Umgebung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Dev `3099/8099`, Prod `3002/8002` — nicht ändern (Reverse Proxy/Fritz!Box hängen daran). |
|
||||
| **Begründung** | Externe URLs (`dev.mitai.jinkendo.de`, `mitai.jinkendo.de`) stabil. |
|
||||
| **Quelle** | CLAUDE.md, Compose |
|
||||
| **Tragfähigkeit** | **hoch** (betriebsspezifisch) |
|
||||
| **Einschränkung** | Andere Projekte brauchen eigene Port-Matrix. |
|
||||
|
||||
### 19. Prod-Schutz: Deploy nur über Git
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Keine direkten Prod-Container-/DB-Schreibzugriffe für Automation; Prod-Änderung = Merge `main` → Workflow. |
|
||||
| **Begründung** | Audit-Trail, Review, keine Drift. |
|
||||
| **Quelle** | ARCHITECTURE.md §7.1, `/deploy` Command |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Menschlicher SSH-Zugriff bleibt möglich — Prozess, nicht Technik. |
|
||||
|
||||
### 20. Versions-Bump als Release-Disziplin
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jede lieferbare Änderung: `APP_VERSION`, betroffene `MODULE_VERSIONS`, `CHANGELOG` in `version.py`; bei Schema auch `DB_SCHEMA_VERSION`. |
|
||||
| **Begründung** | `/api/version`, Support, Korrelation Deploy ↔ Code. |
|
||||
| **Quelle** | ARCHITECTURE.md §2.5, `deploy.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Frontend-`version.js` in Spec erwähnt, im Repo teils nicht vorhanden — Dual-Bump unvollständig. |
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
1. **Unnummerierte Migrationsdateien** — `v9c_*.sql`, `check_*.sql` werden nicht auto-applied; nicht als Vorbild.
|
||||
|
||||
2. **Migration-Datei nach Apply ändern** — Tracking verhindert Re-Run; neue Nummer statt Edit.
|
||||
|
||||
3. **Automatischer Downgrade** — nicht implementiert; Rollback manuell + Tracking-Eintrag löschen.
|
||||
|
||||
4. **Direktes Schema in Prod** — immer Git-Migration + Deploy.
|
||||
|
||||
5. **Breaking DROP ohne Koordination** — App-Code und Migration in einem Release.
|
||||
|
||||
6. **psql-Metacommands in `.sql`** — bricht Python-Runner.
|
||||
|
||||
7. **`git pull` auf Deploy-Server** — Merge-Schmutz; `reset --hard` ist das Muster.
|
||||
|
||||
8. **Prod-Deploy ohne Dev-Validierung** — develop-First ist implizite Policy.
|
||||
|
||||
9. **Schema-Drift ohne `DB_SCHEMA_VERSION`-Bump** — dokumentarische Lücke.
|
||||
|
||||
10. **Cached Docker-Build als Default** — Mitai wählt Reproduzierbarkeit über Geschwindigkeit.
|
||||
|
||||
11. **Migrationen außerhalb Container-Start vergessen** — manuelles psql in Prod als Normalfall.
|
||||
|
||||
12. **Hardcoded Seed-Daten in Migration** — produktive User/Secrets nicht in SQL.
|
||||
|
||||
13. **Port-Änderung „nebenbei“** — Infrastruktur-Kopplung.
|
||||
|
||||
14. **Tests nur lokal, nie auf Runner-Stack** — Mitai testet bewusst post-deploy im Pi-Container (Trade-off verstehen).
|
||||
|
||||
15. **Transaktionssteuerung in SQL-Datei** — Runner committet pro Datei; komplexe multi-step Rollbacks nicht eingebaut.
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Ist-Stand)
|
||||
|
||||
```
|
||||
backend/
|
||||
├── db_init.py # wait, schema, run_migrations, sqlite import
|
||||
├── startup.sh # db_init → uvicorn
|
||||
├── schema.sql # Greenfield
|
||||
├── migrations/ # 001–061+ nummeriert (+ Legacy ohne Nummer)
|
||||
└── version.py # APP_VERSION, DB_SCHEMA_VERSION, MODULE_VERSIONS
|
||||
|
||||
docker-compose.yml # Prod: 3002/8002
|
||||
docker-compose.dev-env.yml # Dev: 3099/8099
|
||||
|
||||
.gitea/workflows/
|
||||
├── deploy-dev.yml # push develop
|
||||
├── deploy-prod.yml # push main
|
||||
└── test.yml # pytest, lint, npm build on Pi
|
||||
|
||||
Server (Pi):
|
||||
/home/lars/docker/bodytrack-dev/ # develop
|
||||
/home/lars/docker/bodytrack/ # main
|
||||
```
|
||||
|
||||
**Migrationen (Stand):** 60+ nummerierte Dateien (`001` … `061`); höchste Nummer im Repo prüfen vor neuer Migration.
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Operativ: [MIGRATIONS.md](../../technical/MIGRATIONS.md)
|
||||
- Architektur: `.claude/rules/ARCHITECTURE.md` §2 (Versionierung), §7 (Prod-Schutz)
|
||||
- Deploy-Command: `.claude/commands/deploy.md`, `merge-to-prod.md`
|
||||
- Import/Migration-Grenze: [UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md](./UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md)
|
||||
- Auth auf Prod: [AUTH_SESSION_DESIGN_PRINCIPLES.md](./AUTH_SESSION_DESIGN_PRINCIPLES.md)
|
||||
|
||||
---
|
||||
|
||||
## Serie – Übersicht (abgeschlossen)
|
||||
|
||||
| # | Modul | Status |
|
||||
|---|-------|--------|
|
||||
| 1 | Prompt Engine | ✅ `PROMPT_ENGINE_DESIGN_PRINCIPLES.md` |
|
||||
| 2 | Data Layer | ✅ `DATA_LAYER_DESIGN_PRINCIPLES.md` |
|
||||
| 3 | Feature & Entitlement | ✅ `FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md` |
|
||||
| 4 | Registry / Plugin (Meta) | ✅ `REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md` |
|
||||
| 5 | Auth & Session | ✅ `AUTH_SESSION_DESIGN_PRINCIPLES.md` |
|
||||
| 6 | Universal Import | ✅ `UNIVERSAL_IMPORT_DESIGN_PRINCIPLES.md` |
|
||||
| 7 | Dashboard Widgets | ✅ `DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md` |
|
||||
| 8 | Navigation / IA | ✅ `NAVIGATION_IA_DESIGN_PRINCIPLES.md` |
|
||||
| 9 | Migration & Deploy | ✅ dieses Dokument |
|
||||
@@ -0,0 +1,346 @@
|
||||
# Navigation & Informationsarchitektur – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** App-Navigation, Bereichs-Shells, Admin-IA, Responsive Shell — keine Seiteninhalte oder Domänenlogik
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 8 von n
|
||||
**Vorgänger:** [DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md](./DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| Hauptnavigation | `frontend/src/config/appNav.js` |
|
||||
| Erfassung | `frontend/src/config/captureNav.js`, `layouts/CaptureShell.jsx` |
|
||||
| Einstellungen | `frontend/src/config/settingsNav.js`, `layouts/SettingsShell.jsx` |
|
||||
| Admin | `frontend/src/config/adminNav.js`, `layouts/AdminShell.jsx`, `RequireAdmin.jsx` |
|
||||
| KI-Analyse (Kategorien) | `frontend/src/config/analysisCategories.js`, `pages/Analysis.jsx` |
|
||||
| Routing | `frontend/src/App.jsx` |
|
||||
| Desktop-Sidebar | `frontend/src/components/DesktopSidebar.jsx` |
|
||||
| Responsive CSS | `frontend/src/app.css` (`--nav-h`, `.bottom-nav`, `.analysis-split`, `.desktop-sidebar`) |
|
||||
| Abnahme-Doku | `docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md` |
|
||||
| Responsive-Spec | `.claude/docs/functional/RESPONSIVE_UI.md` |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Navigation & Informationsarchitektur (IA)**
|
||||
|
||||
Schichtenmodell für die PWA: **eine primäre Hauptnavigation** (6–7 Bereiche), darunter **Bereichs-Shells** mit eigener Sub-Navigation, getrennte **Admin-Realm**, **Auth-Gates** und **ein Breakpoint** für Mobile vs. Desktop.
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Das Modul übernimmt:
|
||||
|
||||
1. **Hauptnav-SSoT** — Reihenfolge, Labels, Icons, Admin-Sichtbarkeit (`getMainNavItems`).
|
||||
2. **Routing-Struktur** — Welche URL gehört zu welchem Bereich (Übersicht, Erfassen, Verlauf, Ziele, Analyse, Einstellungen, Admin).
|
||||
3. **Sub-Navigation pro Bereich** — Capture-Hub, Settings-Tabs, Admin-Gruppen, Analyse-Kategorien.
|
||||
4. **Layout-Muster** — Bottom-Nav (mobil), Sidebar (Desktop), `analysis-split` für tiefe Bereiche.
|
||||
5. **Zugriffskontrolle (UI)** — `RequireAdmin`, Admin-Link nur bei `role === 'admin'`.
|
||||
6. **Active-State** — Nested Routes (Erfassung unter `/capture`, Admin unter `/admin/*`).
|
||||
7. **PWA-Tauglichkeit** — Safe Area, Scrollbare Bottom-Nav, Content-Padding.
|
||||
|
||||
Es übernimmt **nicht**:
|
||||
|
||||
- Backend-Autorisierung (→ [AUTH_SESSION_DESIGN_PRINCIPLES.md](./AUTH_SESSION_DESIGN_PRINCIPLES.md))
|
||||
- Feature-Entitlements in der Nav (Tier-Gates an Endpoints/Widgets, nicht an jedem NavLink)
|
||||
- Inhaltliche Tab-Logik innerhalb von Verlauf/Analyse (Seiten concern)
|
||||
|
||||
### IA-Modell (Nutzerperspektive)
|
||||
|
||||
| Ebene | Mental Model | Beispiel-Routen |
|
||||
|-------|--------------|-----------------|
|
||||
| **Primär** | Wo bin ich in der App? | `/`, `/capture`, `/history`, `/goals`, `/analysis`, `/settings` |
|
||||
| **Sekundär (Shell)** | Was mache ich in diesem Bereich? | `/weight`, `/admin/g/features`, `/settings/dashboard-layout` |
|
||||
| **Tertiär (Seite)** | Tabs/Filter innerhalb einer Maske | Verlauf-Tabs, Analyse-Kategorien |
|
||||
|
||||
### Strategisch vs. taktisch (Ziele)
|
||||
|
||||
| Ebene | Ort | Zweck |
|
||||
|-------|-----|-------|
|
||||
| **Strategisch** | `/goals` (Hauptnav) | Ziele definieren, Prioritäten, Focus Areas |
|
||||
| **Taktisch** | `/custom-goals` (Erfassung) | Tägliche Ist-Werte für eigene Ziele |
|
||||
| **Auswertung** | `/history` | Trends, Charts, Vergleiche |
|
||||
|
||||
---
|
||||
|
||||
## Administrierte vs. code-definierte Konfiguration
|
||||
|
||||
| Konfiguration | Speicherort | Wer pflegt? |
|
||||
|---------------|-------------|-------------|
|
||||
| Hauptnav-Reihenfolge & Labels | `appNav.js` | Entwickler |
|
||||
| Erfassungs-Kacheln & Shell-Nav | `captureNav.js` | Entwickler |
|
||||
| Admin-Gruppen & Hub-Karten | `adminNav.js` | Entwickler |
|
||||
| Settings-Subnav | `settingsNav.js` | Entwickler |
|
||||
| Analyse-Kategorie-Reihenfolge | `analysisCategories.js` | Entwickler |
|
||||
| KI-Prompt-Kategorien (Runtime) | DB `ai_prompts.category` | Admin (Prompts) |
|
||||
| React-Routes | `App.jsx` | Entwickler (muss zu Nav-Configs passen) |
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. Eine Quelle für die Hauptnavigation
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `getMainNavItems(isAdmin)` liefert dieselbe Item-Liste für **Bottom-Nav** und **Desktop-Sidebar** — keine parallelen Hardcodings. |
|
||||
| **Begründung** | Reihenfolge und Labels bleiben synchron; Admin-Conditional an einer Stelle. |
|
||||
| **Quelle** | `appNav.js`, `App.jsx`, `DesktopSidebar.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Active-State-Logik ist in zwei Dateien dupliziert (`navItemActive` / `sidebarLinkActive`). |
|
||||
|
||||
### 2. Feste primäre IA-Reihenfolge (Produkt-Story)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Übersicht → Erfassen → Verlauf → **Ziele** → Analyse → Einstellungen → [Admin] — spiegelt Nutzerfluss: sehen → eingeben → auswerten → steuern → interpretieren → konfigurieren. |
|
||||
| **Begründung** | Ziele als eigener Hauptpunkt (nicht unter Analyse versteckt); klare Trennung Capture vs. History vs. Analysis. |
|
||||
| **Quelle** | `GUI_IA_ADMIN_NAV_2026-04-05.md`; `appNav.js` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Produkt-spezifisch; andere Apps können andere Reihenfolge brauchen. |
|
||||
|
||||
### 3. Config-Dateien pro Bereich (Nav-as-Data)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Sub-Navigation lebt in dedizierten Config-Modulen (`captureNav`, `adminNav`, `settingsNav`, `analysisCategories`) — Shell-Komponenten iterieren nur. |
|
||||
| **Begründung** | Neue Erfassungsmaske = Eintrag in Config + Route; kein Nav-HTML in jeder Page. |
|
||||
| **Quelle** | `captureNav.js` Kommentar „Pfade müssen mit Routes übereinstimmen“ |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Kein Build-Time-Check Config ↔ Routes. |
|
||||
|
||||
### 4. Bereichs-Shells für tiefe Navigation
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Capture, Settings und Admin nutzen **Shell-Layouts** mit `<Outlet />`; Nutzer wechselt Sub-Bereiche ohne Hauptnav zu verlassen. |
|
||||
| **Begründung** | Erfassung hat 12+ Masken — wären als Hauptnav-Einträge unbrauchbar. |
|
||||
| **Quelle** | `CaptureShell`, `SettingsShell`, `AdminShell` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Verlauf und Analyse haben eigene Tab-Muster (kein gemeinsames Shell-Config). |
|
||||
|
||||
### 5. Wiederverwendbares `analysis-split`-Layout
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Admin, Settings und KI-Analyse teilen CSS-Muster: mobil horizontale Chips, Desktop linke Spalte + `__main` für Inhalt. |
|
||||
| **Begründung** | Ein visuelles Muster für „Kategorie links, Arbeit rechts“; weniger UI-Drift. |
|
||||
| **Quelle** | `AdminShell.jsx`, `SettingsShell.jsx`, `Analysis.jsx`, `app.css` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Capture nutzt eigenes `capture-shell` (Emoji-Icons, Hub-Kacheln). |
|
||||
|
||||
### 6. Admin: Gruppen in der Shell, Seiten über Hub
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Shell-Nav zeigt nur **Admin-Gruppen** (+ Übersicht); konkrete Seiten als Karten auf `/admin/g/:groupId`. |
|
||||
| **Begründung** | Skaliert bei wachsender Admin-Oberfläche; keine 20er-Sidebar. |
|
||||
| **Quelle** | `adminNav.js` (`ADMIN_GROUPS`, `getAdminShellNavEntries`) |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Ein Klick mehr als flache Nav; bewusster Trade-off. |
|
||||
|
||||
### 7. Admin als eigener Realm
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `/admin/*` hinter `RequireAdmin`; kein Admin-Block mehr in Einstellungen; Profil-Anlage nur Admin → Benutzerverwaltung. |
|
||||
| **Begründung** | Trennung Nutzer- vs. Betreiber-Kontext; weniger Verwechslung. |
|
||||
| **Quelle** | `RequireAdmin.jsx`, `GUI_IA_ADMIN_NAV_2026-04-05.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | UI-Guard ersetzt nicht Backend-`require_admin` auf APIs. |
|
||||
|
||||
### 8. Route-Guard mit Nutzer-Feedback
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Nicht-Admin auf `/admin` → Redirect `/` mit `state.adminDenied`; Dashboard zeigt Hinweis. |
|
||||
| **Begründung** | Stilles Scheitern vermeiden; klare Erwartung. |
|
||||
| **Quelle** | `RequireAdmin.jsx`, `Dashboard.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | — |
|
||||
|
||||
### 9. Nested Active-State für Section-Prefixes
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Custom Active-Logik: `/capture` aktiv bei allen Erfassungs-Pfaden; `/admin` bei gesamten Admin-Baum; `/goals` mit `end: true` (exakt). |
|
||||
| **Begründung** | React-Router `end` allein reicht für Section-Gruppen nicht. |
|
||||
| **Quelle** | `navItemActive`, `adminShellEntryIsActive` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Neue Section-Prefixes brauchen explizite Regel. |
|
||||
|
||||
### 10. Erfassungs-Hub + direkte Deep-Links
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `/capture` = Kachel-Hub; jede Maske auch direkt erreichbar (`/weight`, …); Shell-Nav immer sichtbar. |
|
||||
| **Begründung** | Onboarding über Hub; Power-User/Dashboard-Links springen direkt. |
|
||||
| **Quelle** | `CaptureHub`, `CAPTURE_HUB_TILES` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Hub und Shell-Nav listen dieselben Ziele (Doppelpflege). |
|
||||
|
||||
### 11. Einstellungen: nur aktives Profil
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Settings = Self-Service für **aktives** Profil (Name, E-Mail, Avatar, Quality-Filter); keine Profil-Liste für Endnutzer. |
|
||||
| **Begründung** | Multi-Profil-Verwaltung ist Admin-Aufgabe; reduziert Komplexität. |
|
||||
| **Quelle** | `SettingsPage.jsx`, IA-Doku |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Session-bound Profile-Id-Schwäche bleibt Backend-Thema. |
|
||||
|
||||
### 12. Settings-Subnav für Layout & Export
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Konfiguration schwerer Features (Dashboard-Layout, PDF-Berichte, Referenzwerte) als eigene Settings-Routen unter Shell — nicht in „Allgemein“ verstecken. |
|
||||
| **Begründung** | Entspricht [DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md](./DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md) (Nutzer-Konfigurator). |
|
||||
| **Quelle** | `settingsNav.js` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Admin-Dashboard-Default liegt unter `/admin/...` (getrennte Rolle). |
|
||||
|
||||
### 13. KI-Analyse: Ergebnis im Hauptspalt
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Neue Analyse-Ergebnisse rendern in `analysis-split__main`, nicht in der Kategorie-Nav — Nav bleibt wählbar. |
|
||||
| **Begründung** | Lange Ergebnisse verdrängen sonst die Prompt-Auswahl (Mobile). |
|
||||
| **Quelle** | `GUI_IA_ADMIN_NAV_2026-04-05.md`, `Analysis.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | — |
|
||||
|
||||
### 14. Ein Breakpoint Mobile / Desktop (1024px)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `< 1024px`: Bottom-Nav + Mobile-Header; `≥ 1024px`: Desktop-Sidebar, Bottom-Nav ausgeblendet, breiterer Content. **Kein** separates Tablet-Layout. |
|
||||
| **Begründung** | Einfache Spec, PWA-first; iPad im Portrait = Mobile-Verhalten. |
|
||||
| **Quelle** | `RESPONSIVE_UI.md`, `app.css` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Große Phones und kleine Tablets identisch behandelt. |
|
||||
|
||||
### 15. PWA Safe Area für Bottom-Navigation
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `--nav-h`, `--nav-pad-top`, `env(safe-area-inset-bottom)` auf `.bottom-nav`; Content-`padding-bottom` inkl. Nav-Höhe; horizontal scrollbare Nav bei vielen Items. |
|
||||
| **Begründung** | iPhone Home-Indicator und Notch — kein Clipping, kein verdeckter Content. |
|
||||
| **Quelle** | `app.css`, IA-Doku |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Safe Area nur auf Nav/Content-Padding, nicht global überall. |
|
||||
|
||||
### 16. Auth-Routen außerhalb der App-Shell
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Login, Register, Verify, Reset-Password rendern **ohne** Bottom-Nav/Sidebar — minimale Vollbild-Cards. |
|
||||
| **Begründung** | Keine Navigation ohne Session; klarer Fokus. |
|
||||
| **Quelle** | `App.jsx` (early returns vor `AppShell`) |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Public Routes nicht zentral in einer Route-Config. |
|
||||
|
||||
### 17. Rollen-sichtbare Nav-Einträge (UI only)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Admin-Link erscheint nur wenn `isAdmin`; Backend schützt APIs separat. |
|
||||
| **Begründung** | Progressive disclosure; normale Nutzer sehen keinen toten Link. |
|
||||
| **Quelle** | `getMainNavItems(isAdmin)` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Security nicht durch Ausblenden ersetzt. |
|
||||
|
||||
### 18. Deep-Link-State für Verlauf
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Nav zu `/history` setzt optional `state: { tab: 'overview' }` — konsistenter Einstieg von Hauptnav. |
|
||||
| **Begründung** | Verlauf merkt sich Tabs; Hauptnav soll nicht zufälligen alten Tab öffnen. |
|
||||
| **Quelle** | `App.jsx`, `DesktopSidebar.jsx`, `History.jsx` |
|
||||
| **Tragfähigkeit** | **mittel** |
|
||||
| **Einschränkung** | Nur für History implementiert, nicht app-weit. |
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
1. **Hauptnav an mehreren Stellen hardcoden** — immer `appNav.js`.
|
||||
|
||||
2. **Admin-Funktionen in Einstellungen** — eigener `/admin`-Bereich.
|
||||
|
||||
3. **Alle Erfassungsmasken in die Bottom-Nav** — Shell + Hub skaliert.
|
||||
|
||||
4. **Alle Admin-Seiten in der Shell-Sidebar** — Hub-Gruppen-Muster beibehalten.
|
||||
|
||||
5. **Nav-Config ohne Route-Pflege** — jeder neue Pfad: Config + `App.jsx` + ggf. Active-State.
|
||||
|
||||
6. **UI-Admin-Guard ohne Backend-Guard** — `RequireAdmin` ist UX, APIs brauchen `require_admin`.
|
||||
|
||||
7. **Zwei Tablet-/Desktop-Breakpoints** — Mitai: ein Cut bei 1024px.
|
||||
|
||||
8. **Safe Area ignorieren** — PWA auf iOS bricht sonst an Bottom-Nav.
|
||||
|
||||
9. **Profil-Liste für Endnutzer in Settings** — Multi-Profil = Admin.
|
||||
|
||||
10. **Feature-Tier-Logik in Nav-Komponenten** — Entitlements an Widgets/APIs ([FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)).
|
||||
|
||||
11. **Inkonsistente Layout-Muster pro Bereich** — wo `analysis-split` passt, nicht neues Ad-hoc-Layout erfinden.
|
||||
|
||||
12. **Orphan-Routes ohne Nav-Ergänzung** — z. B. `/subscription`, `/workflow-editor/:id` existieren außerhalb Haupt-IA; bewusst dokumentieren, nicht unkontrolliert multiply.
|
||||
|
||||
13. **Active-State nur per Router-Default** — Section-Prefixes (`/capture/*`, `/admin/*`) brauchen explizite Regeln.
|
||||
|
||||
14. **Analyse-Ergebnisse in der Nav-Spalte** — verdrängt Prompt-Auswahl auf Mobile.
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Ist-Stand)
|
||||
|
||||
```
|
||||
frontend/src/config/
|
||||
├── appNav.js # Hauptnav (6 + Admin)
|
||||
├── captureNav.js # Erfassungs-Hub + Shell
|
||||
├── settingsNav.js # Settings-Subnav
|
||||
├── adminNav.js # ADMIN_GROUPS, Shell-Entries
|
||||
└── analysisCategories.js # KI-Analyse-Gruppen
|
||||
|
||||
frontend/src/layouts/
|
||||
├── CaptureShell.jsx
|
||||
├── SettingsShell.jsx
|
||||
├── AdminShell.jsx
|
||||
└── RequireAdmin.jsx
|
||||
|
||||
frontend/src/components/
|
||||
└── DesktopSidebar.jsx
|
||||
|
||||
frontend/src/App.jsx # Routes + Bottom-Nav + Auth-Gates
|
||||
frontend/src/app.css # Shell, split, safe-area, 1024px breakpoint
|
||||
```
|
||||
|
||||
**Hauptnav (7 Einträge mit Admin):** Übersicht · Erfassen · Verlauf · Ziele · Analyse · Einstellungen · Admin
|
||||
|
||||
**Admin-Gruppen (8):** users · features · subscription · training · goals · prompts · system
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Abnahme-Stand: [GUI_IA_ADMIN_NAV_2026-04-05.md](../../../../docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md)
|
||||
- Responsive-Spec: [RESPONSIVE_UI.md](../../functional/RESPONSIVE_UI.md)
|
||||
- Auth/Session: [AUTH_SESSION_DESIGN_PRINCIPLES.md](./AUTH_SESSION_DESIGN_PRINCIPLES.md)
|
||||
- Dashboard-Konfigurator: [DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md](./DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md)
|
||||
- Gitea #30 (Responsive UI, teilweise erledigt)
|
||||
|
||||
---
|
||||
|
||||
## Geplante Folgedokumente (Serie)
|
||||
|
||||
| # | Modul | Status |
|
||||
|---|-------|--------|
|
||||
| 1–7 | … | ✅ |
|
||||
| 8 | Navigation / IA | ✅ dieses Dokument |
|
||||
| 9 | Migration & Deploy | ✅ |
|
||||
@@ -0,0 +1,305 @@
|
||||
# Prompt Engine – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** Modul „Prompt Engine“ (Unified Prompt System, Issue #28) — keine Mitai-Gesamtarchitektur, keine Domänenlogik (Gesundheit, Ernährung, Messwerte)
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 1 von n
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| Executor | `backend/prompt_executor.py`, `backend/workflow_executor.py` |
|
||||
| Platzhalter | `backend/placeholder_resolver.py`, `backend/placeholder_registry.py`, `backend/placeholder_registrations/` |
|
||||
| API | `backend/routers/prompts.py`, `backend/routers/workflows.py` |
|
||||
| Admin-UI | `frontend/src/pages/AdminPromptsPage.jsx`, `UnifiedPromptModal.jsx`, `WorkflowEditorPage.jsx` |
|
||||
| Fachliche Spec | `.claude/docs/functional/AI_PROMPTS.md` |
|
||||
| Platzhalter-Governance | `.claude/docs/technical/PLACEHOLDER_REGISTRY_FRAMEWORK.md`, `docs/PLACEHOLDER_GOVERNANCE.md` |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Prompt Engine** (Unified Prompt System, Issue #28)
|
||||
|
||||
Backend-Kern: `prompt_executor.py`, `placeholder_resolver.py`, `placeholder_registry` / `placeholder_registrations/`, `workflow_executor.py`
|
||||
API: `routers/prompts.py`
|
||||
Admin-UI: `AdminPromptsPage`, `UnifiedPromptModal`, `WorkflowEditorPage`
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Die Prompt Engine ist die **zentrale Ausführungs- und Konfigurationsschicht für KI-Analysen**. Sie übernimmt:
|
||||
|
||||
1. **Prompt-Orchestrierung** — Laden aktiver Prompt-Definitionen aus der DB und Ausführung als `base` (Einzelprompt), `pipeline` (mehrstufig) oder `workflow` (Graph).
|
||||
2. **Kontextaufbereitung** — Befüllen von Platzhaltern mit profilbezogenen Daten (Resolver → Data Layer).
|
||||
3. **LLM-Aufruf** — Einheitlicher OpenRouter-Call über injizierte Callback-Funktion.
|
||||
4. **Ergebnisbehandlung** — JSON-Validierung, strukturierte Container (Fragenergänzungen), Debug-Metadaten, optionales Speichern in `ai_insights`.
|
||||
5. **Admin-Konfiguration** — CRUD für Prompts/Workflows, Import/Export, Vorschau und Test ohne Produktions-Ausführung.
|
||||
|
||||
### Administrierte Konfigurationen
|
||||
|
||||
| Konfiguration | Speicherort | Inhalt |
|
||||
|---------------|-------------|--------|
|
||||
| Prompt-Metadaten | `ai_prompts` | `name`, `slug`, `category`, `active`, `sort_order`, `display_name` |
|
||||
| Templates | `ai_prompts` | `template` |
|
||||
| Pipeline-Stages | `ai_prompts.stages` (JSONB) | Stages mit `inline` / `reference` |
|
||||
| Workflow-Graphen | `ai_prompts.graph_data` | Knoten, Kanten, Metadaten |
|
||||
| Output-Regeln | `ai_prompts` | `output_format`, `output_schema` |
|
||||
| Fragenergänzungen | `ai_prompts.question_augmentations` | Optionale Standard-Fragen (Hybridmodell: Knoten > Prompt) |
|
||||
| System-Reset | `ai_prompts` | `is_system_default`, `default_template` |
|
||||
| Legacy-Pipeline-Configs | `pipeline_configs` | Module, Zeiträume, Stage-Slugs (parallel zum Unified System) |
|
||||
| Workflow-Fragenkatalog | `workflow_question_catalog` | Fragetypen, Templates, Normalisierung |
|
||||
|
||||
### Bewusst nicht hardcodiert
|
||||
|
||||
- Prompt-Texte, Pipeline-Zusammensetzung, Workflow-Topologie
|
||||
- Kategorie, Sichtbarkeit (`active`), Sortierung
|
||||
- Output-Format und Schema pro Prompt
|
||||
- Referenz vs. Inline in Pipeline-Stages
|
||||
|
||||
### Hardcodiert (Code / Env)
|
||||
|
||||
- Platzhalter-Definitionen und Resolver (`PLACEHOLDER_MAP`, Registry)
|
||||
- LLM-Modell (`OPENROUTER_MODEL`)
|
||||
- Default-Module und -Zeiträume in `/prompts/execute`
|
||||
- Domänen-Kategorien im Frontend (`analysisCategories.js`)
|
||||
- Meta-Prompts für Generate/Optimize (Admin-Tooling)
|
||||
|
||||
### Trennung: Template · Platzhalter · Kontext · Workflow
|
||||
|
||||
| Schicht | Ort | Rolle |
|
||||
|---------|-----|-------|
|
||||
| **Templates** | `ai_prompts.template`, `stages`, Knoten-Templates im Graph | Was an die KI geht |
|
||||
| **Platzhalter** | `placeholder_resolver` + Registry | Semantische API-Keys `{{key}}`, Resolver-Funktionen |
|
||||
| **Kontextdaten** | `execute_prompt_with_data` + Resolver → `data_layer/` | Werte für Platzhalter |
|
||||
| **Workflows** | `graph_data` + `workflow_executor` | Ausführungsgraph, Verzweigung, Join, Aggregation |
|
||||
|
||||
### Durchsetzung: keine Sonderlogik außerhalb der Engine
|
||||
|
||||
**Konzeptionell:** Ein Executor (`execute_prompt` → `execute_prompt_with_data`) als Single Entry Point.
|
||||
|
||||
**Praktisch unvollständig:** Legacy-Pfade in `insights.py` (`/insights/run`, `/insights/pipeline`) mit eigener Template-Logik (`_prepare_template_vars`, `_render_template`) und direkten LLM-Calls; `History.jsx` nutzt noch `runInsight`. Kein technischer Guard (Lint/Policy), nur Konvention.
|
||||
|
||||
### Rollen und Berechtigungen
|
||||
|
||||
| Rolle | Darf |
|
||||
|-------|------|
|
||||
| **Admin** (`require_admin`) | Prompts/Workflows/Pipeline-Configs CRUD, Import/Export, Reset-to-default, Generate/Optimize, Platzhalter-Metadaten-ZIP |
|
||||
| **Nutzer** (`require_auth`) | Aktive Prompts listen (ohne Pipeline-Slugs), ausführen (`/prompts/execute`), Preview, Platzhalter-Katalog, eigene Werte exportieren |
|
||||
|
||||
Workflow-Editor-Route (`/workflow-editor/:id`) ist nicht hinter `RequireAdmin`; Schreib-APIs sind admin-geschützt.
|
||||
|
||||
### Versionierung, Freigabe, Test
|
||||
|
||||
| Mechanismus | Status |
|
||||
|-------------|--------|
|
||||
| Prompt-Versionsverlauf in DB | ❌ Overwrite |
|
||||
| Reset-to-default für System-Prompts | ✅ `is_system_default` + `default_template` |
|
||||
| JSON Import/Export (Dev→Prod) | ✅ `/export-all`, `/import` |
|
||||
| Admin-Test mit Debug | ✅ `debug=true`, UnifiedPromptModal |
|
||||
| Preview ohne LLM | ✅ `POST /preview` |
|
||||
| Platzhalter-Deprecation-Prozess | 📄 dokumentiert, nicht runtime-erzwungen |
|
||||
| Formales Freigabe-Workflow | ❌ |
|
||||
| Executor-E2E-Tests | ⚠️ punktuell (Modifier, Output-Compact) |
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. Single Executor für Prompt-Ausführung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Alle KI-Analysen laufen über `execute_prompt` / `execute_prompt_with_data`. |
|
||||
| **Begründung** | Einheitliche Platzhalter-Auflösung, Debug, JSON-Validierung, Speicher-Metadaten. |
|
||||
| **Quelle** | `backend/prompt_executor.py`; `POST /api/prompts/execute`; `Analysis.jsx` → `executeUnifiedPromptStream` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy `insights.py` und teils `History.jsx` umgehen den Executor noch. |
|
||||
|
||||
### 2. Konfigurierbare Prompt-Bibliothek statt fest verdrahteter Texte
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Prompt-Inhalte und Workflows liegen in `ai_prompts`, nicht im Anwendungscode. |
|
||||
| **Begründung** | Admins können Analysen anpassen, duplizieren, deaktivieren, ohne Deploy. |
|
||||
| **Quelle** | Migration 020; `UnifiedPromptCreate`/`Update` in `models.py`; `AdminPromptsPage.jsx` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Parallel existieren noch `pipeline_configs` und hardcodierte Default-Module/Zeiträume. |
|
||||
|
||||
### 3. Drei Prompt-Typen mit klarer Verantwortung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `base` = wiederverwendbarer Baustein; `pipeline` = sequenzielle Stages; `workflow` = Graph mit Verzweigung. |
|
||||
| **Begründung** | Komposition ohne Copy-Paste; Reference-Prompts in Pipelines (`source: 'reference'`). |
|
||||
| **Quelle** | `execute_prompt()` Typ-Verzweigung; `StagePromptCreate` in `models.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Pipeline-Stages laufen sequentiell, obwohl konzeptionell „parallel“; `workflow_definitions` und `ai_prompts.graph_data` doppelt. |
|
||||
|
||||
### 4. Platzhalter als API-Verträge (Registry)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Platzhalter sind registrierte, dokumentierte Verträge — keine freien Prompt-Hilfsvariablen. |
|
||||
| **Begründung** | Konsistenz für Injektion, GUI-Picker, Export, Validierung. |
|
||||
| **Quelle** | `PLACEHOLDER_REGISTRY_FRAMEWORK.md`; `docs/PLACEHOLDER_GOVERNANCE.md`; `import placeholder_registrations` in `main.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Duplikat `PLACEHOLDER_MAP` in `placeholder_resolver.py` neben Registry; Metadaten teils noch Legacy. |
|
||||
|
||||
### 5. Trennung Template (Was) vs. Resolver (Daten)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Templates enthalten nur `{{keys}}`; Berechnung liegt in Resolver/Data Layer. |
|
||||
| **Begründung** | Prompt-Autoren ändern Text, nicht Berechnungslogik. |
|
||||
| **Quelle** | `resolve_placeholders()` in `prompt_executor.py`; Registry-Felder `resolver_function`, `data_layer_function` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `execute_prompt_with_data` lädt zusätzlich Roh-SQL pro Modul — zweite Kontext-Schicht. |
|
||||
|
||||
### 6. Layer-1-Daten vs. Layer-2a-Prompt-Injektion
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Berechnungen in `data_layer/`; Prompt Engine konsumiert nur formatierte Werte. |
|
||||
| **Begründung** | Single Source of Truth für Charts, Platzhalter, KI. |
|
||||
| **Quelle** | Phase-0c-Architektur; Registry-Felder `data_layer_module` / `layer_1_decision` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy `_prepare_template_vars` in `insights.py` umgeht Data Layer. |
|
||||
|
||||
### 7. Transparenz durch Debug- und Preview-Modus
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Aufgelöste/unaufgelöste Platzhalter, Final-Prompt und Stage-Outputs sind inspizierbar; Preview ohne LLM. |
|
||||
| **Begründung** | Admin kann Prompts testen und Wertetabelle/Expertenmodus speisen. |
|
||||
| **Quelle** | `debug`-Parameter; `/preview`; `UnifiedPromptModal` Test-Button; `ai_insights.metadata` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Debug-Daten in Responses können groß/sensibel sein; kein separates Staging. |
|
||||
|
||||
### 8. Wiederverwendbare Base-Prompts via Reference
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Pipeline-Stages referenzieren Slugs statt Templates zu duplizieren. |
|
||||
| **Begründung** | Ein Baustein, mehrere Workflows; zentral wartbar. |
|
||||
| **Quelle** | `source == 'reference'` in `execute_pipeline_prompt()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Keine Referenz-Versionierung; Änderung am Base-Prompt wirkt sofort auf alle Referenzen. |
|
||||
|
||||
### 9. Strukturierte LLM-Ausgaben per Output-Format
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Pro Prompt/Prompt-Def: `output_format: text\|json`, optional `output_schema`; Pipeline-Outputs als Stage-Keys im Kontext. |
|
||||
| **Begründung** | Maschinenlesbare Zwischenergebnisse für Multi-Stage und Wertetabelle. |
|
||||
| **Quelle** | `validate_json_output()`; Stage `output_key` in Pipeline |
|
||||
| **Tragfähigkeit** | **mittel** |
|
||||
| **Einschränkung** | JSON-Schema-Validierung ist TODO (`jsonschema`); Markdown-Unwrap als Heuristik. |
|
||||
|
||||
### 10. Admin-only Konfiguration, User-only Ausführung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Schreibende Prompt-/Workflow-Operationen nur mit `require_admin`. |
|
||||
| **Begründung** | Produktions-Prompts sind Systemkonfiguration, nicht Nutzerdaten. |
|
||||
| **Quelle** | `require_admin` in `routers/prompts.py`; `RequireAdmin` für `/admin/prompts` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `/workflow-editor/:id` ohne Frontend-Admin-Gate; `/prompts/execute` ohne `check_feature_access` (Legacy-Pfad in `insights.py` hat Enforcement). |
|
||||
|
||||
### 11. Import/Export als Umgebungs-Sync
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Prompt-Sätze als JSON exportierbar/importierbar (Dev→Prod). |
|
||||
| **Begründung** | Konfiguration versionierbar in Git, nicht in der App-DB. |
|
||||
| **Quelle** | `GET /export-all`, `POST /import` in `routers/prompts.py`; Admin-UI Buttons |
|
||||
| **Tragfähigkeit** | **mittel** |
|
||||
| **Einschränkung** | Kein Diff, keine Merge-Strategie, kein Rollback; Overwrite-Flag manuell. |
|
||||
|
||||
### 12. Workflow-Erweiterung: Graph + Fragenergänzungen + Signale
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Workflows als Knoten/Kanten-Graph; optionale Fragen am Knoten; Normalisierung/Logic/Join als Engine-Schicht. |
|
||||
| **Begründung** | Bedingte, verzweigte Analysen jenseits linearer Pipelines. |
|
||||
| **Quelle** | `workflow_executor.py`; Migration 034; `question_augmenter.py` |
|
||||
| **Tragfähigkeit** | **mittel** |
|
||||
| **Einschränkung** | Hohe Komplexität; zwei Speicherorte (`graph_data` vs. `workflow_definitions`); Jinja2 im Workflow-Pfad zusätzlich zu `{{}}`-Resolver. |
|
||||
|
||||
### 13. Platzhalter-Modifier für KI-Kontext
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `{{key\|d}}` (Wert + Beschreibung), `{{key\|x}}` (Erklärung ohne Zahl) über Katalog-Metadaten. |
|
||||
| **Begründung** | Prompts können Kontext für das Modell reichhaltiger machen ohne Template-Duplikate. |
|
||||
| **Quelle** | `resolve_placeholders()` Modifier-Logik; `get_placeholder_catalog()` |
|
||||
| **Tragfähigkeit** | **mittel** |
|
||||
| **Einschränkung** | Modifier-Syntax ad hoc; Katalog-Pflicht für sinnvolle `\|x`-Nutzung. |
|
||||
|
||||
### 14. System-Prompt-Reset statt DB-Versionierung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Shipped Prompts mit `is_system_default` + `default_template`; Admin-Reset auf Original. |
|
||||
| **Begründung** | Schutz vor irreversiblen Fehlkonfigurationen ohne vollständiges Versionsmodell. |
|
||||
| **Quelle** | Migration 019; `POST /{prompt_id}/reset-to-default` |
|
||||
| **Tragfähigkeit** | **mittel** |
|
||||
| **Einschränkung** | Nur ein Default-Snapshot; keine Historie benutzerdefinierter Änderungen. |
|
||||
|
||||
### 15. Governance für Platzhalter-Änderungen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Breaking Changes nur über Deprecation + Replacement; semantische Verträge dokumentiert. |
|
||||
| **Begründung** | Prompts in Produktion brechen nicht still. |
|
||||
| **Quelle** | `docs/PLACEHOLDER_GOVERNANCE.md` §4 |
|
||||
| **Tragfähigkeit** | **mittel** (prozessual) |
|
||||
| **Einschränkung** | Prozess in Doku, nicht im Runtime erzwungen; Checkliste verweist noch auf Legacy-Dateien. |
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
Muster, die sich nicht bewährt haben oder zu produktspezifisch sind — bei Neuentwicklung vermeiden:
|
||||
|
||||
1. **Parallele Ausführungspfade** — Legacy `insights.py` (`/insights/run`, `/insights/pipeline`) mit eigener Template-Engine und LLM-Calls neben `prompt_executor`; Frontend-Split (`Analysis` vs. `History`).
|
||||
|
||||
2. **Doppelte Metadaten für Platzhalter** — `PLACEHOLDER_MAP`, Registry, `placeholder_metadata_complete.py` und Katalog-Fallbacks parallel; erzeugt Sync-Risiko (114 Keys müssen deckungsgleich bleiben).
|
||||
|
||||
3. **Zwei Pipeline-Modelle gleichzeitig** — `pipeline_configs` (3 fixe Stages) und Unified `type=pipeline` in `ai_prompts`; Migration 020 migriert, Tabelle bleibt aktiv.
|
||||
|
||||
4. **Zwei Workflow-Speicher** — `workflow_definitions.graph` und `ai_prompts.graph_data`; unklare Single Source of Truth.
|
||||
|
||||
5. **Roh-SQL-Kontextladung im Executor** — `execute_prompt_with_data` lädt Modul-Rohdaten per SQL, obwohl Resolver/Data Layer existieren; Domänenwissen in der Engine.
|
||||
|
||||
6. **Hardcodierte Execute-Defaults** — Module/Zeiträume in `/execute` fest verdrahtet statt aus Prompt-/Pipeline-Konfiguration.
|
||||
|
||||
7. **Fehlende Feature-Enforcement-Konsistenz** — `check_feature_access` auf Legacy-Insights, nicht auf `/prompts/execute`.
|
||||
|
||||
8. **„Parallel“ als sequentiell implementiert** — Pipeline-Stages kommentiert als parallel, Code sequentiell; irreführendes Modell.
|
||||
|
||||
9. **Unvollständige Output-Validierung** — JSON-Parse + Markdown-Unwrap, Schema-Check auskommentiert/TODO.
|
||||
|
||||
10. **Workflow-Editor ohne klares Admin-Gate in Routing** — Schreib-API geschützt, UI-Route für alle Authentifizierten erreichbar.
|
||||
|
||||
11. **Domänen-spezifische Hardcodings in der Engine** — Kategorien (`körper`, `ernährung`, …), deutsche Meta-Prompts für Generate/Optimize, Fitness-Kontext in Prompt-Generator.
|
||||
|
||||
12. **Kein integriertes Prompt-Versions- und Freigabemodell** — Overwrite + JSON-Export ersetzt keine Revision/Review/Publish-Pipeline.
|
||||
|
||||
13. **Issue #51 (Seitenzuordnung) nicht umgesetzt** — Prompt-Verfügbarkeit kontextuell nicht konfigurierbar; alles über zentrale Analyse-Seite.
|
||||
|
||||
14. **Globales LLM-Modell per Env** — `workflow_executor` übergibt Modell pro Call, `call_openrouter` ignoriert es; keine prompt-spezifische Modellwahl trotz API-Shape.
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Fachliche Spec: [AI_PROMPTS.md](../../functional/AI_PROMPTS.md)
|
||||
- Platzhalter-Registry: [PLACEHOLDER_REGISTRY_FRAMEWORK.md](../../technical/PLACEHOLDER_REGISTRY_FRAMEWORK.md)
|
||||
- Platzhalter-Governance: [PLACEHOLDER_GOVERNANCE.md](../../../../docs/PLACEHOLDER_GOVERNANCE.md)
|
||||
- Issue #28 (Unified Prompt System): abgeschlossen, siehe `CLAUDE.md`
|
||||
- Issue #51 (Prompt-Seitenzuordnung): [issue-51-prompt-page-assignment.md](../../../../docs/issues/issue-51-prompt-page-assignment.md)
|
||||
- **Serie (abgeschlossen):** [Index](./README.md) · [Jinkendo Foundation](../README.md) · Dokumente #1–#9
|
||||
@@ -0,0 +1,315 @@
|
||||
# Registry- & Plugin-Muster – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** Querschnittsmuster für erweiterbare Registries — drei Implementierungen in Mitai (Platzhalter, Dashboard-Widgets, CSV-Import)
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 4 von n
|
||||
**Vorgänger:** [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Die drei Registries:**
|
||||
|
||||
| Registry | Backend-Kanon | Frontend-/Runtime-Registry | Leitfaden |
|
||||
|----------|---------------|----------------------------|-----------|
|
||||
| **Platzhalter** | `placeholder_registry.py` + `placeholder_registrations/` | `PLACEHOLDER_MAP` in `placeholder_resolver.py` | `PLACEHOLDER_REGISTRY_FRAMEWORK.md` |
|
||||
| **Dashboard-Widgets** | `widget_catalog.py` | `registerDashboardWidgets.js` → `dashboardWidgetRegistry.jsx` | `DASHBOARD_WIDGETS_AGENT_GUIDE.md` |
|
||||
| **CSV-Import-Module** | `csv_parser/module_registry.py` | — (Executor + Admin-UI konsumieren API) | `UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md` |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Registry- & Plugin-Muster** (Meta-Schicht)
|
||||
|
||||
Wiederkehrendes Architekturmuster: **Zentral registrierte, ID-basierte Erweiterungspunkte** mit Metadaten, Validierung und getrennten Konsumenten (GUI, API, Batch). Kein einzelnes Runtime-Modul — ein **Familien-Designpattern**, das in Mitai dreimal konkret umgesetzt ist.
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Registries übernehmen:
|
||||
|
||||
1. **Autoritative ID-Liste** — Was existiert, was ist erlaubt, in welcher Reihenfolge (optional).
|
||||
2. **Metadaten für Mensch & Maschine** — Titel, Beschreibung, Typen, Abhängigkeiten, semantische Verträge.
|
||||
3. **Validierung** — Unbekannte IDs werden abgelehnt; Konfigurationen gegen Kanon geprüft.
|
||||
4. **Entkopplung** — Implementierung (Resolver, React-Komponente, Import-Executor) registriert sich an den Kanon, nicht umgekehrt.
|
||||
5. **Erweiterbarkeit ohne Schema-Explosion** — Neue Einträge über Code-Registrierung (+ ggf. DB-Overrides), nicht über neue DB-Spalten pro Feature.
|
||||
|
||||
Registries übernehmen **nicht**:
|
||||
|
||||
- Fachliche Berechnung (→ Data Layer)
|
||||
- Entitlement-Auflösung (→ Feature System; Widgets *referenzieren* Features)
|
||||
- Auth / Mandanten
|
||||
|
||||
### Gemeinsames Strukturschema
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ REGISTRY (Kanon) │
|
||||
│ ID + Metadaten + optionale Policies/Abhängigkeiten │
|
||||
└────────────────────┬────────────────────────────────────┘
|
||||
│
|
||||
┌───────────────┼───────────────┐
|
||||
▼ ▼ ▼
|
||||
Implementierung Validierung Konsumenten
|
||||
(Resolver/ (Schema/ (GUI-Picker,
|
||||
Component/ Tests) API, Executor)
|
||||
Executor)
|
||||
```
|
||||
|
||||
### Vergleich der drei Implementierungen
|
||||
|
||||
| Aspekt | Platzhalter | Dashboard-Widgets | CSV-Import |
|
||||
|--------|-------------|-------------------|------------|
|
||||
| **Primär-ID** | `key` (snake_case) | `id` (snake_case) | Modul-Name (`nutrition`, `activity`, …) |
|
||||
| **Kanon-Speicher** | Python Singleton + Cluster-Module | Python-Liste `WIDGET_CATALOG` | Python-Dict `MODULE_DEFINITIONS` |
|
||||
| **Metadaten-Tiefe** | Sehr hoch (22+ Felder, Evidence) | Mittel (title, description, requires_feature) | Hoch (fields, types, duplicate_key, aggregates) |
|
||||
| **Runtime-Registry** | `register_placeholder()` beim Import | `registerDashboardWidget()` idempotent | Keine — Executor liest Dict |
|
||||
| **Frontend-Spiegel** | PlaceholderPicker, Admin-Prompt-Modal | `ensureDashboardWidgetsRegistered()` | Admin CSV Template Editor |
|
||||
| **Validierung** | `metadata.validate()`, Governance-Docs | Pydantic Layout + `validate_widget_entry_config` | `validate_field_mappings`, `validate_csv_template` |
|
||||
| **Tests** | `test_placeholder_metadata.py`, … | `test_widget_catalog.py` | `test_template_validator.py`, … |
|
||||
| **DB-Override** | Nein (nur Code) | Ja (`widget_feature_requirements`, Layout pro Profil) | Ja (Vorlagen, Nutzer-Mappings) |
|
||||
| **Entitlements** | Indirekt (Data/Features) | `requires_feature` → `check_feature_access` | Feature-Limits beim Import |
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien (übergreifend)
|
||||
|
||||
### 1. Single Source of Truth für erlaubte IDs
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jede erweiterbare Einheit hat **eine** autoritative ID-Liste; Router und UI duplizieren keine Feld-/Widget-/Platzhalter-Listen. |
|
||||
| **Begründung** | Verhindert „funktioniert in der UI, scheitert in der API“ und umgekehrt. |
|
||||
| **Quelle** | `module_registry.py` Kommentar; `widget_catalog.py`; `PLACEHOLDER_REGISTRY_FRAMEWORK.md` §2.3 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Platzhalter: paralleles `PLACEHOLDER_MAP` neben Registry. |
|
||||
|
||||
### 2. ID-Stabilität als Vertrag
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | IDs/Keys sind stabile API-Verträge; Umbenennung = neuer Key + Deprecation, nicht stilles Rename. |
|
||||
| **Begründung** | Prompts, Layouts und CSV-Vorlagen referenzieren IDs persistent. |
|
||||
| **Quelle** | `docs/PLACEHOLDER_GOVERNANCE.md` §4.2–4.3; Widget-Layout in `profiles.dashboard_layout` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht überall runtime-erzwungen (Platzhalter-Governance prozessual). |
|
||||
|
||||
### 3. Metadaten getrennt von Implementierung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Registry speichert **Was** (ID, Beschreibung, Typ, Policies); Implementierung lebt in separaten Modulen. |
|
||||
| **Begründung** | GUI, Export, Validierung und Docs können Metadaten nutzen ohne Resolver/Component zu laden. |
|
||||
| **Quelle** | `PlaceholderMetadata` Dataclass; `WidgetCatalogEntry`; `MODULE_DEFINITIONS.fields` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Platzhalter bindet `_resolver_func` optional an Metadata-Objekt. |
|
||||
|
||||
### 4. Zwei-Phasen-Registrierung (Backend-Kanon + Runtime-Binding)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Phase A: Kanon definiert IDs und Metadaten. Phase B: Implementierung registriert sich (Platzhalter-Cluster-Import, `registerDashboardWidget`, Executor nutzt Modul-Def). |
|
||||
| **Begründung** | Backend bleibt autoritativ; Frontend/plugins können nachziehen, Tests können Lücken finden. |
|
||||
| **Quelle** | `import placeholder_registrations` in `main.py`; `ensureDashboardWidgetsRegistered()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Fehlende Frontend-Registrierung zeigt „Unbekanntes Widget“ — kein Build-Time-Fail. |
|
||||
|
||||
### 5. Auto-Registration via Package-Import
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Side-Effect-Import eines Packages triggert vollständige Registrierung (`placeholder_registrations/__init__.py`). |
|
||||
| **Begründung** | Keine vergessene manuelle Registrierungsliste in `main.py` pro Eintrag. |
|
||||
| **Quelle** | `placeholder_registrations/__init__.py`; `main.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Import-Reihenfolge und zirkuläre Imports beachten. |
|
||||
|
||||
### 6. Validierung am Registry-Rand
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Unbekannte Keys/Widget-IDs/Feld-Mappings werden an Registry-Grenzen abgewiesen, nicht erst in der Business-Logik. |
|
||||
| **Begründung** | Frühes, klares Fehlerbild für Admins und Entwickler. |
|
||||
| **Quelle** | `DashboardWidgetEntry` + `ALLOWED_WIDGET_IDS`; `validate_field_mappings()`; `get_unknown_placeholders()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Prompt-Templates können unbekannte Platzhalter erst zur Laufzeit offenbaren. |
|
||||
|
||||
### 7. Konsumenten-Agnostik
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Dieselbe Registry bedient mehrere Konsumenten (KI, Charts, Export, Admin-Browser) ohne duplizierte Metadaten. |
|
||||
| **Begründung** | DRY für Beschreibungen, Kategorien, Beispielwerte. |
|
||||
| **Quelle** | `PLACEHOLDER_REGISTRY_FRAMEWORK.md` §2.2; `get_placeholder_catalog()` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Legacy-Export-Pfade mergen noch „Registry + Legacy“. |
|
||||
|
||||
### 8. Erweiterungs-Checkliste statt Ad-hoc
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jedes Registry hat dokumentierte Schritte A→G (Katalog-Eintrag, Validierung, Tests, Version-Bump). |
|
||||
| **Begründung** | Agenten und Menschen erweitern konsistent; Review an Checkliste. |
|
||||
| **Quelle** | `DASHBOARD_WIDGETS_AGENT_GUIDE.md` §2; `UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md` §2; `PLACEHOLDER_DEVELOPMENT_GUIDE.md` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Drei separate Guides — kein unified „Registry Agent Guide“. |
|
||||
|
||||
### 9. Tests auf Katalog-Konsistenz
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Automatisierte Tests prüfen Eindeutigkeit, Reihenfolge, Payload-Shape, ID-Abgleich Kanon ↔ abgeleitete Sets. |
|
||||
| **Begründung** | Regression wenn Katalog wächst but Registry/Layout nicht mitzieht. |
|
||||
| **Quelle** | `test_widget_catalog.py`; Placeholder-Metadata-Tests |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Kein Cross-Registry-Test „Frontend widget IDs == backend catalog“. |
|
||||
|
||||
### 10. Optionale Entitlement-Referenz im Kanon
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Registry-Einträge **referenzieren** Feature-IDs (`requires_feature`), lösen Entitlements aber nicht selbst auf. |
|
||||
| **Begründung** | Tier-Logik bleibt in `check_feature_access`; Katalog bleibt deklarativ. |
|
||||
| **Quelle** | `WidgetCatalogEntry.requires_feature`; `dashboard_widget_entitlements.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Platzhalter haben kein direktes `requires_feature` — Gating nur indirekt. |
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien (spezifisch pro Registry)
|
||||
|
||||
### Platzhalter-Registry
|
||||
|
||||
| # | Prinzip | Tragfähigkeit | Schwäche |
|
||||
|---|---------|---------------|----------|
|
||||
| P1 | **Semantischer Vertrag** (`semantic_contract`) pro Key — Platzhalter sind API, nicht Prompt-Hilfe | hoch | Viele Legacy-Keys mit schwachem Vertrag |
|
||||
| P2 | **Evidence-Tagging** — Herkunft jedes Metadatenfelds nachvollziehbar | mittel | Pflegeaufwand |
|
||||
| P3 | **Cluster-Module** — Registrierung nach Domäne (`nutrition_part_a`, `body_metrics`, …) | hoch | 114 Keys Sync mit `PLACEHOLDER_MAP` |
|
||||
| P4 | **Data-Layer-Referenz** in Metadata (`data_layer_function`) — Bindung an Layer 1 | hoch | Nicht alle Keys vollständig verknüpft |
|
||||
| P5 | **Singleton** `get_registry()` — globaler Kanon | hoch | Test-Isolation braucht Disziplin |
|
||||
|
||||
### Dashboard-Widget-Registry
|
||||
|
||||
| # | Prinzip | Tragfähigkeit | Schwäche |
|
||||
|---|---------|---------------|----------|
|
||||
| W1 | **Backend-Katalog = ALLOWED_WIDGET_IDS** — Layout-Schema leitet ab | hoch | Frontend-Registry manuell parallel |
|
||||
| W2 | **`merge_missing_catalog_widgets`** — neue Katalog-IDs erscheinen im Layout ohne User-Reset | hoch | — |
|
||||
| W3 | **Strikte `config`-Validierung** nur für whitelisted Widgets (`WIDGETS_ALLOWING_CONFIG`) | hoch | Config-Schemas pro Widget heterogen |
|
||||
| W4 | **Graceful Degradation** — unregistrierte ID → Fehler-Karte, nicht Crash | mittel | Maskiert Deploy-Fehler |
|
||||
| W5 | **WidgetErrorBoundary** pro Instanz | hoch | — |
|
||||
|
||||
### CSV-Modul-Registry
|
||||
|
||||
| # | Prinzip | Tragfähigkeit | Schwäche |
|
||||
|---|---------|---------------|----------|
|
||||
| C1 | **`MODULE_DEFINITIONS` = einzige Feldliste** — Router duplizieren nicht | hoch | Activity erweitert dynamisch um `training_parameters` |
|
||||
| C2 | **Deklarative Duplikat-Strategie** (`duplicate_key`, `update`/`skip`) | hoch | Modul-spezifische Executor-Sonderfälle |
|
||||
| C3 | **`import_row_processing`** — Aggregation in Registry, nicht im Router | hoch | Legacy-Defaults in Modul-Def |
|
||||
| C4 | **`validate_field_mappings`** vor Persistenz | hoch | Nutzer-Mappings teils ohne volle Validator-Parität (#71) |
|
||||
| C5 | **Persistenz-Orchestrator** liest Registry-Felder (`activity_persistence_orchestrator`) | hoch | Nur Activity voll ausgebaut |
|
||||
|
||||
---
|
||||
|
||||
## Anti-Pattern: Doppel-Registry
|
||||
|
||||
Mitai zeigt an **Platzhaltern** das Risiko explizit:
|
||||
|
||||
```
|
||||
placeholder_registrations/ ──register──► PlaceholderRegistry (Metadata)
|
||||
│ ▲
|
||||
└── resolver in code ──► PLACEHOLDER_MAP (Runtime, 114 Keys)
|
||||
```
|
||||
|
||||
**Regel für Produktfamilie:** Runtime-Auflösung soll Metadata-Registry **lesen**, nicht spiegeln.
|
||||
|
||||
Widgets sind näher am Ideal: Backend `WIDGET_CATALOG` ist Kanon; Frontend muss IDs manuell in `registerDashboardWidgets.js` binden — akzeptabel, aber testbar machen (Cross-Check).
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
1. **Parallele Runtime-Maps** — `PLACEHOLDER_MAP` + Registry; eine Quelle für Keys und Resolver-Pfad.
|
||||
|
||||
2. **Frontend-Registry ohne Build-/Test-Gate** — fehlende `registerDashboardWidget`-Einträge erst zur Laufzeit sichtbar.
|
||||
|
||||
3. **Metadaten-Duplikation in Export-Code** — hardcodierte Beschreibungen außerhalb der Registry.
|
||||
|
||||
4. **Registry-Einträge ohne Validierungs-Tests** — besonders bei 100+ Platzhaltern.
|
||||
|
||||
5. **Import-Feldlisten in Routern** — alles über `module_registry` (Mitai-Zielbild, noch nicht überall).
|
||||
|
||||
6. **Evidence-/Metadata-Pflicht für einfache Plugins** — 22 Felder für Widgets wären Overkill; **Metadaten-Tiefe an Risiko anpassen**.
|
||||
|
||||
7. **Dynamische Registry aus DB ohne Versionierung** — Widget-Feature-Overrides OK; kompletter Kanon nur in DB wäre schwer testbar.
|
||||
|
||||
8. **Registry ohne Deprecation-Pfad** — Breaking Key-Changes still (Platzhalter-Governance existiert, durchsetzen).
|
||||
|
||||
9. **Entitlements in Registry auflösen** — Widgets richtig: referenzieren; nicht Tier-Logik im Katalog.
|
||||
|
||||
10. **Schlaf-Modul leeres `fields: {}`** — Sondermodus (`import_mode`) statt sauberem Registry-Eintrag; technische Schuld.
|
||||
|
||||
---
|
||||
|
||||
## Entscheidungsmatrix: Welche Registry-Tiefe?
|
||||
|
||||
| Wenn … | dann Metadaten-Tiefe … | Beispiel |
|
||||
|--------|------------------------|----------|
|
||||
| Externe Verträge / KI / Compliance | Hoch (Vertrag, Evidence, Missing-Policy) | Platzhalter |
|
||||
| UI-Plugin mit optionaler Config | Mittel (ID, title, config schema, feature ref) | Widgets |
|
||||
| Daten-Ingest / Schema-Mapping | Hoch (Typen, keys, constraints) | CSV-Module |
|
||||
| Internes Hilfsmodul | Minimal (ID + Handler-Ref) | — |
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Querschnitt)
|
||||
|
||||
```
|
||||
backend/
|
||||
├── placeholder_registry.py
|
||||
├── placeholder_registrations/ # Auto-import Cluster
|
||||
├── placeholder_resolver.py # PLACEHOLDER_MAP (Legacy-Spiegel)
|
||||
├── placeholder_registry_export.py
|
||||
├── widget_catalog.py
|
||||
├── dashboard_layout_schema.py
|
||||
├── dashboard_widget_config.py
|
||||
├── dashboard_widget_entitlements.py
|
||||
├── widget_feature_requirements_db.py
|
||||
└── csv_parser/
|
||||
└── module_registry.py
|
||||
|
||||
frontend/src/
|
||||
├── widgetSystem/
|
||||
│ ├── registerDashboardWidgets.js
|
||||
│ └── dashboardWidgetRegistry.jsx
|
||||
└── components/workflow/panels/PlaceholderPicker.jsx
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Platzhalter: [PLACEHOLDER_REGISTRY_FRAMEWORK.md](../../technical/PLACEHOLDER_REGISTRY_FRAMEWORK.md), [PLACEHOLDER_GOVERNANCE.md](../../../../docs/PLACEHOLDER_GOVERNANCE.md)
|
||||
- Widgets: [DASHBOARD_WIDGETS_AGENT_GUIDE.md](../../technical/DASHBOARD_WIDGETS_AGENT_GUIDE.md)
|
||||
- Import: [UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md](../../technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md)
|
||||
- Entitlements (Widget-Gating): [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
- Data Layer (Platzhalter-Berechnung): [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md)
|
||||
- Prompt Engine (Platzhalter-Konsument): [PROMPT_ENGINE_DESIGN_PRINCIPLES.md](./PROMPT_ENGINE_DESIGN_PRINCIPLES.md)
|
||||
|
||||
---
|
||||
|
||||
## Geplante Folgedokumente (Serie)
|
||||
|
||||
| # | Modul | Status |
|
||||
|---|-------|--------|
|
||||
| 1 | Prompt Engine | ✅ |
|
||||
| 2 | Data Layer | ✅ |
|
||||
| 3 | Feature & Entitlement | ✅ |
|
||||
| 4 | Registry-/Plugin-Muster | ✅ dieses Dokument |
|
||||
| 5 | Auth & Session | ✅ `AUTH_SESSION_DESIGN_PRINCIPLES.md` |
|
||||
| 6 | Universal Import | ✅ |
|
||||
| 7 | Dashboard Widgets | ✅ |
|
||||
| 8 | Navigation / IA | ✅ |
|
||||
| 9 | Migration & Deploy | ✅ |
|
||||
|
||||
*Hinweis:* Dokumente 6 und 7 vertiefen Einzel-Registries; dieses Meta-Dokument ist die übergreifende Extraktion.
|
||||
@@ -0,0 +1,325 @@
|
||||
# Universal CSV Import – Designprinzipien (Extraktion)
|
||||
|
||||
**Status:** Analyse / Arbeitspapier
|
||||
**Stand:** 2026-07-04
|
||||
**Geltungsbereich:** Universal CSV Import (Issue #21) — Ingest/Mapping/Persistenz, keine Auswertungslogik
|
||||
|
||||
**Serie:** Designprinzipien für Produktfamilie · Dokument 6 von n
|
||||
**Vorgänger:** [AUTH_SESSION_DESIGN_PRINCIPLES.md](./AUTH_SESSION_DESIGN_PRINCIPLES.md)
|
||||
|
||||
**Kernkomponenten:**
|
||||
|
||||
| Bereich | Pfade |
|
||||
|---------|-------|
|
||||
| Modul-Kanon | `backend/csv_parser/module_registry.py` |
|
||||
| Ausführung | `backend/csv_parser/executor.py` |
|
||||
| Parsing/Typen | `core.py`, `type_converter.py`, `field_units.py` |
|
||||
| Aggregation | `import_row_processing.py` |
|
||||
| Validierung | `template_validator.py` |
|
||||
| Fehler-Hints | `import_errors.py` |
|
||||
| Mapping-Vorschläge | `mapping_suggest.py` |
|
||||
| Nutzer-API | `backend/routers/csv_import.py` |
|
||||
| Admin-Vorlagen | `backend/routers/admin_csv_templates.py` |
|
||||
| Persistenz-Orchestrator | `data_layer/activity_persistence_orchestrator.py` |
|
||||
| Leitfaden | `UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md` |
|
||||
| Import-Grenze | `.claude/rules/ARCHITECTURE.md` §8 |
|
||||
|
||||
---
|
||||
|
||||
## Modul
|
||||
|
||||
**Universal CSV Import**
|
||||
|
||||
Konfigurierbare Pipeline: **CSV-Datei → Feld-Mapping → Typkonvertierung → (optional Aggregation) → DB-Upsert** — mit Vorlagen, Audit-Log und row-level Fehlertoleranz.
|
||||
|
||||
---
|
||||
|
||||
## Fachliche Verantwortung
|
||||
|
||||
Das Modul übernimmt:
|
||||
|
||||
1. **Modul-Registry** — Welche Zieltabellen/Felder importierbar sind (Typen, Duplikat-Keys, Strategien).
|
||||
2. **Vorlagen (Mappings)** — System-Templates (Admin) + Nutzer-Kopien (`csv_field_mappings`).
|
||||
3. **Analyse** — Delimiter-Erkennung, Spalten-Signatur, Mapping-Vorschläge, Diagnose einzelner Zeilen.
|
||||
4. **Ausführung** — Upsert pro Modul, `source=csv`, Statistik, `affected_ids`.
|
||||
5. **Fehlertransparenz** — Row-level Errors mit `code`/`hint`; kein Silent-Fail der ganzen Transaktion.
|
||||
6. **Audit** — `csv_import_log` mit Status, Counts, betroffenen IDs.
|
||||
7. **Limits** — Dateigröße/Zeilen aus `system_config`; Feature-Entitlements pro Modul.
|
||||
|
||||
Es übernimmt **nicht**:
|
||||
|
||||
- Fachliche Metriken / Scores (→ Data Layer, siehe [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md))
|
||||
- Prompt-/KI-Logik
|
||||
- Vollständiger Ersatz aller Legacy-Import-Endpoints (noch parallel)
|
||||
|
||||
### Pipeline (Happy Path)
|
||||
|
||||
```
|
||||
Upload CSV
|
||||
→ decode_raw_bytes + resolve_effective_csv_delimiter
|
||||
→ Vorlage laden (csv_field_mappings)
|
||||
→ validate (optional Admin) / feature check
|
||||
→ run_universal_csv_import(cur, …) // eine Transaktion
|
||||
→ build_row_after_mapping (type_converter)
|
||||
→ aggregate_mapped_rows (import_row_processing)
|
||||
→ UPSERT / activity_persistence_orchestrator
|
||||
→ csv_import_log UPDATE + increment_feature_usage
|
||||
```
|
||||
|
||||
### Unterstützte Module (Registry)
|
||||
|
||||
| Modul | Zieltabelle | Besonderheit |
|
||||
|-------|-------------|--------------|
|
||||
| `nutrition` | `nutrition_log` | Tages-Aggregation |
|
||||
| `weight` | `weight_log` | Duplikat: profile + date |
|
||||
| `activity` | `activity_log` | SAVEPOINT pro Zeile; EAV via Orchestrator |
|
||||
| `vitals_baseline` | `vitals_baseline` | Tages-Aggregation |
|
||||
| `blood_pressure` | `blood_pressure_log` | Composite `measured_at` |
|
||||
| `sleep` | `sleep_log` | Legacy-Adapter `import_mode: apple_sleep_aggregate` |
|
||||
|
||||
---
|
||||
|
||||
## Administrierte vs. code-definierte Konfiguration
|
||||
|
||||
| Konfiguration | Speicherort | Wer pflegt? |
|
||||
|---------------|-------------|-------------|
|
||||
| Zielfelder, Typen, Duplikat-Keys | `MODULE_DEFINITIONS` | Entwickler (Code) |
|
||||
| System-Vorlagen | `csv_field_mappings` (`is_system=true`) | Admin (+ Migration Seeds) |
|
||||
| Nutzer-Mappings | `csv_field_mappings` (`profile_id`) | Nutzer (Kopie/Anpassung) |
|
||||
| `field_mappings`, `type_conversions`, `import_row_processing` | JSONB in Vorlage | Admin/Nutzer |
|
||||
| Import-Limits | `system_config.csv_import` | Admin |
|
||||
| Delimiter-Sniffing-Heuristik | `core.py` | Code |
|
||||
| Header-Aliases (Vorschläge) | `mapping_suggest.py` | Code |
|
||||
|
||||
**Bewusst nicht in Routern hardcodiert:** Feldlisten, Duplikat-Logik — nur Registry + Executor.
|
||||
|
||||
---
|
||||
|
||||
## Designprinzipien
|
||||
|
||||
### 1. Module Registry als Single Source of Truth
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Alle erlaubten Zielfelder, Typen und Duplikat-Keys leben in `MODULE_DEFINITIONS` — Router duplizieren nicht. |
|
||||
| **Begründung** | Admin-UI, Validator, Executor und `/api/csv/modules` bleiben synchron. |
|
||||
| **Quelle** | `module_registry.py`; Agent-Guide §1 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Activity erweitert Felder dynamisch aus `training_parameters` (DB). |
|
||||
|
||||
### 2. Ingest vs. Interpretation (Import-Grenze)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Import: Mapping + Typ/Einheit + Duplikat/Upsert. **Keine** fachliche Auswertung beim Insert. |
|
||||
| **Begründung** | Semantik gehört in Data Layer; Import bleibt austauschbar und testbar. |
|
||||
| **Quelle** | `ARCHITECTURE.md` §8; [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md) |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | `sleep_apple_import.py` ist Legacy-Adapter mit quellenspezifischer Logik. |
|
||||
|
||||
### 3. Vorlagen trennen Struktur von Datei
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `csv_field_mappings` speichert Modul, Delimiter, Header-Flag, Mappings, Conversions, Row-Processing — unabhängig vom Upload. |
|
||||
| **Begründung** | Wiederverwendung (Apple Health, Omron, …); Nutzer wählt Vorlage statt jedes Mal neu zu mappen. |
|
||||
| **Quelle** | Migration 042; Admin + User APIs |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nutzer-Kopien nicht immer durch `validate_csv_template` (#71). |
|
||||
|
||||
### 4. Effektives Trennzeichen aus Datei, nicht blind aus Vorlage
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `resolve_effective_csv_delimiter` — DE-Export (`;`) vs. EN-Vorlage (`,`) wird aus Header-Feldanzahl erkannt. |
|
||||
| **Begründung** | Regionale CSV-Exporte brechen sonst das gesamte Mapping (eine Spalte). |
|
||||
| **Quelle** | `core.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Heuristik, kein 100%-Garant für exotische Formate. |
|
||||
|
||||
### 5. Typ- und Einheiten-Konvertierung deklarativ
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `type_conversions` + `source_unit` in Vorlage; Logik in `type_converter` / `field_units`. |
|
||||
| **Begründung** | kJ→kcal, Datumsformate, Dezimal-Komma ohne Code pro Quelle. |
|
||||
| **Quelle** | `type_converter.py`, `field_units.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Falsche `source_unit` → DB-Overflow; `enrich_row_error` hilft nachträglich. |
|
||||
|
||||
### 6. Zeilen-Aggregation vor Upsert
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `import_row_processing` (group_by + aggregates) fasst mehrere CSV-Zeilen pro logischem Tag/Datensatz zusammen. |
|
||||
| **Begründung** | Ernährung/Vitals: viele Rohzeilen → ein Tageseintrag. |
|
||||
| **Quelle** | `import_row_processing.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Modul-Default als Legacy-Fallback wenn Vorlage leer; Admin „Format prüfen“ kann Processing auslassen. |
|
||||
|
||||
### 7. Ein Cursor, eine Transaktion, SAVEPOINT pro Zeile
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `run_universal_csv_import(cur, …)` nutzt **bestehenden** Cursor; bei Row-Fehlern SAVEPOINT + ROLLBACK TO, nicht ganze Xact abbrechen. |
|
||||
| **Begründung** | PostgreSQL „transaction aborted“; partielle Imports mit Fehlerliste. |
|
||||
| **Quelle** | `executor.py` (activity, vitals); `csv_import.py` SAVEPOINT `csv_import_exec` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nicht alle Module gleich implementiert; Disziplin pro Modul. |
|
||||
|
||||
### 8. Kein verschachteltes get_db im Importpfad
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | FK-Auflösung (z. B. Trainingstyp) und Activity-Persistenz mit **demselben** `cur` wie der Import. |
|
||||
| **Begründung** | Pool-Deadlocks, konsistente Transaktion. |
|
||||
| **Quelle** | `_resolve_training_type_for_activity`; Agent-Guide §2 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Lazy-Import aus Router in Executor (Kopplung). |
|
||||
|
||||
### 9. Strukturierte Fehler mit Hints
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `enrich_row_error()` mappt DB-/Parse-Fehler auf `code` + menschenlesbaren `hint`. |
|
||||
| **Begründung** | Nutzer/Admin können Vorlagen korrigieren ohne PostgreSQL-Kenntnis. |
|
||||
| **Quelle** | `import_errors.py`; Import-Response `error_details` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Heuristische String-Matches, nicht vollständig. |
|
||||
|
||||
### 10. Vorlagen-Validierung vor Persistenz (Admin)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `validate_csv_template` → `{ valid, errors[], warnings[] }`; Admin Create/Update → HTTP 422 bei Fehlern. |
|
||||
| **Begründung** | Fehler früh, nicht erst beim Nutzer-Import. |
|
||||
| **Quelle** | `template_validator.py`; `admin_csv_templates.py` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Dry-Run / User-Mappings Lücken (#71). |
|
||||
|
||||
### 11. System- vs. User-Mappings (Permissions)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `is_system=true`: nur Admin editierbar; Nutzer kopiert und passt eigene Zeile an. |
|
||||
| **Begründung** | Shipped Templates schützen; Individualisierung erlauben. |
|
||||
| **Quelle** | `permissions.py`; DB CHECK + Unique Indexes |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | — |
|
||||
|
||||
### 12. Import-Audit und Rollback-Vorbereitung
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Jeder Lauf schreibt `csv_import_log` mit Counts, `error_details`, `affected_ids` (PKs pro Tabelle). |
|
||||
| **Begründung** | Nachvollziehbarkeit, spätere Bereinigung/Rollback, Erfolgsrate pro Vorlage. |
|
||||
| **Quelle** | Migration 042; `csv_import_execute` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Automatischer Rollback-Button nicht überall umgesetzt. |
|
||||
|
||||
### 13. Feature-Entitlements an Import gebunden
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `data_import` global + modulspezifisch (`nutrition_entries`, …); Increment nur für **neue** Zeilen. |
|
||||
| **Begründung** | Konsistent mit Membership-System. |
|
||||
| **Quelle** | `csv_import.py` `_check_module_feature_access`, `increment_feature_usage` |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Bulk-Increment-Schleife ineffizient (wie Feature-Doc). |
|
||||
|
||||
### 14. Mapping-Vorschläge (Heuristik, nicht Autorität)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | `mapping_suggest.py` schlägt Spalten-Zuordnung aus Header-Aliases vor — Admin bestätigt. |
|
||||
| **Begründung** | Schneller Editor-Start; Kanon bleibt menschlich/administrativ freigegeben. |
|
||||
| **Quelle** | `_MODULE_HEADER_ALIASES` |
|
||||
| **Tragfähigkeit** | **mittel–hoch** |
|
||||
| **Einschränkung** | Domänenspezifische Aliases hardcodiert (DE/EN). |
|
||||
|
||||
### 15. Persistenz-Orchestrator für komplexe Domänen
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Prinzip** | Activity: nach Registry-Mapping → `activity_persistence_orchestrator` (Upsert + EAV + Eval-Hook). |
|
||||
| **Begründung** | Gleiche Schreiblogik wie REST-API; kein divergierender CSV-Pfad. |
|
||||
| **Quelle** | `activity_persistence_orchestrator.py`; [DATA_LAYER_DESIGN_PRINCIPLES.md](./DATA_LAYER_DESIGN_PRINCIPLES.md) §9 |
|
||||
| **Tragfähigkeit** | **hoch** |
|
||||
| **Einschränkung** | Nur Activity vollständig; andere Module direkt im Executor. |
|
||||
|
||||
---
|
||||
|
||||
## Nicht übernehmen
|
||||
|
||||
1. **Parallele Legacy-Import-Endpoints** — `/api/nutrition/import-csv`, `/api/activity/import-csv` neben Universal-Pfad; neue Quellen nur über Universal + Vorlage (ARCHITECTURE §8.2).
|
||||
|
||||
2. **Quellenspezifische Aggregat-Logik im Import** — `sleep_apple_import` als Dauerlösung; Ziel: mapping-nah + Layer 1 (Gitea #69).
|
||||
|
||||
3. **Feldlisten in Routern** — jede neue Spalte nur via `module_registry` + Migration.
|
||||
|
||||
4. **Verschachtelte DB-Connections im Executor** — Pool-Risiko; immer Caller-`cur` durchreichen.
|
||||
|
||||
5. **Transaktion ohne SAVEPOINT bei Multi-Row-Import** — ein Fehler killt gesamten Import + opaque „transaction aborted“.
|
||||
|
||||
6. **Blindes Vorlagen-Delimiter** — regionaler Export bricht Mapping.
|
||||
|
||||
7. **Nutzer-Mappings ohne Validierung** — #71; Copy-from-System muss durch Validator.
|
||||
|
||||
8. **Dry-Run ohne `import_row_processing`** — Admin „Format prüfen“ unvollständig vs. echter Import.
|
||||
|
||||
9. **`source`-CHECK in DB vergessen** — Import setzt `csv`, Constraint muss Migration sein.
|
||||
|
||||
10. **NUMERIC-Overflow durch falsche Einheit** — Schema + `source_unit` + Migrationbreite gemeinsam planen.
|
||||
|
||||
11. **Interpretation/Auswertung beim Import** — Scores, TDEE, Training-Quality nicht in `executor.py`.
|
||||
|
||||
12. **Executor-Monolith ohne Modul-Split** — `executor.py` wächst pro Modul; langfristig Executor-Strategie pro Registry-Key.
|
||||
|
||||
---
|
||||
|
||||
## Modul-Inventar (Ist-Stand)
|
||||
|
||||
```
|
||||
backend/csv_parser/
|
||||
├── module_registry.py # MODULE_DEFINITIONS
|
||||
├── executor.py # run_universal_csv_import
|
||||
├── core.py # decode, delimiter, limits
|
||||
├── type_converter.py
|
||||
├── field_units.py
|
||||
├── import_row_processing.py
|
||||
├── template_validator.py
|
||||
├── import_errors.py
|
||||
├── mapping_suggest.py
|
||||
├── permissions.py
|
||||
└── sleep_apple_import.py # Legacy-Adapter
|
||||
|
||||
backend/routers/
|
||||
├── csv_import.py # Nutzer: modules, analyze, import, mappings
|
||||
└── admin_csv_templates.py # Admin: CRUD + validate
|
||||
|
||||
DB:
|
||||
├── csv_field_mappings
|
||||
└── csv_import_log
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verwandte Dokumentation
|
||||
|
||||
- Agent-Guide (normativ): [UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md](../../technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md)
|
||||
- Registry-Meta: [REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md](./REGISTRY_PLUGIN_DESIGN_PRINCIPLES.md)
|
||||
- Import-Grenze: [ARCHITECTURE.md](../../../rules/ARCHITECTURE.md) §8
|
||||
- Feature-Limits: [FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md](./FEATURE_ENTITLEMENT_DESIGN_PRINCIPLES.md)
|
||||
- Gitea #71: Dry-Run, User-Mapping-Validierung
|
||||
|
||||
---
|
||||
|
||||
## Geplante Folgedokumente (Serie)
|
||||
|
||||
| # | Modul | Status |
|
||||
|---|-------|--------|
|
||||
| 1–5 | … | ✅ |
|
||||
| 6 | Universal Import | ✅ dieses Dokument |
|
||||
| 7 | Dashboard Widgets | ✅ `DASHBOARD_WIDGETS_DESIGN_PRINCIPLES.md` |
|
||||
| 8 | Navigation / IA | ✅ |
|
||||
| 9 | Migration & Deploy | ✅ |
|
||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user