2 Commits

Author SHA1 Message Date
Bernd (Hermes) 5a9cf5f160 fix: Rainer-Quality-Loop — 4 Fixes (2 release-blockierend, 2 dringend)
D1 (RELEASE-BLOCKIEREND): Guard 2.5 — LLM schlägt excluded room vor
  router.py: Nach Guard 2 (Catch-All) prüft Guard 2.5 ob LLM-Raum
  excluded ist → stay_in_room. Verhindert Move-Request in excluded room.

D2 (RELEASE-BLOCKIEREND): DMs können in Projekträume geroutet werden
  router.py: Schritt 0 DM-Guard VOR allem anderen. origin_room_id leer
  (DM) → sofort stay_in_room. DMs nie vom Routing betroffen.

D3 (DRINGEND): Self-Match-Schutz in Schritt 3, 3.5, 4.5
  router.py: Keyword-Match (Schritt 3), FAISS auto-route (Schritt 3.5),
  Keyword-Match vor LLM (Schritt 4.5) prüfen alle auf
  matched_room.room_id == origin_room_id → stay_in_room.

D4 (DRINGEND): install.sh base_url-Löschung zu aggressiv
  install.sh: base_url mit openrouter nur löschen wenn
  _RC_PROVIDER == ollama-cloud. Bei explizitem openrouter bleibt sie.
2026-07-09 17:41:01 +02:00
Bernd (Hermes) 8b67e03f7e feat(v6): Phase 1 — Origin-First Guard + LLM Fix + Proaktiver Broadcast
P3: LLM_CONFIG base_url jetzt aus OLLAMA_BASE_URL Env-Var (config.py:150)
I1: LLM_ROOM_PROMPT umgeschrieben — STAY/ROUTE statt CATCH_ALL,
    Ursprungsraum-Kontext, Few-Shot-Beispiele, Catch-All nicht als Option
    (config.py:175-195, router.py:_llm_room_lookup)
P2: Origin-First Guard (Schritt -0.5) in router.py:route():
    - origin_room_id leer (echte DM) → normaler Flow
    - origin_room ist Catch-All → stay_in_room
    - origin_room ist excluded → ignore
    - LLM sagt STAY → stay_in_room
    - LLM == origin_room → stay_in_room
    - LLM == catch_all_room → stay_in_room (kein DM-Routing!)
    - LLM == anderer Raum → Move-Request (Butler-Prinzip)
Catch-All-Schutz: DM-Nachrichten skippen Routing-Flow (router.py:270-282)
Move-Request-Routing-Fix (adapter.py):
    - 1️⃣ Rüberkopieren → _CURRENT_ORIGIN_ROOM = Zielraum
    - 2️⃣ Generell hier bleiben → Sticky-Eintrag
    - 3️⃣ Hier bleiben → nur diesmal, kein Sticky
    - Button-Labels aktualisiert: 1️⃣ Rüber / 2️⃣ Generell / 3️⃣ Hier
B6: Proaktiver Raum-Broadcast (tools.py):
    - Neues Tool rocketchat_broadcast mit 5-Min-Cooldown
    - Format: menschenähnlich, kein Bot-Ton
    - Registriert in _TOOLS mit 📢 Emoji
