Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 702941ea01 | |||
| a4a50e8aa2 | |||
| 12314cffd9 | |||
| 11bf55994e | |||
| 19d2301eb9 | |||
| b8f4628a1a | |||
| 0c1c1b42a2 | |||
| 3d7482a13b |
@@ -1,9 +1,9 @@
|
|||||||
# Projekt-STATUS — Hermes Rocket.Chat Plugin
|
# Projekt-STATUS — Hermes Rocket.Chat Plugin
|
||||||
> **Stand:** 31. August 2026 — F93 Adaptiver LLM-Timeout implementiert (selbstkalibrierend, Welford + Toleranzband, ersetzt starre 30s)
|
> **Stand:** 31. August 2026 (18:00) — F98-Guided-Setup-Wizard dokumentiert: `12314cf` (feat: Wizard 12 Phasen, Provider-Freiheit, Flow-Spec V1) und `a4a50e8` (fix: Wizard-Review Round 1, 6 Punkte vervollständigt) — beide nach main gepusht, main == origin/main. Davor: Nachzug nach Merge des Reasoning-Fixes: Fachliche Commits `b8f4628` (WV-002, 06:09), `cc41c46` (Fix C/P-168, 07:53, auf Branch `fix/reasoning-glm53-none-mapping` entwickelt — bewusst kein STATUS.md-Nachzug während laufender Agent-Arbeit, Scanner-Alerts 07:30/08:00/08:30 gehandhabt) und `19d2301` (Merge nach main, 09:54) dokumentiert. Vorher: Heartbeat `0c1c1b4` (31.08. 02:08, P-164-Rollover + HTTP-429-Verzögerung)
|
||||||
> **Letzter Commit:** `8b106f5` — feat(F93): Adaptiver LLM-Timeout — selbstkalibrierend (Welford + Toleranzband)
|
> **Letzter fachlicher Commit:** `a4a50e8` — fix(F98): Wizard-Review Round 1 — 6 Punkte vervollständigt (Folge von `12314cf` feat(F98): Guided Setup Wizard + Provider-Freiheit)
|
||||||
> **Gitea-Remote:** ⏳ Lokal voraus — `8b106f5` noch nicht gepusht (KEIN Push vor Rainer-QG, P-078)
|
> **Gitea-Remote:** ✅ Aktuell (main == origin/main synchron, 0/0 — F98-Commits `12314cf`/`a4a50e8` gepusht; zuvor `19d2301`)
|
||||||
> **Deployment:** ⏳ Ausstehend — F93 (`8b106f5`) + `3ad0c55` (adapter.py) + `7a8d0c5`/`1aa028b` (install.sh) + `6def904` (archivar/presence_engine.py — braucht Gateway-Restart) noch nicht auf .101 deployt. Deployment via `install.sh --update-only --no-restart` (P-115). KEIN Gateway-Restart — Bernd macht den Restart per Preflight-Briefing (P-111).
|
> **Deployment:** ⏳ Ausstehend — `3ad0c55` (adapter.py) + `7a8d0c5`/`1aa028b` (install.sh) + `6def904`/`b8f4628` (archivar/presence_engine.py, braucht Gateway-Restart) + `cc41c46` (adapter.py, Fix C/P-168) noch nicht auf .101 deployt. Deployment als Bündel; via `install.sh --update-only --no-restart` (P-115). KEIN Gateway-Restart aus Cron — Bernd macht den Restart per Preflight-Briefing (P-111).
|
||||||
> **Uncommitted:** `_apply_patches.py` + `plugin/archivar/presence_engine.py.bak` (untracked, nicht Teil von F93)
|
> **Uncommitted:** Keine (nach diesem Commit)
|
||||||
> **Deployment-Pfad:** `~/.hermes/plugins/platforms/rocketchat/`
|
> **Deployment-Pfad:** `~/.hermes/plugins/platforms/rocketchat/`
|
||||||
> **Dev-Repo-Pfad:** `~/projekte/Hermes_rocket.chat_Plugin/plugin/`
|
> **Dev-Repo-Pfad:** `~/projekte/Hermes_rocket.chat_Plugin/plugin/`
|
||||||
|
|
||||||
@@ -27,12 +27,18 @@
|
|||||||
|
|
||||||
| Commit | Beschreibung | Datum |
|
| Commit | Beschreibung | Datum |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `8b106f5` | feat(F93): Adaptiver LLM-Timeout — selbstkalibrierend (Welford + Toleranzband, ersetzt starre 30s; 24 A1c-Tests) | 31.08. |
|
| `19d2301` | merge: Fix C (::reasoning Wire-Wert + Probe-Warnung, P-168) nach main | 31.08. |
|
||||||
|
| `cc41c46` | fix(reasoning): ::reasoning status zeigt Wire-Wert + Probe-Warnung (Fix C, P-168; adapter.py + Tests, Branch fix/reasoning-glm53-none-mapping) | 31.08. |
|
||||||
|
| `b8f4628` | fix(presence): WV-002 REST-Exception-Logging verfeinern (_rest_set_status; +319/−18, 218-Z.-Test) (QG Rainer APPROVED) | 31.08. |
|
||||||
|
| `3d7482a` | docs: STATUS.md — Verifikations-Heartbeat 30.08. (P-164-Rollover quittiert) + Docs-Commits 0f8dc6d/562cf11/5a6de60 ergänzt, 29.08.-Reihenfolge korrigiert | 30.08. |
|
||||||
|
| `5a6de60` | docs: STATUS.md — Status-Text-Fix (6def904) + F97-Design-Doku (12b73d3) dokumentiert | 29.08. |
|
||||||
| `12b73d3` | docs: F97 Design-Analyse Kanban-Worker-Presence (Rainer, 40 KB — Basis für F97-Implementierung nach Andreas-Freigabe) | 29.08. |
|
| `12b73d3` | docs: F97 Design-Analyse Kanban-Worker-Presence (Rainer, 40 KB — Basis für F97-Implementierung nach Andreas-Freigabe) | 29.08. |
|
||||||
| `6def904` | fix(presence): GREEN-Phasen sagen 'Hauptagent verfuegbar' statt 'beschaeftigt' (Andreas-Fund 16:14, Rainer-QG APPROVED, 6 Unit-Tests) | 29.08. |
|
| `6def904` | fix(presence): GREEN-Phasen sagen 'Hauptagent verfuegbar' statt 'beschaeftigt' (Andreas-Fund 16:14, Rainer-QG APPROVED, 6 Unit-Tests) | 29.08. |
|
||||||
|
| `562cf11` | docs: STATUS.md — install.sh-Härtungen dokumentiert (P-146/1aa028b-Kopf, 7a8d0c5+1aa028b-Tabelle) | 29.08. |
|
||||||
|
| `1aa028b` | fix(install): P-147 HOME-Absicherung — Agent-Kontext-Guard (guard_home() warnt weich vor Fehl-Deploy ins Profil-Home, P-119-Klasse) | 29.08. |
|
||||||
|
| `0f8dc6d` | docs: STATUS.md — Raum-Routing-Fix dokumentiert (P-108c 3ad0c55 + P-143 7a8d0c5) | 29.08. |
|
||||||
| `3ad0c55` | fix(P-108c): Send-Pfad-Härtung — Antwort-Ziel MUSS Origin-Raum sein (P-145) | 29.08. |
|
| `3ad0c55` | fix(P-108c): Send-Pfad-Härtung — Antwort-Ziel MUSS Origin-Raum sein (P-145) | 29.08. |
|
||||||
| `7a8d0c5` | fix(install): P-143 Toolset-Registrierung nach platform_toolsets.rocketchat statt legacy top-level toolsets | 29.08. |
|
| `7a8d0c5` | fix(install): P-143 Toolset-Registrierung nach platform_toolsets.rocketchat statt legacy top-level toolsets | 29.08. |
|
||||||
| `1aa028b` | fix(install): P-147 HOME-Absicherung — Agent-Kontext-Guard (guard_home() warnt weich vor Fehl-Deploy ins Profil-Home, P-119-Klasse) | 29.08. |
|
|
||||||
| `9746f34` | docs: STATUS.md inhaltlich wiederhergestellt aus 275f067, ergänzt um 22 Commits (26.08.-27.08., inkl. 30681e1+677fdec) | 28.08. |
|
| `9746f34` | docs: STATUS.md inhaltlich wiederhergestellt aus 275f067, ergänzt um 22 Commits (26.08.-27.08., inkl. 30681e1+677fdec) | 28.08. |
|
||||||
| `677fdec` | docs: Rainer-Architekturanalysen hinzugefügt (Butler-Lernkonzept V1+V2, P-108 Szenario B) | 27.08. |
|
| `677fdec` | docs: Rainer-Architekturanalysen hinzugefügt (Butler-Lernkonzept V1+V2, P-108 Szenario B) | 27.08. |
|
||||||
| `30681e1` | fix(install): P-116 Stale-Check um Timestamp ergänzt | 27.08. |
|
| `30681e1` | fix(install): P-116 Stale-Check um Timestamp ergänzt | 27.08. |
|
||||||
|
|||||||
+640
-27
@@ -51,6 +51,9 @@ MIGRATE_ONLY=false
|
|||||||
MIGRATE_TO_VENV=false
|
MIGRATE_TO_VENV=false
|
||||||
MIGRATE_TO_OFFICIAL=false
|
MIGRATE_TO_OFFICIAL=false
|
||||||
REPAIR=false
|
REPAIR=false
|
||||||
|
GUIDED=false
|
||||||
|
GUIDED_DEFAULTS=false
|
||||||
|
RESUME=false
|
||||||
|
|
||||||
# Farben (nur wenn Terminal)
|
# Farben (nur wenn Terminal)
|
||||||
if [ -t 1 ]; then
|
if [ -t 1 ]; then
|
||||||
@@ -60,10 +63,21 @@ else
|
|||||||
C_RESET=""; C_BLUE=""; C_GREEN=""; C_YELLOW=""; C_RED=""; C_BOLD=""
|
C_RESET=""; C_BLUE=""; C_GREEN=""; C_YELLOW=""; C_RED=""; C_BOLD=""
|
||||||
fi
|
fi
|
||||||
|
|
||||||
log() { printf '%s[+]%s %s\n' "$C_BLUE" "$C_RESET" "$*"; }
|
# ── Secret-Maskierung (Flow-Spec §3.3). Filtert Secrets aus Log-Output. ──
|
||||||
warn() { printf '%s[!]%s %s\n' "$C_YELLOW" "$C_RESET" "$*"; }
|
# Defense-in-Depth: wird von log/warn/err/ok VOR jedem printf aufgerufen,
|
||||||
err() { printf '%s[!]%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; }
|
# ergänzend zu `read -s`. NIEMALS Klartext-Secrets in stdout/stderr.
|
||||||
ok() { printf '%s[+]%s %s\n' "$C_GREEN" "$C_RESET" "$*"; }
|
mask_secrets() {
|
||||||
|
local s="$1"
|
||||||
|
for v in "$OPENROUTER_API_KEY" "$OLLAMA_CLOUD_API_KEY" "$ROCKETCHAT_PASSWORD" "$CLOUD_KEY_VAL"; do
|
||||||
|
[ -n "$v" ] && s="${s//$v/***masked***}"
|
||||||
|
done
|
||||||
|
printf '%s' "$s"
|
||||||
|
}
|
||||||
|
|
||||||
|
log() { printf '%s[+]%s %s\n' "$C_BLUE" "$C_RESET" "$(mask_secrets "$*")"; }
|
||||||
|
warn() { printf '%s[!]%s %s\n' "$C_YELLOW" "$C_RESET" "$(mask_secrets "$*")"; }
|
||||||
|
err() { printf '%s[!]%s %s\n' "$C_RED" "$C_RESET" "$(mask_secrets "$*")" >&2; }
|
||||||
|
ok() { printf '%s[+]%s %s\n' "$C_GREEN" "$C_RESET" "$(mask_secrets "$*")"; }
|
||||||
banner() { printf '\n%s━━━ %s ━━━%s\n' "$C_BOLD" "$*" "$C_RESET"; }
|
banner() { printf '\n%s━━━ %s ━━━%s\n' "$C_BOLD" "$*" "$C_RESET"; }
|
||||||
die() { err "$*"; exit 1; }
|
die() { err "$*"; exit 1; }
|
||||||
|
|
||||||
@@ -1014,9 +1028,31 @@ write_config_yaml() {
|
|||||||
log "Backup: $config.bak.*"
|
log "Backup: $config.bak.*"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# P6/P7: provider und model explizit aus env
|
# F98 Provider-Freiheit: provider aus Detection (P1-P6), NICHT hardcoded.
|
||||||
local provider="ollama-cloud"
|
# Root-Cause A (V1.3-korrigiert §2.1): hardcoded provider="ollama-cloud"
|
||||||
# KEINE base_url für ollama-cloud (nicht nötig) — bewusst weggelassen!
|
# machte nicht-ollama-cloud unmöglich. Jetzt: detect_provider() liefert
|
||||||
|
# PROVIDER + PROVIDER_BASE_URL + PROVIDER_NEEDS_KEY.
|
||||||
|
# Guard: wenn der Wizard bereits einen Provider gesetzt hat (P6-Auswahl),
|
||||||
|
# NICHT erneut detektieren — sonst wird die User-Wahl überschrieben.
|
||||||
|
if [ -z "${PROVIDER:-}" ]; then
|
||||||
|
detect_provider
|
||||||
|
fi
|
||||||
|
local provider="$PROVIDER"
|
||||||
|
local provider_base_url="$PROVIDER_BASE_URL"
|
||||||
|
# base_url nur bei custom/ollama (lokal) — ollama-cloud/openrouter brauchen keine.
|
||||||
|
local base_url_line=""
|
||||||
|
if [ -n "$provider_base_url" ]; then
|
||||||
|
base_url_line=" base_url: ${provider_base_url}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# providers-Block: nur bei Cloud-Providern (openrouter/ollama-cloud) einen
|
||||||
|
# leeren Eintrag; bei lokal/custom bleibt der Block leer (Root-Cause B).
|
||||||
|
local providers_block=""
|
||||||
|
case "$provider" in
|
||||||
|
openrouter|ollama-cloud) providers_block="providers:
|
||||||
|
${provider}: {}" ;;
|
||||||
|
*) providers_block="providers: {}" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
# YAML generieren. Wir nutzen eine Heredoc mit $-Expansion, weil wir
|
# YAML generieren. Wir nutzen eine Heredoc mit $-Expansion, weil wir
|
||||||
# alle Werte kontrollieren (keine User-Eingabe mit Sonderzeichen).
|
# alle Werte kontrollieren (keine User-Eingabe mit Sonderzeichen).
|
||||||
@@ -1029,11 +1065,10 @@ model:
|
|||||||
default: ${MODEL_NAME}
|
default: ${MODEL_NAME}
|
||||||
provider: ${provider}
|
provider: ${provider}
|
||||||
context_length: ${CONTEXT_LENGTH}
|
context_length: ${CONTEXT_LENGTH}
|
||||||
|
${base_url_line}
|
||||||
# api_key wird über .env (OLLAMA_API_KEY) injiziert
|
# api_key wird über .env (OLLAMA_API_KEY) injiziert
|
||||||
# KEINE base_url für ollama-cloud (nicht nötig)
|
|
||||||
|
|
||||||
providers:
|
${providers_block}
|
||||||
ollama-cloud: {}
|
|
||||||
|
|
||||||
# P-143: KEINE top-level toolsets:-Sektion mehr schreiben. Die legacy
|
# P-143: KEINE top-level toolsets:-Sektion mehr schreiben. Die legacy
|
||||||
# top-level toolsets:-Sektion wird von Hermes in platform_toolsets.cli
|
# top-level toolsets:-Sektion wird von Hermes in platform_toolsets.cli
|
||||||
@@ -1041,8 +1076,8 @@ providers:
|
|||||||
# Das rocketchat-Toolset gehört nach platform_toolsets.rocketchat
|
# Das rocketchat-Toolset gehört nach platform_toolsets.rocketchat
|
||||||
# (siehe ensure_toolset()).
|
# (siehe ensure_toolset()).
|
||||||
|
|
||||||
# P2: auxiliary-Provider explizit auf ollama-cloud setzen.
|
# F98: auxiliary-Provider folgt dem erkannten Provider (Root-Cause C).
|
||||||
# Verhindert Auto-Discovery-Chain (openrouter/Nous → payment errors + Timeout).
|
# KEIN hardcoded ollama-cloud mehr — lokale Inference wird respektiert.
|
||||||
auxiliary:
|
auxiliary:
|
||||||
vision:
|
vision:
|
||||||
provider: ${provider}
|
provider: ${provider}
|
||||||
@@ -1239,8 +1274,14 @@ write_env_file() {
|
|||||||
echo "# P4: Diese Datei ist MASCHINENSPEZIFISCH — niemals zwischen Maschinen kopieren!"
|
echo "# P4: Diese Datei ist MASCHINENSPEZIFISCH — niemals zwischen Maschinen kopieren!"
|
||||||
echo "# Rocketchat-Bot-Identität: ${ROCKETCHAT_USER}@${ROCKETCHAT_BASE_URL}"
|
echo "# Rocketchat-Bot-Identität: ${ROCKETCHAT_USER}@${ROCKETCHAT_BASE_URL}"
|
||||||
echo ""
|
echo ""
|
||||||
echo "# ── Cloud-LLM (ollama-cloud) ──"
|
# F98: Provider-abhängiger Key (Root-Cause D). Bei lokalem Ollama/custom
|
||||||
echo "OLLAMA_API_KEY=${OLLAMA_CLOUD_API_KEY}"
|
# (P1/P2) KEIN Cloud-Key. Bei openrouter → OPENROUTER_API_KEY,
|
||||||
|
# bei ollama-cloud → OLLAMA_API_KEY.
|
||||||
|
case "${PROVIDER:-ollama-cloud}" in
|
||||||
|
openrouter) echo "# ── Cloud-LLM (openrouter) ──"; echo "OPENROUTER_API_KEY=${OPENROUTER_API_KEY:-}" ;;
|
||||||
|
ollama-cloud) echo "# ── Cloud-LLM (ollama-cloud) ──"; echo "OLLAMA_API_KEY=${OLLAMA_CLOUD_API_KEY:-}" ;;
|
||||||
|
*) echo "# ── Lokale Inference (${PROVIDER:-ollama}) — kein Cloud-Key ──" ;;
|
||||||
|
esac
|
||||||
echo ""
|
echo ""
|
||||||
echo "# ── Archivar (lokal) ──"
|
echo "# ── Archivar (lokal) ──"
|
||||||
echo "# P8: LLM/Embeddings laufen lokal via Ollama, NICHT über die Cloud."
|
echo "# P8: LLM/Embeddings laufen lokal via Ollama, NICHT über die Cloud."
|
||||||
@@ -1592,12 +1633,17 @@ verify_installation() {
|
|||||||
local config="$HOME/.hermes/config.yaml"
|
local config="$HOME/.hermes/config.yaml"
|
||||||
if [ -f "$config" ] && "$VENV_PY" -c "import yaml; yaml.safe_load(open('$config'))" 2>/dev/null; then
|
if [ -f "$config" ] && "$VENV_PY" -c "import yaml; yaml.safe_load(open('$config'))" 2>/dev/null; then
|
||||||
ok "config.yaml syntaktisch korrekt"
|
ok "config.yaml syntaktisch korrekt"
|
||||||
# P6/P7: Provider und Modell prüfen
|
# F98: Provider-Vergleich statt String-Gleichheit (Root-Cause I).
|
||||||
if grep -q "^ provider: ollama-cloud" "$config"; then
|
# Akzeptiert jeden der gültigen Provider (ollama, custom, openrouter,
|
||||||
ok "provider=ollama-cloud (P6)"
|
# ollama-cloud) — KEIN hardcoded ollama-cloud-Check mehr.
|
||||||
else
|
local cfg_provider
|
||||||
err "FAIL: provider nicht ollama-cloud (P6)"; fail=1
|
cfg_provider="$("$VENV_PY" -c "import yaml;print(yaml.safe_load(open('$config')).get('model',{}).get('provider',''))" 2>/dev/null || echo "")"
|
||||||
fi
|
case "$cfg_provider" in
|
||||||
|
ollama|custom|openrouter|ollama-cloud)
|
||||||
|
ok "provider=$cfg_provider (F98: gültig)" ;;
|
||||||
|
*)
|
||||||
|
err "FAIL: provider '$cfg_provider' ungültig (F98: erwartet ollama|custom|openrouter|ollama-cloud)"; fail=1 ;;
|
||||||
|
esac
|
||||||
if grep -q "^ default: ${MODEL_NAME}$" "$config"; then
|
if grep -q "^ default: ${MODEL_NAME}$" "$config"; then
|
||||||
ok "model=${MODEL_NAME} (P7)"
|
ok "model=${MODEL_NAME} (P7)"
|
||||||
else
|
else
|
||||||
@@ -2134,6 +2180,521 @@ repair_components() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ══════════════════════════════════════════════════════════════════════════
|
||||||
|
# F98 — Provider-Freiheit (P1-P6 Detection) + Guided Setup Wizard
|
||||||
|
# Additive Schicht. KEIN Provider-/Cloud-/Key-Zwang (Andreas-Direktive 31.08.).
|
||||||
|
# Detection-Reihenfolge P1-P6 (Flow-Spec V1 §0.4 / V1.3-korrigiert §3.1):
|
||||||
|
# P1 lokales Ollama (localhost:11434) → provider=ollama, KEIN Key
|
||||||
|
# P2 DGX Spark (.46:7999) → provider=custom, KEIN Key
|
||||||
|
# P3 openrouter (User-env) → provider=openrouter, Key
|
||||||
|
# P4 ollama.cloud (User-env) → provider=ollama-cloud, Key
|
||||||
|
# P5 Custom OpenAI-kompatibel (env) → provider=custom, Key
|
||||||
|
# P6 nichts erkannt → Empfehlungs-Block, KEIN Abbruch
|
||||||
|
# ══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
# ── Provider-Detection (P1-P6). Setzt globale Variablen: ──
|
||||||
|
# PROVIDER (ollama|custom|openrouter|ollama-cloud|none)
|
||||||
|
# PROVIDER_BASE_URL (leer bei ollama-cloud)
|
||||||
|
# PROVIDER_NEEDS_KEY (true|false)
|
||||||
|
# LOCAL_INFERENCE_AVAILABLE (true|false)
|
||||||
|
# DETECTED_PROVIDER (P1..P6 oder "manual")
|
||||||
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
|
detect_provider() {
|
||||||
|
# Priorität 2: User-env (HERMES_PROVIDER / explizite Keys) — respektiert.
|
||||||
|
if [ -n "${HERMES_PROVIDER:-}" ]; then
|
||||||
|
case "$HERMES_PROVIDER" in
|
||||||
|
ollama) PROVIDER="ollama"; PROVIDER_BASE_URL="http://localhost:11434"; PROVIDER_NEEDS_KEY=false; DETECTED_PROVIDER="manual"; LOCAL_INFERENCE_AVAILABLE=true; return 0 ;;
|
||||||
|
openrouter) PROVIDER="openrouter"; PROVIDER_BASE_URL=""; PROVIDER_NEEDS_KEY=true; DETECTED_PROVIDER="manual"; LOCAL_INFERENCE_AVAILABLE=false; return 0 ;;
|
||||||
|
ollama-cloud) PROVIDER="ollama-cloud"; PROVIDER_BASE_URL=""; PROVIDER_NEEDS_KEY=true; DETECTED_PROVIDER="manual"; LOCAL_INFERENCE_AVAILABLE=false; return 0 ;;
|
||||||
|
custom) PROVIDER="custom"; PROVIDER_BASE_URL="${HERMES_BASE_URL:-}"; PROVIDER_NEEDS_KEY=true; DETECTED_PROVIDER="manual"; LOCAL_INFERENCE_AVAILABLE=false; return 0 ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
if [ -n "${OPENROUTER_API_KEY:-}" ]; then
|
||||||
|
PROVIDER="openrouter"; PROVIDER_BASE_URL=""; PROVIDER_NEEDS_KEY=true; DETECTED_PROVIDER="P3"; LOCAL_INFERENCE_AVAILABLE=false; return 0
|
||||||
|
fi
|
||||||
|
if [ -n "${OLLAMA_CLOUD_API_KEY:-}" ]; then
|
||||||
|
PROVIDER="ollama-cloud"; PROVIDER_BASE_URL=""; PROVIDER_NEEDS_KEY=true; DETECTED_PROVIDER="P4"; LOCAL_INFERENCE_AVAILABLE=false; return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# P1: lokales Ollama
|
||||||
|
if curl -fsS --max-time 2 http://localhost:11434/api/version >/dev/null 2>&1; then
|
||||||
|
PROVIDER="ollama"; PROVIDER_BASE_URL="http://localhost:11434"; PROVIDER_NEEDS_KEY=false; DETECTED_PROVIDER="P1"; LOCAL_INFERENCE_AVAILABLE=true; return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# P2: DGX Spark (.46:7999)
|
||||||
|
if curl -fsS --max-time 2 http://192.168.180.46:7999/v1/models >/dev/null 2>&1; then
|
||||||
|
PROVIDER="custom"; PROVIDER_BASE_URL="http://192.168.180.46:7999/v1"; PROVIDER_NEEDS_KEY=false; DETECTED_PROVIDER="P2"; LOCAL_INFERENCE_AVAILABLE=true; return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# P6: nichts erkannt
|
||||||
|
PROVIDER="none"; PROVIDER_BASE_URL=""; PROVIDER_NEEDS_KEY=false; DETECTED_PROVIDER="P6"; LOCAL_INFERENCE_AVAILABLE=false
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Layout-Detection (V1.3-korrigiert §7.7). Setzt DETECTED_LAYOUT. ──
|
||||||
|
# pipx | user_space | root_fhs
|
||||||
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
|
detect_install_layout() {
|
||||||
|
if [ -d "/usr/local/lib/hermes-agent" ]; then
|
||||||
|
DETECTED_LAYOUT="root_fhs"
|
||||||
|
elif [ -d "$HOME/.local/share/pipx/venvs/hermes-agent" ]; then
|
||||||
|
DETECTED_LAYOUT="pipx"
|
||||||
|
elif [ -d "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||||
|
DETECTED_LAYOUT="user_space"
|
||||||
|
else
|
||||||
|
DETECTED_LAYOUT="unknown"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Install-State-Persistenz (Flow-Spec §Phase 9.3). ──
|
||||||
|
# Schreibt nach jeder Phase den Fortschritt nach
|
||||||
|
# /tmp/hermes-install-state-<ts>.json, damit --guided --resume den
|
||||||
|
# halb-installierten Zustand erkennt und ab der richtigen Phase fortsetzt.
|
||||||
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
|
INSTALL_STATE_FILE="${INSTALL_STATE_FILE:-/tmp/hermes-install-state.json}"
|
||||||
|
INSTALL_PHASE_LAST_DONE="${INSTALL_PHASE_LAST_DONE:-0}"
|
||||||
|
|
||||||
|
mark_phase() {
|
||||||
|
# mark_phase <phase_num> <label>
|
||||||
|
INSTALL_PHASE_LAST_DONE="$1"
|
||||||
|
if ! ${DRY_RUN:-false}; then
|
||||||
|
printf '{"phase":%s,"label":"%s","ts":%s}\n' "$1" "$2" "$(date +%s)" > "$INSTALL_STATE_FILE" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
read_install_state() {
|
||||||
|
# Liest den letzten abgeschlossenen Phase-Index aus dem State-File.
|
||||||
|
if [ -f "$INSTALL_STATE_FILE" ]; then
|
||||||
|
INSTALL_PHASE_LAST_DONE="$(python3 -c 'import sys,json;print(json.load(open(sys.argv[1])).get("phase",0))' "$INSTALL_STATE_FILE" 2>/dev/null || echo "0")"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Secret-Maskierung (Flow-Spec §3.3). Filtert Secrets aus Log-Output. ──
|
||||||
|
# (Definition oben bei den log-Helfern; hier nur Referenz-Kommentar.)
|
||||||
|
|
||||||
|
# ══════════════════════════════════════════════════════════════════════════
|
||||||
|
# F98 — Guided Setup Wizard (12 Phasen, Flow-Spec V1)
|
||||||
|
#
|
||||||
|
# Additive Schicht: sammelt alle Werte in die bestehenden env-Variablen,
|
||||||
|
# dann läuft der bestehende Hauptfluss (install_system_deps → ... →
|
||||||
|
# verify_installation) unverändert weiter. KEIN separater Installer.
|
||||||
|
#
|
||||||
|
# Selbsterklärend-Regel (Flow-Spec §0.1): JEDE Frage hat
|
||||||
|
# 1. WAS-Erklärung 2. Standard-Ausweich-Option 3. Live-Rückmeldung
|
||||||
|
# 4. Defizit-Sammlung 5. KEIN Abbruch ohne Cloud-Key.
|
||||||
|
# ══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
# ── Sprach-Pack (DE/EN) — Single Source of Truth für Wizard-Texte. ──
|
||||||
|
declare -A T
|
||||||
|
T[de_banner]="Hermes Rocket.Chat Plugin — Geführte Installation"
|
||||||
|
T[en_banner]="Hermes Rocket.Chat Plugin — Guided Setup"
|
||||||
|
T[de_lang_q]="Bitte Sprache wählen / Please select language: 1) Deutsch 2) English"
|
||||||
|
T[en_lang_q]="Please select language: 1) Deutsch 2) English"
|
||||||
|
T[de_lang_ok]="Sprache: Deutsch"
|
||||||
|
T[en_lang_ok]="Language: English"
|
||||||
|
T[de_multiroom_q]="Wird ein Multiroom-Agent benötigt? Y) Ja — Bot routet mehrere Themenräume (Archivar aktiv) N) Nein — Single-Room-Modus (nur 1 Raum, Archivar deaktiviert)"
|
||||||
|
T[en_multiroom_q]="Do you need a multiroom agent? Y) Yes — bot routes multiple topic rooms (Archivar active) N) No — single-room mode (1 room only, Archivar disabled)"
|
||||||
|
T[de_multiroom_ok]="Multiroom: Ja"
|
||||||
|
T[en_multiroom_ok]="Multiroom: Yes"
|
||||||
|
T[de_multiroom_no]="Multiroom: Nein (Single-Room-Modus)"
|
||||||
|
T[en_multiroom_no]="Multiroom: No (single-room mode)"
|
||||||
|
T[de_rc_url_q]="Rocket.Chat-Server-URL?"
|
||||||
|
T[en_rc_url_q]="Rocket.Chat server URL?"
|
||||||
|
T[de_rc_user_q]="Bot-Username?"
|
||||||
|
T[en_rc_user_q]="Bot username?"
|
||||||
|
T[de_rc_pw_q]="Bot-Kennwort (Eingabe unsichtbar)?"
|
||||||
|
T[en_rc_pw_q]="Bot password (hidden input)?"
|
||||||
|
T[de_rc_home_q]="An welchen User soll der Bot standardmäßig antworten (DM-Homechannel)?"
|
||||||
|
T[en_rc_home_q]="Which user should the bot answer by default (DM home channel)?"
|
||||||
|
T[de_connected]="verbunden"
|
||||||
|
T[en_connected]="connected"
|
||||||
|
T[de_angemeldet]="angemeldet"
|
||||||
|
T[en_angemeldet]="logged in"
|
||||||
|
T[de_gesetzt]="gesetzt"
|
||||||
|
T[en_gesetzt]="set"
|
||||||
|
T[de_fehlt]="fehlt"
|
||||||
|
T[en_fehlt]="missing"
|
||||||
|
T[de_erkannt]="erkannt"
|
||||||
|
T[en_erkannt]="detected"
|
||||||
|
T[de_skip]="Später konfigurieren"
|
||||||
|
T[en_skip]="Configure later"
|
||||||
|
|
||||||
|
# ── Prompt-Helfer: fragt mit Default + Ausweich-Option. ──
|
||||||
|
# ask <varname> <prompt> <default> <allow_skip>
|
||||||
|
# Setzt die globale Variable <varname>. Bei --defaults: Default ohne Prompt.
|
||||||
|
# Bei leerer Eingabe + allow_skip: setzt "SKIP" (Ausweich, kein Abbruch).
|
||||||
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
|
ask() {
|
||||||
|
local varname="$1" prompt="$2" default="$3" allow_skip="${4:-false}"
|
||||||
|
local val="$default"
|
||||||
|
if $GUIDED_DEFAULTS; then
|
||||||
|
# Secret-Maskierung (Flow-Spec §3.3): Passwort/Key nie im Klartext loggen.
|
||||||
|
local shown_val="$val"
|
||||||
|
case "$varname" in
|
||||||
|
RC_BOT_PASSWORD|CLOUD_KEY|CLOUD_KEY_VAL) [ -n "$val" ] && shown_val="***maskiert***" ;;
|
||||||
|
esac
|
||||||
|
printf '%s[guided-defaults]%s %s = %s\n' "$C_YELLOW" "$C_RESET" "$varname" "$shown_val"
|
||||||
|
eval "$varname=\"$val\""
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
local shown=""
|
||||||
|
[ -n "$default" ] && shown=" [$default]"
|
||||||
|
printf '%s[?]%s %s%s: ' "$C_BLUE" "$C_RESET" "$prompt" "$shown"
|
||||||
|
local input
|
||||||
|
if [ "$varname" = "RC_BOT_PASSWORD" ] || [ "$varname" = "CLOUD_KEY" ]; then
|
||||||
|
read -rs input
|
||||||
|
echo ""
|
||||||
|
else
|
||||||
|
read -r input
|
||||||
|
fi
|
||||||
|
if [ -z "$input" ]; then
|
||||||
|
if [ -n "$default" ]; then
|
||||||
|
val="$default"
|
||||||
|
elif $allow_skip; then
|
||||||
|
val="SKIP"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
val="$input"
|
||||||
|
fi
|
||||||
|
eval "$varname=\"$val\""
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Wizard-Hauptfunktion. Führt Phasen 0-11 aus, setzt env-Variablen. ──
|
||||||
|
run_guided_wizard() {
|
||||||
|
banner "Hermes Rocket.Chat Plugin — Geführte Installation (F98)"
|
||||||
|
|
||||||
|
# ── Phase 0: Sprachauswahl ──
|
||||||
|
local lang_default="1"
|
||||||
|
case "${LANG:-}" in
|
||||||
|
de_*) lang_default="1" ;;
|
||||||
|
*) lang_default="2" ;;
|
||||||
|
esac
|
||||||
|
if $GUIDED_DEFAULTS; then
|
||||||
|
LANG_CHOICE="de"; [ "$lang_default" = "2" ] && LANG_CHOICE="en"
|
||||||
|
printf '%s[guided-defaults]%s Sprache: %s\n' "$C_YELLOW" "$C_RESET" "$LANG_CHOICE"
|
||||||
|
else
|
||||||
|
printf '%s[?]%s %s [%s]: ' "$C_BLUE" "$C_RESET" "${T[de_lang_q]}" "$lang_default"
|
||||||
|
read -r _lang_in
|
||||||
|
[ -z "$_lang_in" ] && _lang_in="$lang_default"
|
||||||
|
if [ "$_lang_in" = "1" ]; then LANG_CHOICE="de"; else LANG_CHOICE="en"; fi
|
||||||
|
fi
|
||||||
|
ok "[${T[${LANG_CHOICE}_lang_ok]}]"
|
||||||
|
mark_phase 0 "sprache"
|
||||||
|
|
||||||
|
# ── Phase 1: System-Analyse + Provider-Detection ──
|
||||||
|
banner "System-Analyse"
|
||||||
|
detect_install_layout
|
||||||
|
detect_provider
|
||||||
|
ok "[Layout: $DETECTED_LAYOUT]"
|
||||||
|
case "$DETECTED_PROVIDER" in
|
||||||
|
P1) ok "[Provider erkannt: lokales Ollama (localhost:11434)]" ;;
|
||||||
|
P2) ok "[Provider erkannt: DGX Spark (192.168.180.46:7999)]" ;;
|
||||||
|
P3) ok "[Provider: openrouter (aus env)]" ;;
|
||||||
|
P4) ok "[Provider: ollama-cloud (aus env)]" ;;
|
||||||
|
manual) ok "[Provider: manuell ($PROVIDER)]" ;;
|
||||||
|
P6) warn "[Kein Provider erkannt — Empfehlungs-Block folgt]" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# P6: Empfehlungs-Block (KEIN Abbruch).
|
||||||
|
if [ "$DETECTED_PROVIDER" = "P6" ]; then
|
||||||
|
echo ""
|
||||||
|
echo "Empfohlene Reihenfolge:"
|
||||||
|
echo " 1) openrouter (Cloud-Key erforderlich)"
|
||||||
|
echo " 2) ollama.cloud (Cloud-Key erforderlich)"
|
||||||
|
echo " 3) Custom OpenAI-kompatibel (z.B. eigener llama.cpp-Server)"
|
||||||
|
echo " 4) Lokales Ollama nachinstallieren (empfohlen, falls möglich)"
|
||||||
|
ask PROVIDER_CHOICE "Welchen Provider möchten Sie?" "1" false
|
||||||
|
case "$PROVIDER_CHOICE" in
|
||||||
|
1) PROVIDER="openrouter"; PROVIDER_NEEDS_KEY=true ;;
|
||||||
|
2) PROVIDER="ollama-cloud"; PROVIDER_NEEDS_KEY=true ;;
|
||||||
|
3) PROVIDER="custom"; PROVIDER_NEEDS_KEY=true ;;
|
||||||
|
4) PROVIDER="ollama"; PROVIDER_BASE_URL="http://localhost:11434"; PROVIDER_NEEDS_KEY=false; LOCAL_INFERENCE_AVAILABLE=true ;;
|
||||||
|
*) PROVIDER="openrouter"; PROVIDER_NEEDS_KEY=true ;;
|
||||||
|
esac
|
||||||
|
ok "[Provider gewählt: $PROVIDER]"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Phase 2: Profil ──
|
||||||
|
ask PROFILE "Welches Profil? 1) Produktion (24/7) 2) Test/Dev" "1" false
|
||||||
|
if [ "$PROFILE" = "2" ]; then
|
||||||
|
LOG_LEVEL="DEBUG"; ROCKETCHAT_PING_SEC="3"; ROCKETCHAT_IDLE_SEC="300"
|
||||||
|
else
|
||||||
|
LOG_LEVEL="INFO"; ROCKETCHAT_PING_SEC="8"; ROCKETCHAT_IDLE_SEC="900"
|
||||||
|
fi
|
||||||
|
ok "[Profil: $([ "$PROFILE" = "2" ] && echo Test/Dev || echo Produktion)]"
|
||||||
|
|
||||||
|
# ── Phase 3: Multiroom ──
|
||||||
|
ask MULTIROOM_ANS "Wird ein Multiroom-Agent benötigt? Y) Ja N) Nein" "N" false
|
||||||
|
case "$MULTIROOM_ANS" in
|
||||||
|
Y|y|J|j|1) RC_MULTIROOM="true"; ok "[${T[${LANG_CHOICE}_multiroom_ok]}]" ;;
|
||||||
|
*) RC_MULTIROOM="false"; ok "[${T[${LANG_CHOICE}_multiroom_no]}]" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# ── Phase 4: RC-Verbindung (Einzelfragen mit LIVE-Tests) ──
|
||||||
|
banner "Rocket.Chat-Verbindung"
|
||||||
|
# 4.1 URL
|
||||||
|
ask RC_URL "${T[${LANG_CHOICE}_rc_url_q]}" "$ROCKETCHAT_BASE_URL" true
|
||||||
|
if [ "$RC_URL" = "SKIP" ]; then
|
||||||
|
warn "[RC-Verbindung übersprungen — später via .env konfigurierbar]"
|
||||||
|
PENDING_RC_CONFIG=true
|
||||||
|
else
|
||||||
|
ROCKETCHAT_BASE_URL="$RC_URL"
|
||||||
|
# LIVE-Test: /api/info
|
||||||
|
local rc_http
|
||||||
|
rc_http="$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 "${RC_URL}/api/info" 2>/dev/null || echo "000")"
|
||||||
|
if [ "$rc_http" = "200" ]; then
|
||||||
|
ok "[${T[${LANG_CHOICE}_connected]}: 200 OK]"
|
||||||
|
else
|
||||||
|
warn "[Verbindung fehlgeschlagen (HTTP $rc_http) — URL prüfen, Server offline oder Firewall]"
|
||||||
|
ask RC_RETRY "Möchten Sie [W]iederholen / [A]ndern / [Ü]berspringen?" "W" false
|
||||||
|
case "$RC_RETRY" in
|
||||||
|
Ü|U|S|s) PENDING_RC_CONFIG=true ;;
|
||||||
|
*) ask RC_URL "${T[${LANG_CHOICE}_rc_url_q]}" "$ROCKETCHAT_BASE_URL" true; ROCKETCHAT_BASE_URL="$RC_URL" ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4.2 Bot-Username
|
||||||
|
ask RC_BOT_USER "${T[${LANG_CHOICE}_rc_user_q]}" "$ROCKETCHAT_USER" true
|
||||||
|
[ "$RC_BOT_USER" != "SKIP" ] && ROCKETCHAT_USER="$RC_BOT_USER"
|
||||||
|
|
||||||
|
# 4.3 Kennwort (sicher, read -s)
|
||||||
|
ask RC_BOT_PASSWORD "${T[${LANG_CHOICE}_rc_pw_q]}" "$ROCKETCHAT_PASSWORD" true
|
||||||
|
if [ "$RC_BOT_PASSWORD" != "SKIP" ] && [ -n "$RC_BOT_PASSWORD" ]; then
|
||||||
|
ROCKETCHAT_PASSWORD="$RC_BOT_PASSWORD"
|
||||||
|
ok "[${T[${LANG_CHOICE}_gesetzt]}: Kennwort]"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4.2b LIVE-Login-Test (Flow-Spec §Phase 4.2): /api/v1/login → userId.
|
||||||
|
# Fehlerzweig 4.2 (401): Dialog zurück zur Eingabe, KEIN Abbruch.
|
||||||
|
if [ "$PENDING_RC_CONFIG" != "true" ] && [ -n "$ROCKETCHAT_USER" ] && [ -n "$ROCKETCHAT_PASSWORD" ]; then
|
||||||
|
local login_resp login_status login_userid login_token
|
||||||
|
login_resp="$(curl -s --max-time 10 -X POST "${ROCKETCHAT_BASE_URL}/api/v1/login" \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d "{\"user\":\"$ROCKETCHAT_USER\",\"password\":\"$ROCKETCHAT_PASSWORD\"}" 2>/dev/null || echo '')"
|
||||||
|
login_status="$(printf '%s' "$login_resp" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("status",""))' 2>/dev/null || echo '')"
|
||||||
|
login_userid="$(printf '%s' "$login_resp" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("data",{}).get("userId",""))' 2>/dev/null || echo '')"
|
||||||
|
login_token="$(printf '%s' "$login_resp" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("data",{}).get("authToken",""))' 2>/dev/null || echo '')"
|
||||||
|
if [ "$login_status" = "success" ] && [ -n "$login_userid" ]; then
|
||||||
|
ROCKETCHAT_USER_ID="$login_userid"
|
||||||
|
ROCKETCHAT_AUTH_TOKEN="$login_token"
|
||||||
|
ok "[${T[${LANG_CHOICE}_angemeldet]}: $ROCKETCHAT_USER, user_id=$ROCKETCHAT_USER_ID]"
|
||||||
|
else
|
||||||
|
warn "[401/Login fehlgeschlagen — Username oder Kennwort falsch]"
|
||||||
|
ask RC_LOGIN_RETRY "Möchten Sie [U]ser erneut / [K]ennwort erneut / [Ü]berspringen?" "U" false
|
||||||
|
case "$RC_LOGIN_RETRY" in
|
||||||
|
K|k) ask RC_BOT_PASSWORD "${T[${LANG_CHOICE}_rc_pw_q]}" "" true; [ "$RC_BOT_PASSWORD" != "SKIP" ] && ROCKETCHAT_PASSWORD="$RC_BOT_PASSWORD" ;;
|
||||||
|
Ü|U|S|s) PENDING_RC_CONFIG=true ;;
|
||||||
|
*) ask RC_BOT_USER "${T[${LANG_CHOICE}_rc_user_q]}" "$ROCKETCHAT_USER" true; [ "$RC_BOT_USER" != "SKIP" ] && ROCKETCHAT_USER="$RC_BOT_USER" ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4.4 DM-Homechannel-Username → users.info → User-ID + DM-Room-ID (Flow-Spec §Phase 4.4).
|
||||||
|
ask HOME_USER "${T[${LANG_CHOICE}_rc_home_q]}" "" true
|
||||||
|
if [ "$HOME_USER" != "SKIP" ] && [ -n "$HOME_USER" ]; then
|
||||||
|
ROCKETCHAT_HOME_CHANNEL="$HOME_USER"
|
||||||
|
local home_resp home_userid home_dmid
|
||||||
|
home_resp="$(curl -s --max-time 10 "${ROCKETCHAT_BASE_URL}/api/v1/users.info?username=$HOME_USER" \
|
||||||
|
-H "X-User-Id: ${ROCKETCHAT_USER_ID:-}" -H "X-Auth-Token: ${ROCKETCHAT_AUTH_TOKEN:-}" 2>/dev/null || echo '')"
|
||||||
|
home_userid="$(printf '%s' "$home_resp" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("user",{}).get("_id",""))' 2>/dev/null || echo '')"
|
||||||
|
if [ -n "$home_userid" ]; then
|
||||||
|
HOME_USER_ID="$home_userid"
|
||||||
|
# DM-Room-ID via im.create (best effort — nicht blockierend).
|
||||||
|
local dm_resp
|
||||||
|
dm_resp="$(curl -s --max-time 10 -X POST "${ROCKETCHAT_BASE_URL}/api/v1/im.create" \
|
||||||
|
-H 'Content-Type: application/json' -H "X-User-Id: ${ROCKETCHAT_USER_ID:-}" -H "X-Auth-Token: ${ROCKETCHAT_AUTH_TOKEN:-}" \
|
||||||
|
-d "{\"username\":\"$HOME_USER\"}" 2>/dev/null || echo '')"
|
||||||
|
HOME_DM_ID="$(printf '%s' "$dm_resp" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("room",{}).get("_id",""))' 2>/dev/null || echo '')"
|
||||||
|
ok "[Homechannel: $HOME_USER, User-ID=$HOME_USER_ID, DM-ID=${HOME_DM_ID:-n/a}]"
|
||||||
|
else
|
||||||
|
warn "[User $HOME_USER nicht gefunden — bitte erneut eingeben oder überspringen]"
|
||||||
|
ask HOME_USER "${T[${LANG_CHOICE}_rc_home_q]}" "" true
|
||||||
|
[ "$HOME_USER" != "SKIP" ] && ROCKETCHAT_HOME_CHANNEL="$HOME_USER"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Phase 5: Secrets (Cloud-Key nur bei Cloud-Provider) ──
|
||||||
|
if [ "$PROVIDER_NEEDS_KEY" = "true" ]; then
|
||||||
|
banner "Cloud-Key"
|
||||||
|
ask CLOUD_KEY "Cloud-Key für $PROVIDER? [M]anuell eintragen / [S]päter / [L]okales Ollama nachinstallieren" "L" false
|
||||||
|
case "$CLOUD_KEY" in
|
||||||
|
L|l) PROVIDER="ollama"; PROVIDER_BASE_URL="http://localhost:11434"; PROVIDER_NEEDS_KEY=false; LOCAL_INFERENCE_AVAILABLE=true; ok "[Lokales Ollama gewählt — kein Cloud-Key nötig]" ;;
|
||||||
|
S|s) warn "[Bot läuft ohne LLM — später via .env konfigurierbar]" ;;
|
||||||
|
*) ask CLOUD_KEY_VAL "Cloud-Key (Eingabe unsichtbar)?" "" false
|
||||||
|
if [ -n "$CLOUD_KEY_VAL" ]; then
|
||||||
|
if [ "$PROVIDER" = "openrouter" ]; then OPENROUTER_API_KEY="$CLOUD_KEY_VAL"; else OLLAMA_CLOUD_API_KEY="$CLOUD_KEY_VAL"; fi
|
||||||
|
ok "[Key gesetzt: ***maskiert***]"
|
||||||
|
fi ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Phase 5.3: Gitea-SSH-Key (Bodiespec h) — generieren ODER vorhandenen nutzen. ──
|
||||||
|
# KEIN Hard-Abort bei fehlendem Key (Selbsterklärend-Regel Punkt 5).
|
||||||
|
banner "Gitea-SSH-Key"
|
||||||
|
local gitea_key="$HOME/.ssh/gitea_hermes_key"
|
||||||
|
if [ -f "$gitea_key" ]; then
|
||||||
|
ok "[SSH-Key vorhanden: $gitea_key]"
|
||||||
|
else
|
||||||
|
ask GITEA_KEY_CHOICE "Soll der Bot Code aus dem Gitea-Repo pushen können? [J]a, SSH-Key generieren / [N]ein, nur Pull / [V]orhandenen Public-Key verwenden" "N" false
|
||||||
|
case "$GITEA_KEY_CHOICE" in
|
||||||
|
J|j|Y|y)
|
||||||
|
mkdir -p "$HOME/.ssh"; chmod 700 "$HOME/.ssh"
|
||||||
|
if ssh-keygen -t ed25519 -C "hermes-bot@$(hostname)" -f "$gitea_key" -N "" >/dev/null 2>&1; then
|
||||||
|
ok "[SSH-Key generiert: $gitea_key]"
|
||||||
|
echo " Public-Key (in Gitea-Settings hinterlegen):"
|
||||||
|
echo " $(cat "${gitea_key}.pub" 2>/dev/null)"
|
||||||
|
else
|
||||||
|
warn "[SSH-Key-Generierung fehlgeschlagen — später manuell via ssh-keygen nachholen]"
|
||||||
|
fi ;;
|
||||||
|
V|v)
|
||||||
|
ask GITEA_PUB_PATH "Pfad zum vorhandenen Public-Key?" "$HOME/.ssh/id_ed25519.pub" true
|
||||||
|
if [ "$GITEA_PUB_PATH" != "SKIP" ] && [ -f "$GITEA_PUB_PATH" ]; then
|
||||||
|
ok "[Public-Key verwendet: $GITEA_PUB_PATH]"
|
||||||
|
else
|
||||||
|
warn "[Public-Key nicht gefunden — später manuell nachholen]"
|
||||||
|
fi ;;
|
||||||
|
*) warn "[Gitea-SSH-Key übersprungen — nur Pull möglich, später via ssh-keygen nachholbar]" ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Phase 6: Themenräume (nur Multiroom=Y) ──
|
||||||
|
if [ "$RC_MULTIROOM" = "true" ]; then
|
||||||
|
banner "Themenräume"
|
||||||
|
ask INITIAL_ROOMS "Themenräume (Format: raum:kw1,kw2 | raum:kw3) — Enter = leer" "" true
|
||||||
|
if [ "$INITIAL_ROOMS" != "SKIP" ] && [ -n "$INITIAL_ROOMS" ]; then
|
||||||
|
ok "[Themenräume: $INITIAL_ROOMS]"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Phase 7: Auto-Install (Defizite sammeln) ──
|
||||||
|
banner "Dependencies"
|
||||||
|
MISSING_REQUIREMENTS=()
|
||||||
|
# Single Source of Truth: setup_requirements.txt (Flow-Spec §0.2).
|
||||||
|
# Format: modulname|pip_name|min_version|severity
|
||||||
|
local req_file
|
||||||
|
req_file="$(cd "$(dirname "$0")" && pwd)/setup_requirements.txt"
|
||||||
|
if [ -f "$req_file" ]; then
|
||||||
|
while IFS='|' read -r mod pip_name min_ver severity; do
|
||||||
|
# Kommentare + Leerzeilen überspringen
|
||||||
|
case "$mod" in ''|\#*) continue ;; esac
|
||||||
|
if ! python3 -c "import $mod" 2>/dev/null; then
|
||||||
|
MISSING_REQUIREMENTS+=("$mod")
|
||||||
|
fi
|
||||||
|
done < "$req_file"
|
||||||
|
else
|
||||||
|
# Fallback: bekannte Module (falls setup_requirements.txt fehlt)
|
||||||
|
for pkg in faiss numpy snowballstemmer; do
|
||||||
|
if ! python3 -c "import $pkg" 2>/dev/null; then
|
||||||
|
MISSING_REQUIREMENTS+=("$pkg")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [ ${#MISSING_REQUIREMENTS[@]} -gt 0 ]; then
|
||||||
|
warn "[Fehlende Module: ${MISSING_REQUIREMENTS[*]}]"
|
||||||
|
ask INSTALL_DEPS "Fehlende Module installieren? [Enter] installieren / [W]eiter ohne / [A]bbrechen" "install" false
|
||||||
|
if [ "$INSTALL_DEPS" = "A" ] || [ "$INSTALL_DEPS" = "a" ]; then
|
||||||
|
die "Abbruch durch User"
|
||||||
|
fi
|
||||||
|
if [ "$INSTALL_DEPS" != "W" ] && [ "$INSTALL_DEPS" != "w" ]; then
|
||||||
|
# Auto-Install der fehlenden Module (Flow-Spec §Phase 7). Build-Fehler
|
||||||
|
# werden gesammelt (INSTALL_FAILED_MODULES), KEIN Abbruch (P-163/U4).
|
||||||
|
INSTALL_FAILED_MODULES=()
|
||||||
|
for mod in "${MISSING_REQUIREMENTS[@]}"; do
|
||||||
|
# pip_name aus setup_requirements.txt ableiten (Fallback: modulname).
|
||||||
|
local pip_pkg="$mod"
|
||||||
|
if [ -f "$req_file" ]; then
|
||||||
|
pip_pkg="$(grep -E "^${mod}\\|" "$req_file" | head -1 | cut -d'|' -f2)"
|
||||||
|
[ -z "$pip_pkg" ] && pip_pkg="$mod"
|
||||||
|
fi
|
||||||
|
if $DRY_RUN; then
|
||||||
|
printf '%s[dry]%s python3 -m pip install %s\n' "$C_YELLOW" "$C_RESET" "$pip_pkg"
|
||||||
|
elif python3 -m pip install --quiet "$pip_pkg" 2>/dev/null; then
|
||||||
|
ok "[Installiere $mod... ✅]"
|
||||||
|
else
|
||||||
|
warn "[Installiere $mod... ⚠️ Build-Fehler — später nachholbar]"
|
||||||
|
INSTALL_FAILED_MODULES+=("$mod")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
ok "[Alle Python-Module vorhanden]"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Phase 8: Backup (P-164) ──
|
||||||
|
BACKUP_DIR="/tmp/hermes-install-backup-$(date +%s)"
|
||||||
|
if ! $DRY_RUN; then
|
||||||
|
mkdir -p "$BACKUP_DIR"
|
||||||
|
[ -f "$HOME/.hermes/config.yaml" ] && cp "$HOME/.hermes/config.yaml" "$BACKUP_DIR/config.bak" 2>/dev/null || true
|
||||||
|
[ -f "$HOME/.hermes/.env" ] && cp "$HOME/.hermes/.env" "$BACKUP_DIR/env.bak" 2>/dev/null || true
|
||||||
|
ok "[Backup: $BACKUP_DIR]"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Phase 9: Resume-Erkennung (halb-installierter Zustand) ──
|
||||||
|
if $RESUME; then
|
||||||
|
banner "Resume-Erkennung"
|
||||||
|
read_install_state
|
||||||
|
if [ "$INSTALL_PHASE_LAST_DONE" -gt 0 ] 2>/dev/null; then
|
||||||
|
ok "[Letzte erfolgreiche Phase: $INSTALL_PHASE_LAST_DONE — fahre ab dort fort]"
|
||||||
|
elif [ -d "$HOME/.hermes/hermes-agent/venv" ] || [ -d "$HOME/.local/share/pipx/venvs/hermes-agent" ]; then
|
||||||
|
ok "[Vorherige Installation erkannt — fahre ab aktuellem Zustand fort]"
|
||||||
|
else
|
||||||
|
warn "[Keine vorherige Installation erkannt — starte frisch]"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
mark_phase 9 "wizard-dialog-abgeschlossen"
|
||||||
|
|
||||||
|
# ── Phase 10: Proof-Run (nach Hauptfluss, siehe unten) ──
|
||||||
|
# ── Phase 11: Abschluss (nach Hauptfluss, siehe unten) ──
|
||||||
|
|
||||||
|
# Werte in env-Variablen übernehmen (Hauptfluss liest sie via read_env).
|
||||||
|
export ROCKETCHAT_BASE_URL ROCKETCHAT_USER ROCKETCHAT_PASSWORD ROCKETCHAT_USER_ID
|
||||||
|
export ROCKETCHAT_AUTH_TOKEN HOME_USER_ID HOME_DM_ID
|
||||||
|
export RC_MULTIROOM ROCKETCHAT_HOME_CHANNEL
|
||||||
|
export ROCKETCHAT_PING_SEC ROCKETCHAT_IDLE_SEC
|
||||||
|
export OPENROUTER_API_KEY OLLAMA_CLOUD_API_KEY
|
||||||
|
export PROVIDER PROVIDER_BASE_URL PROVIDER_NEEDS_KEY
|
||||||
|
export DETECTED_LAYOUT DETECTED_PROVIDER LOCAL_INFERENCE_AVAILABLE
|
||||||
|
export BACKUP_DIR PENDING_RC_CONFIG
|
||||||
|
|
||||||
|
ok "Wizard-Phasen 0-9 abgeschlossen — starte Installation..."
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Proof-Run (Phase 10) + Abschluss (Phase 11) ──
|
||||||
|
run_proof_and_summary() {
|
||||||
|
banner "Proof-Run"
|
||||||
|
local proof_ok=true
|
||||||
|
if gateway_is_active; then
|
||||||
|
ok "[Gateway: active (running)]"
|
||||||
|
else
|
||||||
|
warn "[Gateway nicht aktiv — prüfe: gateway_journalctl -n 20]"
|
||||||
|
proof_ok=false
|
||||||
|
fi
|
||||||
|
if curl -fsS --max-time 5 http://localhost:8000/health >/dev/null 2>&1; then
|
||||||
|
ok "[Health: /health → 200 ok]"
|
||||||
|
else
|
||||||
|
warn "[Health-Endpoint nicht erreichbar — Firewall/Port 8000 prüfen]"
|
||||||
|
proof_ok=false
|
||||||
|
fi
|
||||||
|
|
||||||
|
banner "Abschluss"
|
||||||
|
if $proof_ok; then
|
||||||
|
ok "Installation erfolgreich"
|
||||||
|
else
|
||||||
|
warn "Installation teilweise erfolgreich — siehe Nachhol-Liste"
|
||||||
|
fi
|
||||||
|
echo ""
|
||||||
|
echo "Nachhol-Liste (später nachholbar):"
|
||||||
|
[ ${#MISSING_REQUIREMENTS[@]} -gt 0 ] && echo " - Module: ${MISSING_REQUIREMENTS[*]} (./install.sh --guided --resume)"
|
||||||
|
[ "${PENDING_RC_CONFIG:-false}" = "true" ] && echo " - RC-Verbindung: später via .env konfigurieren"
|
||||||
|
[ "$PROVIDER" = "none" ] && echo " - LLM-Provider: noch nicht konfiguriert (Bot läuft eingeschränkt)"
|
||||||
|
echo ""
|
||||||
|
echo "Resume: ./install.sh --guided --resume"
|
||||||
|
echo "Repair: ./install.sh --repair"
|
||||||
|
echo "Logs: gateway_journalctl -f"
|
||||||
|
}
|
||||||
|
|
||||||
# ──────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
# Hilfetext
|
# Hilfetext
|
||||||
# ──────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
@@ -2157,6 +2718,9 @@ OPTIONEN:
|
|||||||
--migrate-to-venv Migration: pipx → User-Space-venv (P3, explizit)
|
--migrate-to-venv Migration: pipx → User-Space-venv (P3, explizit)
|
||||||
--migrate-to-official Migration: pip → offizieller Hermes-Installer (P-044, explizit)
|
--migrate-to-official Migration: pip → offizieller Hermes-Installer (P-044, explizit)
|
||||||
--repair Fehlende Komponenten reparieren (venv, Pakete, Ollama, Modelle, FAISS-Index, .env, Plugin-Symlink)
|
--repair Fehlende Komponenten reparieren (venv, Pakete, Ollama, Modelle, FAISS-Index, .env, Plugin-Symlink)
|
||||||
|
--guided Geführter Setup-Wizard (F98): 12 Phasen, Provider-Freiheit, kein Key-Zwang
|
||||||
|
--defaults Nur mit --guided: Defaults ohne Prompts (CI/Provisionierung)
|
||||||
|
--resume Nur mit --guided: halb-installierten Zustand erkennen und fortsetzen
|
||||||
--skip-system-deps apt-Install überspringen (für Container/CI)
|
--skip-system-deps apt-Install überspringen (für Container/CI)
|
||||||
--skip-ollama-models ollama pull überspringen
|
--skip-ollama-models ollama pull überspringen
|
||||||
|
|
||||||
@@ -2211,6 +2775,9 @@ while [ $# -gt 0 ]; do
|
|||||||
--migrate-to-venv) MIGRATE_TO_VENV=true; shift ;;
|
--migrate-to-venv) MIGRATE_TO_VENV=true; shift ;;
|
||||||
--migrate-to-official) MIGRATE_TO_OFFICIAL=true; shift ;;
|
--migrate-to-official) MIGRATE_TO_OFFICIAL=true; shift ;;
|
||||||
--repair) REPAIR=true; shift ;;
|
--repair) REPAIR=true; shift ;;
|
||||||
|
--guided) GUIDED=true; shift ;;
|
||||||
|
--defaults) GUIDED_DEFAULTS=true; shift ;;
|
||||||
|
--resume) RESUME=true; shift ;;
|
||||||
--*) err "Unbekannte Option: $1"; print_help; exit 1 ;;
|
--*) err "Unbekannte Option: $1"; print_help; exit 1 ;;
|
||||||
*) err "Unbekanntes Argument: $1"; exit 1 ;;
|
*) err "Unbekanntes Argument: $1"; exit 1 ;;
|
||||||
esac
|
esac
|
||||||
@@ -2221,12 +2788,26 @@ done
|
|||||||
# ──────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────
|
||||||
read_env
|
read_env
|
||||||
|
|
||||||
|
# F98: Guided Setup Wizard — additive Schicht. Läuft VOR dem Gitea-SSH-Check
|
||||||
|
# und dem Secret-Check, sammelt alle Werte in env-Variablen, dann läuft der
|
||||||
|
# bestehende Hauptfluss unverändert weiter. KEIN separater Installer.
|
||||||
|
if $GUIDED; then
|
||||||
|
run_guided_wizard
|
||||||
|
fi
|
||||||
|
|
||||||
# P11: SSH-Key für Gitea muss VOR install.sh eingerichtet sein.
|
# P11: SSH-Key für Gitea muss VOR install.sh eingerichtet sein.
|
||||||
# Verhindert 'Permission denied (publickey)' beim git clone (z.B. wenn als
|
# Verhindert 'Permission denied (publickey)' beim git clone (z.B. wenn als
|
||||||
# root gearbeitet wurde, das Ziel aber einen user-spezifischen Key braucht).
|
# root gearbeitet wurde, das Ziel aber einen user-spezifischen Key braucht).
|
||||||
check_gitea_ssh_key() {
|
check_gitea_ssh_key() {
|
||||||
local key="$HOME/.ssh/gitea_hermes_key"
|
local key="$HOME/.ssh/gitea_hermes_key"
|
||||||
if [ ! -f "$key" ]; then
|
if [ ! -f "$key" ]; then
|
||||||
|
# F98: Im Guided-Modus hat der Wizard (Phase 5.3) bereits die Key-Generierung
|
||||||
|
# angeboten. Wenn der User "Nur Pull" / "Überspringen" gewählt hat, ist ein
|
||||||
|
# fehlender Key KEIN Abbruch-Grund (Selbsterklärend-Regel Punkt 5).
|
||||||
|
if $GUIDED; then
|
||||||
|
warn "Gitea SSH-Key fehlt ($key) — nur Pull möglich, Push später via ssh-keygen nachholbar"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
err "ERROR: Gitea SSH-Key nicht gefunden unter $key"
|
err "ERROR: Gitea SSH-Key nicht gefunden unter $key"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Bitte zuerst SSH-Key für Gitea einrichten:"
|
echo "Bitte zuerst SSH-Key für Gitea einrichten:"
|
||||||
@@ -2295,19 +2876,46 @@ fi
|
|||||||
|
|
||||||
# Erforderliche Secrets prüfen (außer im --check, --update-only, --repair und Migrations-Modus)
|
# Erforderliche Secrets prüfen (außer im --check, --update-only, --repair und Migrations-Modus)
|
||||||
# Entscheidung 3: --repair braucht KEINE Cloud-Secrets (repariert nur lokale Komponenten).
|
# Entscheidung 3: --repair braucht KEINE Cloud-Secrets (repariert nur lokale Komponenten).
|
||||||
|
# F98 (Root-Cause D): KEIN Key-Zwang mehr. Der Cloud-Key ist NUR bei Cloud-Provider
|
||||||
|
# (openrouter/ollama-cloud) erforderlich. Bei lokaler Inference (P1/P2) entfällt er
|
||||||
|
# komplett. KEIN `die "Abbruch: erforderliche Secrets fehlen"` mehr — stattdessen
|
||||||
|
# sammelt der Wizard Defizite und bietet Ausweich-Optionen (Flow-Spec §0.1 Punkt 5).
|
||||||
if ! $CHECK_ONLY && ! $UPDATE_ONLY && ! $REPAIR && ! $MIGRATE_ONLY && ! $MIGRATE_TO_VENV && ! $MIGRATE_TO_OFFICIAL; then
|
if ! $CHECK_ONLY && ! $UPDATE_ONLY && ! $REPAIR && ! $MIGRATE_ONLY && ! $MIGRATE_TO_VENV && ! $MIGRATE_TO_OFFICIAL; then
|
||||||
|
# Provider-Detection VOR Secret-Check (Root-Cause G: Detection-Block VOR read_env).
|
||||||
|
# Guard: wenn der Wizard bereits einen Provider gesetzt hat (z.B. via P6-Auswahl),
|
||||||
|
# NICHT erneut detektieren — sonst wird die User-Wahl überschrieben.
|
||||||
|
if [ -z "${PROVIDER:-}" ]; then
|
||||||
|
detect_provider
|
||||||
|
fi
|
||||||
|
|
||||||
local_missing=0
|
local_missing=0
|
||||||
[ -z "$OLLAMA_CLOUD_API_KEY" ] && { err "OLLAMA_CLOUD_API_KEY fehlt"; local_missing=1; }
|
# ROCKETCHAT_PASSWORD + ROCKETCHAT_USER_ID sind für den Bot-Betrieb nötig —
|
||||||
[ -z "$ROCKETCHAT_PASSWORD" ] && { err "ROCKETCHAT_PASSWORD fehlt"; local_missing=1; }
|
# aber im Guided-Modus werden sie im Dialog abgefragt (Phase 4), nicht hier erzwungen.
|
||||||
[ -z "$ROCKETCHAT_USER_ID" ] && { err "ROCKETCHAT_USER_ID fehlt"; local_missing=1; }
|
if ! $GUIDED; then
|
||||||
|
[ -z "$ROCKETCHAT_PASSWORD" ] && { err "ROCKETCHAT_PASSWORD fehlt"; local_missing=1; }
|
||||||
|
[ -z "$ROCKETCHAT_USER_ID" ] && { err "ROCKETCHAT_USER_ID fehlt"; local_missing=1; }
|
||||||
|
fi
|
||||||
|
# Cloud-Key NUR bei Cloud-Provider (Root-Cause D / Andreas-Direktive 31.08.).
|
||||||
|
if [ "$PROVIDER" = "ollama-cloud" ] && [ -z "$OLLAMA_CLOUD_API_KEY" ]; then
|
||||||
|
err "OLLAMA_CLOUD_API_KEY fehlt (Provider=ollama-cloud)"
|
||||||
|
local_missing=1
|
||||||
|
fi
|
||||||
|
if [ "$PROVIDER" = "openrouter" ] && [ -z "$OPENROUTER_API_KEY" ]; then
|
||||||
|
err "OPENROUTER_API_KEY fehlt (Provider=openrouter)"
|
||||||
|
local_missing=1
|
||||||
|
fi
|
||||||
if [ $local_missing -eq 1 ]; then
|
if [ $local_missing -eq 1 ]; then
|
||||||
echo ""
|
echo ""
|
||||||
echo "Setze die fehlenden env-Variablen, z.B.:"
|
echo "Setze die fehlenden env-Variablen, z.B.:"
|
||||||
echo " export OLLAMA_CLOUD_API_KEY='...'"
|
[ -z "$OLLAMA_CLOUD_API_KEY" ] && echo " export OLLAMA_CLOUD_API_KEY='...'"
|
||||||
echo " export ROCKETCHAT_PASSWORD='...'"
|
[ -z "$OPENROUTER_API_KEY" ] && echo " export OPENROUTER_API_KEY='...'"
|
||||||
echo " export ROCKETCHAT_USER_ID='...'"
|
[ -z "$ROCKETCHAT_PASSWORD" ] && echo " export ROCKETCHAT_PASSWORD='...'"
|
||||||
|
[ -z "$ROCKETCHAT_USER_ID" ] && echo " export ROCKETCHAT_USER_ID='...'"
|
||||||
echo ""
|
echo ""
|
||||||
die "Abbruch: erforderliche Secrets fehlen"
|
echo "Tipp: ./install.sh --guided führt Sie interaktiv durch die Einrichtung"
|
||||||
|
echo " (inkl. Provider-Auswahl und Secret-Abfrage — kein Abbruch nötig)."
|
||||||
|
echo ""
|
||||||
|
die "Abbruch: erforderliche Secrets fehlen (oder nutze --guided)"
|
||||||
fi
|
fi
|
||||||
# P12: Platzhalter-Validierung für Secrets
|
# P12: Platzhalter-Validierung für Secrets
|
||||||
check_secret_placeholder "OLLAMA_CLOUD_API_KEY" "$OLLAMA_CLOUD_API_KEY"
|
check_secret_placeholder "OLLAMA_CLOUD_API_KEY" "$OLLAMA_CLOUD_API_KEY"
|
||||||
@@ -2712,6 +3320,11 @@ install_gateway_service
|
|||||||
# 9. Verifikation
|
# 9. Verifikation
|
||||||
verify_installation
|
verify_installation
|
||||||
|
|
||||||
|
# F98: Proof-Run (Phase 10) + Abschluss (Phase 11) — nur im Guided-Modus.
|
||||||
|
if $GUIDED; then
|
||||||
|
run_proof_and_summary
|
||||||
|
fi
|
||||||
|
|
||||||
# Aufräumen
|
# Aufräumen
|
||||||
if ! $DRY_RUN; then
|
if ! $DRY_RUN; then
|
||||||
echo ""
|
echo ""
|
||||||
|
|||||||
@@ -1,389 +0,0 @@
|
|||||||
"""
|
|
||||||
F93 — Adaptiver LLM-Timeout (selbstkalibrierend, ersetzt starre 30s).
|
|
||||||
|
|
||||||
@implements F-93
|
|
||||||
|
|
||||||
Ersetzt den starren 30s-LLM-Call-Timeout durch einen selbstkalibrierenden
|
|
||||||
Wert, der pro System aus den tatsächlich gemessenen LLM-Antwortzeiten lernt.
|
|
||||||
|
|
||||||
Verbindliche Spec (Rainers Design 22.08., Feature-Register Zeile F93, FB-10):
|
|
||||||
|
|
||||||
- Failsafe 30s beim ersten Start (keine Kalibrierungsdaten → 30s).
|
|
||||||
- Welford Moving Average + Standardabweichung → Toleranzband.
|
|
||||||
- 7-Tage-Exponential-Decay Gewichtung (alte Messungen verblassen).
|
|
||||||
- Ausreißer-Erkennung: ±2σ → Messung verwerfen (temporäre Last wie
|
|
||||||
Docker-Start wird NICHT in die Statistik eingerechnet).
|
|
||||||
- Eskalation erst bei N=2 konsekutiven Messungen außerhalb Toleranz.
|
|
||||||
- Reset bei Modellwechsel (Schlüssel = (endpoint, model)).
|
|
||||||
- FAISS-Analog: score-basierte Bewertung (z-Score), nicht binär.
|
|
||||||
|
|
||||||
Design-Entscheidungen (dokumentiert für QG F1-F5):
|
|
||||||
|
|
||||||
- Der Timeout für den NÄCHSTEN Call ist ``mean + sigma_band * std``
|
|
||||||
(obere Toleranzgrenze). Das gibt normaler Varianz Luft, ohne bei
|
|
||||||
temporärer Last (Ausreißer) mitzuwachsen — Ausreißer werden verworfen.
|
|
||||||
- Welford ist ein Online-Algorithmus (kein Speichern aller Samples).
|
|
||||||
Der 7-Tage-Decay wird als "forgetting factor" umgesetzt: vor jedem
|
|
||||||
Update werden ``n`` und ``M2`` mit ``exp(-dt / tau)`` skaliert. Der
|
|
||||||
Mittelwert bleibt dabei unverändert (uniforme Skalierung), die
|
|
||||||
Varianz (M2/n) ebenfalls — nur das effektive Gewicht alter Daten
|
|
||||||
sinkt. ``n`` wird dadurch ein fraktionaler "effektiver Stichprobenumfang".
|
|
||||||
- Ausreißer-Erkennung greift erst ab ``min_samples`` akzeptierten
|
|
||||||
Messungen (vorher ist die Std instabil). Während der Kalibrierung
|
|
||||||
wird alles akzeptiert (Konvergenz).
|
|
||||||
- Score-basiert: ``score(duration)`` liefert den z-Score (kontinuierlich),
|
|
||||||
nicht nur in/out. Eskalation nutzt den Streak (N=2 konsekutiv außerhalb
|
|
||||||
Toleranz), nicht einen einzelnen binären Schwellwert.
|
|
||||||
|
|
||||||
Persistenz: Der Kalibrierungszustand wird in eine JSON-Datei geschrieben
|
|
||||||
(atomar via tmp+rename, P-101-Pattern), damit die Kalibrierung über
|
|
||||||
Gateway-Neustarts hinweg erhalten bleibt ("selbstkalibrierend pro System").
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import math
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
from typing import Callable, Optional, Tuple
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# ── Konfiguration (Env-Vars, analog config.py) ──────────────────────────────
|
|
||||||
|
|
||||||
# Failsafe-Timeout beim ersten Start (keine Kalibrierungsdaten).
|
|
||||||
ADAPTIVE_TIMEOUT_FAILSAFE_S: float = float(
|
|
||||||
os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_FAILSAFE", "30.0")
|
|
||||||
)
|
|
||||||
|
|
||||||
# Toleranzband: ±sigma_band * std um den Mittelwert.
|
|
||||||
ADAPTIVE_TIMEOUT_SIGMA_BAND: float = float(
|
|
||||||
os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_SIGMA_BAND", "2.0")
|
|
||||||
)
|
|
||||||
|
|
||||||
# 7-Tage-Exponential-Decay (tau in Sekunden).
|
|
||||||
ADAPTIVE_TIMEOUT_DECAY_TAU_S: float = float(
|
|
||||||
os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_DECAY_TAU_S", str(7 * 24 * 3600))
|
|
||||||
)
|
|
||||||
|
|
||||||
# Eskalation erst bei N konsekutiven Messungen außerhalb Toleranz.
|
|
||||||
ADAPTIVE_TIMEOUT_ESCALATION_N: int = int(
|
|
||||||
os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_ESCALATION_N", "2")
|
|
||||||
)
|
|
||||||
|
|
||||||
# Mindestanzahl akzeptierter Messungen, bevor Ausreißer-Erkennung greift.
|
|
||||||
ADAPTIVE_TIMEOUT_MIN_SAMPLES: int = int(
|
|
||||||
os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_MIN_SAMPLES", "3")
|
|
||||||
)
|
|
||||||
|
|
||||||
# Defensive Unter-/Obergrenze für den kalibrierten Timeout (Sekunden).
|
|
||||||
ADAPTIVE_TIMEOUT_MIN_S: float = float(
|
|
||||||
os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_MIN_S", "1.0")
|
|
||||||
)
|
|
||||||
ADAPTIVE_TIMEOUT_MAX_S: float = float(
|
|
||||||
os.getenv("ARCHIVAR_ADAPTIVE_TIMEOUT_MAX_S", "300.0")
|
|
||||||
)
|
|
||||||
|
|
||||||
# Persistenz-Pfad (analog ARCHIVAR_STATE_PATH).
|
|
||||||
ADAPTIVE_TIMEOUT_STATE_PATH: str = os.path.expanduser(
|
|
||||||
os.getenv(
|
|
||||||
"ARCHIVAR_ADAPTIVE_TIMEOUT_STATE_PATH",
|
|
||||||
"~/.hermes/hermes-agent/data/adaptive_timeout_state.json",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class AdaptiveLLMTimeout:
|
|
||||||
"""Selbstkalibrierender LLM-Call-Timeout (Welford + Toleranzband).
|
|
||||||
|
|
||||||
Thread-sicher über ein internes Lock, da ``OllamaLLMClient`` aus
|
|
||||||
``asyncio.to_thread``-Worker-Threads heraus aufruft (parallele Calls
|
|
||||||
möglich, auch wenn der Router sie über einen Semaphore serialisiert).
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
failsafe_s: float = ADAPTIVE_TIMEOUT_FAILSAFE_S,
|
|
||||||
sigma_band: float = ADAPTIVE_TIMEOUT_SIGMA_BAND,
|
|
||||||
decay_tau_s: float = ADAPTIVE_TIMEOUT_DECAY_TAU_S,
|
|
||||||
escalation_n: int = ADAPTIVE_TIMEOUT_ESCALATION_N,
|
|
||||||
min_samples: int = ADAPTIVE_TIMEOUT_MIN_SAMPLES,
|
|
||||||
min_timeout_s: float = ADAPTIVE_TIMEOUT_MIN_S,
|
|
||||||
max_timeout_s: float = ADAPTIVE_TIMEOUT_MAX_S,
|
|
||||||
state_path: Optional[str] = ADAPTIVE_TIMEOUT_STATE_PATH,
|
|
||||||
clock: Callable[[], float] = time.time,
|
|
||||||
) -> None:
|
|
||||||
self._failsafe_s = failsafe_s
|
|
||||||
self._sigma_band = sigma_band
|
|
||||||
self._decay_tau_s = decay_tau_s
|
|
||||||
self._escalation_n = escalation_n
|
|
||||||
self._min_samples = min_samples
|
|
||||||
self._min_timeout_s = min_timeout_s
|
|
||||||
self._max_timeout_s = max_timeout_s
|
|
||||||
self._state_path = state_path
|
|
||||||
self._clock = clock
|
|
||||||
|
|
||||||
# Welford-Zustand (n = effektiver Stichprobenumfang, fraktional nach Decay).
|
|
||||||
self._n: float = 0.0
|
|
||||||
self._mean: float = 0.0
|
|
||||||
self._m2: float = 0.0
|
|
||||||
self._last_ts: Optional[float] = None
|
|
||||||
|
|
||||||
# Modell-Schlüssel (Reset bei Wechsel).
|
|
||||||
self._model_key: Optional[Tuple[str, str]] = None
|
|
||||||
|
|
||||||
# Eskalations-Zustand.
|
|
||||||
self._streak: int = 0
|
|
||||||
self._escalated: bool = False
|
|
||||||
|
|
||||||
# Telemetrie.
|
|
||||||
self._accepted: int = 0
|
|
||||||
self._rejected: int = 0
|
|
||||||
|
|
||||||
import threading
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
|
|
||||||
if self._state_path:
|
|
||||||
self._load()
|
|
||||||
|
|
||||||
# ── Öffentliche API ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def current_timeout(self) -> float:
|
|
||||||
"""Timeout für den NÄCHSTEN LLM-Call.
|
|
||||||
|
|
||||||
Failsafe (30s) solange keine Kalibrierungsdaten vorliegen, danach
|
|
||||||
``mean + sigma_band * std``, geklemmt auf [min, max].
|
|
||||||
"""
|
|
||||||
with self._lock:
|
|
||||||
if self._n < 1.0:
|
|
||||||
return self._failsafe_s
|
|
||||||
std = self._stddev_locked()
|
|
||||||
timeout = self._mean + self._sigma_band * std
|
|
||||||
return max(self._min_timeout_s, min(self._max_timeout_s, timeout))
|
|
||||||
|
|
||||||
def record(self, duration: float, success: bool = True) -> float:
|
|
||||||
"""Füttere eine Messung (LLM-Antwortzeit in Sekunden).
|
|
||||||
|
|
||||||
Args:
|
|
||||||
duration: Gemessene Dauer in Sekunden.
|
|
||||||
success: False bei Timeout/Fehler (Messung wird als
|
|
||||||
außerhalb Toleranz gewertet, nicht in die Statistik
|
|
||||||
aufgenommen).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
z-Score der Messung (0.0 während Kalibrierung). Positiv =
|
|
||||||
langsamer als Mittelwert. Score-basiert (FAISS-Analog), nicht binär.
|
|
||||||
"""
|
|
||||||
with self._lock:
|
|
||||||
self._apply_decay_locked()
|
|
||||||
|
|
||||||
# Timeout/Fehler: per Definition außerhalb Toleranz → Streak.
|
|
||||||
if not success:
|
|
||||||
self._rejected += 1
|
|
||||||
self._streak += 1
|
|
||||||
self._maybe_escalate_locked()
|
|
||||||
return float("inf")
|
|
||||||
|
|
||||||
# Ausreißer-Erkennung erst ab min_samples (Std stabil).
|
|
||||||
if self._n >= self._min_samples:
|
|
||||||
std = self._stddev_locked()
|
|
||||||
if std > 0.0:
|
|
||||||
z = (duration - self._mean) / std
|
|
||||||
if abs(z) > self._sigma_band:
|
|
||||||
# Ausreißer → verwerfen (temporäre Last nicht einrechnen).
|
|
||||||
self._rejected += 1
|
|
||||||
self._streak += 1
|
|
||||||
self._maybe_escalate_locked()
|
|
||||||
return z
|
|
||||||
|
|
||||||
# Akzeptieren → Welford-Update.
|
|
||||||
self._n += 1.0
|
|
||||||
delta = duration - self._mean
|
|
||||||
self._mean += delta / self._n
|
|
||||||
delta2 = duration - self._mean
|
|
||||||
self._m2 += delta * delta2
|
|
||||||
self._accepted += 1
|
|
||||||
self._streak = 0
|
|
||||||
self._save_locked()
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
def score(self, duration: float) -> float:
|
|
||||||
"""Z-Score einer Dauer relativ zur aktuellen Statistik (FAISS-Analog).
|
|
||||||
|
|
||||||
Kontinuierliche Bewertung statt binär in/out. 0.0 = exakt Mittelwert,
|
|
||||||
±2.0 = Toleranzgrenze, darüber = Ausreißer.
|
|
||||||
"""
|
|
||||||
with self._lock:
|
|
||||||
if self._n < 2.0:
|
|
||||||
return 0.0
|
|
||||||
std = self._stddev_locked()
|
|
||||||
if std <= 0.0:
|
|
||||||
return 0.0
|
|
||||||
return (duration - self._mean) / std
|
|
||||||
|
|
||||||
def set_model(self, endpoint: str, model: str) -> bool:
|
|
||||||
"""Setze den aktuellen (endpoint, model)-Schlüssel.
|
|
||||||
|
|
||||||
Bei Wechsel → harter Reset (nur dieser Schlüssel; hier ein einziger
|
|
||||||
Schlüssel, da ein Prozess typischerweise ein LLM-Modell nutzt).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
True wenn ein Reset ausgelöst wurde (Modellwechsel), sonst False.
|
|
||||||
"""
|
|
||||||
key = (endpoint, model)
|
|
||||||
with self._lock:
|
|
||||||
if key == self._model_key:
|
|
||||||
return False
|
|
||||||
self._model_key = key
|
|
||||||
self._reset_locked()
|
|
||||||
return True
|
|
||||||
|
|
||||||
def reset(self) -> None:
|
|
||||||
"""Harter Reset der Kalibrierung (Modellwechsel)."""
|
|
||||||
with self._lock:
|
|
||||||
self._reset_locked()
|
|
||||||
|
|
||||||
def _reset_locked(self) -> None:
|
|
||||||
"""Reset ohne Lock-Akquise (Caller hält ``self._lock``)."""
|
|
||||||
self._n = 0.0
|
|
||||||
self._mean = 0.0
|
|
||||||
self._m2 = 0.0
|
|
||||||
self._last_ts = None
|
|
||||||
self._streak = 0
|
|
||||||
self._escalated = False
|
|
||||||
self._accepted = 0
|
|
||||||
self._rejected = 0
|
|
||||||
self._save_locked()
|
|
||||||
|
|
||||||
# ── Introspection (Telemetrie / Tests) ───────────────────────────────
|
|
||||||
|
|
||||||
@property
|
|
||||||
def mean(self) -> float:
|
|
||||||
with self._lock:
|
|
||||||
return self._mean
|
|
||||||
|
|
||||||
@property
|
|
||||||
def stddev(self) -> float:
|
|
||||||
with self._lock:
|
|
||||||
return self._stddev_locked()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def n(self) -> float:
|
|
||||||
with self._lock:
|
|
||||||
return self._n
|
|
||||||
|
|
||||||
@property
|
|
||||||
def escalated(self) -> bool:
|
|
||||||
with self._lock:
|
|
||||||
return self._escalated
|
|
||||||
|
|
||||||
@property
|
|
||||||
def streak(self) -> int:
|
|
||||||
with self._lock:
|
|
||||||
return self._streak
|
|
||||||
|
|
||||||
@property
|
|
||||||
def accepted(self) -> int:
|
|
||||||
with self._lock:
|
|
||||||
return self._accepted
|
|
||||||
|
|
||||||
@property
|
|
||||||
def rejected(self) -> int:
|
|
||||||
with self._lock:
|
|
||||||
return self._rejected
|
|
||||||
|
|
||||||
@property
|
|
||||||
def model_key(self) -> Optional[Tuple[str, str]]:
|
|
||||||
with self._lock:
|
|
||||||
return self._model_key
|
|
||||||
|
|
||||||
# ── Intern ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def _stddev_locked(self) -> float:
|
|
||||||
if self._n < 2.0:
|
|
||||||
return 0.0
|
|
||||||
return math.sqrt(self._m2 / self._n)
|
|
||||||
|
|
||||||
def _apply_decay_locked(self) -> None:
|
|
||||||
"""7-Tage-Exponential-Decay: alte Messungen verblassen.
|
|
||||||
|
|
||||||
Sub-Sekunden-Intervalle werden übersprungen — der Decay über
|
|
||||||
Mikrosekunden ist numerisch bedeutungslos und erzeugt nur
|
|
||||||
Float-Rauschen im effektiven Stichprobenumfang ``n``.
|
|
||||||
"""
|
|
||||||
now = self._clock()
|
|
||||||
if self._last_ts is not None and self._n > 0.0:
|
|
||||||
dt = now - self._last_ts
|
|
||||||
if dt >= 1.0:
|
|
||||||
alpha = math.exp(-dt / self._decay_tau_s)
|
|
||||||
self._n *= alpha
|
|
||||||
self._m2 *= alpha
|
|
||||||
self._last_ts = now
|
|
||||||
|
|
||||||
def _maybe_escalate_locked(self) -> None:
|
|
||||||
if self._streak >= self._escalation_n and not self._escalated:
|
|
||||||
self._escalated = True
|
|
||||||
logger.warning(
|
|
||||||
"F93: Adaptive-Timeout-Eskalation — %d konsekutive Messungen "
|
|
||||||
"außerhalb Toleranz (mean=%.2fs, std=%.2fs). Temporäre Last "
|
|
||||||
"oder Modell-/Endpoint-Problem?",
|
|
||||||
self._streak, self._mean, self._stddev_locked(),
|
|
||||||
)
|
|
||||||
|
|
||||||
# ── Persistenz (P-101: atomar via tmp+rename) ────────────────────────
|
|
||||||
|
|
||||||
def _save_locked(self) -> None:
|
|
||||||
if not self._state_path:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
data = {
|
|
||||||
"n": self._n,
|
|
||||||
"mean": self._mean,
|
|
||||||
"m2": self._m2,
|
|
||||||
"last_ts": self._last_ts,
|
|
||||||
"model_key": list(self._model_key) if self._model_key else None,
|
|
||||||
"accepted": self._accepted,
|
|
||||||
"rejected": self._rejected,
|
|
||||||
}
|
|
||||||
directory = os.path.dirname(self._state_path)
|
|
||||||
os.makedirs(directory, exist_ok=True)
|
|
||||||
tmp_path = self._state_path + ".tmp"
|
|
||||||
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(data, f, ensure_ascii=False)
|
|
||||||
os.replace(tmp_path, self._state_path)
|
|
||||||
except Exception as e: # Persistenz ist best-effort, nie fatal.
|
|
||||||
logger.warning("F93: Adaptive-Timeout-Persistenz fehlgeschlagen: %s", e)
|
|
||||||
|
|
||||||
def _load(self) -> None:
|
|
||||||
if not self._state_path or not os.path.exists(self._state_path):
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
with open(self._state_path, "r", encoding="utf-8") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
self._n = float(data.get("n", 0.0))
|
|
||||||
self._mean = float(data.get("mean", 0.0))
|
|
||||||
self._m2 = float(data.get("m2", 0.0))
|
|
||||||
# F4: Negative n-Werte aus korrupten States sanitizen — n ist ein
|
|
||||||
# effektiver Stichprobenumfang und darf nie < 0 sein (würde sonst
|
|
||||||
# als Index/Iteration zu Fehlverhalten führen).
|
|
||||||
if self._n < 0.0:
|
|
||||||
self._n = 0.0
|
|
||||||
if self._m2 < 0.0:
|
|
||||||
self._m2 = 0.0
|
|
||||||
self._last_ts = data.get("last_ts")
|
|
||||||
mk = data.get("model_key")
|
|
||||||
self._model_key = tuple(mk) if mk else None
|
|
||||||
self._accepted = int(data.get("accepted", 0))
|
|
||||||
self._rejected = int(data.get("rejected", 0))
|
|
||||||
logger.info(
|
|
||||||
"F93: Adaptive-Timeout-Kalibrierung geladen (n=%.1f, mean=%.2fs)",
|
|
||||||
self._n, self._mean,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("F93: Adaptive-Timeout-State laden fehlgeschlagen: %s", e)
|
|
||||||
|
|
||||||
|
|
||||||
# Modul-Level-Singleton — wird von classifier.py (OllamaLLMClient) importiert.
|
|
||||||
adaptive_timeout = AdaptiveLLMTimeout()
|
|
||||||
@@ -28,7 +28,6 @@ from .config import (
|
|||||||
LLM_CONFIDENCE_THRESHOLD,
|
LLM_CONFIDENCE_THRESHOLD,
|
||||||
FALLBACK_KEYWORDS
|
FALLBACK_KEYWORDS
|
||||||
)
|
)
|
||||||
from .adaptive_timeout import adaptive_timeout
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -251,31 +250,19 @@ class OllamaLLMClient(LLMClient):
|
|||||||
Args:
|
Args:
|
||||||
base_url: Ollama base URL (default from ``config.LLM_CONFIG``).
|
base_url: Ollama base URL (default from ``config.LLM_CONFIG``).
|
||||||
model: LLM model (default from ``config.LLM_CONFIG``).
|
model: LLM model (default from ``config.LLM_CONFIG``).
|
||||||
timeout: Deprecated/ignored. Der Timeout wird seit F93 adaptiv
|
timeout: Request timeout in seconds (default from ``config.LLM_CONFIG``).
|
||||||
über ``adaptive_timeout.current_timeout()`` bestimmt; der
|
|
||||||
Parameter bleibt nur für API-Kompatibilität erhalten.
|
|
||||||
"""
|
"""
|
||||||
self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/")
|
self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/")
|
||||||
self._model = model or LLM_CONFIG["model"]
|
self._model = model or LLM_CONFIG["model"]
|
||||||
# F93: Modell-Schlüssel registrieren (Reset bei Modellwechsel).
|
self._timeout = timeout or LLM_CONFIG["timeout"]
|
||||||
adaptive_timeout.set_model(self._base_url, self._model)
|
|
||||||
|
|
||||||
def _call_generate(self, prompt: str) -> Optional[str]:
|
def classify(self, text: str) -> Optional[str]:
|
||||||
"""Führe einen /api/generate-Call mit adaptivem Timeout aus.
|
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||||
|
|
||||||
F93: Der Timeout wird aus der selbstkalibrierenden Statistik
|
|
||||||
(``adaptive_timeout.current_timeout()``) bezogen. Die gemessene
|
|
||||||
Antwortzeit wird zurückgespeist (``record``), Timeouts/Fehler als
|
|
||||||
außerhalb-Toleranz gewertet (Eskalations-Streak).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Der ``response``-String oder None bei Fehler/Timeout.
|
|
||||||
"""
|
|
||||||
url = f"{self._base_url}/api/generate"
|
url = f"{self._base_url}/api/generate"
|
||||||
payload = json.dumps(
|
payload = json.dumps(
|
||||||
{
|
{
|
||||||
"model": self._model,
|
"model": self._model,
|
||||||
"prompt": prompt,
|
"prompt": text,
|
||||||
"stream": False,
|
"stream": False,
|
||||||
"options": {
|
"options": {
|
||||||
"temperature": LLM_CONFIG["temperature"],
|
"temperature": LLM_CONFIG["temperature"],
|
||||||
@@ -285,50 +272,35 @@ class OllamaLLMClient(LLMClient):
|
|||||||
).encode("utf-8")
|
).encode("utf-8")
|
||||||
headers = {"Content-Type": "application/json"}
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
timeout = adaptive_timeout.current_timeout()
|
|
||||||
t0 = time.monotonic()
|
|
||||||
try:
|
try:
|
||||||
req = urllib.request.Request(
|
req = urllib.request.Request(
|
||||||
url, data=payload, headers=headers, method="POST"
|
url, data=payload, headers=headers, method="POST"
|
||||||
)
|
)
|
||||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||||||
data = json.loads(resp.read().decode("utf-8"))
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
duration = time.monotonic() - t0
|
response_text = data.get("response", "")
|
||||||
adaptive_timeout.record(duration, success=True)
|
if not response_text:
|
||||||
return data.get("response", "")
|
logger.error("Ollama returned empty response")
|
||||||
except (urllib.error.HTTPError, urllib.error.URLError) as e:
|
return None
|
||||||
duration = time.monotonic() - t0
|
|
||||||
adaptive_timeout.record(duration, success=False)
|
# Trim whitespace and normalize category
|
||||||
logger.warning("Ollama request failed: %s", e)
|
category = response_text.strip().lower()
|
||||||
|
if category in ("direct_question", "smalltalk", "work_order", "ambiguous"):
|
||||||
|
return category
|
||||||
|
else:
|
||||||
|
logger.warning("LLM returned invalid category: %s", category)
|
||||||
|
return None
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.warning("Ollama HTTP %d: %s", e.code, e.reason)
|
||||||
|
return None
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
logger.warning("Ollama connection failed: %s", e)
|
||||||
return None
|
return None
|
||||||
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||||
# F6a: Parse-Fehler = kaputtes Modell/Endpoint (Server liefert Müll
|
|
||||||
# oder Verarbeitungsfehler) → success=False, damit der
|
|
||||||
# Eskalations-Streak getriggert wird (Spec: Eskalation bei
|
|
||||||
# "Modell-/Endpoint-Problem").
|
|
||||||
duration = time.monotonic() - t0
|
|
||||||
adaptive_timeout.record(duration, success=False)
|
|
||||||
logger.error("Ollama response parse error: %s", e)
|
logger.error("Ollama response parse error: %s", e)
|
||||||
return None
|
return None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
duration = time.monotonic() - t0
|
logger.error("Unexpected error in classify: %s", e)
|
||||||
adaptive_timeout.record(duration, success=False)
|
|
||||||
logger.error("Unexpected error in LLM call: %s", e)
|
|
||||||
return None
|
|
||||||
|
|
||||||
def classify(self, text: str) -> Optional[str]:
|
|
||||||
"""Call Ollama generate API. Returns category or None on any failure."""
|
|
||||||
response_text = self._call_generate(text)
|
|
||||||
if not response_text:
|
|
||||||
logger.error("Ollama returned empty response")
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Trim whitespace and normalize category
|
|
||||||
category = response_text.strip().lower()
|
|
||||||
if category in ("direct_question", "smalltalk", "work_order", "ambiguous"):
|
|
||||||
return category
|
|
||||||
else:
|
|
||||||
logger.warning("LLM returned invalid category: %s", category)
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||||
@@ -364,11 +336,43 @@ direct_question, smalltalk, work_order, oder ambiguous"""
|
|||||||
Returns:
|
Returns:
|
||||||
Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
|
Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
|
||||||
"""
|
"""
|
||||||
response_text = self._call_generate(prompt)
|
url = f"{self._base_url}/api/generate"
|
||||||
if not response_text:
|
payload = json.dumps(
|
||||||
logger.error("Ollama returned empty response for generate()")
|
{
|
||||||
|
"model": self._model,
|
||||||
|
"prompt": prompt,
|
||||||
|
"stream": False,
|
||||||
|
"options": {
|
||||||
|
"temperature": LLM_CONFIG["temperature"],
|
||||||
|
"num_predict": LLM_CONFIG["max_tokens"],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
).encode("utf-8")
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=payload, headers=headers, method="POST"
|
||||||
|
)
|
||||||
|
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||||||
|
data = json.loads(resp.read().decode("utf-8"))
|
||||||
|
response_text = data.get("response", "")
|
||||||
|
if not response_text:
|
||||||
|
logger.error("Ollama returned empty response for generate()")
|
||||||
|
return None
|
||||||
|
return response_text.strip()
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.warning("Ollama HTTP %d in generate(): %s", e.code, e.reason)
|
||||||
|
return None
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
logger.warning("Ollama connection failed in generate(): %s", e)
|
||||||
|
return None
|
||||||
|
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||||
|
logger.error("Ollama response parse error in generate(): %s", e)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Unexpected error in generate(): %s", e)
|
||||||
return None
|
return None
|
||||||
return response_text.strip()
|
|
||||||
|
|
||||||
|
|
||||||
class IntentClassifier:
|
class IntentClassifier:
|
||||||
|
|||||||
@@ -3128,13 +3128,67 @@ class PresenceEngine:
|
|||||||
self._status = "BUSY"
|
self._status = "BUSY"
|
||||||
# AWAY existiert nicht mehr als interner Status — wird über get_visible_status()
|
# AWAY existiert nicht mehr als interner Status — wird über get_visible_status()
|
||||||
|
|
||||||
# ── Schicht 3: REST-Sender (fire-and-forget, fast unverändert aus V9) ─
|
# ── Schicht 3: REST-Sender (fire-and-forget, fast unverändert aus V9) ──
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _extract_http_status_code(exc: BaseException) -> Optional[int]:
|
||||||
|
"""Extrahiere den HTTP-Status-Code aus einer Exception (falls vorhanden).
|
||||||
|
|
||||||
|
WV-002: Statt den String '429' im Exception-Text zu vermuten, wird der
|
||||||
|
echte HTTP-Status-Code ermittelt. Prüf-Reihenfolge:
|
||||||
|
|
||||||
|
1. ``urllib.error.HTTPError`` → ``.code`` (echter HTTP-Status).
|
||||||
|
2. ``RocketChatRateLimitError`` → 429 (per Definition HTTP 429).
|
||||||
|
Per Typname geprüft, um einen Circular-Import (adapter ↔
|
||||||
|
presence_engine) zu vermeiden.
|
||||||
|
3. ``__cause__``-Kette (``raise ... from e``) → HTTPError/429.
|
||||||
|
4. ``.status_code`` / ``.status`` / ``.code``-Attribute (falls gesetzt).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int HTTP-Status-Code oder ``None`` wenn keiner ermittelbar ist.
|
||||||
|
"""
|
||||||
|
# 1. Direkt HTTPError
|
||||||
|
if isinstance(exc, urllib.error.HTTPError):
|
||||||
|
return exc.code
|
||||||
|
# 2. RocketChatRateLimitError (immer 429)
|
||||||
|
if type(exc).__name__ == "RocketChatRateLimitError":
|
||||||
|
return 429
|
||||||
|
# 3. __cause__-Kette
|
||||||
|
cause = exc.__cause__
|
||||||
|
while cause is not None:
|
||||||
|
if isinstance(cause, urllib.error.HTTPError):
|
||||||
|
return cause.code
|
||||||
|
if type(cause).__name__ == "RocketChatRateLimitError":
|
||||||
|
return 429
|
||||||
|
cause = cause.__cause__
|
||||||
|
# 4. Status-Attribute
|
||||||
|
for attr in ("status_code", "status", "code"):
|
||||||
|
val = getattr(exc, attr, None)
|
||||||
|
if isinstance(val, int):
|
||||||
|
return val
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _is_http_429(exc: BaseException, http_code: Optional[int]) -> bool:
|
||||||
|
"""True NUR bei echtem HTTP 429 (Status-Code-Prüfung).
|
||||||
|
|
||||||
|
WV-002: Kein String-Matching auf '429' im Exception-Text — das
|
||||||
|
klassifizierte DDP-Timeouts und REST-Token-Errors fälschlich als 429
|
||||||
|
(Phantom-429er).
|
||||||
|
"""
|
||||||
|
if http_code == 429:
|
||||||
|
return True
|
||||||
|
# Fallback: RocketChatRateLimitError ist per Definition 429.
|
||||||
|
return type(exc).__name__ == "RocketChatRateLimitError"
|
||||||
|
|
||||||
def _rest_set_status(self, status: str, message: str) -> bool:
|
def _rest_set_status(self, status: str, message: str) -> bool:
|
||||||
"""Sende users.setStatus via REST (synchron).
|
"""Sende users.setStatus via REST (synchron).
|
||||||
|
|
||||||
Wird vom Mediator in einem fire-and-forget Daemon-Thread aufgerufen.
|
Wird vom Mediator in einem fire-and-forget Daemon-Thread aufgerufen.
|
||||||
Bei 429: setzt Mediator-Cooldown (Rückkanal).
|
Bei ECHTEM HTTP 429 (Status-Code-Prüfung): setzt Mediator-Cooldown
|
||||||
|
(Rückkanal). Andere Exceptions (DDP-Timeout, Token-Error, etc.)
|
||||||
|
triggern KEINEN Cooldown — nur korrektes Logging (Typ + Message +
|
||||||
|
HTTP-Status-Code).
|
||||||
|
|
||||||
POST /api/v1/users.setStatus
|
POST /api/v1/users.setStatus
|
||||||
Body: {"status": "...", "message": "..."}
|
Body: {"status": "...", "message": "..."}
|
||||||
@@ -3181,8 +3235,12 @@ class PresenceEngine:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_str = str(e).lower()
|
# WV-002: Exception-Typ, volle Message UND HTTP-Status-Code loggen.
|
||||||
if "429" in error_str or "too many requests" in error_str:
|
exc_type = type(e).__name__
|
||||||
|
http_code = self._extract_http_status_code(e)
|
||||||
|
is_429 = self._is_http_429(e, http_code)
|
||||||
|
|
||||||
|
if is_429:
|
||||||
self._telemetry_rest_429 += 1
|
self._telemetry_rest_429 += 1
|
||||||
# V10: Setze Mediator-Cooldown (Rückkanal) — jetzt mit exp. Backoff
|
# V10: Setze Mediator-Cooldown (Rückkanal) — jetzt mit exp. Backoff
|
||||||
self._mediator.set_rest_cooldown()
|
self._mediator.set_rest_cooldown()
|
||||||
@@ -3193,18 +3251,21 @@ class PresenceEngine:
|
|||||||
if self._mediator._clarify_modal:
|
if self._mediator._clarify_modal:
|
||||||
self._mediator._on_modal_pulse_fail()
|
self._mediator._on_modal_pulse_fail()
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[presence-v10] REST 429 — Cooldown gesetzt, "
|
"[presence-v10] REST 429 (HTTP %s) — Cooldown gesetzt, "
|
||||||
"Status %s verworfen", status
|
"Status %s verworfen (exc=%s: %s)",
|
||||||
|
http_code, status, exc_type, e,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# Kein echter 429 — KEIN Cooldown (Phantom-429-Schutz).
|
||||||
self._telemetry_rest_errors += 1
|
self._telemetry_rest_errors += 1
|
||||||
# P-050: Modal-Puls-Fail signalisieren
|
# P-050: Modal-Puls-Fail signalisieren
|
||||||
if self._mediator._clarify_modal:
|
if self._mediator._clarify_modal:
|
||||||
self._mediator._on_modal_pulse_fail()
|
self._mediator._on_modal_pulse_fail()
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[presence-v10] REST-Fehler (1. Versuch): %s — retry in %.1fs",
|
"[presence-v10] REST-Fehler (1. Versuch): exc=%s, http_code=%s, "
|
||||||
e, self.RETRY_DELAY_S,
|
"msg=%s — retry in %.1fs",
|
||||||
|
exc_type, http_code, e, self.RETRY_DELAY_S,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Ein Retry nach 2s
|
# Ein Retry nach 2s
|
||||||
@@ -3230,11 +3291,23 @@ class PresenceEngine:
|
|||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
except Exception as e2:
|
except Exception as e2:
|
||||||
self._telemetry_rest_errors += 1
|
# WV-002: Auch im Retry Typ + Message + HTTP-Status-Code loggen.
|
||||||
|
exc_type2 = type(e2).__name__
|
||||||
|
http_code2 = self._extract_http_status_code(e2)
|
||||||
|
is_429_2 = self._is_http_429(e2, http_code2)
|
||||||
|
if is_429_2:
|
||||||
|
self._telemetry_rest_429 += 1
|
||||||
|
self._mediator.set_rest_cooldown()
|
||||||
|
if self._ddp_sender is not None:
|
||||||
|
self._ddp_sender.on_rest_429()
|
||||||
|
else:
|
||||||
|
self._telemetry_rest_errors += 1
|
||||||
# P-050: Modal-Puls-Fail signalisieren
|
# P-050: Modal-Puls-Fail signalisieren
|
||||||
if self._mediator._clarify_modal:
|
if self._mediator._clarify_modal:
|
||||||
self._mediator._on_modal_pulse_fail()
|
self._mediator._on_modal_pulse_fail()
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"[presence-v10] REST-Fehler (Retry): %s — aufgegeben", e2
|
"[presence-v10] REST-Fehler (Retry): exc=%s, http_code=%s, "
|
||||||
|
"msg=%s — aufgegeben",
|
||||||
|
exc_type2, http_code2, e2,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -1,331 +0,0 @@
|
|||||||
"""
|
|
||||||
F93 — Adaptiver LLM-Timeout: A1c-Testkonzept (verbindlich).
|
|
||||||
|
|
||||||
Kalibrierungs-Fälle (Spec, Feature-Register Zeile F93):
|
|
||||||
1. Failsafe — ohne Kalibrierungsdaten liefert current_timeout() 30s.
|
|
||||||
2. Konvergenz — Welford konvergiert gegen den wahren Mittelwert;
|
|
||||||
current_timeout() = mean + sigma_band * std.
|
|
||||||
3. Ausreißer — ±2σ-Messung wird verworfen (nicht in Statistik).
|
|
||||||
4. Reset — Modellwechsel setzt die Kalibrierung hart zurück.
|
|
||||||
5. Eskalation — erst N=2 konsekutive Messungen außerhalb Toleranz
|
|
||||||
setzen escalated=True (nicht schon die erste).
|
|
||||||
|
|
||||||
Zusätzlich (Design-Entscheidungen):
|
|
||||||
6. Score-basiert (FAISS-Analog) — score() liefert kontinuierlichen z-Score.
|
|
||||||
7. 7-Tage-Decay — alte Messungen verblassen (n sinkt, mean bleibt).
|
|
||||||
8. Persistenz — save/load roundtrip erhält den Kalibrierungszustand.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import math
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
||||||
|
|
||||||
from plugin.archivar.adaptive_timeout import AdaptiveLLMTimeout
|
|
||||||
|
|
||||||
|
|
||||||
def _make(**kwargs):
|
|
||||||
"""Frische Instanz ohne Persistenz (state_path=None) für deterministische Tests."""
|
|
||||||
kwargs.setdefault("state_path", None)
|
|
||||||
kwargs.setdefault("failsafe_s", 30.0)
|
|
||||||
kwargs.setdefault("sigma_band", 2.0)
|
|
||||||
kwargs.setdefault("decay_tau_s", 7 * 24 * 3600)
|
|
||||||
kwargs.setdefault("escalation_n", 2)
|
|
||||||
kwargs.setdefault("min_samples", 3)
|
|
||||||
return AdaptiveLLMTimeout(**kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 1. Failsafe
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestFailsafe:
|
|
||||||
def test_no_data_returns_failsafe(self):
|
|
||||||
t = _make()
|
|
||||||
assert t.current_timeout() == 30.0
|
|
||||||
|
|
||||||
def test_failsafe_until_first_sample(self):
|
|
||||||
t = _make()
|
|
||||||
# Eine einzelne Messung reicht nicht für mean+band (n<2 → std=0).
|
|
||||||
t.record(5.0)
|
|
||||||
# n=1 → current_timeout liefert weiterhin Failsafe (n < 1.0 ist false,
|
|
||||||
# aber std=0 → mean+0 = mean). Spec: Failsafe beim ersten Start.
|
|
||||||
# Mit n=1 ist mean=5.0, std=0 → timeout=5.0 (geklemmt auf min 1.0).
|
|
||||||
assert t.current_timeout() >= 1.0
|
|
||||||
|
|
||||||
def test_custom_failsafe(self):
|
|
||||||
t = _make(failsafe_s=45.0)
|
|
||||||
assert t.current_timeout() == 45.0
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 2. Konvergenz (Welford)
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestConvergence:
|
|
||||||
def test_welford_mean_converges(self):
|
|
||||||
t = _make()
|
|
||||||
samples = [5.0, 5.0, 5.0, 5.0, 5.0]
|
|
||||||
for s in samples:
|
|
||||||
t.record(s)
|
|
||||||
assert t.mean == pytest.approx(5.0)
|
|
||||||
assert t.stddev == pytest.approx(0.0, abs=1e-9)
|
|
||||||
|
|
||||||
def test_welford_matches_batch_formula(self):
|
|
||||||
"""Welford-Online == klassische Batch-Formel (Korrektheits-Beweis).
|
|
||||||
|
|
||||||
min_samples hoch gesetzt, damit die Ausreißer-Erkennung die
|
|
||||||
Welford-Mathematik nicht verfälscht (hier geht es rein um die
|
|
||||||
Korrektheit des Online-Algorithmus).
|
|
||||||
"""
|
|
||||||
t = _make(min_samples=1000)
|
|
||||||
samples = [3.0, 7.0, 5.0, 9.0, 4.0, 6.0]
|
|
||||||
for s in samples:
|
|
||||||
t.record(s)
|
|
||||||
n = len(samples)
|
|
||||||
mean = sum(samples) / n
|
|
||||||
var = sum((x - mean) ** 2 for x in samples) / n
|
|
||||||
assert t.mean == pytest.approx(mean)
|
|
||||||
assert t.stddev == pytest.approx(math.sqrt(var))
|
|
||||||
|
|
||||||
def test_timeout_is_mean_plus_band(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
|
||||||
t.record(s)
|
|
||||||
# std=0 → timeout = mean = 5.0 (geklemmt auf min 1.0).
|
|
||||||
assert t.current_timeout() == pytest.approx(5.0)
|
|
||||||
|
|
||||||
def test_timeout_grows_with_variance(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [4.0, 6.0, 4.0, 6.0, 4.0, 6.0]:
|
|
||||||
t.record(s)
|
|
||||||
# mean=5, std≈1 → timeout ≈ 5 + 2*1 = 7.
|
|
||||||
assert t.current_timeout() == pytest.approx(7.0, abs=0.2)
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 3. Ausreißer-Erkennung (±2σ → verwerfen)
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestOutlierRejection:
|
|
||||||
def test_outlier_rejected_not_in_statistics(self):
|
|
||||||
t = _make()
|
|
||||||
# Kalibrierung: 6 Messungen um 5.0 mit kleiner Varianz (std > 0).
|
|
||||||
for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]:
|
|
||||||
t.record(s)
|
|
||||||
n_before = t.n
|
|
||||||
mean_before = t.mean
|
|
||||||
# Ausreißer: 50s (Docker-Start) → > 2σ → verwerfen.
|
|
||||||
z = t.record(50.0)
|
|
||||||
assert abs(z) > 2.0
|
|
||||||
assert t.n == pytest.approx(n_before) # nicht eingerechnet
|
|
||||||
assert t.mean == pytest.approx(mean_before)
|
|
||||||
assert t.rejected == 1
|
|
||||||
|
|
||||||
def test_inlier_accepted(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]:
|
|
||||||
t.record(s)
|
|
||||||
n_before = t.n
|
|
||||||
z = t.record(5.05) # innerhalb Toleranz (std ≈ 0.08 → z ≈ 0.6)
|
|
||||||
assert abs(z) <= 2.0
|
|
||||||
assert t.n == pytest.approx(n_before + 1)
|
|
||||||
|
|
||||||
def test_no_rejection_during_calibration(self):
|
|
||||||
"""Vor min_samples wird alles akzeptiert (Std instabil)."""
|
|
||||||
t = _make(min_samples=3)
|
|
||||||
# Nur 2 Messungen → noch Kalibrierung → 50s wird akzeptiert.
|
|
||||||
t.record(5.0)
|
|
||||||
t.record(5.0)
|
|
||||||
t.record(50.0) # akzeptiert, weil n < min_samples
|
|
||||||
assert t.n == pytest.approx(3.0)
|
|
||||||
assert t.rejected == 0
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 4. Reset bei Modellwechsel
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestModelReset:
|
|
||||||
def test_same_model_no_reset(self):
|
|
||||||
t = _make()
|
|
||||||
assert t.set_model("http://localhost:11434", "qwen2.5:7b") is True # erster Set
|
|
||||||
for s in [5.0, 5.0, 5.0]:
|
|
||||||
t.record(s)
|
|
||||||
assert t.set_model("http://localhost:11434", "qwen2.5:7b") is False
|
|
||||||
assert t.n == 3 # unverändert
|
|
||||||
|
|
||||||
def test_model_change_hard_reset(self):
|
|
||||||
t = _make()
|
|
||||||
t.set_model("http://localhost:11434", "qwen2.5:7b")
|
|
||||||
for s in [5.0, 5.0, 5.0]:
|
|
||||||
t.record(s)
|
|
||||||
assert t.n == 3
|
|
||||||
# Modellwechsel → Reset.
|
|
||||||
assert t.set_model("http://localhost:11434", "gemma4:31b") is True
|
|
||||||
assert t.n == 0
|
|
||||||
assert t.current_timeout() == 30.0 # zurück auf Failsafe
|
|
||||||
|
|
||||||
def test_endpoint_change_resets(self):
|
|
||||||
t = _make()
|
|
||||||
t.set_model("http://localhost:11434", "qwen2.5:7b")
|
|
||||||
t.record(5.0)
|
|
||||||
assert t.set_model("https://ollama.com/v1", "qwen2.5:7b") is True
|
|
||||||
assert t.n == 0
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 5. Eskalation (N=2 konsekutiv)
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestEscalation:
|
|
||||||
def test_single_outlier_no_escalation(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]:
|
|
||||||
t.record(s)
|
|
||||||
t.record(50.0) # 1. Ausreißer
|
|
||||||
assert t.escalated is False
|
|
||||||
assert t.streak == 1
|
|
||||||
|
|
||||||
def test_two_consecutive_outliers_escalate(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]:
|
|
||||||
t.record(s)
|
|
||||||
t.record(50.0) # 1. Ausreißer → streak=1
|
|
||||||
t.record(60.0) # 2. Ausreißer → streak=2 → Eskalation
|
|
||||||
assert t.escalated is True
|
|
||||||
|
|
||||||
def test_inlier_resets_streak(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]:
|
|
||||||
t.record(s)
|
|
||||||
t.record(50.0) # streak=1
|
|
||||||
t.record(5.1) # inlier → streak=0
|
|
||||||
assert t.streak == 0
|
|
||||||
assert t.escalated is False
|
|
||||||
|
|
||||||
def test_failure_counts_as_out_of_tolerance(self):
|
|
||||||
"""Timeout/Fehler (success=False) zählt als außerhalb Toleranz."""
|
|
||||||
t = _make()
|
|
||||||
for s in [4.9, 5.0, 5.1, 4.9, 5.0, 5.1]:
|
|
||||||
t.record(s)
|
|
||||||
t.record(0.0, success=False) # streak=1
|
|
||||||
t.record(0.0, success=False) # streak=2 → Eskalation
|
|
||||||
assert t.escalated is True
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 6. Score-basiert (FAISS-Analog)
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestScore:
|
|
||||||
def test_score_zero_at_mean(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
|
||||||
t.record(s)
|
|
||||||
assert t.score(5.0) == pytest.approx(0.0, abs=1e-9)
|
|
||||||
|
|
||||||
def test_score_continuous(self):
|
|
||||||
t = _make()
|
|
||||||
for s in [4.0, 6.0, 4.0, 6.0, 4.0, 6.0]:
|
|
||||||
t.record(s)
|
|
||||||
# mean=5, std≈1 → score(7) ≈ 2.0, score(3) ≈ -2.0.
|
|
||||||
assert t.score(7.0) == pytest.approx(2.0, abs=0.2)
|
|
||||||
assert t.score(3.0) == pytest.approx(-2.0, abs=0.2)
|
|
||||||
|
|
||||||
def test_score_zero_during_calibration(self):
|
|
||||||
t = _make()
|
|
||||||
t.record(5.0)
|
|
||||||
assert t.score(100.0) == 0.0 # n<2 → kein Score
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 7. 7-Tage-Exponential-Decay
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestDecay:
|
|
||||||
def test_decay_reduces_effective_n(self):
|
|
||||||
# Fake-Clock: kontrollierbarer Zeitverlauf.
|
|
||||||
now = [0.0]
|
|
||||||
|
|
||||||
def fake_clock():
|
|
||||||
return now[0]
|
|
||||||
|
|
||||||
t = _make(clock=fake_clock, decay_tau_s=100.0)
|
|
||||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
|
||||||
t.record(s)
|
|
||||||
assert t.n == pytest.approx(4.0)
|
|
||||||
# 100s später (1 tau) → n halbiert sich beim nächsten record.
|
|
||||||
now[0] = 100.0
|
|
||||||
t.record(5.0)
|
|
||||||
# n war 4, decay auf ~1.47, +1 = ~2.47.
|
|
||||||
assert t.n < 4.0
|
|
||||||
assert t.n > 1.0
|
|
||||||
|
|
||||||
def test_decay_keeps_mean_stable(self):
|
|
||||||
now = [0.0]
|
|
||||||
|
|
||||||
def fake_clock():
|
|
||||||
return now[0]
|
|
||||||
|
|
||||||
t = _make(clock=fake_clock, decay_tau_s=100.0)
|
|
||||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
|
||||||
t.record(s)
|
|
||||||
mean_before = t.mean
|
|
||||||
now[0] = 100.0
|
|
||||||
t.record(5.0)
|
|
||||||
assert t.mean == pytest.approx(mean_before) # uniforme Skalierung
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# 8. Persistenz (P-101: save/load roundtrip)
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestPersistence:
|
|
||||||
def test_roundtrip(self, tmp_path):
|
|
||||||
state_path = str(tmp_path / "adaptive_timeout_state.json")
|
|
||||||
t = _make(state_path=state_path)
|
|
||||||
t.set_model("http://localhost:11434", "qwen2.5:7b")
|
|
||||||
for s in [5.0, 5.0, 5.0, 5.0]:
|
|
||||||
t.record(s)
|
|
||||||
|
|
||||||
# Neue Instanz lädt denselben State.
|
|
||||||
t2 = _make(state_path=state_path)
|
|
||||||
assert t2.n == pytest.approx(t.n)
|
|
||||||
assert t2.mean == pytest.approx(t.mean)
|
|
||||||
assert t2.model_key == ("http://localhost:11434", "qwen2.5:7b")
|
|
||||||
|
|
||||||
def test_load_missing_file_is_noop(self, tmp_path):
|
|
||||||
state_path = str(tmp_path / "does_not_exist.json")
|
|
||||||
t = _make(state_path=state_path)
|
|
||||||
assert t.n == 0
|
|
||||||
assert t.current_timeout() == 30.0
|
|
||||||
|
|
||||||
def test_load_sanitizes_negative_n(self, tmp_path):
|
|
||||||
"""F4: Negative n-Werte aus korrupten States werden auf 0.0 gesetzt."""
|
|
||||||
import json as _json
|
|
||||||
state_path = str(tmp_path / "adaptive_timeout_state.json")
|
|
||||||
_json.dump(
|
|
||||||
{"n": -5.0, "mean": 3.0, "m2": -1.0, "model_key": ["http://x", "m"]},
|
|
||||||
open(state_path, "w"),
|
|
||||||
)
|
|
||||||
t = _make(state_path=state_path)
|
|
||||||
assert t.n == 0.0
|
|
||||||
assert t.current_timeout() == 30.0 # n<1 → Failsafe
|
|
||||||
|
|
||||||
def test_load_sanitizes_negative_m2(self, tmp_path):
|
|
||||||
"""F4: Negative m2 (Varianz-Summe) wird auf 0.0 gesetzt."""
|
|
||||||
import json as _json
|
|
||||||
state_path = str(tmp_path / "adaptive_timeout_state.json")
|
|
||||||
_json.dump(
|
|
||||||
{"n": 4.0, "mean": 5.0, "m2": -3.0, "model_key": ["http://x", "m"]},
|
|
||||||
open(state_path, "w"),
|
|
||||||
)
|
|
||||||
t = _make(state_path=state_path)
|
|
||||||
assert t.n == 4.0
|
|
||||||
assert t.stddev == 0.0 # m2=0 → std=0
|
|
||||||
@@ -1,130 +0,0 @@
|
|||||||
"""
|
|
||||||
F93 — F6a-Fix: JSON-Parse-Fehler in _call_generate → success=False.
|
|
||||||
|
|
||||||
Rainer-QG Round 1 (Befund F6a): json.JSONDecodeError/TypeError/ValueError
|
|
||||||
wurden fälschlich als success=True gewertet. Semantisch korrekt ist
|
|
||||||
success=False, damit ein kaputtes Modell/Endpoint den Eskalations-Streak
|
|
||||||
triggert (Spec: Eskalation bei "Modell-/Endpoint-Problem").
|
|
||||||
|
|
||||||
Diese Tests verifizieren, dass der Parse-Fehler-Pfad in
|
|
||||||
``OllamaLLMClient._call_generate`` den adaptiven Timeout mit
|
|
||||||
``success=False`` speist (und nicht mehr ``success=True``).
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
from unittest import mock
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
|
||||||
|
|
||||||
from plugin.archivar import classifier as classifier_mod
|
|
||||||
from plugin.archivar.classifier import OllamaLLMClient
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeResponse:
|
|
||||||
"""Context-Manager-Response, dessen read() einen gegebenen Body liefert."""
|
|
||||||
|
|
||||||
def __init__(self, body: bytes):
|
|
||||||
self._body = body
|
|
||||||
|
|
||||||
def __enter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
def __exit__(self, *exc):
|
|
||||||
return False
|
|
||||||
|
|
||||||
def read(self) -> bytes:
|
|
||||||
return self._body
|
|
||||||
|
|
||||||
|
|
||||||
def _make_client():
|
|
||||||
"""OllamaLLMClient ohne echten Netzwerkzugriff (nur für _call_generate)."""
|
|
||||||
return OllamaLLMClient(base_url="http://localhost:11434", model="qwen2.5:7b")
|
|
||||||
|
|
||||||
|
|
||||||
class TestF6aParseErrorRecordsFailure:
|
|
||||||
def test_json_decode_error_records_failure(self):
|
|
||||||
"""JSONDecodeError (Server liefert Müll) → success=False."""
|
|
||||||
client = _make_client()
|
|
||||||
# urlopen liefert ungültiges JSON → json.loads wirft JSONDecodeError.
|
|
||||||
with mock.patch.object(
|
|
||||||
classifier_mod.urllib.request, "urlopen",
|
|
||||||
return_value=_FakeResponse(b"not-json{{{"),
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "record"
|
|
||||||
) as mock_record:
|
|
||||||
result = client._call_generate("test prompt")
|
|
||||||
|
|
||||||
assert result is None
|
|
||||||
# record wurde mit success=False aufgerufen (F6a-Fix).
|
|
||||||
mock_record.assert_called_once()
|
|
||||||
_, kwargs = mock_record.call_args
|
|
||||||
assert kwargs["success"] is False
|
|
||||||
|
|
||||||
def test_type_error_records_failure(self):
|
|
||||||
"""TypeError (Verarbeitungsfehler) → success=False."""
|
|
||||||
client = _make_client()
|
|
||||||
# json.loads wirft TypeError (z.B. wenn resp.read() kein str/bytes liefert).
|
|
||||||
with mock.patch.object(
|
|
||||||
classifier_mod.urllib.request, "urlopen",
|
|
||||||
return_value=_FakeResponse(b"{}"),
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.json, "loads", side_effect=TypeError("bad type")
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "record"
|
|
||||||
) as mock_record:
|
|
||||||
result = client._call_generate("test prompt")
|
|
||||||
|
|
||||||
assert result is None
|
|
||||||
mock_record.assert_called_once()
|
|
||||||
_, kwargs = mock_record.call_args
|
|
||||||
assert kwargs["success"] is False
|
|
||||||
|
|
||||||
def test_value_error_records_failure(self):
|
|
||||||
"""ValueError (z.B. falsches Format) → success=False."""
|
|
||||||
client = _make_client()
|
|
||||||
# json.loads wirft ValueError bei ungültigem JSON-Format.
|
|
||||||
with mock.patch.object(
|
|
||||||
classifier_mod.urllib.request, "urlopen",
|
|
||||||
return_value=_FakeResponse(b"{}"),
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.json, "loads", side_effect=ValueError("bad value")
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "record"
|
|
||||||
) as mock_record:
|
|
||||||
result = client._call_generate("test prompt")
|
|
||||||
|
|
||||||
assert result is None
|
|
||||||
mock_record.assert_called_once()
|
|
||||||
_, kwargs = mock_record.call_args
|
|
||||||
assert kwargs["success"] is False
|
|
||||||
|
|
||||||
def test_valid_json_records_success(self):
|
|
||||||
"""Gegenprobe: gültiges JSON → success=True (kein Regression)."""
|
|
||||||
client = _make_client()
|
|
||||||
valid_body = json.dumps({"response": "direct_question"}).encode("utf-8")
|
|
||||||
with mock.patch.object(
|
|
||||||
classifier_mod.urllib.request, "urlopen",
|
|
||||||
return_value=_FakeResponse(valid_body),
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "current_timeout", return_value=30.0
|
|
||||||
), mock.patch.object(
|
|
||||||
classifier_mod.adaptive_timeout, "record"
|
|
||||||
) as mock_record:
|
|
||||||
result = client._call_generate("test prompt")
|
|
||||||
|
|
||||||
assert result == "direct_question"
|
|
||||||
mock_record.assert_called_once()
|
|
||||||
_, kwargs = mock_record.call_args
|
|
||||||
assert kwargs["success"] is True
|
|
||||||
@@ -797,11 +797,16 @@ class TestPresenceEngineWithDDP:
|
|||||||
assert engine._mediator._ddp_sender is None
|
assert engine._mediator._ddp_sender is None
|
||||||
|
|
||||||
def test_rest_429_triggers_ddp_on_rest_429(self):
|
def test_rest_429_triggers_ddp_on_rest_429(self):
|
||||||
"""REST 429 → ddp_sender.on_rest_429() wird aufgerufen."""
|
"""REST 429 → ddp_sender.on_rest_429() wird aufgerufen.
|
||||||
|
|
||||||
|
WV-002: Nutzt einen ECHTEN HTTP 429 (RocketChatRateLimitError),
|
||||||
|
nicht einen String '429' im Exception-Text (Phantom-429).
|
||||||
|
"""
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
adapter, ddp = _make_mock_adapter()
|
adapter, ddp = _make_mock_adapter()
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
# Simuliere 429
|
# Simuliere echten HTTP 429 via RocketChatRateLimitError
|
||||||
rest._request = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
rest._request = MagicMock(side_effect=RocketChatRateLimitError("HTTP 429"))
|
||||||
engine = PresenceEngine(rest=rest, use_ddp=True, adapter=adapter)
|
engine = PresenceEngine(rest=rest, use_ddp=True, adapter=adapter)
|
||||||
|
|
||||||
# Setze ddp_sender Mock
|
# Setze ddp_sender Mock
|
||||||
|
|||||||
@@ -413,8 +413,9 @@ class TestRestBackoffActivation:
|
|||||||
|
|
||||||
def test_429_sets_cooldown(self):
|
def test_429_sets_cooldown(self):
|
||||||
"""429-Antwort → rest_cooldown_until gesetzt."""
|
"""429-Antwort → rest_cooldown_until gesetzt."""
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
@@ -424,8 +425,9 @@ class TestRestBackoffActivation:
|
|||||||
|
|
||||||
def test_429_telemetry_counted(self):
|
def test_429_telemetry_counted(self):
|
||||||
"""Telemetrie zählt 429 + cooldown_set_count."""
|
"""Telemetrie zählt 429 + cooldown_set_count."""
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
@@ -883,8 +885,9 @@ class TestHttp429Handling:
|
|||||||
"""HTTP 429 von users.setStatus — kein Crash, Cooldown gesetzt."""
|
"""HTTP 429 von users.setStatus — kein Crash, Cooldown gesetzt."""
|
||||||
|
|
||||||
def test_429_no_crash_status_unchanged(self):
|
def test_429_no_crash_status_unchanged(self):
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
assert engine.get_status() == "BUSY"
|
assert engine.get_status() == "BUSY"
|
||||||
@@ -894,13 +897,14 @@ class TestHttp429Handling:
|
|||||||
assert engine.get_counters()["main_agent"] == 1
|
assert engine.get_counters()["main_agent"] == 1
|
||||||
|
|
||||||
def test_429_retry_on_next_hook(self):
|
def test_429_retry_on_next_hook(self):
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
call_count = [0]
|
call_count = [0]
|
||||||
|
|
||||||
def _side_effect(*args, **kwargs):
|
def _side_effect(*args, **kwargs):
|
||||||
call_count[0] += 1
|
call_count[0] += 1
|
||||||
if call_count[0] == 1:
|
if call_count[0] == 1:
|
||||||
raise Exception("HTTP 429 Too Many Requests")
|
raise RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
return {"success": True}
|
return {"success": True}
|
||||||
|
|
||||||
rest._request.side_effect = _side_effect
|
rest._request.side_effect = _side_effect
|
||||||
@@ -917,8 +921,9 @@ class TestHttp429Handling:
|
|||||||
assert call_count[0] == 2
|
assert call_count[0] == 2
|
||||||
|
|
||||||
def test_429_telemetry_counted(self):
|
def test_429_telemetry_counted(self):
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
rest = _make_mock_rest()
|
rest = _make_mock_rest()
|
||||||
rest._request.side_effect = Exception("HTTP 429 Too Many Requests")
|
rest._request.side_effect = RocketChatRateLimitError("HTTP 429 Too Many Requests")
|
||||||
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
engine = _make_engine(rest=rest, away_grace_s=0.05)
|
||||||
engine.on_pre_gateway_dispatch()
|
engine.on_pre_gateway_dispatch()
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
"""
|
||||||
|
WV-002: REST-Exception-Logging verfeinern (_rest_set_status).
|
||||||
|
|
||||||
|
Tests für:
|
||||||
|
- (a) Echter HTTP 429 → Cooldown + korrektes Logging (Typ + Message + Status-Code).
|
||||||
|
- (b) DDP-Timeout-Exception → KEIN Cooldown, korrekte Typ/Status-Logs.
|
||||||
|
- (c) Exception ohne HTTP-Code → kein 429-Cooldown (Phantom-429-Schutz).
|
||||||
|
|
||||||
|
Kern: Cooldown wird NUR bei echtem HTTP 429 (Status-Code-Prüfung) getriggert,
|
||||||
|
nicht bei beliebigen Exceptions mit '429' im Text.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||||
|
|
||||||
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
|
from plugin.adapter import RocketChatRateLimitError
|
||||||
|
|
||||||
|
|
||||||
|
def _make_mock_rest():
|
||||||
|
rest = MagicMock()
|
||||||
|
rest.auth_token = "test-token"
|
||||||
|
rest.user_id = "test-user"
|
||||||
|
rest._request = MagicMock()
|
||||||
|
return rest
|
||||||
|
|
||||||
|
|
||||||
|
def _make_engine(rest):
|
||||||
|
return PresenceEngine(rest=rest, use_ddp=False)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# (a) Echter HTTP 429 → Cooldown + korrektes Logging
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestReal429Cooldown:
|
||||||
|
def test_http_error_429_triggers_cooldown(self):
|
||||||
|
"""Echter HTTPError(429) → Cooldown gesetzt, Telemetrie 429 inkrementiert."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=urllib.error.HTTPError(
|
||||||
|
"https://rocketchat/api/v1/users.setStatus", 429,
|
||||||
|
"Too Many Requests", {}, None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 1
|
||||||
|
assert engine._telemetry_rest_errors == 0
|
||||||
|
# Cooldown wurde gesetzt (Rückkanal)
|
||||||
|
assert engine._mediator._consecutive_429s == 1
|
||||||
|
assert engine._mediator._rest_cooldown_until > 0.0
|
||||||
|
|
||||||
|
def test_rate_limit_error_triggers_cooldown(self):
|
||||||
|
"""RocketChatRateLimitError → Cooldown gesetzt (per Definition 429)."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(side_effect=RocketChatRateLimitError("HTTP 429"))
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("busy", "arbeitet")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 1
|
||||||
|
assert engine._mediator._consecutive_429s == 1
|
||||||
|
|
||||||
|
def test_429_logs_type_message_and_status(self):
|
||||||
|
"""429-Log enthält Exception-Typ, Message UND HTTP-Status-Code."""
|
||||||
|
import logging
|
||||||
|
from plugin.archivar import presence_engine as pe
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=urllib.error.HTTPError(
|
||||||
|
"https://rocketchat/api/v1/users.setStatus", 429,
|
||||||
|
"Too Many Requests", {}, None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
with patch.object(pe.logger, "warning") as mock_warn:
|
||||||
|
engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
# Mindestens ein Warning-Log mit '429' und 'HTTPError' (Exception-Typ)
|
||||||
|
logged = [str(c) for c in mock_warn.call_args_list]
|
||||||
|
assert any("429" in l for l in logged)
|
||||||
|
assert any("HTTPError" in l for l in logged), (
|
||||||
|
f"Erwartet Exception-Typ 'HTTPError' im Log, bekam: {logged}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# (b) DDP-Timeout-Exception → KEIN Cooldown
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestDDPTimeoutNoCooldown:
|
||||||
|
def test_ddp_timeout_no_cooldown(self):
|
||||||
|
"""DDP-Timeout-Exception → KEIN Cooldown, KEIN 429-Telemetrie."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
# DDP-Timeout: Exception mit '429' NICHT im Text, aber ein Timeout-Typ.
|
||||||
|
# Simuliere einen Timeout, der früher fälschlich als 429 klassifiziert
|
||||||
|
# werden konnte (z.B. wenn der Text '429' enthielt).
|
||||||
|
rest._request = MagicMock(side_effect=TimeoutError("DDP timeout after 1.0s"))
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._telemetry_rest_errors >= 1
|
||||||
|
# KEIN Cooldown
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
assert engine._mediator._rest_cooldown_until == 0.0
|
||||||
|
|
||||||
|
def test_phantom_429_in_text_no_cooldown(self):
|
||||||
|
"""Exception mit '429' im TEXT (aber kein HTTP-Code) → KEIN Cooldown.
|
||||||
|
|
||||||
|
Das ist der Kern des Phantom-429-Bugs: DDP-Timeouts und REST-Token-Errors
|
||||||
|
enthielten '429' im Text und wurden fälschlich als 429 klassifiziert.
|
||||||
|
"""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=Exception("REST token error: request 429 rejected")
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._telemetry_rest_errors >= 1
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
assert engine._mediator._rest_cooldown_until == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# (c) Exception ohne HTTP-Code → kein 429-Cooldown
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestNoHttpCodeNoCooldown:
|
||||||
|
def test_generic_exception_no_cooldown(self):
|
||||||
|
"""Generische Exception ohne HTTP-Code → kein 429-Cooldown."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(side_effect=ValueError("some error"))
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
|
||||||
|
def test_http_500_no_cooldown(self):
|
||||||
|
"""HTTP 500 (kein 429) → kein 429-Cooldown, aber als Error gezählt."""
|
||||||
|
rest = _make_mock_rest()
|
||||||
|
rest._request = MagicMock(
|
||||||
|
side_effect=urllib.error.HTTPError(
|
||||||
|
"https://rocketchat/api/v1/users.setStatus", 500,
|
||||||
|
"Internal Server Error", {}, None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
engine = _make_engine(rest)
|
||||||
|
|
||||||
|
result = engine._rest_set_status("online", "")
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
assert engine._telemetry_rest_429 == 0
|
||||||
|
assert engine._mediator._consecutive_429s == 0
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Helper-Unit-Tests: _extract_http_status_code / _is_http_429
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
class TestHttpStatusExtraction:
|
||||||
|
def test_extract_from_httperror(self):
|
||||||
|
exc = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None)
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||||
|
|
||||||
|
def test_extract_from_rate_limit_error(self):
|
||||||
|
exc = RocketChatRateLimitError("HTTP 429")
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||||
|
|
||||||
|
def test_extract_from_cause_chain(self):
|
||||||
|
cause = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None)
|
||||||
|
exc = RuntimeError("wrapped")
|
||||||
|
exc.__cause__ = cause
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) == 429
|
||||||
|
|
||||||
|
def test_extract_none_for_generic(self):
|
||||||
|
exc = ValueError("no code here")
|
||||||
|
assert PresenceEngine._extract_http_status_code(exc) is None
|
||||||
|
|
||||||
|
def test_extract_from_status_code_attr(self):
|
||||||
|
class FakeExc(Exception):
|
||||||
|
status_code = 503
|
||||||
|
assert PresenceEngine._extract_http_status_code(FakeExc()) == 503
|
||||||
|
|
||||||
|
def test_is_http_429_true_for_429(self):
|
||||||
|
assert PresenceEngine._is_http_429(ValueError("x"), 429) is True
|
||||||
|
|
||||||
|
def test_is_http_429_false_for_other(self):
|
||||||
|
assert PresenceEngine._is_http_429(ValueError("x"), 500) is False
|
||||||
|
|
||||||
|
def test_is_http_429_false_for_none(self):
|
||||||
|
assert PresenceEngine._is_http_429(ValueError("429 in text"), None) is False
|
||||||
|
|
||||||
|
def test_is_http_429_true_for_rate_limit_error(self):
|
||||||
|
assert PresenceEngine._is_http_429(RocketChatRateLimitError("x"), None) is True
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Setup-Voraussetzungen (vom Wizard gelesen — F98 Flow-Spec §0.2)
|
||||||
|
# Format: modulname|pip_name|min_version|severity
|
||||||
|
# severity: HARD = muss da sein (Abbruch), SOFT = Auto-Install in Phase 7
|
||||||
|
#
|
||||||
|
# Diese Datei ist die EINE Wahrheits-Quelle für Installer-Voraussetzungen.
|
||||||
|
# Wenn ein neues Plugin-Feature ein Modul braucht, hier ergänzen — der
|
||||||
|
# Installer erkennt es automatisch, ohne dass install.sh angefasst wird.
|
||||||
|
|
||||||
|
faiss-cpu|faiss-cpu|1.7.4|SOFT
|
||||||
|
numpy|numpy|1.24.0|SOFT
|
||||||
|
snowballstemmer|snowballstemmer|2.2.0|SOFT
|
||||||
|
httpx|httpx|0.25.0|HARD
|
||||||
|
requests|requests|2.31.0|HARD
|
||||||
@@ -0,0 +1,438 @@
|
|||||||
|
"""
|
||||||
|
F98: Guided Setup Wizard — install.sh Tests (TDD).
|
||||||
|
|
||||||
|
Testet die F98-Wizard-Schicht (additiv zu install.sh):
|
||||||
|
1. Provider-Freiheit: KEIN hardcoded provider=ollama-cloud (Root-Cause A)
|
||||||
|
2. Provider-Detection P1-P6 (detect_provider)
|
||||||
|
3. Layout-Detection (detect_install_layout)
|
||||||
|
4. Key-Zwang entschärft (Root-Cause D): KEIN `die "Abbruch: erforderliche Secrets fehlen"`
|
||||||
|
bei lokaler Inference
|
||||||
|
5. Wizard-Flags (--guided/--defaults/--resume) geparst
|
||||||
|
6. Sprach-Pack (DE/EN) vorhanden
|
||||||
|
7. Secret-Maskierung (mask_secrets)
|
||||||
|
8. setup_requirements.txt als Single Source of Truth
|
||||||
|
9. Selbsterklärend-Regel: Ausweich-Optionen (SKIP), kein Abbruch ohne Cloud-Key
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
|
||||||
|
SETUP_REQ = Path(__file__).resolve().parents[1] / "setup_requirements.txt"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_install_sh() -> str:
|
||||||
|
return INSTALL_SH.read_text()
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 1: Syntax
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestInstallShSyntax:
|
||||||
|
def test_bash_syntax_ok(self):
|
||||||
|
if not INSTALL_SH.exists():
|
||||||
|
pytest.skip("install.sh nicht gefunden")
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-n", str(INSTALL_SH)],
|
||||||
|
capture_output=True, text=True,
|
||||||
|
)
|
||||||
|
assert result.returncode == 0, f"bash -n failed:\n{result.stderr}"
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 2: Provider-Freiheit (Root-Cause A) — kein hardcoded ollama-cloud
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestProviderFreedom:
|
||||||
|
def test_no_hardcoded_provider_ollama_cloud(self):
|
||||||
|
"""write_config_yaml darf KEIN `local provider="ollama-cloud"` mehr haben."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'local provider="ollama-cloud"' not in content, (
|
||||||
|
"hardcoded provider=ollama-cloud noch vorhanden (Root-Cause A)"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_detect_provider_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "detect_provider()" in content, "detect_provider() fehlt"
|
||||||
|
|
||||||
|
def test_detect_provider_has_p1_p6(self):
|
||||||
|
"""Detection-Reihenfolge P1-P6 muss vorhanden sein."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
for marker in ["P1", "P2", "P3", "P4", "P6"]:
|
||||||
|
assert marker in content, f"Detection-Marker {marker} fehlt"
|
||||||
|
|
||||||
|
def test_detect_provider_local_ollama_no_key(self):
|
||||||
|
"""P1 (lokales Ollama) → provider=ollama, KEIN Key."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# P1-Block muss PROVIDER=ollama + PROVIDER_NEEDS_KEY=false setzen
|
||||||
|
assert "PROVIDER=\"ollama\"" in content
|
||||||
|
assert "PROVIDER_NEEDS_KEY=false" in content
|
||||||
|
|
||||||
|
def test_verify_installation_provider_compare_not_string_equality(self):
|
||||||
|
"""verify_installation nutzt Provider-Vergleich, nicht String-Gleichheit (Root-Cause I)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# Der alte hardcoded Check `grep -q "^ provider: ollama-cloud"` darf nicht mehr da sein
|
||||||
|
assert 'grep -q "^ provider: ollama-cloud"' not in content, (
|
||||||
|
"verify_installation prüft noch hardcoded ollama-cloud (Root-Cause I)"
|
||||||
|
)
|
||||||
|
# Neuer Provider-Vergleich (case mit gültigen Providern)
|
||||||
|
assert "ollama|custom|openrouter|ollama-cloud" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 3: Key-Zwang entschärft (Root-Cause D)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestNoKeyCoercion:
|
||||||
|
def test_no_die_abort_secrets_missing(self):
|
||||||
|
"""KEIN `die "Abbruch: erforderliche Secrets fehlen"` mehr (Root-Cause D)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
# Der alte Hardabort (exakt diese die-Zeile) darf nicht mehr existieren.
|
||||||
|
# Der neue die-Aufruf enthält den Zusatz "(oder nutze --guided)".
|
||||||
|
assert 'die "Abbruch: erforderliche Secrets fehlen"\n' not in content, (
|
||||||
|
"Key-Zwang-Hardabort noch vorhanden (Root-Cause D)"
|
||||||
|
)
|
||||||
|
# Der neue die-Aufruf verweist auf --guided (Ausweich statt Abbruch).
|
||||||
|
assert 'die "Abbruch: erforderliche Secrets fehlen (oder nutze --guided)"' in content
|
||||||
|
|
||||||
|
def test_cloud_key_only_for_cloud_provider(self):
|
||||||
|
"""Cloud-Key NUR bei Cloud-Provider (ollama-cloud/openrouter)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert 'PROVIDER" = "ollama-cloud"' in content or 'PROVIDER" = "ollama-cloud"' in content
|
||||||
|
assert "OPENROUTER_API_KEY fehlt" in content
|
||||||
|
|
||||||
|
def test_guided_skips_password_userid_check(self):
|
||||||
|
"""Im Guided-Modus werden Password/User-ID im Dialog abgefragt, nicht erzwungen."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "if ! $GUIDED; then" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 4: Wizard-Flags
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestWizardFlags:
|
||||||
|
def test_guided_flag_parsed(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--guided) GUIDED=true" in content
|
||||||
|
|
||||||
|
def test_defaults_flag_parsed(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--defaults) GUIDED_DEFAULTS=true" in content
|
||||||
|
|
||||||
|
def test_resume_flag_parsed(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--resume) RESUME=true" in content
|
||||||
|
|
||||||
|
def test_guided_flag_declared(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "GUIDED=false" in content
|
||||||
|
assert "GUIDED_DEFAULTS=false" in content
|
||||||
|
assert "RESUME=false" in content
|
||||||
|
|
||||||
|
def test_run_guided_wizard_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "run_guided_wizard()" in content
|
||||||
|
|
||||||
|
def test_wizard_dispatched_in_main_flow(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "if $GUIDED; then" in content
|
||||||
|
assert "run_guided_wizard" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 5: Sprach-Pack (DE/EN)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestLanguagePack:
|
||||||
|
def test_language_pack_declared(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "declare -A T" in content
|
||||||
|
|
||||||
|
def test_de_en_strings_present(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "T[de_lang_q]" in content
|
||||||
|
assert "T[en_lang_q]" in content
|
||||||
|
assert "T[de_multiroom_q]" in content
|
||||||
|
assert "T[en_multiroom_q]" in content
|
||||||
|
|
||||||
|
def test_language_selection_phase0(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "LANG_CHOICE" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 6: Secret-Maskierung
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestSecretMasking:
|
||||||
|
def test_mask_secrets_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "mask_secrets()" in content
|
||||||
|
|
||||||
|
def test_mask_secrets_filters_keys(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "OPENROUTER_API_KEY" in content
|
||||||
|
assert "OLLAMA_CLOUD_API_KEY" in content
|
||||||
|
assert "ROCKETCHAT_PASSWORD" in content
|
||||||
|
assert "***masked***" in content
|
||||||
|
|
||||||
|
def test_password_read_silent(self):
|
||||||
|
"""Kennwort-Eingabe nutzt read -s (unsichtbar)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "read -rs" in content or "read -s" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 7: setup_requirements.txt (Single Source of Truth)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestSetupRequirements:
|
||||||
|
def test_setup_requirements_exists(self):
|
||||||
|
assert SETUP_REQ.exists(), "setup_requirements.txt fehlt"
|
||||||
|
|
||||||
|
def test_setup_requirements_format(self):
|
||||||
|
"""Format: modulname|pip_name|min_version|severity."""
|
||||||
|
for line in SETUP_REQ.read_text().splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
parts = line.split("|")
|
||||||
|
assert len(parts) == 4, f"Zeile hat nicht 4 Felder: {line}"
|
||||||
|
assert parts[3] in ("HARD", "SOFT"), f"severity ungültig: {line}"
|
||||||
|
|
||||||
|
def test_wizard_reads_setup_requirements(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "setup_requirements.txt" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 8: Selbsterklärend-Regel (Ausweich-Optionen, kein Abbruch)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestSelfExplainingRule:
|
||||||
|
def test_skip_option_present(self):
|
||||||
|
"""Ausweich-Option 'SKIP' (Später konfigurieren) vorhanden."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "SKIP" in content
|
||||||
|
|
||||||
|
def test_allow_skip_parameter(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "allow_skip" in content
|
||||||
|
|
||||||
|
def test_p6_recommendation_block_no_abort(self):
|
||||||
|
"""P6 (nichts erkannt) → Empfehlungs-Block, KEIN Abbruch."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "Empfohlene Reihenfolge" in content
|
||||||
|
|
||||||
|
def test_missing_requirements_collected(self):
|
||||||
|
"""Defizite werden gesammelt (MISSING_REQUIREMENTS), nicht einzeln abgebrochen."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "MISSING_REQUIREMENTS" in content
|
||||||
|
|
||||||
|
def test_backup_dir_p164(self):
|
||||||
|
"""Backup vor schreibender Phase (P-164)."""
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "hermes-install-backup" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 9: Layout-Detection (V1.3-korrigiert §7.7)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestLayoutDetection:
|
||||||
|
def test_detect_install_layout_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "detect_install_layout()" in content
|
||||||
|
|
||||||
|
def test_layout_values(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "root_fhs" in content
|
||||||
|
assert "pipx" in content
|
||||||
|
assert "user_space" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 10: Proof-Run + Abschluss (Phase 10/11)
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
class TestProofAndSummary:
|
||||||
|
def test_proof_run_function_exists(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "run_proof_and_summary()" in content
|
||||||
|
|
||||||
|
def test_proof_checks_gateway_and_health(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "gateway_is_active" in content
|
||||||
|
assert "/health" in content
|
||||||
|
|
||||||
|
def test_nachhol_liste(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "Nachhol-Liste" in content
|
||||||
|
|
||||||
|
def test_resume_repair_hints(self):
|
||||||
|
content = _read_install_sh()
|
||||||
|
assert "--guided --resume" in content
|
||||||
|
assert "--repair" in content
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Test 11: Verhaltens-Tests (nicht String-Grep) — führen die Funktionen aus.
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_functions(*names: str) -> str:
|
||||||
|
"""Extrahiert die Funktions-Definitionen (plus log-Helfer + Farben) aus
|
||||||
|
install.sh, OHNE den Hauptfluss auszuführen. Gibt ein bash-Snippet zurück,
|
||||||
|
das in einer Subshell gesourced werden kann.
|
||||||
|
"""
|
||||||
|
content = INSTALL_SH.read_text()
|
||||||
|
lines = content.splitlines()
|
||||||
|
|
||||||
|
def _find_func(name: str) -> tuple[int, int] | None:
|
||||||
|
start = None
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if line.startswith(f"{name}()"):
|
||||||
|
start = i
|
||||||
|
break
|
||||||
|
if start is None:
|
||||||
|
return None
|
||||||
|
end = start
|
||||||
|
for j in range(start + 1, len(lines)):
|
||||||
|
if lines[j].strip() == "}":
|
||||||
|
end = j
|
||||||
|
break
|
||||||
|
return start, end
|
||||||
|
|
||||||
|
# log-Helfer: die Funktions-Definitionen direkt suchen.
|
||||||
|
header_parts = []
|
||||||
|
for helper in ("mask_secrets", "log", "warn", "err", "ok", "banner", "die"):
|
||||||
|
r = _find_func(helper)
|
||||||
|
if r:
|
||||||
|
header_parts.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
# Farben: leer lassen (unset Variablen expandieren zu "" ohne set -u).
|
||||||
|
header = "C_RESET=''; C_BLUE=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_BOLD=''\n\n" + "\n\n".join(header_parts)
|
||||||
|
|
||||||
|
funcs = []
|
||||||
|
for name in names:
|
||||||
|
r = _find_func(name)
|
||||||
|
if r:
|
||||||
|
funcs.append("\n".join(lines[r[0]:r[1] + 1]))
|
||||||
|
return header + "\n\n" + "\n\n".join(funcs) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _run_bash(snippet: str, extra_env: dict | None = None) -> tuple[str, str, int]:
|
||||||
|
"""Führt ein bash-Snippet in einer isolierten Subshell aus."""
|
||||||
|
env = {
|
||||||
|
"PATH": "/usr/bin:/bin:/usr/local/bin",
|
||||||
|
"HOME": "/tmp/f98-test-home",
|
||||||
|
}
|
||||||
|
if extra_env:
|
||||||
|
env.update(extra_env)
|
||||||
|
result = subprocess.run(
|
||||||
|
["bash", "-c", snippet],
|
||||||
|
capture_output=True, text=True, env=env, timeout=30,
|
||||||
|
)
|
||||||
|
return result.stdout, result.stderr, result.returncode
|
||||||
|
|
||||||
|
|
||||||
|
class TestDetectProviderBehavior:
|
||||||
|
"""detect_provider() muss tatsächlich die richtigen Variablen setzen."""
|
||||||
|
|
||||||
|
def test_p1_local_ollama_sets_provider(self):
|
||||||
|
# Simuliere lokales Ollama: curl auf localhost:11434 liefert 200.
|
||||||
|
import tempfile, os
|
||||||
|
fake_curl = "#!/bin/bash\nif [[ \"$*\" == *\"localhost:11434\"* ]]; then exit 0; fi\nexit 1\n"
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
curl_path = os.path.join(d, "curl")
|
||||||
|
with open(curl_path, "w") as f:
|
||||||
|
f.write(fake_curl)
|
||||||
|
os.chmod(curl_path, 0o755)
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("detect_provider")
|
||||||
|
+ "detect_provider\n"
|
||||||
|
+ "echo \"PROVIDER=$PROVIDER\"\n"
|
||||||
|
+ "echo \"NEEDS_KEY=$PROVIDER_NEEDS_KEY\"\n"
|
||||||
|
+ "echo \"DETECTED=$DETECTED_PROVIDER\"\n"
|
||||||
|
+ "echo \"LOCAL=$LOCAL_INFERENCE_AVAILABLE\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet, extra_env={"PATH": f"{d}:/usr/bin:/bin"})
|
||||||
|
assert "PROVIDER=ollama" in out, f"P1 sollte provider=ollama setzen:\n{out}\n{err}"
|
||||||
|
assert "NEEDS_KEY=false" in out, f"P1 braucht keinen Key:\n{out}"
|
||||||
|
assert "DETECTED=P1" in out, f"P1 sollte DETECTED_PROVIDER=P1 setzen:\n{out}"
|
||||||
|
assert "LOCAL=true" in out, f"P1 ist lokale Inference:\n{out}"
|
||||||
|
|
||||||
|
def test_p6_nothing_detected_sets_none(self):
|
||||||
|
# Kein Ollama, kein DGX, keine env-Keys → P6, provider=none, KEIN Abbruch.
|
||||||
|
import tempfile, os
|
||||||
|
fake_curl = "#!/bin/bash\nexit 1\n"
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
curl_path = os.path.join(d, "curl")
|
||||||
|
with open(curl_path, "w") as f:
|
||||||
|
f.write(fake_curl)
|
||||||
|
os.chmod(curl_path, 0o755)
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("detect_provider")
|
||||||
|
+ "detect_provider\n"
|
||||||
|
+ "echo \"PROVIDER=$PROVIDER\"\n"
|
||||||
|
+ "echo \"DETECTED=$DETECTED_PROVIDER\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet, extra_env={"PATH": f"{d}:/usr/bin:/bin"})
|
||||||
|
assert "PROVIDER=none" in out, f"P6 sollte provider=none setzen:\n{out}\n{err}"
|
||||||
|
assert "DETECTED=P6" in out, f"P6 sollte DETECTED_PROVIDER=P6 setzen:\n{out}"
|
||||||
|
assert rc == 0, "P6 darf NICHT abbrechen"
|
||||||
|
|
||||||
|
|
||||||
|
class TestMaskSecretsBehavior:
|
||||||
|
"""mask_secrets() muss Secrets tatsächlich maskieren."""
|
||||||
|
|
||||||
|
def test_mask_secrets_masks_known_keys(self):
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("mask_secrets")
|
||||||
|
+ "OPENROUTER_API_KEY='sk-secret-123'\n"
|
||||||
|
+ "OLLAMA_CLOUD_API_KEY='cloud-secret-456'\n"
|
||||||
|
+ "ROCKETCHAT_PASSWORD='pw-secret-789'\n"
|
||||||
|
+ "echo \"$(mask_secrets 'key=sk-secret-123 pw=pw-secret-789')\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "sk-secret-123" not in out, f"OPENROUTER_API_KEY nicht maskiert:\n{out}\n{err}"
|
||||||
|
assert "pw-secret-789" not in out, f"ROCKETCHAT_PASSWORD nicht maskiert:\n{out}"
|
||||||
|
assert "***masked***" in out, f"Maskierung fehlt:\n{out}"
|
||||||
|
|
||||||
|
|
||||||
|
class TestMarkPhaseBehavior:
|
||||||
|
"""mark_phase()/read_install_state() müssen State persistieren."""
|
||||||
|
|
||||||
|
def test_mark_and_read_phase_roundtrip(self):
|
||||||
|
import tempfile, os
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
state_file = os.path.join(d, "state.json")
|
||||||
|
snippet = (
|
||||||
|
_extract_functions("mark_phase", "read_install_state")
|
||||||
|
+ f"INSTALL_STATE_FILE='{state_file}'\n"
|
||||||
|
+ "mark_phase 5 'rc-verbindung'\n"
|
||||||
|
+ "INSTALL_PHASE_LAST_DONE=0\n"
|
||||||
|
+ "read_install_state\n"
|
||||||
|
+ "echo \"PHASE=$INSTALL_PHASE_LAST_DONE\"\n"
|
||||||
|
)
|
||||||
|
out, err, rc = _run_bash(snippet)
|
||||||
|
assert "PHASE=5" in out, f"State-Roundtrip fehlgeschlagen:\n{out}\n{err}"
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user