2026-07-09 17:33:14 +02:00
5 changed files with 340 additions and 94 deletions
+45 -9
View File
@@ -937,13 +937,45 @@ if [ ! -f "$CONFIG" ]; then
msg config_provisioned
fi
fi
# ─── Fix M4: Hermes-Installer Default-Konfiguration korrigieren ──
# Der offizielle Hermes-Installer (curl install.sh) schreibt in die
# config.yaml: model.default=anthropic/claude-opus-4.6, model.provider=auto,
# base_url=https://openrouter.ai/api/v1. Auf ollama-cloud existiert dieses
# Modell nicht (404). Der Plugin-Installer MUSS die config.yaml nachbessern,
# selbst wenn bereits eine existiert (Fall: Hermes zuerst installiert, dann
# Plugin-Installer). Defaults: OLLAMA_MODEL=glm-5.2, OLLAMA_PROVIDER=ollama-cloud.
if [ -f "$CONFIG" ]; then
_RC_MODEL="${OLLAMA_MODEL:-glm-5.2}"
_RC_PROVIDER="${OLLAMA_PROVIDER:-ollama-cloud}"
if grep -q '^[[:space:]]*default:' "$CONFIG" 2>/dev/null; then
sed -i "s|^[[:space:]]*default:.*| default: ${_RC_MODEL}|" "$CONFIG"
fi
if grep -q '^[[:space:]]*provider:' "$CONFIG" 2>/dev/null; then
sed -i "s|^[[:space:]]*provider:.*| provider: ${_RC_PROVIDER}|" "$CONFIG"
fi
# base_url aus der model-Sektion entfernen (gilt nur für OpenRouter, nicht ollama-cloud)
# ABER: Nur löschen wenn provider == ollama-cloud (Default). Wenn User explizit
# openrouter nutzen will (OLLAMA_PROVIDER=openrouter), base_url BEHALTEN.
if grep -q '^[[:space:]]*base_url:.*openrouter' "$CONFIG" 2>/dev/null; then
if [ "$_RC_PROVIDER" = "ollama-cloud" ]; then
sed -i '/^[[:space:]]*base_url:.*openrouter/d' "$CONFIG"
fi
elif [ -n "${OLLAMA_BASE_URL:-}" ]; then
# Explizit übergebene OLLAMA_BASE_URL setzen statt entfernen
if grep -q '^[[:space:]]*base_url:' "$CONFIG" 2>/dev/null; then
sed -i "s|^[[:space:]]*base_url:.*| base_url: ${OLLAMA_BASE_URL}|" "$CONFIG"
fi
fi
fi
if [ ! -f "$ENVFILE" ] && [ -f "$SCRIPT_DIR/templates/.env" ]; then
cp "$SCRIPT_DIR/templates/.env" "$ENVFILE"
chmod 600 "$ENVFILE"
msg env_provisioned
fi
# ─── Fix #9b: OLLAMA_API_KEY in ~/.hermes/.env persistieren ─
# ─── Fix #9b: OLLAMA_API_KEY in ~/.hermes/.env persistieren ─┘
# Secret gehört NICHT in die systemd-Unit, sondern in die .env-Datei.
if [ -n "${OLLAMA_API_KEY:-}" ]; then
mkdir -p "$HERMES_HOME"
@@ -957,8 +989,6 @@ if [ -n "${OLLAMA_API_KEY:-}" ]; then
echo "OLLAMA_API_KEY=${OLLAMA_API_KEY}" >> "$ENVFILE"
fi
fi
# ─── Patch config.yaml ────────────────────────────────────
if [ -f "$CONFIG" ]; then
# Ensure rocketchat-platform is in plugins.enabled
if ! grep -q 'rocketchat-platform' "$CONFIG" 2>/dev/null; then
@@ -977,12 +1007,17 @@ fi
# ─── Gateway service ──────────────────────────────────────
cd "$HERMES_DIR"
if [ -f "venv/bin/python" ]; then
PYTHON="venv/bin/python"
elif [ -f ".venv/bin/python" ]; then
PYTHON=".venv/bin/python"
# ─── Fix M1: ExecStart benötigt absoluten Pfad ─────────────
# systemd erlaubt KEINE relativen Pfade in ExecStart. Bisher wurde
# "venv/bin/python" (relativ) geschrieben → Service-Start schlägt fehl.
# Lösung: Absoluten Pfad aus $HERMES_DIR ableiten (liefert z.B.
# /home/bernd/.hermes/hermes-agent/venv/bin/python).
if [ -f "$HERMES_DIR/venv/bin/python" ]; then
PYTHON="$HERMES_DIR/venv/bin/python"
elif [ -f "$HERMES_DIR/.venv/bin/python" ]; then
PYTHON="$HERMES_DIR/.venv/bin/python"
else
PYTHON="python3"
PYTHON="$(command -v python3 || echo python3)"
fi
# Install / refresh systemd user service
@@ -995,6 +1030,7 @@ $PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
UNIT_FILE="$HOME/.config/systemd/user/hermes-gateway.service"
if [ -f "$UNIT_FILE" ]; then
# Replace ExecStart to use "gateway run" instead of "run_agent.py gateway"
# $PYTHON ist jetzt absolut (siehe Fix M1 oben).
sed -i 's|ExecStart=.*|ExecStart='"$PYTHON"' -m hermes_cli.main gateway run|' "$UNIT_FILE"
systemctl --user daemon-reload 2>/dev/null || true
fi
@@ -1035,7 +1071,7 @@ systemctl --user enable hermes-gateway 2>/dev/null || true
# Gateway stoppen (mit Timeout — kann bis 60s dauern)
systemctl --user stop hermes-gateway 2>/dev/null || true
local stop_wait=0
stop_wait=0 # Fix M2: 'local' removed — not inside a function (Bash-Syntaxfehler)
while systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $stop_wait -lt 60 ]; do
sleep 2
stop_wait=$((stop_wait + 2))
+21 -15
View File
@@ -534,7 +534,13 @@ class RocketChatAdapter(BasePlatformAdapter):
return False
return False
async def connect(self) -> bool:
async def connect(self, *, is_reconnect: bool = False) -> bool:
"""Connect to Rocket.Chat (REST + DDP) and start listen loop.
is_reconnect: True wenn dies ein Reconnect-Versuch ist (z.B. nach
Silent-Death-Erkennung). Core ruft connect() mit diesem Keyword-Arg
auf; fehlt es → TypeError. Siehe Bug M3.
"""
if not self.base_url or not self.user or not self.password:
logger.error("[rocketchat] Missing configuration")
return False
@@ -831,7 +837,7 @@ class RocketChatAdapter(BasePlatformAdapter):
if choice.startswith("MOVE_REQ:") and "::" in choice:
_, choice = choice.split("::", 1)
choice = choice.strip()
# Normalisiere: "1️⃣ Rüber" → "1️⃣", "2 Hier" → "2"
# Normalisiere: "1️⃣ Rüber" → "1️⃣", "2 Generell" → "2"
if choice and choice[0] in "123":
choice = choice[0]
elif choice and choice[:2] in ("1️⃣", "2️⃣", "3️⃣"):
@@ -843,28 +849,28 @@ class RocketChatAdapter(BasePlatformAdapter):
if num == 1:
choice = "rüberkopieren"
elif num == 2:
choice = "hier bleiben"
choice = "generell" # v6: 2 = Generell hier bleiben (sticky)
else:
choice = "generell"
choice = "hier bleiben" # v6: 3 = Hier bleiben (nur diesmal)
choice = choice.lower()
# Neue Mapping-Logik für verbesserte Button-UX
# Neue Mapping-Logik für verbesserte Button-UX (v6)
feedback_type = "stay" # Default
if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren", "kopieren", "confirm_move", "✅ja"):
# Rüberkopieren
# 1️⃣ Rüberkopieren → Antwort im Zielraum
target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}"
if move_req.get("username"):
await self._post_message_with_retry(move_req["target_room"], target_txt)
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
forwarded = True
feedback_type = "confirm"
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
# Nicht mehr fragen / sticky_room setzen
elif choice in ("2", "2️⃣", "generell", "generell hier bleiben"):
# 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag
self._sticky_rooms[room_id] = time.time()
await self._post_message_with_retry(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
feedback_type = "never"
else:
# "Hier bleiben" / "2" / "2️⃣" — Default
# 3️⃣ Hier bleiben → Antwort im Ursprungsraum (nur diesmal, kein Sticky)
await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
feedback_type = "stay"
@@ -981,14 +987,14 @@ class RocketChatAdapter(BasePlatformAdapter):
try:
move_prefix = f"MOVE_REQ:{room_id}"
buttons = _build_custom_buttons(
["1️⃣ Rüber", "2️⃣ Hier", "3️⃣ Nein"],
["1️⃣ Rüber", "2️⃣ Generell", "3️⃣ Hier"],
prefix=move_prefix
)
note = (f"Dein Auftrag passt thematisch besser in **{target_name}**.\n\n"
f"**Was soll ich tun?**\n\n"
f"1️⃣ **Rüberkopieren** = Auftrag verschieben, ich antworte dort\n"
f"2️⃣ **Hier bleiben** = Auftrag bleibt hier, ich kümmere mich drum\n"
f"3️⃣ **Nicht mehr fragen** = Raum wird bis Neustart nicht mehr geroutet\n\n"
f"2️⃣ **Generell hier bleiben** = Auftrag bleibt hier + Raum wird bis Neustart nicht mehr geroutet\n"
f"3️⃣ **Hier bleiben** = Auftrag bleibt hier (nur diesmal)\n\n"
f"Wohin soll ich den Auftrag verschieben?")
attachments = [{
"color": "#1d74f5",
@@ -1009,9 +1015,9 @@ class RocketChatAdapter(BasePlatformAdapter):
note = (
f"Dein Auftrag passt thematisch besser in **{target_name}**.\n"
f"Antworte mit einer Zahl:\n"
f"1 = Ja, rüberkopieren und dort abarbeiten\n"
f"2 = Hier bleiben\n"
f"3 = Generell hier bleiben"
f"1 = Rüberkopieren und dort abarbeiten\n"
f"2 = Generell hier bleiben (Sticky)\n"
f"3 = Hier bleiben (nur diesmal)"
)
self._pending_move_requests[room_id] = {
"text": text,
+15 -3
View File
@@ -147,7 +147,7 @@ LLM_CONFIG = {
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
"model": "qwen2.5:7b",
"timeout": 30.0, # Iterative Optimierung: Start 30s (19.06.2026)
"base_url": "http://localhost:11434",
"base_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"),
"temperature": 0.0,
"max_tokens": 30, # Raum-ID = 24 chars + Puffer
}
@@ -173,12 +173,24 @@ LLM_CONFIDENCE_THRESHOLD = 0.90
# Ausgabe: Direkt die Raum-ID (keine Kategorien, kein Name-Matching).
LLM_ROOM_PROMPT = """Du bist ein Raum-Zuordner. Ordne die Nachricht EINEM Raum zu.
Antworte NUR mit der exakten Raum-ID aus der Liste. Keine Erklärungen, keine Sätze.
Wenn unsicher, antworte mit dem einzelnen Wort: CATCH_ALL
Antworte mit der exakten Raum-ID aus der Liste ODER dem Wort STAY.
Wähle STAY wenn die Nachricht thematisch zum Ursprungsraum passt ODER wenn du unsicher bist.
Antworte NUR mit einem Wort, keine Erklärungen.
Ursprungsraum: {origin_room}
Verfügbare Räume (ID | Name | Keywords):
{room_list}
Beispiele für STAY:
- Eine Frage zum aktuellen Raumthema → STAY
- Smalltalk, Begrüßung, Dank → STAY
- Unklare oder mehrdeutige Nachricht → STAY
Beispiele für ROUTE (Raum-ID):
- Ein klarer Arbeitsauftrag für ein anderes Raumthema → die passende Raum-ID
- Eine Frage, die eindeutig in einen anderen Raum gehört → die passende Raum-ID
Nachricht: {text}
Raum-ID:"""
+180 -67
View File
@@ -218,22 +218,26 @@ class BidirectionalRouter:
# ── Public API ──────────────────────────────────────────────────────
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
"""Klassifiziere und route eine Nachricht (korrigierter Flow).
"""Klassifiziere und route eine Nachricht (v6 Flow mit Origin-First Guard).
Der neue Routing-Flow (Architekturskizze):
1. origin_room_id in excluded_rooms? → IGNORE (silent)
2. Raum-Zustand prüfen (persistenter Zustand)
3. Meta-Fragen-Erkennung
4. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig)
5. FAISS Phase-1: Raum-Index + Keyword-Booster
- FAISS-Score >= FAISS_AUTO_ROUTE → direkt routen (kein LLM)
- Score unter Schwelle → Fall-through zu Embedding + LLM
6. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag"
- Klarer Smalltalk → stay_in_room
- Unsicher → weiter zu LLM-Raum-Router
7. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste mit Keywords → room_id direkt
8. Raum gefunden → Move-Request-Button (Butler-Prinzip: ✅Ja/📍Hier)
9. Kein Treffer → catch_all_room
Der neue Routing-Flow (v6):
-0.5 ORIGIN-FIRST GUARD (VOR allen anderen Schritten):
1. origin_room_id leer (echte DM) → normaler Flow
2. origin_room ist Catch-All-Raum → stay_in_room
3. origin_room ist excluded → ignore
0. Excluded rooms check
1. Raum-Zustand prüfen (persistenter Zustand)
2. Meta-Fragen-Erkennung
3. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig)
3.5 FAISS Phase-1: Raum-Index + Keyword-Booster
4. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag"
5. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste → STAY oder room_id
6. ORIGIN-FIRST GUARD (nach LLM):
- LLM sagt STAY → stay_in_room
- LLM == origin_room → stay_in_room
- LLM == catch_all_room → stay_in_room (kein DM-Routing aus Projekträumen!)
- LLM == anderer Raum → Move-Request (Butler-Prinzip)
7. LLM-Fehler → stay_in_room
Args:
text: Der Nachrichtentext.
@@ -254,6 +258,21 @@ class BidirectionalRouter:
text = text.strip()
try:
# ── Schritt 0: DM-Guard (VOR allem anderen) ──────────────────
# DMs haben origin_room_id=''. Der Origin-First Guard greift
# nicht für DMs. LLM kann Projektraum vorschlagen → Guard 3 →
# Move-Request im DM → Antwort landet in Projektraum statt DM.
# DMs sollen nie vom Routing betroffen sein — sie bleiben IMMER
# im DM. (Release-blockierend)
if not origin_room_id:
logger.debug("DM-Guard: origin_room_id leer → stay_in_room (DM)")
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
)
# ── Schritt 0: Excluded rooms check ──────────────────────────
if origin_room_id and self._room_map.is_excluded(origin_room_id):
logger.debug(
@@ -314,6 +333,21 @@ class BidirectionalRouter:
# ── Schritt 3: Keyword-Match (aus RoomMap) ──────────────────
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
if matched_room is not None:
# Self-Match-Schutz: Wenn Keyword-Match den Ursprungsraum
# selbst trifft (z.B. 'RC' matched #RC und User ist bereits
# in #RC), dann stay_in_room statt Routing.
if matched_room.room_id == origin_room_id:
logger.debug(
"Keyword self-match: '%s' matched origin room %s → stay_in_room",
text[:80], matched_room.name,
)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
)
logger.debug(
"Keyword match: '%s' → %s", text[:80], matched_room.name
)
@@ -356,6 +390,19 @@ class BidirectionalRouter:
if top_score >= FAISS_AUTO_ROUTE:
room = self._room_map.get_room_by_id(top_room_id)
if room is not None:
# Self-Match-Schutz: FAISS matched origin room
if top_room_id == origin_room_id:
logger.debug(
"FAISS self-match: '%s' matched origin room %s → stay_in_room",
text[:80], room.name,
)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
)
room_name = (
room.name.replace("#", "")
if room.name.startswith("#")
@@ -425,6 +472,19 @@ class BidirectionalRouter:
if result is not None and result.category == "work_order" and result.confidence < 0.9:
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
if matched_room is not None:
# Self-Match-Schutz (auch in Schritt 4.5)
if matched_room.room_id == origin_room_id:
logger.debug(
"Keyword self-match (4.5): '%s' matched origin room %s → stay_in_room",
text[:80], matched_room.name,
)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
)
logger.info(
"Keyword-Match vor LLM: '%s' → %s (embedding conf=%.3f)",
text[:80], matched_room.name, result.confidence,
@@ -443,31 +503,14 @@ class BidirectionalRouter:
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
# liefert room_id direkt (keine Kategorien, kein Name-Matching)
llm_room, llm_failed = await self._llm_room_lookup(text)
if llm_room is not None:
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
logger.info(
"LLM-Raum-Router: '%s' → %s (%s)",
text[:80], llm_room.name, llm_room.room_id[:8],
)
# liefert STAY oder room_id direkt (keine Kategorien, kein Name-Matching)
llm_room, llm_stay, llm_failed = await self._llm_room_lookup(text, origin_room_id)
# ── Schritt 6: Move-Request-Button (Butler-Prinzip) ──────
# Vor dem Routing: Button an Andreas — "Soll ich nach [Raum] kopieren?"
# ✅Ja → Route, 📍Hier → stay_in_room
return RoutingDecision(
category="work_order",
target_room=llm_room.room_id,
confidence=0.90,
matched_room_name=llm_room.name,
move_request_sent=True,
move_request_target_name=llm_room.name,
move_request_target_id=llm_room.room_id,
)
# ── Schritt 7: LLM-Fehler oder kein Treffer ──────────────────
# ── Schritt 6: ORIGIN-FIRST GUARD (v6) ──────────────────────
# Paradigmenwechsel: Ursprungsraum entscheidet WOHIN die Antwort geht.
# Archivar schlägt nur VERLEGUNG vor (Move-Request).
if llm_failed:
# FIX 1: Timeout/Exception → Fallback auf Ursprungsraum, NICHT Catch-All
# LLM-Aufruf fehlgeschlagen → stay_in_room
logger.warning(
"LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...' → stay_in_room (Ursprungsraum)",
text,
@@ -479,20 +522,80 @@ class BidirectionalRouter:
stay_in_room=True,
is_catch_all=False,
)
else:
# LLM erfolgreich, aber kein Match → catch_all
if llm_stay or llm_room is None:
# LLM sagt STAY oder unsicher → stay_in_room
logger.info(
"LLM-Raum-Router: kein Treffer für '%.80s...' → catch_all", text
"LLM-Raum-Router: STAY für '%.80s...' → stay_in_room", text[:80]
)
catch_all = self._room_map.catch_all_room
return RoutingDecision(
category="direct_question",
target_room=catch_all.room_id if catch_all else "",
target_room="",
confidence=0.0,
is_catch_all=True,
stay_in_room=True,
)
# LLM hat einen Raum vorgeschlagen — Origin-First Guard prüfen
catch_all = self._room_map.catch_all_room
catch_all_id = catch_all.room_id if catch_all else ""
# Guard 1: LLM == origin_room → stay_in_room
if origin_room_id and llm_room.room_id == origin_room_id:
logger.info(
"Origin-First Guard: LLM schlägt Ursprungsraum vor → stay_in_room"
)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
)
# Guard 2: LLM == catch_all_room → stay_in_room
# (Kein DM-Routing aus Projekträumen!)
if catch_all_id and llm_room.room_id == catch_all_id:
logger.info(
"Origin-First Guard: LLM schlägt Catch-All vor → stay_in_room"
)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
)
# Guard 2.5: LLM == excluded room → stay_in_room
# Verhindert, dass der LLM einen excluded room vorschlägt und
# ein Move-Request dorthin gesendet wird (Release-blockierend).
if self._room_map.is_excluded(llm_room.room_id):
logger.warning(
"Origin-First Guard: LLM schlug excluded room '%s' (%s) vor → stay_in_room",
llm_room.name, llm_room.room_id[:8],
)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=0.0,
stay_in_room=True,
)
# Guard 3: LLM == anderer Raum → Move-Request (Butler-Prinzip)
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
logger.info(
"LLM-Raum-Router: '%s' → %s (%s) — Move-Request pending",
text[:80], llm_room.name, llm_room.room_id[:8],
)
return RoutingDecision(
category="work_order",
target_room=llm_room.room_id,
confidence=0.90,
matched_room_name=llm_room.name,
move_request_sent=True,
move_request_target_name=llm_room.name,
move_request_target_id=llm_room.room_id,
)
except Exception as e:
# ── Catch-All-Schutz: unerwarteter Fehler → Fallback ──────
logger.error(
@@ -546,7 +649,7 @@ class BidirectionalRouter:
return catch_all.room_id
async def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]:
async def _llm_room_lookup(self, text: str, origin_room_id: str = "") -> Tuple[Optional[RoomEntry], bool, bool]:
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap
@@ -559,13 +662,15 @@ class BidirectionalRouter:
Args:
text: Der Nachrichtentext.
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums (für Kontext).
Returns:
(RoomEntry, False) — LLM erfolgreich, Raum gefunden
(None, False) — LLM erfolgreich, kein Match (CATCH_ALL)
(None, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout)
(RoomEntry, False, False) — LLM erfolgreich, Raum gefunden (ROUTE)
(None, False, False) — LLM erfolgreich, STAY (kein Routing)
(None, False, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout)
"""
# Build room list for LLM prompt: "ID | Name | Keywords"
# Nur Nicht-Catch-All-Räume als Optionen (Catch-All ist nie ein Routing-Ziel)
room_list_parts = []
for room in self._room_map.rooms.values():
if room.catch_all:
@@ -576,47 +681,55 @@ class BidirectionalRouter:
room_list_parts.append(
f"{room.room_id} | {room.name} | {kw_str}"
)
# Catch-All als Fallback
catch_all_id = (
self._room_map.catch_all_room.room_id
if self._room_map.catch_all_room
else "CATCH_ALL"
)
room_list_parts.append(
f"{catch_all_id} | CATCH_ALL | (Fallback für unklare Nachrichten)"
)
if not room_list_parts:
# Keine Nicht-Catch-All-Räume → STAY
return None, False, False
room_list = "\n".join(room_list_parts)
prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text)
# Ursprungsraum-Name für Kontext
origin_name = ""
if origin_room_id:
origin_room = self._room_map.get_room_by_id(origin_room_id)
if origin_room:
origin_name = origin_room.name
# Try LLM — expects room ID directly
prompt = LLM_ROOM_PROMPT.format(
room_list=room_list,
text=text,
origin_room=origin_name or "unbekannt",
)
# Try LLM — expects room ID directly or "STAY"
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
async with self._llm_semaphore:
llm_result = await self._classifier._llm_raw(prompt)
if llm_result is None:
return None, True # LLM-Aufruf fehlgeschlagen
return None, False, True # LLM-Aufruf fehlgeschlagen
# Parse LLM response — should be a room ID or "CATCH_ALL"
# Parse LLM response — should be a room ID or "STAY"
response = llm_result.strip()
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
return None, False # LLM erfolgreich, kein Match
# STAY = Nachricht bleibt im Ursprungsraum
if response.upper() == "STAY":
return None, False, False # LLM erfolgreich, STAY
# Direct lookup by room ID (LLM returns the ID directly)
room = self._room_map.get_room_by_id(response)
if room is not None:
return room, False
return room, False, False
# Fallback: try name matching (for LLMs that return names instead of IDs)
response_lower = response.lower()
for room in self._room_map.rooms.values():
if response_lower == room.name.lower():
return room, False
return room, False, False
if response_lower in room.name.lower():
return room, False
return room, False, False
logger.debug("LLM returned unknown room: %s", response)
return None, False
return None, False, False # Unbekannte Antwort → STAY
# ── Route Validation ─────────────────────────────────────────────
+79
View File
@@ -958,6 +958,84 @@ ROCKETCHAT_FILES_SCHEMA = {
}
# ── Proaktiver Raum-Broadcast (B6) ──────────────────────────────────────
# Cooldown-Tracking: verhindert Spam bei vielen kleinen Aktionen.
# Nur "Fertig"-Markierungen triggern einen Broadcast.
_broadcast_cooldowns: Dict[str, float] = {} # room_id → timestamp
_BROADCAST_COOLDOWN_SECONDS: float = 300.0 # 5 Minuten
def _handle_rocketchat_broadcast(args: dict, **kw) -> str:
"""Sende einen proaktiven Status-Broadcast in einen Projektraum.
Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.'
Cooldown: 5 Minuten pro Raum — verhindert Spam bei vielen kleinen Aktionen.
Nur bei expliziten "Fertig"-Markierungen verwenden, nicht bei jeder kleinen Aktion.
Args:
room_id: Zielraum-ID (aus room-map.json oder ROCKETCHAT.MAP.md)
text: Der Broadcast-Text (menschenähnlich, kein Bot-Ton)
"""
global _broadcast_cooldowns
client = _rc_client()
if not client:
return _rc_error()
room_id = str(args.get("room_id") or "").strip()
text = str(args.get("text") or "").strip()
if not room_id:
return tool_error("room_id is required for rocketchat_broadcast")
if not text:
return tool_error("text is required for rocketchat_broadcast")
# Cooldown-Check
now = time.time()
last = _broadcast_cooldowns.get(room_id, 0.0)
if now - last < _BROADCAST_COOLDOWN_SECONDS:
remaining = int(_BROADCAST_COOLDOWN_SECONDS - (now - last))
return tool_result({
"success": False,
"cooldown": True,
"message": f"Broadcast-Cooldown aktiv: noch {remaining}s für Raum {room_id[:8]}...",
})
try:
result = client.send_message(room_id, text)
if result.get("success"):
_broadcast_cooldowns[room_id] = now
return tool_result({
"success": True,
"room_id": room_id,
"text": text[:200],
})
else:
return tool_error(f"Broadcast failed: {result.get('error', 'unknown error')}")
except Exception as exc:
return tool_error(f"rocketchat_broadcast failed: {type(exc).__name__}: {exc}")
ROCKETCHAT_BROADCAST_SCHEMA = {
"name": "rocketchat_broadcast",
"description": (
"Send a proactive status broadcast to a project room. "
"Use this after completing a task to inform the team. "
"Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.' "
"Cooldown: 5 minutes per room to prevent spam. "
"Only use for explicit 'done' markers, not for every small action."
),
"parameters": {
"type": "object",
"properties": {
"room_id": {"type": "string", "description": "Target project room ID (from room-map.json)"},
"text": {"type": "string", "description": "Broadcast message (human-like, not bot-like)"},
},
"required": ["room_id", "text"],
},
}
# ---------------------------------------------------------------------------
# Registration helpers for the plugin register() function
# ---------------------------------------------------------------------------
@@ -970,6 +1048,7 @@ _TOOLS = (
("rocketchat_upload", ROCKETCHAT_UPLOAD_SCHEMA, _handle_rocketchat_upload, "📎"),
("rocketchat_download", ROCKETCHAT_DOWNLOAD_SCHEMA, _handle_rocketchat_download, "📥"),
("rocketchat_files", ROCKETCHAT_FILES_SCHEMA, _handle_rocketchat_files, "📁"),
("rocketchat_broadcast", ROCKETCHAT_BROADCAST_SCHEMA, _handle_rocketchat_broadcast, "📢"),
)