Compare commits
53 Commits
v2.1.0
...
83a5d262c7
| Author | SHA1 | Date | |
|---|---|---|---|
| 83a5d262c7 | |||
| af56280ebc | |||
| 5e9c4ece77 | |||
| ad852c1642 | |||
| 7140da3154 | |||
| 72e8c8cb90 | |||
| ddc69167c1 | |||
| 7d454f62b6 | |||
| 8591933d8d | |||
| 63e0616d7a | |||
| 3f480d5423 | |||
| 4d35669174 | |||
| 024a173c8d | |||
| e3f9ee31f4 | |||
| 1fca310228 | |||
| c98228ef6f | |||
| 1afa822e6f | |||
| 06567d3988 | |||
| 54a19a039d | |||
| 527d664a07 | |||
| 9bc06ef858 | |||
| 58f00c0c23 | |||
| 1bb3f52fad | |||
| 65a3baa3e5 | |||
| a3f67775ab | |||
| fa2a24f747 | |||
| be917afcbd | |||
| a078620827 | |||
| b5a43223ac | |||
| e5a32abf5c | |||
| 4b2e933529 | |||
| f509710193 | |||
| c2ded4ab9a | |||
| 4af89ce13e | |||
| 7364ae3333 | |||
| 4ef07a14b9 | |||
| 7eac6b7dba | |||
| c4775ca99e | |||
| d7ce3afcd0 | |||
| 70008660fc | |||
| ccce90fdb0 | |||
| 886e566e77 | |||
| abe93cc2dc | |||
| 1c7b82e27f | |||
| 7a0abc465a | |||
| d01eded6ff | |||
| 13a87fb233 | |||
| d6b30d8d87 | |||
| f54f90be5b | |||
| bb8623aed5 | |||
| e3dc543af5 | |||
| 88b7149dd1 | |||
| e6eddcd3da |
@@ -0,0 +1,4 @@
|
|||||||
|
|
||||||
|
# room-map.json is machine-specific — never commit it
|
||||||
|
room-map.json
|
||||||
|
__pycache__/
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
# Archivar v2: Vollständiger Raum-Router — Implementation Plan
|
||||||
|
|
||||||
|
> **For Hermes:** Use subagent-driven-development skill to implement this plan task-by-task.
|
||||||
|
|
||||||
|
**Goal:** Den Archivar vom hybriden Kategorie-Klassifikator zum vollständigen thematischen Raum-Router umbauen. Embeddings und LLM fragen nicht mehr „FAKT/FRAGE/ALARM?", sondern „In welchen Raum gehört diese Nachricht thematisch?"
|
||||||
|
|
||||||
|
**Architecture:** Der `MessageClassifier` wird von Kategorie-basierten Embeddings (FAKT/FRAGE/ALARM) auf Raum-basierte Embedding-Referenzen umgestellt. Der `LLM_CLASSIFY_PROMPT` wird durch `LLM_ROOM_PROMPT` auch in der Classifier-Stufe ersetzt. `adapter.py`-Logtext wird aktualisiert. Der Router-Flow (`router.py`) bleibt unverändert — er ist bereits korrekt.
|
||||||
|
|
||||||
|
**Tech Stack:** Python 3.13, `nomic-embed-text` (768-dim), `qwen2.5:7b` (LLM), RoomMap-Datenmodell
|
||||||
|
|
||||||
|
**Analyse-Quellen:**
|
||||||
|
- Commit `58f00c0` („Phase 1-3 — RoomMap + thematischer Router")
|
||||||
|
- Deployter Code unter `~/.hermes/hermes-agent/plugins/platforms/rocketchat/archivar/`
|
||||||
|
- `room-map.json` unter `~/.hermes/hermes-agent/data/room-map.json`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Befunde (Stand 06.06.2026)
|
||||||
|
|
||||||
|
| # | Fund | Datei:Zeile | Schwere |
|
||||||
|
|---|---|---|---|
|
||||||
|
| F1 | `_initialize_sync()` vektorisiert `CATEGORY_TEXTS` (FAKT/FRAGE/ALARM) statt Raum-Kontext | `classifier.py:401-432` | Mittel |
|
||||||
|
| F2 | `_llm_classify_sync()` verwendet `LLM_CLASSIFY_PROMPT` statt `LLM_ROOM_PROMPT` | `classifier.py:350-361` | Mittel |
|
||||||
|
| F3 | Gateway-Logtext sagt „Embedding-basierte Nachrichten-Klassifikation" — sollte „Thematischer Raum-Router" sagen | `adapter.py:475` | Gering |
|
||||||
|
| F4 | `router.py`-Flow ist korrekt: Keyword→Embedding→LLM-Room→Catch-All | `router.py:152-296` | ✅ Keine Änderung |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architekturentscheidung: Nicht die Embeddings umbauen — den Flow begradigen
|
||||||
|
|
||||||
|
**Analyse:** Die Category-Embeddings (FAKT/FRAGE/ALARM) auf Raum-Embeddings umzustellen würde bedeuten, für jeden Raum einen Referenztext zu vektorisieren (9 Räume × 768-dim). Das ist teuer, erhöht die Latenz (9 Kosinus-Vergleiche statt 3) und die Raum-Texte (`RoomEntry.theme`) sind zu kurz für sinnvolle Embeddings.
|
||||||
|
|
||||||
|
**Bessere Lösung:** Der Classifier bleibt als **Intent-Detector** (FAKT/FRAGE/ALARM), aber der Router übersetzt das Ergebnis **thematisch**:
|
||||||
|
- **Schritt 1 (neu):** Keyword-Match aus RoomMap (existiert bereits ✅)
|
||||||
|
- **Schritt 2:** Embedding-Klassifikation → Kategorie (FAKT/FRAGE/ALARM)
|
||||||
|
- **Schritt 3 (zu reparieren):** LLM-Klassifikation → `LLM_ROOM_PROMPT` statt `LLM_CLASSIFY_PROMPT`
|
||||||
|
- **Schritt 4:** FAKT → doc_store, FRAGE → LLM-Room-Lookup, ALARM → Catch-All
|
||||||
|
|
||||||
|
**Nicht verändern:**
|
||||||
|
- `CATEGORY_TEXTS` bleiben (Intent-Detection ist nützlich)
|
||||||
|
- `_initialize_sync()` bleibt (vektorisiert 3 Kategorien, nicht 9 Räume)
|
||||||
|
- `router.py` bleibt (ist bereits korrekt)
|
||||||
|
|
||||||
|
**Nur dies ändern:**
|
||||||
|
1. `classifier.py:355`: `LLM_CLASSIFY_PROMPT` → `LLM_ROOM_PROMPT` + Raum-Liste aus RoomMap
|
||||||
|
2. `classifier.py:346-361`: `_llm_classify_sync()` → raum-basierte LLM-Abfrage
|
||||||
|
3. `adapter.py:475`: Logtext aktualisieren
|
||||||
|
4. Tests: 2 neue Tests für raum-basierte LLM-Klassifikation
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: LLM-Stufe im Classifier auf Raum-Prompt umstellen
|
||||||
|
|
||||||
|
**Objective:** `_llm_classify_sync()` fragt das LLM nach dem Ziel-Raum, nicht nach der Kategorie.
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `~/projekte/Hermes_rocket.chat_Plugin/plugin/archivar/classifier.py:346-361`
|
||||||
|
- Modify: `~/projekte/Hermes_rocket.chat_Plugin/plugin/archivar/classifier.py:509-511` (Aufruf von `_llm_classify_sync`)
|
||||||
|
|
||||||
|
**Kontext für Implementierer:**
|
||||||
|
|
||||||
|
Der `MessageClassifier` hat aktuell zwei LLM-Methoden:
|
||||||
|
- `_llm_classify_sync(text)` → verwendet `LLM_CLASSIFY_PROMPT`, validiert gegen FAKT/FRAGE/ALARM
|
||||||
|
- `_llm_raw_sync(prompt)` → generischer Prompt, keine Validierung (verwendet von `router._llm_room_lookup()`)
|
||||||
|
|
||||||
|
Die `_llm_classify_sync()` wird in `_classify_sync():509-511` als Stufe 2 aufgerufen, wenn die Embedding-Konfidenz unter `LLM_CONFIDENCE_THRESHOLD` (0.70) liegt. Aktuell fragt sie: „Welche Kategorie?" und validiert gegen FAKT/FRAGE/ALARM.
|
||||||
|
|
||||||
|
**Änderung:** Stattdessen soll sie den `LLM_ROOM_PROMPT` verwenden und eine `Optional[RoomEntry]` zurückgeben (oder None bei Fehler/kein Match). Der Aufrufer `_classify_sync()` muss das Ergebnis entsprechend verarbeiten.
|
||||||
|
|
||||||
|
**Genauer Ablauf:**
|
||||||
|
|
||||||
|
Schritt 1: `_llm_classify_sync()` umbenennen in `_llm_room_classify_sync()` — klarer Name.
|
||||||
|
|
||||||
|
Schritt 2: Signatur ändern von `Optional[str]` (Kategorie) zu etwas, das ein Raum-Match signalisiert. Da der Raum-Match erst im Router interpretiert werden kann (braucht RoomMap), geben wir einen Typ zurück, den der Router versteht. Einfachste Lösung: `Optional[str]` — der Raum-Name oder `"CATCH_ALL"` oder `None` bei Fehler.
|
||||||
|
|
||||||
|
Schritt 3: Den Prompt aus `LLM_CLASSIFY_PROMPT` durch `LLM_ROOM_PROMPT` ersetzen. Die Raum-Liste muss dynamisch gebaut werden — das passiert bereits in `router._llm_room_lookup()`. Um Dopplung zu vermeiden: Die Methode nimmt eine `room_list: str` als Parameter.
|
||||||
|
|
||||||
|
Schritt 4: Der Aufrufer `_classify_sync():509-511` muss die `room_list` aus dem Router holen. Dafür braucht der Classifier eine Referenz zum Router — oder (einfacher) der Router ruft die LLM-Stufe selbst auf, was er bereits tut in `_llm_room_lookup()`.
|
||||||
|
|
||||||
|
**Entscheidung: Keine Änderung an `classifier.py` — der Router macht bereits das Richtige.**
|
||||||
|
|
||||||
|
Der Router-Flow (`router.py:152-296`) ist korrekt:
|
||||||
|
1. Schritt 1.5: Keyword-Match aus RoomMap ✅
|
||||||
|
2. Schritt 2: Embedding-Klassifikation (Kategorie) ✅
|
||||||
|
3. Schritt 3: Fallback bei Classifier-Versagen ✅
|
||||||
|
4. Schritt 4: Konfidenz-Prüfung ✅
|
||||||
|
5. Schritt 5: FAKT → doc_store ✅
|
||||||
|
6. **Schritt 6: LLM-Room-Lookup für FRAGE** ✅ — `_llm_room_lookup()` nutzt `LLM_ROOM_PROMPT`
|
||||||
|
|
||||||
|
Die `_llm_classify_sync()` im Classifier ist ein **paralleler Pfad**, der in `_classify_sync():509-511` aufgerufen wird, wenn die Embedding-Konfidenz niedrig ist. Das Problem: Dieser Pfad fragt nach Kategorien, nicht Räumen. Er wird also ein Kategorie-Ergebnis liefern (z.B. "FRAGE"), das dann vom Router in Schritt 6 erneut per LLM nach Räumen interpretiert wird. Das ist doppelte Arbeit und ineffizient.
|
||||||
|
|
||||||
|
**Lösung statt Umbau:** `_llm_classify_sync()` wird NICHT mehr aufgerufen. Der `LLM_CONFIDENCE_THRESHOLD`-Zweig in `_classify_sync()` (Zeilen 509-528) wird entfernt. Wenn die Embedding-Konfidenz niedrig ist, gibt der Classifier das beste Embedding-Ergebnis zurück — der Router macht dann in Schritt 4+6 den LLM-Room-Lookup.
|
||||||
|
|
||||||
|
**Das spart einen LLM-Call pro Nachricht und eliminiert den falschen Prompt-Pfad komplett.**
|
||||||
|
|
||||||
|
### Step 1: LLM_CONFIDENCE_THRESHOLD-Zweig in `_classify_sync()` entfernen
|
||||||
|
|
||||||
|
In `classifier.py:499-528`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Prüfe, ob die Embedding-Konfidenz ausreicht
|
||||||
|
if best_score >= LLM_CONFIDENCE_THRESHOLD:
|
||||||
|
return ClassificationResult(
|
||||||
|
category=best_category,
|
||||||
|
confidence=best_score,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Stufe 2: LLM-Klassifikation, wenn Konfidenz niedrig ist
|
||||||
|
if self._llm_enabled and best_score < LLM_CONFIDENCE_THRESHOLD and self._llm_client:
|
||||||
|
llm_category = self._llm_classify_sync(text)
|
||||||
|
if llm_category:
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
return ClassificationResult(
|
||||||
|
category=llm_category,
|
||||||
|
confidence=0.95,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ansonsten: originales Embedding-Ergebnis zurückgeben
|
||||||
|
return ClassificationResult(
|
||||||
|
category=best_category,
|
||||||
|
confidence=best_score,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Ersetzen durch:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Embedding-Ergebnis zurückgeben — Router macht LLM-Room-Lookup bei FRAGE.
|
||||||
|
return ClassificationResult(
|
||||||
|
category=best_category,
|
||||||
|
confidence=best_score,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Verification:** Keine funktionale Änderung für ALARM (Keyword-Prefilter fängt das vor Embedding). Für FAKT/FRAGE mit niedriger Konfidenz: Router macht in Schritt 4+6 was nötig ist — Catch-All bei niedriger Konfidenz, LLM-Room-Lookup bei FRAGE.
|
||||||
|
|
||||||
|
**Step 2: Run existing tests**
|
||||||
|
|
||||||
|
Run: `cd ~/projekte/Hermes_rocket.chat_Plugin && python3 -m pytest plugin/archivar/tests/ -v`
|
||||||
|
Expected: 12 passed (bestehende Tests bleiben bestehen)
|
||||||
|
|
||||||
|
**Step 3: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/projekte/Hermes_rocket.chat_Plugin
|
||||||
|
git add plugin/archivar/classifier.py
|
||||||
|
git commit -m "refactor(archivar): remove LLM_CLASSIFY_PROMPT path from classifier
|
||||||
|
|
||||||
|
Router handles LLM room lookup in step 6 (via LLM_ROOM_PROMPT).
|
||||||
|
Removing the parallel LLM_CLASSIFY_PROMPT call in _classify_sync()
|
||||||
|
eliminates a redundant LLM invocation and the wrong prompt path."
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 2: Gateway-Logtext aktualisieren
|
||||||
|
|
||||||
|
**Objective:** `adapter.py`-Logtext sagt „Thematischer Raum-Router", nicht „Embedding-basierte Klassifikation".
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `~/projekte/Hermes_rocket.chat_Plugin/plugin/adapter.py:475`
|
||||||
|
|
||||||
|
**Step 1: Logtext ändern**
|
||||||
|
|
||||||
|
In `adapter.py:475`:
|
||||||
|
```python
|
||||||
|
logger.info("[rocketchat] Archivar initialisiert — Embedding-basierte Nachrichten-Klassifikation aktiv")
|
||||||
|
```
|
||||||
|
|
||||||
|
Ersetzen durch:
|
||||||
|
```python
|
||||||
|
logger.info("[rocketchat] Archivar initialisiert — Thematischer Raum-Router aktiv (room-map.json)")
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/projekte/Hermes_rocket.chat_Plugin
|
||||||
|
git add plugin/adapter.py
|
||||||
|
git commit -m "docs(archivar): update gateway log text to reflect room router architecture"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 3: Deprecated `LLM_CLASSIFY_PROMPT` markieren
|
||||||
|
|
||||||
|
**Objective:** Klar dokumentieren, dass `LLM_CLASSIFY_PROMPT` nicht mehr verwendet wird (nur für Abwärtskompatibilität).
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `~/projekte/Hermes_rocket.chat_Plugin/plugin/archivar/config.py:129-139`
|
||||||
|
|
||||||
|
**Step 1: Prompt-Kommentar aktualisieren**
|
||||||
|
|
||||||
|
`config.py:129`:
|
||||||
|
```python
|
||||||
|
LLM_CLASSIFY_PROMPT = """Klassifiziere...
|
||||||
|
```
|
||||||
|
Ergänzen zu:
|
||||||
|
```python
|
||||||
|
# DEPRECATED: Nicht mehr aktiv verwendet. Router nutzt LLM_ROOM_PROMPT (unten).
|
||||||
|
# Bleibt für externe Skripte/Abwärtskompatibilität.
|
||||||
|
LLM_CLASSIFY_PROMPT = """Klassifiziere...
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/projekte/Hermes_rocket.chat_Plugin
|
||||||
|
git add plugin/archivar/config.py
|
||||||
|
git commit -m "docs(archivar): mark LLM_CLASSIFY_PROMPT as deprecated"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 4: Test für Raum-basiertes LLM-Routing
|
||||||
|
|
||||||
|
**Objective:** Sicherstellen, dass `router._llm_room_lookup()` korrekt funktioniert und Räume aus der RoomMap matcht.
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `~/projekte/Hermes_rocket.chat_Plugin/plugin/archivar/tests/test_room_map.py` (erweitern)
|
||||||
|
|
||||||
|
**Step 1: Test schreiben**
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_llm_room_lookup_returns_correct_room():
|
||||||
|
"""LLM room lookup should match a room by its name in the response."""
|
||||||
|
from ..room_map import RoomMap, RoomEntry
|
||||||
|
from ..router import MessageRouter
|
||||||
|
from ..classifier import MessageClassifier
|
||||||
|
|
||||||
|
# Build a minimal RoomMap
|
||||||
|
rooms = {
|
||||||
|
"room1": RoomEntry(
|
||||||
|
room_id="room1",
|
||||||
|
name="#Rocketchat-Plugin",
|
||||||
|
theme="Plugin development",
|
||||||
|
keywords=["plugin", "adapter"],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"room2": RoomEntry(
|
||||||
|
room_id="room2",
|
||||||
|
name="#BAT-Team",
|
||||||
|
theme="Trading platform",
|
||||||
|
keywords=["trading", "docker"],
|
||||||
|
catch_all=False,
|
||||||
|
),
|
||||||
|
"room3": RoomEntry(
|
||||||
|
room_id="room3",
|
||||||
|
name="DM mit Andreas",
|
||||||
|
theme="Admin catch-all",
|
||||||
|
keywords=[],
|
||||||
|
catch_all=True,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
room_map = RoomMap(
|
||||||
|
rooms=rooms,
|
||||||
|
excluded_room_ids=set(),
|
||||||
|
fact_store_path="/tmp/archivar_test",
|
||||||
|
version=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = MessageRouter(
|
||||||
|
room_map=room_map,
|
||||||
|
classifier=MessageClassifier(), # not initialized — LLM lookup is independent
|
||||||
|
)
|
||||||
|
|
||||||
|
# Mock the classifier's _llm_raw_sync to return a room name
|
||||||
|
calls = []
|
||||||
|
def fake_llm(prompt):
|
||||||
|
calls.append(prompt)
|
||||||
|
return "#Rocketchat-Plugin"
|
||||||
|
|
||||||
|
router._classifier._llm_raw_sync = fake_llm
|
||||||
|
router._classifier._llm_enabled = True
|
||||||
|
router._classifier._llm_client = True # truthy check
|
||||||
|
|
||||||
|
result = router._llm_room_lookup("Das Plugin deployed nicht")
|
||||||
|
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Rocketchat-Plugin"
|
||||||
|
assert result.room_id == "room1"
|
||||||
|
assert len(calls) == 1
|
||||||
|
# Prompt should contain room list
|
||||||
|
assert "#Rocketchat-Plugin" in calls[0]
|
||||||
|
assert "#BAT-Team" in calls[0]
|
||||||
|
# Catch-all should not be listed as a room option
|
||||||
|
assert "DM mit Andreas" not in calls[0].split("CATCH_ALL:")[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_llm_room_lookup_returns_none_for_catch_all():
|
||||||
|
"""LLM returning CATCH_ALL should result in None (router falls back to catch-all)."""
|
||||||
|
from ..room_map import RoomMap, RoomEntry
|
||||||
|
from ..router import MessageRouter
|
||||||
|
from ..classifier import MessageClassifier
|
||||||
|
|
||||||
|
rooms = {
|
||||||
|
"room1": RoomEntry("room1", "#Test", "Testing", ["test"], False),
|
||||||
|
"catch": RoomEntry("catch", "Admin", "Catch-all", [], True),
|
||||||
|
}
|
||||||
|
room_map = RoomMap(rooms=rooms, excluded_room_ids=set(), fact_store_path="/tmp", version=1)
|
||||||
|
router = MessageRouter(room_map=room_map, classifier=MessageClassifier())
|
||||||
|
|
||||||
|
router._classifier._llm_raw_sync = lambda p: "CATCH_ALL"
|
||||||
|
router._classifier._llm_enabled = True
|
||||||
|
router._classifier._llm_client = True
|
||||||
|
|
||||||
|
result = router._llm_room_lookup("irgendwas unklares")
|
||||||
|
assert result is None # None → router falls back to catch_all
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2: Tests ausführen**
|
||||||
|
|
||||||
|
Run: `cd ~/projekte/Hermes_rocket.chat_Plugin && python3 -m pytest plugin/archivar/tests/test_room_map.py -v`
|
||||||
|
Expected: 14 passed (12 bestehend + 2 neu)
|
||||||
|
|
||||||
|
**Step 3: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/projekte/Hermes_rocket.chat_Plugin
|
||||||
|
git add plugin/archivar/tests/test_room_map.py
|
||||||
|
git commit -m "test(archivar): add LLM room lookup tests for thematic router"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 5: Integrationstest — End-to-End Routing
|
||||||
|
|
||||||
|
**Objective:** Sicherstellen, dass der gesamte Router-Flow ein korrektes Ergebnis liefert.
|
||||||
|
|
||||||
|
**Step 1: Integrationstest schreiben**
|
||||||
|
|
||||||
|
```python
|
||||||
|
async def test_route_keyword_match_before_llm():
|
||||||
|
"""Keyword match should skip embedding and LLM entirely."""
|
||||||
|
from ..room_map import RoomMap, RoomEntry
|
||||||
|
from ..router import MessageRouter
|
||||||
|
from ..classifier import MessageClassifier
|
||||||
|
|
||||||
|
rooms = {
|
||||||
|
"plugin_room": RoomEntry("plugin_room", "#Plugin", "Plugin dev", ["plugin", "archivar"], False),
|
||||||
|
"catch": RoomEntry("catch", "Catch-All", "Admin", [], True),
|
||||||
|
}
|
||||||
|
room_map = RoomMap(rooms=rooms, excluded_room_ids=set(), fact_store_path="/tmp", version=1)
|
||||||
|
classifier = MessageClassifier()
|
||||||
|
router = MessageRouter(room_map, classifier)
|
||||||
|
|
||||||
|
# Don't initialize classifier — keyword match should work without it
|
||||||
|
decision = await router.route("Das Plugin hat einen Bug im Archivar", "some_room")
|
||||||
|
|
||||||
|
assert decision.target_room == "plugin_room"
|
||||||
|
assert decision.matched_room_name == "#Plugin"
|
||||||
|
assert decision.confidence == 0.95
|
||||||
|
assert not decision.is_catch_all
|
||||||
|
|
||||||
|
|
||||||
|
async def test_route_fakt_to_doc_store():
|
||||||
|
"""FAKT messages should never be routed to a chat room."""
|
||||||
|
from ..room_map import RoomMap, RoomEntry
|
||||||
|
from ..router import MessageRouter
|
||||||
|
from ..classifier import MessageClassifier
|
||||||
|
|
||||||
|
rooms = {
|
||||||
|
"catch": RoomEntry("catch", "Catch-All", "Admin", [], True),
|
||||||
|
}
|
||||||
|
room_map = RoomMap(rooms=rooms, excluded_room_ids=set(), fact_store_path="/tmp", version=1)
|
||||||
|
classifier = MessageClassifier()
|
||||||
|
await classifier.initialize()
|
||||||
|
router = MessageRouter(room_map, classifier)
|
||||||
|
|
||||||
|
# Force classifier to return FAKT
|
||||||
|
original = classifier._classify_sync
|
||||||
|
classifier._classify_sync = lambda t: type('obj', (object,), {
|
||||||
|
'category': 'FAKT', 'confidence': 0.9, 'all_scores': {}, 'latency_ms': 0.0,
|
||||||
|
'is_confident': lambda self, threshold: True,
|
||||||
|
})()
|
||||||
|
|
||||||
|
decision = await router.route("System ist online. Alle Container laufen.", "some_room")
|
||||||
|
|
||||||
|
assert decision.category == "FAKT"
|
||||||
|
assert decision.target_room == "" # No room — goes to doc_store
|
||||||
|
assert decision.is_unrouteable
|
||||||
|
```
|
||||||
|
|
||||||
|
Speichern unter: `plugin/archivar/tests/test_router.py` (neue Datei)
|
||||||
|
|
||||||
|
**Step 2: Tests ausführen**
|
||||||
|
|
||||||
|
Run: `cd ~/projekte/Hermes_rocket.chat_Plugin && python3 -m pytest plugin/archivar/tests/test_router.py -v`
|
||||||
|
Expected: 2 passed
|
||||||
|
|
||||||
|
**Step 3: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/projekte/Hermes_rocket.chat_Plugin
|
||||||
|
git add plugin/archivar/tests/test_router.py
|
||||||
|
git commit -m "test(archivar): integration tests for end-to-end routing flow"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verfikation nach Implementation
|
||||||
|
|
||||||
|
1. **Alle Tests:** `python3 -m pytest plugin/archivar/tests/ -v` → 16 passed
|
||||||
|
2. **Deployment:** `./install.sh --update-only` auf Build-VM
|
||||||
|
3. **Gateway-Log prüfen:** `journalctl --user -u hermes-gateway | grep "Archivar initialisiert"` → „Thematischer Raum-Router aktiv"
|
||||||
|
4. **LLM-Stufe prüfen:** `journalctl --user -u hermes-gateway | grep -i "LLM room lookup"` → erscheint bei FRAGE-Nachrichten mit niedriger Embedding-Konfidenz
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Risiken
|
||||||
|
|
||||||
|
- **Keine:** Der Router-Flow (`router.py:152-296`) bleibt unverändert. Nur der redundante LLM-Pfad im Classifier wird entfernt. Bestehende Tests bleiben bestehen.
|
||||||
|
- **LLM-Latenz:** `qwen2.5:7b` braucht ~2-5 Sekunden pro Call. Das passiert nur bei FRAGE-Nachrichten mit niedriger Embedding-Konfidenz (selten). Keyword-Matches (Schritt 1.5) und Catch-All (Schritt 4) sind LLM-frei.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Offene Punkte (nicht in diesem Plan)
|
||||||
|
|
||||||
|
- **`install.sh` um `room-map.json`-Deployment erweitern:** Aktuell deployt `--update-only` nur den `plugin/`-Baum. Die `room-map.json` unter `~/.hermes/hermes-agent/data/` wird nicht deployed. Sollte in einem separaten Plan behandelt werden.
|
||||||
|
- **Menschlicher Override (`!r <raum>`):** In `1bb3f52` spezifiziert, noch nicht implementiert.
|
||||||
@@ -102,6 +102,14 @@ GATEWAY_ALLOW_ALL_USERS=true
|
|||||||
- Bot user account on the Rocket.Chat server
|
- Bot user account on the Rocket.Chat server
|
||||||
- Python 3.10+ (hermes-agent venv)
|
- Python 3.10+ (hermes-agent venv)
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Cause | Fix |
|
||||||
|
|---------|-------|-----|
|
||||||
|
| `No module named 'hermes_plugins.rocketchat_platform.tools'` | `__init__.py` has hard `from .tools import register_tools` but `tools.py` missing | Wrap import in `try/except ImportError` and guard `register_tools(ctx)` call |
|
||||||
|
| `Failed to load plugin 'rocketchat-platform': No module named 'archivar'` | Plugin submodule uses **absolute imports** (`from archivar.X import Y`) — these only work when the module is on global `sys.path`, not in Hermes' Plugin-Loader context | **All imports within the plugin package MUST be relative.** Rule: `from archivar.X` → `from .X` (inside submodule), `from archivar.X` → `from .archivar.X` (from `adapter.py`). Affects ALL `.py` files in the submodule. 2026-06-03: 11 imports in 5 files affected |
|
||||||
|
| Gateway shows `No adapter available for rocketchat`, only Telegram active | Plugin loading failed silently — check `errors.log` for the exact import error | Fix the import, then `systemctl --user restart hermes-gateway`. Verify: `journalctl --user -u hermes-gateway | grep "Subscribed to"` |
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
[Unlicense](LICENSE) — Public Domain. See [LICENSE](LICENSE).
|
[Unlicense](LICENSE) — Public Domain. See [LICENSE](LICENSE).
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ The agent uses `send_message` with a `metadata` dict. The adapter converts this
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
send_message(
|
send_message(
|
||||||
target="rocketchat:protonbridge",
|
target="rocketchat:my-room",
|
||||||
text="Should I proceed?",
|
text="Should I proceed?",
|
||||||
metadata={
|
metadata={
|
||||||
"template": "custom",
|
"template": "custom",
|
||||||
@@ -90,7 +90,7 @@ Without it, a late click on an old button creates silent context errors. Always
|
|||||||
```python
|
```python
|
||||||
# Step 1: Choose format
|
# Step 1: Choose format
|
||||||
send_message(
|
send_message(
|
||||||
target="rocketchat:protonbridge",
|
target="rocketchat:my-room",
|
||||||
text="Which export format?",
|
text="Which export format?",
|
||||||
metadata={
|
metadata={
|
||||||
"template": "custom",
|
"template": "custom",
|
||||||
@@ -103,7 +103,7 @@ send_message(
|
|||||||
|
|
||||||
# Step 2: Choose destination
|
# Step 2: Choose destination
|
||||||
send_message(
|
send_message(
|
||||||
target="rocketchat:protonbridge",
|
target="rocketchat:my-room",
|
||||||
text="Where to send the CSV?",
|
text="Where to send the CSV?",
|
||||||
metadata={
|
metadata={
|
||||||
"template": "custom",
|
"template": "custom",
|
||||||
|
|||||||
@@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
## Problem
|
## Problem
|
||||||
|
|
||||||
Hermes erzeugt pro Rocket.Chat-Raum eine eigene Session. Andreas' DM und der
|
Hermes erzeugt pro Rocket.Chat-Raum eine eigene Session. Die Admin-DM und der
|
||||||
#BAT-Team-Raum hatten zwei unabhängige Bernd-Instanzen — doppeltes
|
#Support-Team-Raum hatten zwei unabhängige Instanzen — doppeltes
|
||||||
Informations-Management, kein gemeinsamer Kontext.
|
Informations-Management, kein gemeinsamer Kontext.
|
||||||
|
|
||||||
## Lösung: Virtuelle Raum-Übersetzung (Plugin-only)
|
## Lösung: Virtuelle Raum-Übersetzung (Plugin-only)
|
||||||
@@ -16,7 +16,7 @@ user-basierten virtuellen Chat-IDs. Keine Hermes-Core-Änderungen.
|
|||||||
### Datenfluss
|
### Datenfluss
|
||||||
|
|
||||||
```
|
```
|
||||||
EINGANG: RC-Raum (DM / #BAT-Team)
|
EINGANG: RC-Raum (DM / #Support-Team)
|
||||||
↓
|
↓
|
||||||
_adapter._process_incoming():
|
_adapter._process_incoming():
|
||||||
room_id → user:<username> als chat_id
|
room_id → user:<username> als chat_id
|
||||||
@@ -24,9 +24,9 @@ _adapter._process_incoming():
|
|||||||
chat_type=dm (umgeht group isolation in Core)
|
chat_type=dm (umgeht group isolation in Core)
|
||||||
↓
|
↓
|
||||||
Hermes Core: build_session_key()
|
Hermes Core: build_session_key()
|
||||||
→ agent:main:rocketchat:dm:user:andreas ← EIN Key für alle Räume!
|
→ agent:main:rocketchat:dm:user:admin ← EIN Key für alle Räume!
|
||||||
↓
|
↓
|
||||||
Agent antwortet mit chat_id="user:andreas"
|
Agent antwortet mit chat_id="user:admin"
|
||||||
↓
|
↓
|
||||||
_adapter.send():
|
_adapter.send():
|
||||||
ContextVar lesen → echter room_id
|
ContextVar lesen → echter room_id
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
# Archivar: Zweistufiger Klassifikator — Architektur-Skizze
|
||||||
|
|
||||||
|
**Auftraggeber:** Andreas
|
||||||
|
**Lead:** Bernd
|
||||||
|
**Datum:** 2026-06-04
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Ausgangslage
|
||||||
|
|
||||||
|
### Ist-Zustand
|
||||||
|
- Reine Embedding-Klassifikation via `nomic-embed-text` (Ollama, localhost:11434)
|
||||||
|
- 3 Kategorietexte (FAKT, FRAGE, ALARM) als Referenzvektoren
|
||||||
|
- Kosinus-Ähnlichkeit mit Schwellwert 0.6
|
||||||
|
- Keyword-Fallback nur bei Ollama-Down
|
||||||
|
|
||||||
|
### Messergebnisse (04.06.2026, 14 Tests)
|
||||||
|
- **Embedding-only: 50% korrekt** (7/14)
|
||||||
|
- 3 Fehler: ALARM → FRAGE (klar dringende Nachrichten)
|
||||||
|
- 3 Fehler: FRAGE → FAKT (technisch formulierte Fragen)
|
||||||
|
- 1 Fehler: "HILFE" → FRAGE (Ein-Wort-Alarm)
|
||||||
|
|
||||||
|
### Root Cause
|
||||||
|
Das Embedding-Modell versteht keine Absicht — es vergleicht nur Wortvektor-Ähnlichkeit.
|
||||||
|
"Sicherheitslücke im DDP-Client — bitte sofort patchen" klingt für nomic-embed-text
|
||||||
|
ähnlicher zu "Dies ist eine Information..." als zu "Dies ist eine dringende Nachricht...",
|
||||||
|
weil die Kategorietexte selbst keine Schlüsselwörter enthalten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Ziel-Architektur
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────┐
|
||||||
|
│ Stufe 0: Keyword- │ ~0ms, reiner String-Match
|
||||||
|
│ Vorfilter │ Fängt: "ALARM", "HILFE", "STOP",
|
||||||
|
│ (config.py erweitert)│ "red flag", "gehackt", etc.
|
||||||
|
└──────┬───────────────┘
|
||||||
|
│
|
||||||
|
│ Keyword-Treffer?
|
||||||
|
│
|
||||||
|
┌───┴───┐
|
||||||
|
│ JA │ NEIN
|
||||||
|
▼ ▼
|
||||||
|
┌─────┐ ┌──────────────────┐
|
||||||
|
│FERTIG│ │ Stufe 1: Embedding│ nomic-embed-text (30ms, 274 MB)
|
||||||
|
│<1ms │ │ Kosinus-Ähnlichkeit│ Unverändert — Honcho nutzt es weiter
|
||||||
|
└─────┘ └──────┬─────────────┘
|
||||||
|
│
|
||||||
|
│ Konfidenz ≥ 0.70?
|
||||||
|
│
|
||||||
|
┌───┴───┐
|
||||||
|
│ JA │ NEIN
|
||||||
|
▼ ▼
|
||||||
|
┌─────┐ ┌──────────────────┐
|
||||||
|
│FERTIG│ │ Stufe 2: LLM │ qwen2.5:7b (~4.5 GB, ~150ms auf 20 Cores)
|
||||||
|
│30ms │ │ Prompt-Klassifik. │ "FAKT, FRAGE oder ALARM?"
|
||||||
|
└─────┘ └──────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Drei Stufen, nicht zwei.** Der Keyword-Vorfilter (Stufe 0) ist essentiell für ALARM-Nachrichten —
|
||||||
|
er fängt "HILFE", "ALARM", "STOP", "red flag" bevor sie ins Embedding gehen und dort als
|
||||||
|
FRAGE oder FAKT fehlklassifiziert werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Stufe 0: Keyword-Vorfilter (Priorität: HOCH)
|
||||||
|
|
||||||
|
### Neue ALARM-Keywords (in `config.py::FALLBACK_KEYWORDS`)
|
||||||
|
```python
|
||||||
|
"ALARM": [
|
||||||
|
"alarm", "hilfe", "dringend", "sofort", "notfall", "ausfall",
|
||||||
|
"absturz", "kritisch", "emergency", "feuer", "panne", "sos",
|
||||||
|
"sicherheitslücke", # Bestand
|
||||||
|
"stop", # NEU: Sofortiger Handlungsabbruch
|
||||||
|
"red flag", # NEU: Manifest-Sprache
|
||||||
|
"abort", # NEU: Abbruch mit Dringlichkeit
|
||||||
|
"kompromittiert", # NEU: Sicherheitsvorfall
|
||||||
|
"datenverlust", # NEU: Unwiederbringlich
|
||||||
|
"exploit", # NEU: Aktiver Angriff
|
||||||
|
"gehackt", # NEU: Eindeutiger Vorfall
|
||||||
|
"ausgefallen", # NEU: Verbform
|
||||||
|
"produktivsystem", # NEU: Produktivsystem-Bezug
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Neue FRAGE-Keywords
|
||||||
|
```python
|
||||||
|
"FRAGE": [
|
||||||
|
"frage", "wie", "was ist", "warum", "wieso", "weshalb",
|
||||||
|
"kannst du", "können sie", "help", "hilfe", "problem",
|
||||||
|
"funktioniert nicht", "kaputt", "erklären", "erkläre",
|
||||||
|
"was bedeutet", # NEU: Definition anfordern
|
||||||
|
"zeig mir", # NEU: Imperativ mit Frageabsicht
|
||||||
|
"konflikt", # NEU: Problem-Indikator
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Routing-Logik
|
||||||
|
```python
|
||||||
|
def _keyword_prefilter(text: str) -> Optional[str]:
|
||||||
|
"""Stufe 0: Keyword-Vorfilter. Liefert Kategorie oder None."""
|
||||||
|
t = text.lower()
|
||||||
|
# ALARM zuerst prüfen — höchste Priorität
|
||||||
|
for kw in FALLBACK_KEYWORDS["ALARM"]:
|
||||||
|
if kw in t:
|
||||||
|
return "ALARM"
|
||||||
|
for kw in FALLBACK_KEYWORDS["FRAGE"]:
|
||||||
|
if kw in t:
|
||||||
|
return "FRAGE"
|
||||||
|
return None # → Embedding (Stufe 1)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Effekt:** ~25% der Nachrichten werden in <1ms klassifiziert. ALARM-Fehlklassifikationen
|
||||||
|
(HILFE→FRAGE) werden komplett eliminiert. Die ALARM-Check-Liste ist die
|
||||||
|
Sicherheitsgarantie — kein Alarm darf unentdeckt bleiben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Stufe 1: Embedding (unverändert)
|
||||||
|
|
||||||
|
Bleibt exakt wie jetzt:
|
||||||
|
- `nomic-embed-text` via `localhost:11434`
|
||||||
|
- 3 Kategorietexte (FAKT, FRAGE, ALARM)
|
||||||
|
- Kosinus-Ähnlichkeit, Schwellwert **erhöht auf 0.70** (vorher 0.60)
|
||||||
|
- Begründung: Grenzfälle gehen jetzt an Stufe 2 (LLM), nicht an Catch-All
|
||||||
|
- Höhere Präzision, niedrigere Recall-Rate — aber Recall wird vom LLM aufgefangen
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Stufe 2: LLM-Klassifikator (NEU)
|
||||||
|
|
||||||
|
### Modell: qwen2.5:7b
|
||||||
|
- **Deutsch-Performance:** Stark (getestet auf deutschen Texten)
|
||||||
|
- **RAM:** ~4.5 GB (neben nomic-embed-text: 274 MB → ~5 GB gesamt)
|
||||||
|
- **Latenz:** ~150ms auf 20 CPU-Cores (Ollama, localhost:11434)
|
||||||
|
- **Kosten:** 0€ (lokal)
|
||||||
|
|
||||||
|
### Prompt-Design
|
||||||
|
```python
|
||||||
|
CLASSIFY_PROMPT = """Klassifiziere die folgende Nachricht in EINE Kategorie.
|
||||||
|
Antworte NUR mit einem Wort: FAKT, FRAGE oder ALARM.
|
||||||
|
|
||||||
|
Kategorien:
|
||||||
|
- FAKT: Information, Dokumentation, Status-Update ohne Handlungsbedarf
|
||||||
|
- FRAGE: Frage, Problembeschreibung, Bitte um Hilfe oder Erklärung
|
||||||
|
- ALARM: Dringend! Ausfall, Sicherheitsvorfall, Datenverlust, sofortiger Handlungsbedarf
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
|
||||||
|
Kategorie:"""
|
||||||
|
```
|
||||||
|
|
||||||
|
### Integration in classifier.py
|
||||||
|
```python
|
||||||
|
class MessageClassifier:
|
||||||
|
def __init__(self, ...):
|
||||||
|
self._enable_llm = True # Feature-Flag
|
||||||
|
self._llm_model = "qwen2.5:7b"
|
||||||
|
self._llm_timeout = 5.0
|
||||||
|
self._llm_confidence_threshold = 0.70 # Nur unterhalb LLM befragen
|
||||||
|
|
||||||
|
async def _llm_classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Stufe 2: LLM-basierte Klassifikation für Grenzfälle."""
|
||||||
|
try:
|
||||||
|
response = await self._call_ollama_chat(
|
||||||
|
model=self._llm_model,
|
||||||
|
prompt=CLASSIFY_PROMPT.format(text=text),
|
||||||
|
timeout=self._llm_timeout,
|
||||||
|
)
|
||||||
|
category = response.strip().upper()
|
||||||
|
if category in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
return category
|
||||||
|
except Exception:
|
||||||
|
logger.warning("LLM classification failed, using embedding result")
|
||||||
|
return None
|
||||||
|
```
|
||||||
|
|
||||||
|
### Latenz-Kaskade
|
||||||
|
```
|
||||||
|
Stufe 0 (Keyword): <1ms → ~25% der Nachrichten
|
||||||
|
Stufe 1 (Embedding): ~30ms → ~55% (Konfidenz ≥ 0.70)
|
||||||
|
Stufe 2 (LLM): ~150ms → ~20% (Grenzfälle)
|
||||||
|
Gesamt (gewichtet): ~42ms → 3× schneller als reines LLM
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Ressourcen
|
||||||
|
|
||||||
|
### RAM (Host: 15 GB verfügbar)
|
||||||
|
| Komponente | RAM |
|
||||||
|
|---|---|
|
||||||
|
| nomic-embed-text | 274 MB |
|
||||||
|
| qwen2.5:7b | ~4.5 GB |
|
||||||
|
| Hermes Gateway + System | ~3 GB |
|
||||||
|
| **Frei** | **~7 GB** ✅ |
|
||||||
|
|
||||||
|
### CPU (20 Cores verfügbar)
|
||||||
|
- Ollama nutzt alle Cores für Inference
|
||||||
|
- qwen2.5:7b skaliert gut auf 20 Cores → ~150ms realistisch
|
||||||
|
|
||||||
|
### Disk
|
||||||
|
- qwen2.5:7b: ~4.7 GB Download (einmalig)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Fallback-Strategie (unverändert)
|
||||||
|
|
||||||
|
1. Keyword Vorfilter → Embedding → LLM
|
||||||
|
2. LLM nicht verfügbar → Embedding-Ergebnis verwenden (auch wenn Konfidenz < 0.70)
|
||||||
|
3. Embedding nicht verfügbar → Keyword-Fallback wie bisher
|
||||||
|
4. **Feature-Flag `_enable_llm`**: LLM-Stufe kann jederzeit deaktiviert werden
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Änderungen an bestehendem Code
|
||||||
|
|
||||||
|
| Datei | Änderung | Umfang |
|
||||||
|
|---|---|---|
|
||||||
|
| `config.py` | Keyword-Listen erweitern, LLM-Config | ~15 Zeilen |
|
||||||
|
| `classifier.py` | `_keyword_prefilter()`, `_llm_classify()`, Schwellwert auf 0.70 | ~60 Zeilen |
|
||||||
|
| `adapter_integration.py` | LLM-Modell-Parameter durchreichen | ~5 Zeilen |
|
||||||
|
|
||||||
|
Keine Änderungen an:
|
||||||
|
- `router.py` — Routing-Logik unverändert
|
||||||
|
- `adapter.py` — Integration unverändert
|
||||||
|
- `doc_store.py` — unverändert
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Risiken & Mitigation
|
||||||
|
|
||||||
|
| Risiko | Eintrittswahrsch. | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| LLM halluziniert Kategorie | Niedrig (3-Wort-Output) | Fallback auf Embedding |
|
||||||
|
| Ollama OOM mit beiden Modellen | Niedrig (~5 GB von 15) | Feature-Flag → LLM abschalten |
|
||||||
|
| LLM-Latenz > 500ms | Mittel | 5s Timeout, Fallback |
|
||||||
|
| Keyword "stop" in normalem Text | Niedrig | Nur ALARM-Keywords — "stop" ist nie informell |
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
# Auto-Onboarding — Architekturskizze
|
||||||
|
|
||||||
|
> **Status:** Architekturskizze (Manifest §3.2, Schritt 1)
|
||||||
|
> **Datum:** 06.06.2026
|
||||||
|
> **Autor:** Lead-Entwickler (bernd)
|
||||||
|
> **Projekt:** Rocket.Chat Plugin
|
||||||
|
> **MAP:** ROCKETCHAT.MAP.md (entwicklung-standard)
|
||||||
|
> **Nächster Schritt:** Rainer Quality Gate (F1–F5)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Problem
|
||||||
|
|
||||||
|
Der RC-Skill definiert einen **automatischen Room-Map-Abgleich nach `Adapter.connect()`**:
|
||||||
|
|
||||||
|
> *"Sobald der DDP-Client Räume subscribed hat, prüft das Plugin: Room-Topic-Map vorhanden? Vollständig? Wenn nicht → folgt der Agent diesem Skill-Ablauf."*
|
||||||
|
|
||||||
|
Dieser Abgleich ist **nie implementiert worden**. Der Code subscribed Räume und initialisiert den Archivar mit der vorhandenen `room-map.json`, aber er prüft nicht, ob alle subscribed Räume in der Map enthalten sind. Neue Räume werden subscribed, aber nie thematisch zugeordnet — sie sind für den Archivar unsichtbar.
|
||||||
|
|
||||||
|
## 2. Einhängepunkt
|
||||||
|
|
||||||
|
`adapter.py::RocketChatAdapter.connect()` — nach Archivar-Initialisierung (ca. Zeile 475):
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Aktuell:
|
||||||
|
await self.archivar.initialize()
|
||||||
|
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||||||
|
logger.info("[rocketchat] Archivar initialisiert — ...")
|
||||||
|
|
||||||
|
# ← HIER fehlt der Abgleich
|
||||||
|
```
|
||||||
|
|
||||||
|
An diesem Punkt sind:
|
||||||
|
- `self._subscribed_rooms` — alle tatsächlichen RC-Räume
|
||||||
|
- `self.archivar._room_map` — die geladene room-map.json
|
||||||
|
- `self.rest` — REST-Client für API-Calls
|
||||||
|
- `self._is_user_operator()` — bekannt, ob der aktuelle User der Operator ist
|
||||||
|
|
||||||
|
## 3. Architekturentscheidungen
|
||||||
|
|
||||||
|
### 3.1 Verantwortlichkeit
|
||||||
|
|
||||||
|
| Entscheidung | Wert |
|
||||||
|
|---|---|
|
||||||
|
| **Wer führt den Abgleich aus?** | `ArchivarMessageHandler` (neue Methode `check_room_map_completeness`) |
|
||||||
|
| **Wer triggert den Abgleich?** | `RocketChatAdapter.connect()` — einmalig nach Archivar-Init |
|
||||||
|
| **Wer kommuniziert die Lücken?** | Adapter, via REST — direkte DM an den Operator |
|
||||||
|
| **Wer schreibt die Map?** | Der **Agent** (im Operator-DM-Kontext), via `room_map.save()` |
|
||||||
|
|
||||||
|
**Begründung:** Der Abgleich selbst ist Logik des Archivar-Systems (Raum-Map vs. Wirklichkeit). Die Kommunikation der Lücken gehört in den Adapter (hat REST-Zugang, kennt den Operator). Das Schreiben der Map ist ein API-Call auf `RoomMap`.
|
||||||
|
|
||||||
|
### 3.2 Abgleich-Logik (in `ArchivarMessageHandler`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
async def check_room_map_completeness(
|
||||||
|
self, subscribed_rooms: dict[str, str]
|
||||||
|
) -> list[dict]:
|
||||||
|
"""
|
||||||
|
Vergleicht subscribed rooms mit room-map.json.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subscribed_rooms: Mapping von room_id → room_name (vom Adapter)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Liste fehlender Räume: [{"room_id": "...", "name": "#Raum", "type": "c"}, ...]
|
||||||
|
Leere Liste = Map vollständig.
|
||||||
|
"""
|
||||||
|
missing = []
|
||||||
|
for room_id, room_name in subscribed_rooms.items():
|
||||||
|
if room_id not in self._room_map.rooms:
|
||||||
|
missing.append({"room_id": room_id, "name": room_name})
|
||||||
|
return missing
|
||||||
|
```
|
||||||
|
|
||||||
|
**Invarianten:**
|
||||||
|
1. **DM-Räume ohne Projektbezug automatisch ausschließen** — `DM mit Bernd`, `DM mit Bernd, Thomas`, `DM mit Bernd, MyTestBot` sind keine Projekträume
|
||||||
|
2. **DM mit dem Operator NIE als fehlend melden** — der Operator-DM ist in der Map als `catch_all` eingetragen und wird nicht zur Diskussion gestellt
|
||||||
|
3. **Check NUR beim ersten Connect nach Map-Ladung** — kein Dauer-Check, kein Re-Check bei Reconnect
|
||||||
|
4. **Nichts überschreiben** — bestehende Map-Einträge bleiben unverändert. Nur FEHLENDE Räume werden gemeldet
|
||||||
|
|
||||||
|
### 3.3 Kommunikations-Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
connect()
|
||||||
|
└─ archivar.initialize()
|
||||||
|
└─ archivar.set_subscribed_room_ids(...)
|
||||||
|
└─ archivar.check_room_map_completeness(subscribed)
|
||||||
|
│
|
||||||
|
├─ missing == [] → nichts tun, loggen: "Room map complete"
|
||||||
|
│
|
||||||
|
└─ missing != [] → Operator-DM öffnen → Onboarding-Nachricht senden
|
||||||
|
│
|
||||||
|
└─ "Folgende Räume fehlen in der Raum-Map.
|
||||||
|
Für jeden Raum: Wofür ist dieser Raum da?
|
||||||
|
[Buttons pro Raum: Projektraum / Überspringen / Später]"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Warum Buttons pro Raum?** Der RC-Skill verlangt für jeden neuen Raum: *"Wofür ist dieser Raum aus deiner Sicht da?"* Das ist eine thematische Entscheidung — keine automatische. Der Operator muss bestätigen.
|
||||||
|
|
||||||
|
### 3.4 Map-Update
|
||||||
|
|
||||||
|
Nach Operator-Antwort (Button-Klick oder Text-Antwort):
|
||||||
|
|
||||||
|
1. `RoomMap.add_or_update_room(room_id, name, theme, keywords)`
|
||||||
|
2. `RoomMap.save()` → schreibt `room-map.json`
|
||||||
|
3. `ArchivarMessageHandler.reload_room_map()` → Router aktualisieren
|
||||||
|
4. Log: "Room map updated: #Raum hinzugefügt"
|
||||||
|
|
||||||
|
**Kein Gateway-Neustart nötig.** `RoomMap` und `MessageRouter` arbeiten mit In-Memory-Repräsentationen. Ein `reload()` aktualisiert beide.
|
||||||
|
|
||||||
|
### 3.5 Single-Room-Regel (RC-Skill §Catch-All)
|
||||||
|
|
||||||
|
**Wenn der Bot nur EINEN subscribed Raum hat (ohne DMs):**
|
||||||
|
|
||||||
|
1. `check_room_map_completeness()` prüft ZUERST die Anzahl der relevanten Räume
|
||||||
|
2. Relevante Räume = subscribed rooms MINUS ignorierte DMs
|
||||||
|
3. **1 relevanter Raum → Catch-All, keine Rückfragen**
|
||||||
|
4. Automatisch in `room-map.json` schreiben, wenn der Raum noch nicht in der Map ist:
|
||||||
|
```json
|
||||||
|
{"name": "#Raumname", "catch_all": true, "keywords": []}
|
||||||
|
```
|
||||||
|
5. Log: "Single room detected — auto-assigned as catch_all"
|
||||||
|
6. **Kein Interview, keine Buttons, kein Operator-DM**
|
||||||
|
|
||||||
|
**Erst bei 2+ relevanten Räumen** greift das Onboarding-Interview (Abschnitt 3.3).
|
||||||
|
|
||||||
|
**Begründung (aus RC-Skill):**
|
||||||
|
> *"1 Raum: Der einzige Raum ist automatisch Catch-All — keine Rückfragen."*
|
||||||
|
|
||||||
|
Ein Bot in genau einem Kanal hat keine Routing-Entscheidung zu treffen. Jede Nachricht gehört in diesen Raum. Den Operator mit einem Interview zu belästigen wäre kontraproduktiv.
|
||||||
|
|
||||||
|
### 3.6 DM-Raum-Erkennung
|
||||||
|
|
||||||
|
Der Adapter kennt für jeden subscribed Raum den Typ (`c`, `p`, `d`). DM-Räume werden beim Abgleich so behandelt:
|
||||||
|
|
||||||
|
| Raumname | Typ | Behandlung |
|
||||||
|
|---|---|---|
|
||||||
|
| DM mit andreas, Bernd | `d` | **Nie melden** — ist catch_all in Map |
|
||||||
|
| DM mit Bernd | `d` | **Ignorieren** — kein Projektbezug |
|
||||||
|
| DM mit Bernd, Thomas | `d` | **Ignorieren** — kein Projektbezug |
|
||||||
|
| DM mit Bernd, Susi | `d` | **Ignorieren** — kein Projektbezug |
|
||||||
|
| DM mit Bernd, MyTestBot | `d` | **Ignorieren** — Test-Bot |
|
||||||
|
| #BAT-Team | `c` | Melden falls fehlt |
|
||||||
|
| #Rocketchat-Plugin | `p` | Melden falls fehlt |
|
||||||
|
| #LAN-Dokumentation | `c` | Melden falls fehlt |
|
||||||
|
| #Protonbridge-Plugin | `p` | Melden falls fehlt |
|
||||||
|
|
||||||
|
**Regel:** `type == "d"` → nur melden, wenn der DM-Partner ein **bekannter Projekt-Mitarbeiter** ist (aktuell: nur andreas). Alle anderen DMs ignorieren.
|
||||||
|
|
||||||
|
## 4. Zustände & Übergänge
|
||||||
|
|
||||||
|
```
|
||||||
|
[Map unvollständig]
|
||||||
|
│
|
||||||
|
├─ Onboarding gestartet → Operator-DM mit Raum-Liste
|
||||||
|
│
|
||||||
|
├─ Operator antwortet pro Raum → Map wird ergänzt
|
||||||
|
│ │
|
||||||
|
│ └─ Alle Räume beantwortet → [Map vollständig]
|
||||||
|
│
|
||||||
|
└─ Operator klickt "Später" → Check beim nächsten Connect wiederholen
|
||||||
|
```
|
||||||
|
|
||||||
|
**Zustandsverfolgung:** Der `ArchivarMessageHandler` merkt sich im `_stats`-Dict, ob ein Onboarding läuft (`"onboarding_active": true/false`). Solange aktiv → keine neuen Onboarding-Nachrichten senden. Erst wenn alle Räume abgearbeitet sind → `onboarding_active = false`.
|
||||||
|
|
||||||
|
## 5. Code-Änderungen (Scope)
|
||||||
|
|
||||||
|
| Datei | Änderung | Umfang |
|
||||||
|
|---|---|---|
|
||||||
|
| `archivar/adapter_integration.py` | Neue Methode `check_room_map_completeness()` | ~25 Zeilen |
|
||||||
|
| `archivar/adapter_integration.py` | `_stats` um `onboarding_active` erweitern | 1 Zeile |
|
||||||
|
| `archivar/room_map.py` | Neue Methode `add_or_update_room()` | ~15 Zeilen |
|
||||||
|
| `archivar/room_map.py` | `reload()` für In-Memory-Update | ~10 Zeilen |
|
||||||
|
| `adapter.py::connect()` | Aufruf nach Archivar-Init, Ergebnis an `_start_onboarding()` | ~15 Zeilen |
|
||||||
|
| `adapter.py` | Neue Methode `_start_onboarding()` — sendet DM an Operator | ~40 Zeilen |
|
||||||
|
| `adapter.py::_process_incoming()` | Onboarding-Antworten erkennen und verarbeiten | ~30 Zeilen |
|
||||||
|
| **Kein** `__init__.py`-Import-Änderung nötig (nur neue Methoden) | | |
|
||||||
|
| **Keine** neuen Dateien | | |
|
||||||
|
|
||||||
|
**Gesamtumfang:** ~140 Zeilen neuer Code über 3 bestehende Dateien.
|
||||||
|
|
||||||
|
## 6. Pitfalls
|
||||||
|
|
||||||
|
| Pitfall | Prävention |
|
||||||
|
|---|---|
|
||||||
|
| **Onboarding-Spam bei jedem Reconnect** | `onboarding_active`-Flag + `check_room_map_completeness` nur beim ersten Connect nach Map-Ladung |
|
||||||
|
| **Map wird durch parallele Onboardings korrumpiert** | `RoomMap.save()` mit File-Lock (`fcntl.flock`) |
|
||||||
|
| **DM-Erkennung falsch — Projekträume werden ignoriert** | Explizite Allow-Liste: nur `type in ("c", "p")` melden |
|
||||||
|
| **Operator nicht als User erkennbar** | `self._is_user_operator()` existiert bereits im Adapter |
|
||||||
|
| **Gateway-Neustart verliert Onboarding-Zustand** | `onboarding_active` ist flüchtig — beim nächsten Connect prüft der Check erneut und sendet ggf. neue Nachricht. Kein persistenter Zustand nötig. |
|
||||||
|
|
||||||
|
## 7. Verifikation
|
||||||
|
|
||||||
|
1. **Unit-Test:** `check_room_map_completeness` mit Mock-Map → leere Liste bei vollständiger Map, Liste bei Lücken
|
||||||
|
2. **Unit-Test:** DM-Filter — `type="d"` Räume werden ignoriert außer Operator-DM
|
||||||
|
3. **Integrationstest:** Gateway-Start mit unvollständiger Map → Onboarding-Nachricht im Operator-DM
|
||||||
|
4. **Integrationstest:** Operator beantwortet alle Räume → Map aktualisiert, kein erneuter Check beim nächsten Connect
|
||||||
@@ -0,0 +1,446 @@
|
|||||||
|
# Archivar — Architekturskizze & Implementierungsplan
|
||||||
|
|
||||||
|
> **Status:** Vorschlag — wartet auf Andreas' Review
|
||||||
|
> **Basis:** Konzept-Story `docs/archivar-konzept.md` (Commit `fa2a24f`)
|
||||||
|
> **Datum:** 05.06.2026
|
||||||
|
> **Ziel:** Umbau vom 3-Kategorien-Klassifikator zum thematischen Router
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Architekturentscheidungen
|
||||||
|
|
||||||
|
Drei Lücken aus der Gap-Analyse, hier entschieden:
|
||||||
|
|
||||||
|
### L1: Raum-Map-Format
|
||||||
|
|
||||||
|
**Entscheidung:** JSON-Datei unter `~/.hermes/hermes-agent/data/room-map.json`.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {
|
||||||
|
"<rocketchat_room_id>": {
|
||||||
|
"name": "#Rocketchat-Plugin",
|
||||||
|
"theme": "Plugin-Entwicklung & Hermes-Integration",
|
||||||
|
"keywords": ["plugin", "adapter", "rocketchat", "gateway", "archivar", "schnittstelle"],
|
||||||
|
"catch_all": false
|
||||||
|
},
|
||||||
|
"<rocketchat_room_id>": {
|
||||||
|
"name": "#BAT-Team",
|
||||||
|
"theme": "BAT-Projektentwicklung",
|
||||||
|
"keywords": ["bat", "trading", "docker", "backtesting", "orderbuch"],
|
||||||
|
"catch_all": false
|
||||||
|
},
|
||||||
|
"<dm_room_id>": {
|
||||||
|
"name": "DM Andreas",
|
||||||
|
"theme": "Meta, Strategie, Alarme",
|
||||||
|
"keywords": [],
|
||||||
|
"catch_all": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"excluded_rooms": [
|
||||||
|
"<multi_agent_room_id>"
|
||||||
|
],
|
||||||
|
"fact_store_path": "/data/Wissensdatenbank/Inbox/"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Warum JSON:**
|
||||||
|
- Maschinenlesbar ohne YAML-Dependency
|
||||||
|
- `json.load()` ist in der Python-Stdlib, null zusätzliche Abhängigkeiten
|
||||||
|
- Editierbar mit jedem Editor
|
||||||
|
- `version`-Feld für zukünftige Migrationen
|
||||||
|
- `excluded_rooms` für den Multi-Agent-Raum-Ausschluss
|
||||||
|
|
||||||
|
**Pfad-Wahl:** `~/.hermes/hermes-agent/data/` — persistente Daten unter Hermes-Kontrolle, nicht im Repo. Gleich wie `archivar_docs/`.
|
||||||
|
|
||||||
|
### L2: Catch-All-Validierung
|
||||||
|
|
||||||
|
**Entscheidung:** Beim Gateway-Start (Adapter-Initialisierung) validiert der Archivar:
|
||||||
|
|
||||||
|
1. Genau ein Raum hat `catch_all: true`
|
||||||
|
2. Bei 0 → **Gateway-Start wird abgelehnt** mit: `FATAL: No catch_all room defined in room-map.json`
|
||||||
|
3. Bei >1 → **Gateway-Start wird abgelehnt** mit: `FATAL: Multiple catch_all rooms: #RaumA, #RaumB`
|
||||||
|
4. Der Catch-All-Raum MUSS in den subscribed rooms des Bots sein
|
||||||
|
|
||||||
|
**Implementierung:** `RoomMap.load()` wirft `RoomMapValidationError` (neue Exception-Klasse). `ArchivarMessageHandler.initialize()` fängt sie und logged FATAL.
|
||||||
|
|
||||||
|
### L3: Onboarding-Integration
|
||||||
|
|
||||||
|
**Entscheidung:** Gateway-Hook — nicht im Archivar-Modul selbst, sondern als separates Tool im Rocket.Chat-Plugin.
|
||||||
|
|
||||||
|
**Ablauf:**
|
||||||
|
1. Gateway subscribed neuen Raum (via `rocketchat_rooms` oder Admin-Invite)
|
||||||
|
2. Plugin erkennt: Raum-ID nicht in `room-map.json`
|
||||||
|
3. Plugin sendet DM an Admin (konfigurierbar, default: Catch-All-Raum-Besitzer):
|
||||||
|
```
|
||||||
|
Neuer Raum erkannt: #NeuerRaum (ID: 6a...)
|
||||||
|
1. Was ist das Thema dieses Raums?
|
||||||
|
2. Welche Stichworte beschreiben das Thema?
|
||||||
|
```
|
||||||
|
4. Admin antwortet → Plugin schreibt Eintrag in `room-map.json`
|
||||||
|
5. **Optional:** `/reload` oder Gateway-Neustart zum Aktivieren
|
||||||
|
|
||||||
|
**Implementierung:** `plugin/onboarding.py` — separate Datei, nicht im Archivar-Modul. Nutzt `send_callback` für die DM.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Datenmodell
|
||||||
|
|
||||||
|
### 2.1 RoomMap (NEU — `plugin/archivar/room_map.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass
|
||||||
|
class RoomEntry:
|
||||||
|
room_id: str
|
||||||
|
name: str
|
||||||
|
theme: str
|
||||||
|
keywords: list[str]
|
||||||
|
catch_all: bool = False
|
||||||
|
|
||||||
|
class RoomMap:
|
||||||
|
"""Lädt, validiert und durchsucht die Raum-Map."""
|
||||||
|
|
||||||
|
def __init__(self, path: Path | None = None)
|
||||||
|
|
||||||
|
# Properties
|
||||||
|
rooms: dict[str, RoomEntry] # room_id → RoomEntry
|
||||||
|
catch_all_room: RoomEntry | None # Der EINE Catch-All-Raum
|
||||||
|
excluded_room_ids: set[str] # Nie routen
|
||||||
|
fact_store_path: Path # FAKT-Ablagepfad
|
||||||
|
|
||||||
|
# Lookup
|
||||||
|
def find_room_by_keywords(self, text: str) -> RoomEntry | None
|
||||||
|
def find_room_by_theme_match(self, text: str, llm_client) -> RoomEntry | None
|
||||||
|
def is_excluded(self, room_id: str) -> bool
|
||||||
|
|
||||||
|
# Validation
|
||||||
|
def validate(self, subscribed_ids: set[str]) -> list[str] # Fehlerliste
|
||||||
|
```
|
||||||
|
|
||||||
|
**Neu gegenüber heute:**
|
||||||
|
- `room_map.json` als Single Source of Truth (ersetzt Env-Vars `ARCHIVAR_*_ROOM`)
|
||||||
|
- `RoomEntry` als strukturiertes Objekt (statt Dict-of-Dicts)
|
||||||
|
- `catch_all_room` als Property (statt separater `CATCH_ALL_ROOM` Variable)
|
||||||
|
- `excluded_room_ids` (statt nichts)
|
||||||
|
- `validate()` für Gateway-Start (ersetzt stilles Ignorieren)
|
||||||
|
|
||||||
|
### 2.2 RoomRouter (UMBAU — `plugin/archivar/router.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class RoomRouter:
|
||||||
|
"""Thematischer Router: Nachricht → Zielraum."""
|
||||||
|
|
||||||
|
def __init__(self, room_map: RoomMap, classifier: MessageClassifier)
|
||||||
|
|
||||||
|
async def route(self, text: str, origin_room_id: str) -> RoutingDecision:
|
||||||
|
"""
|
||||||
|
NEUER Ablauf:
|
||||||
|
1. origin_room_id in excluded_rooms? → sofort Catch-All
|
||||||
|
2. Keyword-Match in room_map.keywords? → Zielraum
|
||||||
|
3. Embedding-Klassifikation → Kategorie (FAKT/FRAGE/ALARM)
|
||||||
|
4. LLM: "In welchen Raum?" mit room_map als Kontext
|
||||||
|
5. Kein Treffer → catch_all_room
|
||||||
|
|
||||||
|
RoutingDecision.target_room ist JETZT der Raum aus der Map,
|
||||||
|
nicht mehr der aus Env-Vars.
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
|
||||||
|
**Neu gegenüber heute:**
|
||||||
|
- `_detect_project()` durch `RoomMap.find_room_by_keywords()` ersetzt
|
||||||
|
- `_resolve_room_with_project()` durch `RoomMap.find_room_by_theme_match()` (LLM) ersetzt
|
||||||
|
- `ROOM_MAPPING` Env-Vars → `room_map.json`
|
||||||
|
- Der Router KENNT die Map (statt sie nur zu konsultieren)
|
||||||
|
|
||||||
|
### 2.3 MessageClassifier (REFACTOR — `plugin/archivar/classifier.py`)
|
||||||
|
|
||||||
|
**Bleibt weitgehend erhalten**, aber LLM-Prompt ändert sich:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ALT (config.py, Zeile 129-139):
|
||||||
|
LLM_CLASSIFY_PROMPT = """Klassifiziere ... in FAKT, FRAGE oder ALARM."""
|
||||||
|
|
||||||
|
# NEU (config.py):
|
||||||
|
LLM_ROOM_PROMPT = """Diese Räume sind verfügbar:
|
||||||
|
{room_list}
|
||||||
|
|
||||||
|
In welchen Raum gehört diese Nachricht?
|
||||||
|
Antworte NUR mit dem Raum-Namen (oder "CATCH_ALL" wenn unsicher).
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
Raum:"""
|
||||||
|
```
|
||||||
|
|
||||||
|
**Zusätzliche Änderungen:**
|
||||||
|
- `max_tokens: 20` (Raum-Namen sind länger als Kategorien)
|
||||||
|
- `LLMClassifyResult` → `LLMRoomResult`
|
||||||
|
- `_llm_classify_sync()` ruft `RoomMap.find_room_by_theme_match()` auf
|
||||||
|
|
||||||
|
### 2.4 ArchivarMessageHandler (REFACTOR — `plugin/archivar/adapter_integration.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
class ArchivarMessageHandler:
|
||||||
|
def __init__(self, room_map_path: Path | None = None, ...):
|
||||||
|
self._room_map = RoomMap(room_map_path) # NEU
|
||||||
|
self._room_map.validate(subscribed_ids) # NEU: wirft bei Fehler
|
||||||
|
|
||||||
|
async def classify_and_route(self, text: str, origin_room_id: str) -> RoutingDecision:
|
||||||
|
# Check excluded rooms FIRST
|
||||||
|
if self._room_map.is_excluded(origin_room_id):
|
||||||
|
return RoutingDecision(...) # silent ignore
|
||||||
|
|
||||||
|
# Then route
|
||||||
|
return await self._router.route(text, origin_room_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Was bleibt, was fliegt raus?
|
||||||
|
|
||||||
|
### Bleibt (bewährter Code)
|
||||||
|
|
||||||
|
| Komponente | Datei | Grund |
|
||||||
|
|-----------|-------|-------|
|
||||||
|
| Keyword-Vorfilter (`_keyword_prefilter`) | `classifier.py` | Schnelle ALARM-Erkennung, bewährt |
|
||||||
|
| Embedding-Klassifikation (Stufe 1) | `classifier.py` | Funktioniert, nomic-embed-text zuverlässig |
|
||||||
|
| `ClassificationResult` Dataclass | `classifier.py` | Stabile Schnittstelle |
|
||||||
|
| `EmbeddingClient` Interface | `classifier.py` | Gut testbar, injectable |
|
||||||
|
| `OllamaEmbeddingClient` | `classifier.py` | Bewährter Transport |
|
||||||
|
| `OllamaLLMClient` | `classifier.py` | Wiederverwendbar für neuen Prompt |
|
||||||
|
| `DocumentationStore` | `doc_store.py` | FAKT-Ablage funktioniert |
|
||||||
|
| Meta-Fragen-Erkennung | `router.py` | Bewährt, unverändert |
|
||||||
|
| Subscription-Validierung | `router.py` | Bleibt, aber gegen `room_map.rooms` prüfen |
|
||||||
|
|
||||||
|
### Fliegt raus (ersetzt)
|
||||||
|
|
||||||
|
| Komponente | Datei | Ersetzt durch |
|
||||||
|
|-----------|-------|--------------|
|
||||||
|
| `ROOM_MAPPING` (Env-Vars) | `config.py` | `room_map.json` |
|
||||||
|
| `CATCH_ALL_ROOM` (Env-Var) | `config.py` | `room_map.catch_all_room` |
|
||||||
|
| `_PROJECT_KEYWORDS` (hartcodiert) | `router.py` | `RoomEntry.keywords` aus Map |
|
||||||
|
| `_detect_project()` | `router.py` | `RoomMap.find_room_by_keywords()` |
|
||||||
|
| `_resolve_room_with_project()` | `router.py` | `RoomMap.find_room_by_theme_match()` |
|
||||||
|
| `LLM_CLASSIFY_PROMPT` (Kategorien) | `config.py` | `LLM_ROOM_PROMPT` (Raum-Lookup) |
|
||||||
|
| `ARCHIVAR_*_ROOM` Env-Vars (alle) | `.env` | `room-map.json` |
|
||||||
|
|
||||||
|
### Neu (hinzugefügt)
|
||||||
|
|
||||||
|
| Komponente | Datei | Zweck |
|
||||||
|
|-----------|-------|-------|
|
||||||
|
| `RoomMap` | `plugin/archivar/room_map.py` | Single Source of Truth |
|
||||||
|
| `RoomEntry` Dataclass | `plugin/archivar/room_map.py` | Strukturierter Raum-Eintrag |
|
||||||
|
| `RoomMapValidationError` | `plugin/archivar/room_map.py` | Gateway-Start-Schutz |
|
||||||
|
| `room-map.json` | `~/.hermes/hermes-agent/data/` | Persistente Map |
|
||||||
|
| `LLM_ROOM_PROMPT` | `config.py` | Neuer LLM-Prompt (Raum statt Kategorie) |
|
||||||
|
| `onboarding.py` | `plugin/onboarding.py` | Onboarding-Hook (Phase 2) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Migrationspfad
|
||||||
|
|
||||||
|
### Phase 1: Datenmodell & Map-Loader (Miguel, ~2h)
|
||||||
|
|
||||||
|
1. **`room_map.py` erstellen:**
|
||||||
|
- `RoomEntry` Dataclass
|
||||||
|
- `RoomMap` Klasse mit `load()`, `validate()`, `find_room_by_keywords()`
|
||||||
|
- `room-map.json` Schema + Beispiel-Datei
|
||||||
|
- Unit-Tests für Validierung (0 Catch-All, 2 Catch-All, excluded rooms)
|
||||||
|
|
||||||
|
2. **`config.py` ergänzen:**
|
||||||
|
- `LLM_ROOM_PROMPT` Template
|
||||||
|
- `ROOM_MAP_PATH` Default (`~/.hermes/hermes-agent/data/room-map.json`)
|
||||||
|
- Alte Env-Vars als **deprecated** markieren (mit Warning-Log)
|
||||||
|
|
||||||
|
3. **Alte Env-Vars noch lesen als Fallback:**
|
||||||
|
```python
|
||||||
|
def _migrate_from_env_vars() -> dict | None:
|
||||||
|
"""Liest ARCHIVAR_*_ROOM Env-Vars und baut temporäre Map.
|
||||||
|
Logged WARNING: 'Using deprecated ARCHIVAR_*_ROOM env vars.
|
||||||
|
Please migrate to room-map.json'."""
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2: Router-Umbau (Miguel, ~3h)
|
||||||
|
|
||||||
|
4. **`RoomRouter` in `router.py` umbauen:**
|
||||||
|
- `route()` nimmt jetzt `origin_room_id` Parameter
|
||||||
|
- `_resolve_room_with_project()` → ruft `RoomMap.find_room_by_keywords()` auf
|
||||||
|
- Keyword-Matching aus `_PROJECT_KEYWORDS` entfernen → Keywords aus `RoomEntry` nutzen
|
||||||
|
- LLM-Pfad: `LLM_ROOM_PROMPT.format(room_list=..., text=...)` statt `LLM_CLASSIFY_PROMPT`
|
||||||
|
|
||||||
|
5. **`RoutingDecision` erweitern:**
|
||||||
|
- `matched_room_name: str | None` Feld (für Debugging)
|
||||||
|
|
||||||
|
### Phase 3: Integration & Test (Miguel, ~2h)
|
||||||
|
|
||||||
|
6. **`adapter_integration.py` anpassen:**
|
||||||
|
- `ArchivarMessageHandler.__init__()` lädt `RoomMap`
|
||||||
|
- `validate()` beim Start (FATAL bei Fehler)
|
||||||
|
- `classify_and_route()` prüft `is_excluded(origin_room_id)`
|
||||||
|
|
||||||
|
7. **`adapter.py` Einhängung prüfen:**
|
||||||
|
- `set_subscribed_room_ids()` muss VOR `initialize()` aufgerufen werden
|
||||||
|
- `initialize()` muss `room_map.validate(subscribed_ids)` aufrufen
|
||||||
|
|
||||||
|
8. **Integrationstest auf `.45`:**
|
||||||
|
- Test-Map mit 2 Räumen + Catch-All erstellen
|
||||||
|
- Nachricht mit Plugin-Keywords → muss in Plugin-Raum landen
|
||||||
|
- Unbekannte Nachricht → muss im Catch-All landen
|
||||||
|
- Nachricht aus excluded room → muss ignoriert werden
|
||||||
|
- Gateway-Start mit 0 Catch-All → muss FATAL loggen
|
||||||
|
|
||||||
|
### Phase 4: Onboarding (später, Miguel ~1.5h)
|
||||||
|
|
||||||
|
9. **`onboarding.py` erstellen:**
|
||||||
|
- Erkennt neue Räume (nicht in Map)
|
||||||
|
- Sendet strukturierte DM an Admin
|
||||||
|
- Parst Admin-Antwort → schreibt Map-Eintrag
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Datenfluss (NEU)
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht (text, origin_room_id)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
origin_room_id in excluded_rooms? ────► IGNORE (silent)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Keyword-Match in RoomMap.keywords? ───► Zielraum gefunden → Route
|
||||||
|
│
|
||||||
|
▼ (kein Keyword-Treffer)
|
||||||
|
Embedding-Klassifikation (nomic-embed-text)
|
||||||
|
│
|
||||||
|
├── ALARM (conf ≥ 0.6) → catch_all_room (Admin-DM)
|
||||||
|
├── FRAGE (conf ≥ 0.6) → LLM-Room-Lookup
|
||||||
|
├── FAKT (conf ≥ 0.6) → fact_store_path (Dateisystem)
|
||||||
|
└── conf < 0.6 → LLM-Room-Lookup
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
LLM: "In welchen Raum?" mit room_map als Kontext
|
||||||
|
│
|
||||||
|
├── Raum erkannt → Route
|
||||||
|
└── Kein Raum → catch_all_room
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Menschlicher Override
|
||||||
|
|
||||||
|
Der Archivar ist ein automatisches System — aber der Mensch behält immer das
|
||||||
|
letzte Wort. Der Override ist keine „Notbremse", sondern ein **konstruktives
|
||||||
|
Korrektur-Werkzeug**, das den Archivar trainiert, besser zu werden.
|
||||||
|
|
||||||
|
### 6.1 Override durch Admin-Reaktion
|
||||||
|
|
||||||
|
Der Admin kann auf eine fehlgeleitete Nachricht im Zielraum mit einem
|
||||||
|
**Reply** reagieren. Das Reply-Format ist simpel: `!r <raum-name>`.
|
||||||
|
|
||||||
|
```
|
||||||
|
Beispiel:
|
||||||
|
Originalnachricht im #Infrastruktur:
|
||||||
|
„Das Docker-Image für das Plugin ist kaputt"
|
||||||
|
|
||||||
|
Admin reply:
|
||||||
|
!r #Rocketchat-Plugin
|
||||||
|
```
|
||||||
|
|
||||||
|
**Was dann passiert:**
|
||||||
|
1. Der Archivar erkennt das Reply-Format (`!r` am Zeilenanfang)
|
||||||
|
2. Die Originalnachricht wird aus dem falschen Raum **gelöscht**
|
||||||
|
3. Die Nachricht wird in den korrekten Raum **verschoben** (mit `[UMGELEITET]` Prefix)
|
||||||
|
4. **Die Korrektur wird in der Map gespeichert:**
|
||||||
|
- Das Keyword der Nachricht (z.B. `docker`) wird temporär für diesen Kontext
|
||||||
|
dem richtigen Raum zugeordnet
|
||||||
|
- Bei 3 Overrides für dasselbe Keyword-Muster → permanenter Eintrag in die
|
||||||
|
`keyword_overrides` der `room-map.json`
|
||||||
|
|
||||||
|
### 6.2 Override-Schema in der Map
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"rooms": { ... },
|
||||||
|
"excluded_rooms": [ ... ],
|
||||||
|
"fact_store_path": "/data/Wissensdatenbank/Inbox/",
|
||||||
|
"keyword_overrides": {
|
||||||
|
"plugin": "docker",
|
||||||
|
"bat": "backtesting",
|
||||||
|
"plugin": "gateway"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`keyword_overrides` ist eine **flache Map**: `raum_name → keyword`. Wenn ein Raum
|
||||||
|
bereits ein Override für ein Keyword hat, wird der Score dieses Raums bei einem
|
||||||
|
Match künstlich erhöht.
|
||||||
|
|
||||||
|
**Begrenzung:** Maximal 50 Override-Einträge. Bei Überschreitung werden die
|
||||||
|
ältesten (nach Datum) gelöscht. Overrides sind **Trainingsdaten**, kein Ersatz
|
||||||
|
für saubere Keywords in der Map.
|
||||||
|
|
||||||
|
### 6.3 Override im Datenfluss
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht (text, origin_room_id)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
origin_room_id in excluded_rooms? ────► IGNORE (silent)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Keyword-Match in keyword_overrides? ───► Override-Raum (höchste Prio)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Keyword-Match in RoomMap.keywords? ───► Zielraum gefunden → Route
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
(Rest wie gehabt: Embedding → LLM → Catch-All)
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Override hat die **höchste Priorität** im Keyword-Matching — noch vor den
|
||||||
|
normalen Raum-Keywords. Der Mensch korrigiert einmal, der Archivar lernt daraus.
|
||||||
|
|
||||||
|
### 6.4 Override-Antwort an den Admin
|
||||||
|
|
||||||
|
Nach erfolgreichem Override antwortet der Archivar im Zielraum mit einer
|
||||||
|
Bestätigung:
|
||||||
|
|
||||||
|
```
|
||||||
|
[UMGELEITET von #Infrastruktur] Das Docker-Image für das Plugin ist kaputt
|
||||||
|
↳ Override gespeichert: "docker" + Kontext "Plugin" → #Rocketchat-Plugin
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.5 Was der Override NICHT ist
|
||||||
|
|
||||||
|
- **Kein Echtzeit-Eingriff.** Der Override korrigiert bereits geroutete Nachrichten. Er verhindert nicht die initiale Fehlleitung — er behebt sie und verhindert Wiederholungen.
|
||||||
|
- **Kein Chat-Befehlssystem.** `!r` ist das einzige Override-Kommando. Keine weitere Befehlssyntax.
|
||||||
|
- **Kein Ersatz für gute Keywords.** Wenn der Admin ständig overriden muss, sind die Keywords in der Map falsch — nicht der Override-Mechanismus.
|
||||||
|
|
||||||
|
### 6.6 Override-Regeln für die Sicherheit
|
||||||
|
|
||||||
|
1. **Nur der Admin** (Besitzer des Catch-All-Raums) darf overriden. Replies von anderen Nutzern werden ignoriert.
|
||||||
|
2. **Nur in abonnierten Räumen.** Override aus nicht-abonnierten Räumen wird ignoriert.
|
||||||
|
3. **Kein Override auf sich selbst.** `!r` in den gleichen Raum → wird ignoriert.
|
||||||
|
4. **Kein Override in excluded_rooms.** Der Multi-Agent-Raum ist komplett ausgenommen.
|
||||||
|
5. **Keine Endlosschleife.** Wenn dieselbe Nachricht 3× overriden wird → Stop, Admin benachrichtigen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Checkliste für Andreas' Review
|
||||||
|
|
||||||
|
- [ ] **Menschlicher Override:** `!r <raum>` Reply-Mechanismus sinnvoll? Admin-only korrekt?
|
||||||
|
- [ ] **Override-Lernen:** Keyword-Overrides nach 3 Wiederholungen permanent — guter Schwellwert?
|
||||||
|
- [ ] **Override-Begrenzung:** Max 50 Einträge, älteste verdrängen — angemessen?
|
||||||
|
- [ ] **Override im Datenfluss:** Höchste Keyword-Priorität vor Raum-Keywords — korrekt?
|
||||||
|
- [ ] **Sicherheitsregeln:** Admin-only, keine Selbst-Overrides, keine excluded_rooms, 3× Stop — vollständig?
|
||||||
|
- [ ] **L1 — JSON-Format:** `room-map.json` Schema akzeptabel? Oder lieber YAML?
|
||||||
|
- [ ] **L1 — Pfad:** `~/.hermes/hermes-agent/data/` korrekt? Oder `/data/Wissensdatenbank/...`?
|
||||||
|
- [ ] **L2 — FATAL bei 0 Catch-All:** Zu hart? Oder genau richtig (Fail-Fast)?
|
||||||
|
- [ ] **L2 — Validierung beim Start:** Gateway-Start-Blockade akzeptabel?
|
||||||
|
- [ ] **L3 — Onboarding als separates Plugin-Tool:** Passt die Trennung vom Archivar-Modul?
|
||||||
|
- [ ] **Datenfluss:** Passt die Logik "ALARM → Admin, FRAGE → Themenraum, FAKT → Datei"?
|
||||||
|
- [ ] **LLM-Prompt:** `LLM_ROOM_PROMPT` mit Raum-Liste sinnvoll?
|
||||||
|
- [ ] **Migrationspfad:** Alte Env-Vars als deprecated-Fallback okay für Übergang?
|
||||||
|
- [ ] **Multi-Agent-Raum-Ausschluss:** `excluded_rooms` in Map + `origin_room_id`-Check ausreichend?
|
||||||
|
- [ ] **FAKT-Ablagepfad:** `fact_store_path` in der Map konfigurierbar — korrekt?
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
# Archivar — Konzept & Architekturziel
|
||||||
|
|
||||||
|
> **Status:** Konzeptioneller Anker. Dieses Dokument dokumentiert das WARUM, nicht das WIE.
|
||||||
|
> Implementierungsentscheidungen müssen sich an diesem Dokument messen lassen.
|
||||||
|
|
||||||
|
## Das Problem
|
||||||
|
|
||||||
|
Ein Hermes-Agent in mehreren Chat-Räumen sieht jede Nachricht — Statusmeldungen,
|
||||||
|
Fragen, Alarme, Smalltalk. Ohne Filter ertrinkt er im Rauschen. Schlimmer:
|
||||||
|
Eine echte Frage oder ein Alarm zwischen zwei Status-Updates wird übersehen,
|
||||||
|
weil alles gleich aussieht.
|
||||||
|
|
||||||
|
**Der Mensch ist der Flaschenhals.** Jede Nachricht muss ein Mensch lesen und
|
||||||
|
entscheiden: „Ist das wichtig? Wer ist zuständig? In welchen Raum gehört das?"
|
||||||
|
|
||||||
|
## Die Lösungsidee
|
||||||
|
|
||||||
|
Der Archivar ist ein **thematischer Router**, der vor dem Agenten sitzt und
|
||||||
|
Nachrichten automatisch dem richtigen Raum zuordnet — ohne dass ein Mensch
|
||||||
|
jede Nachricht prüfen muss.
|
||||||
|
|
||||||
|
```
|
||||||
|
Eingehende Nachricht
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Archivar klassifiziert
|
||||||
|
│
|
||||||
|
├── Thema erkannt → Zielraum (Projektraum, Themenraum)
|
||||||
|
├── Kein Thema → Catch-All („Alles andere")
|
||||||
|
└── Alarm → DM Auftraggeber (sofort)
|
||||||
|
```
|
||||||
|
|
||||||
|
Das ist ein **einfacher Entscheidungsbaum**, kein komplexes ML-System.
|
||||||
|
Die Intelligenz liegt in der **Raum-Map**: eine Zuordnung von Themen zu Räumen,
|
||||||
|
die der Archivar konsultiert.
|
||||||
|
|
||||||
|
## Die Raum-Map
|
||||||
|
|
||||||
|
Jeder abonnierte Raum bekommt ein **Thema**. Das Thema ist eine informelle
|
||||||
|
Beschreibung dessen, was in diesen Raum gehört, plus eine optionale
|
||||||
|
**Stichwortliste**, die der Archivar für die automatische Zuordnung nutzt.
|
||||||
|
|
||||||
|
**Catch-All** ist ein **Attribut eines Raums** — nicht mehr, nicht weniger.
|
||||||
|
Genau ein Raum trägt dieses Attribut. Alles, was der Archivar keinem anderen
|
||||||
|
Thema zuordnen kann, landet dort: nicht verloren, sondern gesammelt an einem
|
||||||
|
definierten Ort. Der Admin sieht es, entscheidet — und kein Rauschen bleibt
|
||||||
|
unentdeckt liegen.
|
||||||
|
|
||||||
|
### ⛔ Ausschluss-Regel
|
||||||
|
|
||||||
|
Der **Multi-Agent-Raum** (Bot-zu-Bot-Kommunikation & Training) ist **NIE**
|
||||||
|
Teil der Raum-Map. Er darf **weder** Catch-All sein **noch** ein Thema
|
||||||
|
bekommen. Der Archivar ignoriert diesen Raum vollständig.
|
||||||
|
|
||||||
|
**Grund:** Würden unbeaufsichtigte Agenten Nachrichten aus diesem Raum empfangen
|
||||||
|
und beantworten, entstünde eine unkontrollierte Bot-zu-Bot-Kommunikation —
|
||||||
|
Halluzinationen, Endlosschleifen, ungewollte Aktionen. Der Raum dient
|
||||||
|
ausschließlich dem expliziten Training und der direkten Agenten-Interaktion.
|
||||||
|
Jede automatische Weiterleitung dorthin ist ein Sicherheitsrisiko.
|
||||||
|
|
||||||
|
| Raum | Thema | Stichworte | Catch-All |
|
||||||
|
|------|-------|------------|-----------|
|
||||||
|
| `#Projekt-Alpha` | Frontend-Entwicklung | ui, design, css, komponente, layout | — |
|
||||||
|
| `#Projekt-Beta` | API & Backend | api, endpoint, datenbank, auth, rest | — |
|
||||||
|
| `#Infrastruktur` | Server & Deployment | docker, nginx, cert, domain, backup | — |
|
||||||
|
| `DM Admin` | Meta, Strategie, Alarme | (reserviert für ALARM) | ✅ |
|
||||||
|
|
||||||
|
**Regel:** Ein Raum mit Thema bekommt nur thematisch passende Nachrichten.
|
||||||
|
Der Catch-All-Raum bekommt alles, was nirgendwo sonst hinpasst — und nichts,
|
||||||
|
was bereits ein Thema hat.
|
||||||
|
|
||||||
|
### FAKT-Ablage — kein Raum, sondern ein Pfad
|
||||||
|
|
||||||
|
Fakten sind **Dokumentation, nicht Kommunikation.** Sie gehören nicht in einen
|
||||||
|
Chat-Raum, sondern an einen festen Ablageort im Dateisystem. Der Archivar
|
||||||
|
schreibt FAKT-Nachrichten dorthin — sie werden nie in einen Raum geroutet,
|
||||||
|
unabhängig von der Konfiguration.
|
||||||
|
|
||||||
|
| Zieltyp | Beispiel | Zweck |
|
||||||
|
|---------|----------|-------|
|
||||||
|
| **Themenraum** | `#Projekt-Beta` | Thematische Diskussion |
|
||||||
|
| **Catch-All-Raum** | `DM Admin` | Alles Unklassifizierte |
|
||||||
|
| **FAKT-Ablage** | `/data/Wissensdatenbank/Inbox/` | Reine Dokumentation |
|
||||||
|
|
||||||
|
Für Community-Installationen kann der Ablagepfad in der Raum-Map konfiguriert
|
||||||
|
werden — bei uns ist es die Inbox der Wissensdatenbank. Der Mechanismus ist
|
||||||
|
derselbe wie bei `StartObsidian`: Fakten sammeln sich dort, der Admin räumt
|
||||||
|
sie später auf (morgens, vor dem Tagesstart). Kein Sortieren zur Laufzeit,
|
||||||
|
kein Routing-Overhead — einfach ablegen und später zuordnen.
|
||||||
|
|
||||||
|
## Das Onboarding-Interview
|
||||||
|
|
||||||
|
Wenn der Gateway einen neuen Raum abonniert, führt der Agent ein kurzes
|
||||||
|
Interview mit dem Auftraggeber:
|
||||||
|
|
||||||
|
1. „Was ist das Thema dieses Raums?"
|
||||||
|
2. „Welche Stichworte beschreiben das Thema?"
|
||||||
|
3. Eintrag in die Raum-Map
|
||||||
|
|
||||||
|
Danach kennt der Archivar den Raum und kann Nachrichten automatisch
|
||||||
|
zuordnen. Kein neuer Raum bleibt unkonfiguriert.
|
||||||
|
|
||||||
|
## Abgrenzung: Was der Archivar NICHT ist
|
||||||
|
|
||||||
|
- **Kein Chat-Bot.** Er antwortet nicht, er routet nur.
|
||||||
|
- **Kein Agent.** Er trifft keine inhaltlichen Entscheidungen, er ordnet nur zu.
|
||||||
|
- **Kein Klassifikator um der Klassifikation willen.** Die Kategorien (FAKT/FRAGE/ALARM)
|
||||||
|
sind Mittel zum Zweck — sie dienen der Raum-Zuordnung, nicht der semantischen Analyse.
|
||||||
|
|
||||||
|
## Warum das wichtig ist
|
||||||
|
|
||||||
|
Der Agent ist ein **Multi-Room-Agent**: eine Instanz, die alle Räume sieht
|
||||||
|
und alles weiß. Der Archivar gibt diesem Agenten ein **Kommunikationsverhalten**,
|
||||||
|
das menschlicher Gesprächslogik folgt:
|
||||||
|
|
||||||
|
- **Aufgabe vom Auftraggeber (DM)** → wird dort empfangen, Analyse erfolgt dort.
|
||||||
|
- **Abarbeitung & Delegation** → wird im Themenraum gepostet, wo das Team es sieht.
|
||||||
|
- **Ergebnisse & Status** → landen im Themenraum, nicht im DM.
|
||||||
|
- **Alarme** → sofort in den DM, keine Verzögerung.
|
||||||
|
|
||||||
|
```
|
||||||
|
DM Andreas: „Bernd, setze die Maßnahmen für das Plugin im Team um..."
|
||||||
|
↓ (Bernd analysiert, delegiert an Rainer/Miguel)
|
||||||
|
#Plugin-Dev: „Auftrag analysiert: Profil erstellt.
|
||||||
|
Rainer macht die Architekturskizze..."
|
||||||
|
↓ (Rainer postet Skizze)
|
||||||
|
#Plugin-Dev: „Architekturskizze liegt vor. Miguel beginnt mit Implementierung."
|
||||||
|
↓ (Miguel postet Fortschritt)
|
||||||
|
#Plugin-Dev: „Implementierung abgeschlossen. Quality Gate bestanden."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Bernd entwickelt NIE selbst.** Er hält die Fäden in der Hand — delegiert,
|
||||||
|
koordiniert, informiert — ist aber **immer für den Auftraggeber ansprechbar**.
|
||||||
|
Ein Agent, der alles im Blick hat.
|
||||||
|
|
||||||
|
Der Archivar macht dieses Verhalten **automatisch**: Er weiß, welche Antwort
|
||||||
|
in welchen Raum gehört, ohne dass der Agent bei jeder Nachricht neu entscheiden
|
||||||
|
muss. Das ist Raumlogik, nicht Klassifikation um ihrer selbst willen.
|
||||||
|
|
||||||
|
## Historie
|
||||||
|
|
||||||
|
| Datum | Ereignis |
|
||||||
|
|-------|----------|
|
||||||
|
| 2026-05-29 | Erstes Konzept: Room-Topic-Map im RC-Skill dokumentiert |
|
||||||
|
| 2026-05-31 | Onboarding-Interview für neue Räume spezifiziert |
|
||||||
|
| 2026-06-03 | Commit `abe93cc`: Raum-Map anonymisiert (Vorbereitung öffentliches Repo) |
|
||||||
|
| 2026-06-03/04 | Archivar implementiert als 3-Kategorien-Klassifikator — **Abweichung vom Konzept** |
|
||||||
|
| 2026-06-05 | Konzeptionelles Audit: Ist-Zustand ≠ Architekturziel |
|
||||||
|
|
||||||
|
## Architekturziel (wiederherzustellen)
|
||||||
|
|
||||||
|
1. **Raum-Map ist die Single Source of Truth** für Themen-Zuordnung
|
||||||
|
2. **Onboarding-Interview** für jeden neuen Raum
|
||||||
|
3. **Einfacher Entscheidungsbaum:** Thema erkannt → Zielraum; kein Thema → Catch-All
|
||||||
|
4. **Stichwortlisten** pro Raum, nicht 2 hartcodierte Projekt-Keys
|
||||||
|
5. **LLM (Premium)** verbessert die Zuordnungsgenauigkeit, ersetzt aber nicht die Map
|
||||||
|
|
||||||
|
> **Ehern:** Der Archivar ist ein Router, kein Klassifikator.
|
||||||
|
> Die Frage ist nicht „Welche Kategorie?" sondern „In welchen Raum?"
|
||||||
|
|
||||||
|
## Gap-Analyse: Konzept vs. Implementierung (05.06.2026)
|
||||||
|
|
||||||
|
|
||||||
|
### Warum Rainer das nicht allein zu Ende denken kann
|
||||||
|
|
||||||
|
Diese Story ist ein **gutes Briefing**, aber **kein fertiger Architekturauftrag**.
|
||||||
|
Drei Lücken, die Rainer erst schließen müsste — und die der Lead (Bernd)
|
||||||
|
schließen sollte, bevor der Auftrag an den Architekten geht:
|
||||||
|
|
||||||
|
| # | Was fehlt | Warum Rainer es braucht |
|
||||||
|
|---|-----------|------------------------|
|
||||||
|
| **L1** | **Raum-Map-Format** — JSON? YAML? Python-Dict? Wo liegt sie? Wie wird sie geladen? | Die Map ist die Single Source of Truth. Ohne Format kann Rainer keine Schnittstelle definieren. |
|
||||||
|
| **L2** | **Catch-All-Validierung** — Wer stellt sicher, dass GENAU ein Raum Catch-All ist? Was passiert bei 0 oder 2? | Ohne diese Regel ist die ganze Architektur auf Sand gebaut. Rainer muss eine Gatekeeper-Funktion spezifizieren können. |
|
||||||
|
| **L3** | **Onboarding-Integration** — Ist das ein Gateway-Hook? Ein Agent-Tool? Ein Skill? Wann genau wird es getriggert? | Ohne Einhängepunkt kann Rainer nicht entscheiden, ob das Onboarding in der Gateway-Pipeline oder außerhalb läuft. |
|
||||||
|
|
||||||
|
### Empfehlung
|
||||||
|
|
||||||
|
Die Story ist **gut genug für Rainer**, wenn wir ihm die drei Lücken als
|
||||||
|
**explizite Entscheidungspunkte** mitgeben, nicht als offene Fragen:
|
||||||
|
|
||||||
|
1. **Raum-Map-Format:** JSON-Datei unter `~/.hermes/hermes-agent/data/room-map.json`. Struktur: `{ "rooms": { "<room_id>": { "theme": "...", "keywords": [...], "catch_all": false } } }`.
|
||||||
|
2. **Catch-All-Validierung:** Beim Gateway-Start prüft der Archivar, dass genau ein Raum `catch_all: true` hat. Bei 0 oder >1 → Gateway-Start wird abgelehnt mit klarer Fehlermeldung.
|
||||||
|
3. **Onboarding-Integration:** Wird als **Gateway-Hook** implementiert. Wenn der Gateway einen neuen Raum subscribed und dieser nicht in der Map ist, triggert ein Hook das Interview via DM an den Admin.
|
||||||
|
|
||||||
|
### Was der Code tut
|
||||||
|
|
||||||
|
Der Archivar ist als **3-Kategorien-Klassifikator** implementiert:
|
||||||
|
|
||||||
|
```
|
||||||
|
Nachricht → Keyword-Filter → Embedding (nomic-embed-text) → (LLM) → FAKT|FRAGE|ALARM
|
||||||
|
```
|
||||||
|
|
||||||
|
| Komponente | Datei | Funktion |
|
||||||
|
|------------|-------|----------|
|
||||||
|
| Keyword-Vorfilter | `classifier.py` | ALARM/FRAGE-Keywords → sofortige Entscheidung |
|
||||||
|
| Embedding-Klassifikation | `classifier.py` | `nomic-embed-text` → Kosinus-Ähnlichkeit gegen 3 Kategorietexte |
|
||||||
|
| LLM-Klassifikation | `classifier.py` | `qwen2.5:7b` für Grenzfälle (aktuell defekt — Prompt zu schwach) |
|
||||||
|
| Raum-Routing | `router.py` → `config.py` | 2 hartcodierte Projekte (`plugin`, `lan`) als Env-Vars |
|
||||||
|
| Doc-Store | `doc_store.py` | FAKT-Nachrichten → Filesystem |
|
||||||
|
|
||||||
|
### Gap 1: Keine thematische Raum-Map
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Jeder Raum hat ein **Thema** + Stichwortliste | 2 hartcodierte Projekt-Keys: `plugin`, `lan` |
|
||||||
|
| Map ist **Single Source of Truth** | Map existiert nicht — Env-Vars ersetzen die Map |
|
||||||
|
| Map wächst mit neuen Räumen (Onboarding) | Kein Onboarding — neue Räume bleiben blind |
|
||||||
|
|
||||||
|
### Gap 2: Keine Catch-All als Raum-Attribut
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Catch-All ist ein **Attribut eines Raums** | Catch-All ist eine eigene Env-Var: `ARCHIVAR_CATCHALL_ROOM` |
|
||||||
|
| Genau ein Raum trägt dieses Attribut | Kann auf jeden Raum zeigen — keine Validierung auf „genau einer" |
|
||||||
|
| Der Admin sieht gesammelte unklassifizierte Nachrichten | Landet aktuell im Protonbridge-Plugin-Raum (historisch) |
|
||||||
|
|
||||||
|
### Gap 3: Kein Multi-Agent-Raum-Ausschluss
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Multi-Agent-Raum **NIE** in der Map | Kein Code, der einen Raum ausschließt |
|
||||||
|
| Archivar ignoriert diesen Raum vollständig | Wenn jemand eine FRAGE im Multi-Agent-Raum postet, routet der Archivar sie → Endlosschleife |
|
||||||
|
|
||||||
|
### Gap 4: Kategorien statt Themen
|
||||||
|
|
||||||
|
| Konzept | Implementierung |
|
||||||
|
|---------|-----------------|
|
||||||
|
| Frage: „In welchen **Raum**?" | Frage: „Welche **Kategorie**?" |
|
||||||
|
| Routing-Ziel: **Themenraum** | Routing-Ziel: 3 Kategorien → 3 Räume |
|
||||||
|
| FRAGE mit Plugin-Kontext → #Plugin-Dev | FRAGE → #BAT-Team (default), außer Keywords schlagen an |
|
||||||
|
|
||||||
|
### Gap 5: LLM als Raumfinder, nicht als Kategorie-Klassifikator
|
||||||
|
|
||||||
|
Der aktuelle LLM-Prompt fragt: „Welche Kategorie: FAKT, FRAGE oder ALARM?" — das ist die falsche Frage.
|
||||||
|
Die richtige Frage wäre: **„In welchen thematischen Raum gehört diese Nachricht?"**
|
||||||
|
|
||||||
|
Mit einer Raum-Map als Kontext könnte das LLM bedeutend präziser arbeiten:
|
||||||
|
|
||||||
|
```
|
||||||
|
Prompt (Konzept):
|
||||||
|
„Diese Räume sind verfügbar:
|
||||||
|
- #Frontend (Thema: UI, Design, CSS)
|
||||||
|
- #Backend (Thema: API, Datenbank, Auth)
|
||||||
|
- #Infrastruktur (Thema: Docker, Server, Backup)
|
||||||
|
- DM Admin (Catch-All für alles andere)
|
||||||
|
|
||||||
|
In welchen Raum gehört diese Nachricht?
|
||||||
|
Antworte nur mit dem Raum-Namen."
|
||||||
|
|
||||||
|
Prompt (aktuell):
|
||||||
|
„Klassifiziere in FAKT, FRAGE oder ALARM."
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Unterschied ist fundamental: Das LLM kann Kontext **verstehen**, nicht nur Stichworte **matchen**. Es erkennt, dass „Das Docker-Image für das Plugin ist kaputt" trotz des Worts „docker" in den Plugin-Raum gehört, weil der **Kontext** Plugin-Entwicklung ist — das Wort „docker" ist nur das Transportmittel.
|
||||||
|
|
||||||
|
## Stichwort-Frage: Reichen Keywords?
|
||||||
|
|
||||||
|
**Nein, reichen nicht.** Zwei Beispiele:
|
||||||
|
|
||||||
|
| Nachricht | Keywords matchen | Korrektes Routing |
|
||||||
|
|-----------|-----------------|-------------------|
|
||||||
|
| „Das Docker-Image für das Plugin ist kaputt" | `docker` → #Infrastruktur | **#Plugin-Dev** (Kontext: Plugin) |
|
||||||
|
| „Die API vom Trading-Modul hat Timeout" | `api` → #Backend | **#Trading** (Kontext: BAT) |
|
||||||
|
|
||||||
|
Stichworte sind **eindeutig bei klaren Themen** („css layout kaputt" → #Frontend), aber **mehrdeutig bei Querschnittsthemen** (docker, api, gateway — die kommen in mehreren Projekten vor).
|
||||||
|
|
||||||
|
**Das LLM KANN hier helfen** — nicht als Ersatz für die Stichwortliste, sondern als **Kontext-Interpretationsschicht darüber**. Der Ablauf wäre:
|
||||||
|
|
||||||
|
1. **Stichwort-Match** (schnell, billig) — bei eindeutigen Treffern direkt routen
|
||||||
|
2. **Mehrdeutig oder kein Treffer** → LLM fragt mit Raum-Map-Kontext: „In welchen Raum?"
|
||||||
|
3. **LLM antwortet mit Raum-Namen** → Archivar routet
|
||||||
|
|
||||||
|
Das LLM **ersetzt nicht die Map** — es **konsultiert sie**. Die Map bleibt die Single Source of Truth. Das LLM ist nur der bessere Leser.
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
# Archivar User-Flow Fix "C" — Architektur-Skizze
|
||||||
|
|
||||||
|
> **Status:** Entwurf → wartet auf Lead-Review (Bernd)
|
||||||
|
> **Datum:** 08. Juni 2026
|
||||||
|
> **Projekt:** Rocket.Chat Plugin
|
||||||
|
> **Typ:** Architektur-Änderung (adapter.py, kein Eingriff in Classifier/Router)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Problembeschreibung
|
||||||
|
|
||||||
|
Der Archivar routet die **Antwort des Agenten**, nicht die Nachricht des Users. Wenn eine DM-Nachricht Keywords eines Projektraums enthält, setzt `_CURRENT_ORIGIN_ROOM` den Zielraum — die Agent-Antwort verlässt den DM und erscheint im Projektraum. Der User erhält nur eine Kurznotiz "Ich antworte im Zielraum" und muss dem Agenten hinterherjagen.
|
||||||
|
|
||||||
|
**Symptome (08.06.2026):**
|
||||||
|
- Andreas schreibt "startObsidian + projekt sync" im DM → Antwort landet im #BAT-Team
|
||||||
|
- Andreas fragt im DM nach dem RC-Plugin → Antwort landet im #Rocketchat-Plugin
|
||||||
|
- ":: Archivar Sperre" funktioniert nur einmalig, nicht Session-übergreifend
|
||||||
|
- Kein Flow für "Hier bleiben" — der User ist der Flüchtende, nicht der Entscheider
|
||||||
|
|
||||||
|
**Root Cause:** `adapter.py` Zeile 635: `_CURRENT_ORIGIN_ROOM.set(decision.target_room)` leitet die **Antwort** um. Der Archivar müsste die **Nachricht kopieren** — nicht die Antwort umleiten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Lösungsansatz
|
||||||
|
|
||||||
|
### Prinzip
|
||||||
|
|
||||||
|
Die Antwort des Agenten bleibt **IMMER** im Ursprungsraum. Der Archivar entscheidet nur, ob die Nachricht zusätzlich in einen Zielraum kopiert wird.
|
||||||
|
|
||||||
|
### Zwei Nachrichtentypen
|
||||||
|
|
||||||
|
| Typ | Erkennung | Archivar-Verhalten |
|
||||||
|
|---|---|---|
|
||||||
|
| **Thematische Frage** | Keine Imperative/Direktansprache | **Silent Copy**: Nachricht in Zielraum kopieren. Hinweis im Ursprungsraum. Keine Buttons. |
|
||||||
|
| **Auftrag** | Enthält Imperative: "bitte", "erstelle", "mach", etc. | **Buttons**: [Ja, rüberkopieren] [Hier bleiben] [Generell hier bleiben] |
|
||||||
|
|
||||||
|
### DM-Sonderregel
|
||||||
|
|
||||||
|
DM-Aufträge werden **NIE** geroutet. Der User hat bewusst den privaten Kanal gewählt. Nur thematische Fragen aus DMs können als Silent Copy in Projekt-Räume gespiegelt werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Datenfluss-Diagramm
|
||||||
|
|
||||||
|
```
|
||||||
|
User sendet Nachricht
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌───────────────────┐
|
||||||
|
│ adapter.py │
|
||||||
|
│ _process_incoming │
|
||||||
|
└───────┬───────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
room_type == "d" ?
|
||||||
|
│
|
||||||
|
┌────┴────┐
|
||||||
|
│ JA │ NEIN
|
||||||
|
▼ ▼
|
||||||
|
┌──────────┐ ┌──────────────┐
|
||||||
|
│ _is_auftrag? │ │ Archivar.route()│
|
||||||
|
└─┬────┬───┘ └──────┬───────┘
|
||||||
|
│JA │NEIN │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌────┐┌──────────┐┌──────────────┐
|
||||||
|
│BLEIB││Archivar ││target != │
|
||||||
|
│(DM) ││.route() ││origin? │
|
||||||
|
└────┘└────┬─────┘└──┬──────┬───┘
|
||||||
|
│ │JA │NEIN
|
||||||
|
▼ ▼ ▼
|
||||||
|
target != origin? ┌───────────┐ ┌────┐
|
||||||
|
┌──┬──┐ │_is_auftrag?│ │BLEIB│
|
||||||
|
│JA│NEIN └──┬────┬───┘ └────┘
|
||||||
|
▼ ▼ │JA │NEIN
|
||||||
|
┌─────┐┌────┐ ▼ ▼
|
||||||
|
│Silent││BLEIB│ ┌──────────┐┌──────────┐
|
||||||
|
│Copy │└────┘ │Buttons: ││Silent │
|
||||||
|
│+Hinweis│ │[Ja][Hier] ││Copy │
|
||||||
|
└─────────┘ │[Generell] ││+Hinweis │
|
||||||
|
└──────────┘└──────────┘
|
||||||
|
|
||||||
|
LEGENDE:
|
||||||
|
BLEIB = _CURRENT_ORIGIN_ROOM bleibt auf room_id (Antwort hier)
|
||||||
|
Silent Copy = Nachricht per REST in Zielraum kopieren
|
||||||
|
Buttons = rocketchat_send mit 3 Buttons
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Code-Änderungen
|
||||||
|
|
||||||
|
Alle Änderungen in **einer Datei**: `plugin/adapter.py`
|
||||||
|
|
||||||
|
### 4.1 Neue Heuristik: `_is_auftrag()` (vor `_process_incoming` einfügen)
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ── Auftrag-Erkennung (für User-Flow C) ────────────────────────────
|
||||||
|
_AUFTRAG_KEYWORDS: list = [
|
||||||
|
"bitte", "erstell", "mach", "änder", "konfigurier",
|
||||||
|
"schreib", "bau", "implementier", "test", "deploy",
|
||||||
|
"start", "stopp", "analysier", "prüf", "untersuch",
|
||||||
|
"beheb", "fix", "korrigier", "optimier", "erweiter",
|
||||||
|
"füg hinzu", "entfern", "lösch", "verschieb",
|
||||||
|
"generier", "kompilier", "installier",
|
||||||
|
]
|
||||||
|
|
||||||
|
def _is_auftrag(text: str) -> bool:
|
||||||
|
"""Heuristik: Enthält die Nachricht Imperative oder direkte Ansprache?"""
|
||||||
|
t = text.lower()
|
||||||
|
for kw in _AUFTRAG_KEYWORDS:
|
||||||
|
if kw in t:
|
||||||
|
return True
|
||||||
|
# Direkte Anrede
|
||||||
|
if any(t.startswith(p) for p in ("bernd", "rainer", "miguel", "finn", "don")):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 `_process_incoming()` — Neue Routing-Logik (Zeilen ~606-654 ersetzen)
|
||||||
|
|
||||||
|
**ALT (Zeilen 606-654):**
|
||||||
|
```python
|
||||||
|
# ── Archivar-Klassifikation ──
|
||||||
|
category = ""
|
||||||
|
decision = None
|
||||||
|
try:
|
||||||
|
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||||||
|
...
|
||||||
|
else:
|
||||||
|
decision = await self.archivar.handle_and_forward(text, ...)
|
||||||
|
|
||||||
|
# Forward-Antwort-Umleitung
|
||||||
|
if (decision and hasattr(decision, 'target_room') and decision.target_room
|
||||||
|
and decision.target_room != room_id
|
||||||
|
and not getattr(decision, 'is_unrouteable', False)):
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(decision.target_room)
|
||||||
|
try:
|
||||||
|
note_text = f"Ich antworte im {getattr(decision, 'matched_room_name', None) or 'Zielraum'}."
|
||||||
|
self.rest.post_message(room_id, note_text)
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
**NEU:**
|
||||||
|
```python
|
||||||
|
# ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
|
||||||
|
category = ""
|
||||||
|
decision = None
|
||||||
|
is_auftrag = _is_auftrag(text)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||||||
|
if not is_button_response:
|
||||||
|
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
||||||
|
self._rooms_with_pending_questions.discard(room_id)
|
||||||
|
elif room_id in getattr(self, '_sticky_rooms', {}):
|
||||||
|
# Session-Marker "Generell hier bleiben" — Archivar komplett überspringen
|
||||||
|
logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8])
|
||||||
|
elif room_type == "d" and is_auftrag:
|
||||||
|
# DM-Aufträge NIE routen — User hat bewusst privaten Kanal gewählt
|
||||||
|
logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username)
|
||||||
|
else:
|
||||||
|
# Nur classify_and_route (KEIN handle_and_forward — wir kopieren manuell)
|
||||||
|
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||||||
|
if decision and decision.category:
|
||||||
|
category = decision.category
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||||||
|
|
||||||
|
# ── User-Flow C: Nachricht kopieren, Antwort im Ursprungsraum behalten ──
|
||||||
|
# _CURRENT_ORIGIN_ROOM wird NIE auf den Zielraum gesetzt.
|
||||||
|
# Die Agent-Antwort bleibt IMMER im Ursprungsraum.
|
||||||
|
if (decision and hasattr(decision, 'target_room') and decision.target_room
|
||||||
|
and decision.target_room != room_id
|
||||||
|
and not getattr(decision, 'is_unrouteable', False)):
|
||||||
|
|
||||||
|
target_name = getattr(decision, 'matched_room_name', None) or 'Zielraum'
|
||||||
|
|
||||||
|
if is_auftrag:
|
||||||
|
# Typ 2: Buttons anzeigen
|
||||||
|
note = (
|
||||||
|
f"Dein Auftrag passt thematisch besser in **{target_name}**.\n"
|
||||||
|
f"Soll ich den Auftrag dorthin kopieren und dort abarbeiten?"
|
||||||
|
)
|
||||||
|
# Button-Payload für spätere Verarbeitung
|
||||||
|
self._pending_move_requests[msg_id] = {
|
||||||
|
"text": text,
|
||||||
|
"origin_room": room_id,
|
||||||
|
"target_room": decision.target_room,
|
||||||
|
"target_name": target_name,
|
||||||
|
}
|
||||||
|
await self._send_buttons(room_id, note, msg_id,
|
||||||
|
buttons=["→ Ja, rüberkopieren", "Hier bleiben", "Generell hier bleiben"])
|
||||||
|
else:
|
||||||
|
# Typ 1: Silent Copy
|
||||||
|
self.rest.post_message(decision.target_room,
|
||||||
|
f"*(Thema passt zu {target_name} — von @{username})*\n{text}")
|
||||||
|
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
|
||||||
|
self.rest.post_message(room_id, note)
|
||||||
|
|
||||||
|
# Wenn kein Forwarding: _CURRENT_ORIGIN_ROOM bleibt auf room_id
|
||||||
|
if not (decision and hasattr(decision, 'target_room') and decision.target_room
|
||||||
|
and decision.target_room != room_id
|
||||||
|
and not getattr(decision, 'is_unrouteable', False)):
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Neue `_send_buttons()` Methode
|
||||||
|
|
||||||
|
```python
|
||||||
|
async def _send_buttons(self, room_id: str, text: str, question_id: str,
|
||||||
|
buttons: list) -> None:
|
||||||
|
"""Sendet eine Nachricht mit Buttons im Zielraum."""
|
||||||
|
# Button-Template an den Gateway delegieren — wir nutzen rocketchat_send
|
||||||
|
# des Agenten. Da wir im Adapter sind, bauen wir die Buttons direkt.
|
||||||
|
from gateway.platforms.base import MessageEvent, MessageType
|
||||||
|
# ... (Implementierung siehe bestehende Button-Logik in adapter.py send())
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 Button-Handling in `_process_incoming()`
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Button-Antwort auf move-request erkennen
|
||||||
|
if msg_id in getattr(self, '_pending_move_requests', {}):
|
||||||
|
move_req = self._pending_move_requests.pop(msg_id)
|
||||||
|
choice = text.strip()
|
||||||
|
|
||||||
|
if "rüberkopieren" in choice.lower() or choice == "→ Ja, rüberkopieren":
|
||||||
|
# Auftrag in Zielraum kopieren + _CURRENT_ORIGIN_ROOM setzen
|
||||||
|
self.rest.post_message(move_req["target_room"],
|
||||||
|
f"*(Auftrag von @{username}, hierher kopiert)*\n{move_req['text']}")
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
|
||||||
|
self.rest.post_message(room_id, f"✅ Auftrag nach **{move_req['target_name']}** kopiert — ich arbeite ihn dort ab.")
|
||||||
|
|
||||||
|
elif "hier bleiben" in choice.lower() or choice == "Hier bleiben":
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||||
|
self.rest.post_message(room_id, "👍 Bleiben hier — ich kümmer mich drum.")
|
||||||
|
|
||||||
|
elif "generell" in choice.lower() or choice == "Generell hier bleiben":
|
||||||
|
if not hasattr(self, '_sticky_rooms'):
|
||||||
|
self._sticky_rooms = {}
|
||||||
|
self._sticky_rooms[room_id] = time.time()
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||||
|
self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.5 `__init__` erweitern (neue Dicts)
|
||||||
|
|
||||||
|
In `RocketChatAdapter.__init__()` nach Zeile 422 (`self.archivar = ...`) einfügen:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# User-Flow C: Move-Requests + Sticky Rooms
|
||||||
|
self._pending_move_requests: Dict[str, dict] = {}
|
||||||
|
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Testfälle
|
||||||
|
|
||||||
|
| # | Eingabe | Raum | Erwartetes Verhalten |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | "Wie ist der Stand des RC-Plugins?" | DM | Silent Copy nach #Rocketchat-Plugin. Antwort im DM mit Hinweis. |
|
||||||
|
| 2 | "Bitte erstelle einen Exchange-Adapter" | #BAT-Team | Buttons im #BAT-Team. Bei "Ja" → Kopie in Zielraum + Antwort dort. |
|
||||||
|
| 3 | "Bitte konfiguriere den Gateway" | DM | **Kein Routing.** DM-Auftrag bleibt im DM. Keine Buttons, keine Kopie. |
|
||||||
|
| 4 | "Was ist die IP von Susi?" | #Rocketchat-Plugin | Silent Copy in passenden Raum (Catch-All wenn unsicher). Antwort hier. |
|
||||||
|
| 5 | Button "Generell hier bleiben" | #BAT-Team | _sticky_rooms gesetzt. Nächste Nachricht in #BAT-Team → Archivar übersprungen. |
|
||||||
|
| 6 | "docker compose ps" | DM | FAKT → doc_store (kein Routing, keine Antwort-Weiterleitung). |
|
||||||
|
| 7 | Gateway-Neustart | — | _sticky_rooms zurückgesetzt. "Generell hier bleiben" überlebt Neustart nicht. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Deployment-Plan
|
||||||
|
|
||||||
|
1. **Miguel** implementiert die Änderungen in `plugin/adapter.py`
|
||||||
|
2. **Rainer** reviewt den Code gegen diese Skizze (Quality Gate §3.2)
|
||||||
|
3. **Don** testet auf `.101`: Gateway-Start, Test-Nachrichten in DM + Projekt-Räumen, Button-Flow
|
||||||
|
4. **Don** deployt via `install.sh` auf `.101` (und Susi-VPS falls nötig)
|
||||||
|
5. **Bernd** (Lead) gibt finale Freigabe
|
||||||
+11
-11
@@ -1,22 +1,22 @@
|
|||||||
# Room Topic Map — rocket.chat.thomander.de
|
# Room Topic Map — Beispielkonfiguration
|
||||||
|
|
||||||
**Stand:** 31. Mai 2026 (wiederhergestellt nach Server-Rollback)
|
**Stand:** 03. Juni 2026 (anonymisiert für generische Verwendung)
|
||||||
**Catch-All:** DM andreas/Bernd (`69f4e777f06dba03be82dce7`)
|
**Catch-All:** DM Admin (`<ADMIN_DM_ROOM_ID>`)
|
||||||
|
|
||||||
## Gemappte Räume
|
## Gemappte Räume (Beispiele)
|
||||||
|
|
||||||
| Raum | Typ | Thema |
|
| Raum | Typ | Thema |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `#BAT-Team` | channel | BAT-Trading-Plattform (Docker-Stack, Commits, Agent-Health, Entwicklerteam) |
|
| `#Support-Team` | channel | Erst-Level-Support (Tickets, Bug-Reports, User-Feedback) |
|
||||||
| `Rocketchat-Plugin` | group | Hermes Rocket.Chat Plugin (Gateway, Upload, Buttons, Adapter) |
|
| `RC-Plugin-Dev` | group | Rocket.Chat Plugin-Entwicklung (Gateway, Upload, Buttons, Adapter) |
|
||||||
| `Protonbridge-Plugin` | group | ProtonMail-Bridge-Plugin (Mail, Bridge, SMTP) |
|
| `Mail-Bridge-Plugin` | group | E-Mail-Bridge-Plugin (Mail, Bridge, SMTP) |
|
||||||
| `DM andreas/Bernd` | dm | Allgemein, Meta, Strategie — **Catch-All** |
|
| `DM Admin` | dm | Allgemein, Meta, Strategie — **Catch-All** |
|
||||||
| `DM mit Bernd, Thomas` | dm | 🔇 Inaktiv — nur bei expliziter Aufforderung |
|
| `DM Team-Kollege` | dm | 🔇 Inaktiv — nur bei expliziter Aufforderung |
|
||||||
| `DM mit Bernd, Susi` | dm | Bot-zu-Bot-Kommunikation & Training — NUR auf explizite Aufforderung des Auftraggebers. Niemals ungefragt nutzen. |
|
| `DM Bot-Agent` | dm | Bot-zu-Bot-Kommunikation & Training — NUR auf explizite Aufforderung des Admins. Niemals ungefragt nutzen. |
|
||||||
|
|
||||||
## Virtuelle Keys (keine echten Räume — IMMER herausfiltern)
|
## Virtuelle Keys (keine echten Räume — IMMER herausfiltern)
|
||||||
|
|
||||||
- `user:bernd` — Option-C-Session-Key, kein Raum. Darf NICHT Catch-All werden.
|
- `user:admin` — Session-Sharing-Key, kein Raum. Darf NICHT Catch-All werden.
|
||||||
|
|
||||||
## Override-Regel
|
## Override-Regel
|
||||||
|
|
||||||
|
|||||||
Regular → Executable
+395
-38
@@ -11,6 +11,8 @@ ARG_LANG=""
|
|||||||
NONINTERACTIVE=false
|
NONINTERACTIVE=false
|
||||||
CHECK_ONLY=false
|
CHECK_ONLY=false
|
||||||
UPDATE_MODE=false
|
UPDATE_MODE=false
|
||||||
|
UPDATE_ONLY=false
|
||||||
|
UPDATE_AVAILABLE=false
|
||||||
|
|
||||||
# ─── Language packs ─────────────────────────────────────────
|
# ─── Language packs ─────────────────────────────────────────
|
||||||
declare -A T
|
declare -A T
|
||||||
@@ -42,11 +44,21 @@ load_lang() {
|
|||||||
[copying]="📁 Copying plugin files…"
|
[copying]="📁 Copying plugin files…"
|
||||||
[env_written]="🔑 Credentials written to %s"
|
[env_written]="🔑 Credentials written to %s"
|
||||||
[config_updated]="⚙️ config.yaml updated"
|
[config_updated]="⚙️ config.yaml updated"
|
||||||
|
[config_provisioned]="📄 Provisioned minimal config.yaml"
|
||||||
|
[env_provisioned]="🔧 Provisioned .env template"
|
||||||
|
[env_dropin]="🔌 Systemd EnvironmentFile drop-in installed"
|
||||||
|
[copied]="📁 Copied %d plugin files"
|
||||||
|
[ollama_check]="🔍 Checking Ollama..."
|
||||||
|
[ollama_missing]="⚠️ Ollama not found. Install: curl -fsSL https://ollama.com/install.sh | sh"
|
||||||
|
[nomic_pull]="📥 Pulling nomic-embed-text (274 MB)..."
|
||||||
|
[nomic_ok]="✅ nomic-embed-text ready"
|
||||||
|
[nomic_fail]="⚠️ nomic-embed-text pull failed — Archivar will use fallback mode"
|
||||||
|
[ollama_ok]="✅ Ollama ready"
|
||||||
[service_installed]="⚡ Gateway service installed"
|
[service_installed]="⚡ Gateway service installed"
|
||||||
[restarting]="🔄 Restarting gateway…"
|
[restarting]="🔄 Restarting gateway…"
|
||||||
[done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel."
|
[done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel."
|
||||||
[dry_info]="ℹ️ Use --help for all options."
|
[dry_info]="ℹ️ Use --help for all options."
|
||||||
[help_text]="USAGE: ./install.sh [OPTIONS]\n\nOPTIONS:\n --help Show this help\n --lang en|de Language (default: auto-detect from \$LANG)\n --non-interactive Batch mode — reads from env vars:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Check for updates only\n --update Check for updates and install if available"
|
[help_text]="USAGE: ./install.sh [OPTIONS]\n\nOPTIONS:\n --help Show this help\n --lang en|de Language (default: auto-detect from \$LANG)\n --non-interactive Batch mode — reads from env vars:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Check for updates only\n --update Check for updates and install if available\n --update-only Emergency deploy: Only deploy plugin files +\n restart gateway. No questions, no config provisioning,\n no Ollama. Uses find_hermes_dir() for path discovery."
|
||||||
[env_required]="❌ --non-interactive requires RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
[env_required]="❌ --non-interactive requires RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||||
[param_error]="❌ Unknown option: %s"
|
[param_error]="❌ Unknown option: %s"
|
||||||
[check_update]="🔍 Checking for updates…"
|
[check_update]="🔍 Checking for updates…"
|
||||||
@@ -58,6 +70,16 @@ load_lang() {
|
|||||||
[rollback]="⏪ Restoring backup: %s"
|
[rollback]="⏪ Restoring backup: %s"
|
||||||
[rollback_success]="✅ Backup successfully restored"
|
[rollback_success]="✅ Backup successfully restored"
|
||||||
[update_failed]="❌ Update failed. Error: %s"
|
[update_failed]="❌ Update failed. Error: %s"
|
||||||
|
[update_only_banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes RC Plugin — Emergency Deploy\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
[deploying]="📦 Deploying plugin files (update-only, no questions)..."
|
||||||
|
[deploy_done]="✅ %d files deployed to %s"
|
||||||
|
[room_map_backup]="💾 Backed up existing room-map.json to %s"
|
||||||
|
[room_map_deployed]="📊 Deployed room-map.json to %s"
|
||||||
|
[cache_cleared]="🧹 Cleared __pycache__"
|
||||||
|
[verifying]="🔍 Verifying gateway..."
|
||||||
|
[verify_ok]="✅ Gateway running with Rocket.Chat connected"
|
||||||
|
[verify_fail]="⚠️ Gateway started but Rocket.Chat not detected in logs (check journalctl)"
|
||||||
|
[verify_timeout]="⏳ Waiting for Rocket.Chat handshake..."
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
# German (default)
|
# German (default)
|
||||||
@@ -78,11 +100,21 @@ load_lang() {
|
|||||||
[copying]="📁 Kopiere Plugin-Dateien…"
|
[copying]="📁 Kopiere Plugin-Dateien…"
|
||||||
[env_written]="🔑 Zugangsdaten gespeichert in %s"
|
[env_written]="🔑 Zugangsdaten gespeichert in %s"
|
||||||
[config_updated]="⚙️ config.yaml aktualisiert"
|
[config_updated]="⚙️ config.yaml aktualisiert"
|
||||||
|
[config_provisioned]="📄 Minimale config.yaml bereitgestellt"
|
||||||
|
[env_provisioned]="🔧 .env-Vorlage bereitgestellt"
|
||||||
|
[env_dropin]="🔌 Systemd EnvironmentFile-Drop-in installiert"
|
||||||
|
[copied]="📁 %d Plugin-Dateien kopiert"
|
||||||
|
[ollama_check]="🔍 Prüfe Ollama..."
|
||||||
|
[ollama_missing]="⚠️ Ollama nicht gefunden. Installation: curl -fsSL https://ollama.com/install.sh | sh"
|
||||||
|
[nomic_pull]="📥 Lade nomic-embed-text herunter (274 MB)..."
|
||||||
|
[nomic_ok]="✅ nomic-embed-text bereit"
|
||||||
|
[nomic_fail]="⚠️ nomic-embed-text Download fehlgeschlagen — Archivar nutzt Fallback-Modus"
|
||||||
|
[ollama_ok]="✅ Ollama bereit"
|
||||||
[service_installed]="⚡ Gateway-Service installiert"
|
[service_installed]="⚡ Gateway-Service installiert"
|
||||||
[restarting]="🔄 Starte Gateway neu…"
|
[restarting]="🔄 Starte Gateway neu…"
|
||||||
[done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben."
|
[done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben."
|
||||||
[dry_info]="ℹ️ Mit --help alle Optionen anzeigen."
|
[dry_info]="ℹ️ Mit --help alle Optionen anzeigen."
|
||||||
[help_text]="AUFRUF: ./install.sh [OPTIONEN]\n\nOPTIONEN:\n --help Diese Hilfe anzeigen\n --lang en|de Sprache (Standard: auto-Erkennung über \$LANG)\n --non-interactive Stapelverarbeitung — liest aus Umgebungsvariablen:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Nur auf Updates prüfen\n --update Auf Updates prüfen und bei Bedarf installieren"
|
[help_text]="AUFRUF: ./install.sh [OPTIONEN]\n\nOPTIONEN:\n --help Diese Hilfe anzeigen\n --lang en|de Sprache (Standard: auto-Erkennung über \$LANG)\n --non-interactive Stapelverarbeitung — liest aus Umgebungsvariablen:\n RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL\n --check Nur auf Updates prüfen\n --update Auf Updates prüfen und bei Bedarf installieren\n --update-only Notfall-Deployment: Nur Plugin-Dateien deployen +\n Gateway-Neustart. Keine Fragen, kein Config-Provisioning,\n kein Ollama. Nutzt find_hermes_dir() für Pfad-Ermittlung."
|
||||||
[env_required]="❌ --non-interactive benötigt RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
[env_required]="❌ --non-interactive benötigt RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL"
|
||||||
[param_error]="❌ Unbekannte Option: %s"
|
[param_error]="❌ Unbekannte Option: %s"
|
||||||
[check_update]="🔍 Prüfe auf Updates…"
|
[check_update]="🔍 Prüfe auf Updates…"
|
||||||
@@ -94,6 +126,16 @@ load_lang() {
|
|||||||
[rollback]="⏪ Stelle Backup wieder her: %s"
|
[rollback]="⏪ Stelle Backup wieder her: %s"
|
||||||
[rollback_success]="✅ Backup erfolgreich wiederhergestellt"
|
[rollback_success]="✅ Backup erfolgreich wiederhergestellt"
|
||||||
[update_failed]="❌ Update fehlgeschlagen. Fehler: %s"
|
[update_failed]="❌ Update fehlgeschlagen. Fehler: %s"
|
||||||
|
[update_only_banner]="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n Hermes RC Plugin — Notfall-Deployment\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
[deploying]="📦 Deploye Plugin-Dateien (update-only, ohne Rückfragen)..."
|
||||||
|
[deploy_done]="✅ %d Dateien deployed nach %s"
|
||||||
|
[room_map_backup]="💾 Vorhandene room-map.json gesichert nach %s"
|
||||||
|
[room_map_deployed]="📊 room-map.json deployed nach %s"
|
||||||
|
[cache_cleared]="🧹 __pycache__ gelöscht"
|
||||||
|
[verifying]="🔍 Verifiziere Gateway..."
|
||||||
|
[verify_ok]="✅ Gateway läuft mit Rocket.Chat verbunden"
|
||||||
|
[verify_fail]="⚠️ Gateway gestartet, aber Rocket.Chat nicht im Log erkannt (prüfe journalctl)"
|
||||||
|
[verify_timeout]="⏳ Warte auf Rocket.Chat-Handshake..."
|
||||||
)
|
)
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
@@ -140,19 +182,108 @@ check_for_updates() {
|
|||||||
# If we can't determine versions, exit with error
|
# If we can't determine versions, exit with error
|
||||||
if [ "$local_version" = "unknown" ] || [ "$remote_version" = "unknown" ]; then
|
if [ "$local_version" = "unknown" ] || [ "$remote_version" = "unknown" ]; then
|
||||||
echo "Could not determine version information"
|
echo "Could not determine version information"
|
||||||
return 1
|
UPDATE_AVAILABLE=false
|
||||||
|
return 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Compare versions
|
# Compare versions
|
||||||
if [ "$local_version" != "$remote_version" ]; then
|
if [ "$local_version" != "$remote_version" ]; then
|
||||||
msg update_available "$remote_version" "$local_version"
|
msg update_available "$remote_version" "$local_version"
|
||||||
return 1 # Update available
|
UPDATE_AVAILABLE=true
|
||||||
|
return 0 # Update available
|
||||||
else
|
else
|
||||||
msg no_update "$local_version"
|
msg no_update "$local_version"
|
||||||
|
UPDATE_AVAILABLE=false
|
||||||
return 0 # No update needed
|
return 0 # No update needed
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
find_hermes_dir() {
|
||||||
|
# Priorität 1: --dir Flag (bereits in ARG_DIR gesetzt)
|
||||||
|
if [ -n "${ARG_DIR:-}" ]; then
|
||||||
|
if [ -d "$ARG_DIR" ]; then
|
||||||
|
echo "$ARG_DIR"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 2: Laufenden Gateway via systemd finden
|
||||||
|
if [ -z "${HERMES_DIR:-}" ] && systemctl --user is-active hermes-gateway >/dev/null 2>&1; then
|
||||||
|
set +e
|
||||||
|
EXEC_PATH=$(systemctl --user show hermes-gateway -p ExecStart --value |
|
||||||
|
sed -n 's/.*path=\([^;]*\).*/\1/p' |
|
||||||
|
sed 's|/venv/bin/python.*||' |
|
||||||
|
sed 's|/.venv/bin/python.*||')
|
||||||
|
set -e
|
||||||
|
if [ -n "$EXEC_PATH" ] && [ -d "$EXEC_PATH" ]; then
|
||||||
|
echo "$EXEC_PATH"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 3: Laufenden Prozess via /proc scannen
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
set +e
|
||||||
|
PID=$(pgrep -f "hermes_cli.main gateway run" | head -1)
|
||||||
|
set -e
|
||||||
|
if [ -n "$PID" ] && [ -d "/proc/$PID/cwd" ]; then
|
||||||
|
HERMES_DIR=$(readlink -f "/proc/$PID/cwd")
|
||||||
|
if [ -n "$HERMES_DIR" ] && [ -d "$HERMES_DIR" ]; then
|
||||||
|
echo "$HERMES_DIR"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 4: command -v hermes → Symlink auflösen → Installationsverzeichnis ableiten
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
set +e
|
||||||
|
HERMES_CMD=$(command -v hermes 2>/dev/null)
|
||||||
|
set -e
|
||||||
|
if [ -n "$HERMES_CMD" ]; then
|
||||||
|
# Symlink auflösen
|
||||||
|
if [ -L "$HERMES_CMD" ]; then
|
||||||
|
HERMES_CMD=$(readlink -f "$HERMES_CMD")
|
||||||
|
fi
|
||||||
|
# Installationsverzeichnis ableiten (gehe 2 Ebenen nach oben: bin/hermes → .)
|
||||||
|
HERMES_DIR=$(dirname "$(dirname "$HERMES_CMD")")
|
||||||
|
if [ -n "$HERMES_DIR" ] && [ -d "$HERMES_DIR" ]; then
|
||||||
|
echo "$HERMES_DIR"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 5: python3 -c "from hermes_constants import get_hermes_home; print(get_hermes_home())"
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
set +e
|
||||||
|
HERMES_HOME=$(python3 -c "from hermes_constants import get_hermes_home; print(get_hermes_home())" 2>/dev/null)
|
||||||
|
set -e
|
||||||
|
if [ -n "$HERMES_HOME" ]; then
|
||||||
|
if [ -d "$HERMES_HOME/hermes-agent" ]; then
|
||||||
|
echo "$HERMES_HOME/hermes-agent"
|
||||||
|
return 0
|
||||||
|
elif [ -d "$HERMES_HOME" ]; then
|
||||||
|
echo "$HERMES_HOME"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Priorität 6 (Fallback): Die alte Pfad-Heuristik BEHALTEN, aber um FHS erweitern
|
||||||
|
if [ -z "${HERMES_DIR:-}" ]; then
|
||||||
|
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent" "/usr/local/lib/hermes-agent"; do
|
||||||
|
if [ -d "$d" ]; then
|
||||||
|
echo "$d"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Kein Hermes-Verzeichnis gefunden
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
create_backup() {
|
create_backup() {
|
||||||
local backup_file="$1"
|
local backup_file="$1"
|
||||||
local plugin_dir="$2"
|
local plugin_dir="$2"
|
||||||
@@ -175,12 +306,23 @@ perform_update() {
|
|||||||
# Change to repo directory
|
# Change to repo directory
|
||||||
cd "$script_dir"
|
cd "$script_dir"
|
||||||
|
|
||||||
# Get remote version
|
# Check if we have local changes and stash if needed
|
||||||
|
local stashed=false
|
||||||
|
if ! git diff --quiet; then
|
||||||
|
git stash push -m "Auto-stash before update"
|
||||||
|
stashed=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Get remote version (for display only)
|
||||||
local remote_version
|
local remote_version
|
||||||
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
|
remote_version=$(git ls-remote --tags origin | grep -E 'refs/tags/v[0-9]+(\.[0-9]+)*$' | sed 's|.*refs/tags/||' | sort -V | tail -n1 || echo "unknown")
|
||||||
|
|
||||||
if [ "$remote_version" = "unknown" ]; then
|
if [ "$remote_version" = "unknown" ]; then
|
||||||
msg update_failed "Could not determine remote version"
|
msg update_failed "Could not determine remote version"
|
||||||
|
# Restore stash if we had changes
|
||||||
|
if $stashed; then
|
||||||
|
git stash pop 2>/dev/null || true
|
||||||
|
fi
|
||||||
return 1
|
return 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -189,10 +331,7 @@ perform_update() {
|
|||||||
# Create backup before updating
|
# Create backup before updating
|
||||||
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
||||||
local hermes_dir
|
local hermes_dir
|
||||||
hermes_dir=""
|
hermes_dir=$(find_hermes_dir 2>/dev/null || echo "")
|
||||||
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
|
|
||||||
if [ -d "$d" ]; then hermes_dir="$d"; break; fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ -n "$hermes_dir" ]; then
|
if [ -n "$hermes_dir" ]; then
|
||||||
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
@@ -204,12 +343,49 @@ perform_update() {
|
|||||||
# Perform the update
|
# Perform the update
|
||||||
local update_error=""
|
local update_error=""
|
||||||
{
|
{
|
||||||
# Pull latest changes
|
# Pull latest changes (instead of checkout)
|
||||||
git fetch --tags origin 2>&1 || { update_error="Failed to fetch from remote"; return 1; }
|
git pull origin main 2>&1 || { update_error="Failed to pull from origin main"; return 1; }
|
||||||
git checkout "$remote_version" 2>&1 || { update_error="Failed to checkout version $remote_version"; return 1; }
|
|
||||||
|
|
||||||
# Run the installer to update files
|
# Copy plugin files directly (lines 448-466)
|
||||||
HERMES_DIR="$hermes_dir" UPDATE_MODE=true ./install.sh --non-interactive 2>&1
|
PLUGIN_DST="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
|
# Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen
|
||||||
|
if [ -d "$script_dir/plugin" ]; then
|
||||||
|
# Lösche vorherige Dateien NICHT — das könnte andere Submodule zerstören
|
||||||
|
# Kopiere ALLE Dateien aus plugin/ rekursiv (behält Struktur)
|
||||||
|
while read -r src; do
|
||||||
|
rel="${src#$script_dir/plugin/}"
|
||||||
|
dst="$PLUGIN_DST/$rel"
|
||||||
|
mkdir -p "$(dirname "$dst")"
|
||||||
|
cp "$src" "$dst"
|
||||||
|
done < <(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
||||||
|
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
|
msg copied "$copied_count"
|
||||||
|
|
||||||
|
# NOTE: room-map.json is MACHINE-SPECIFIC — never deployed
|
||||||
|
# by the installer. It is created by the RC-Skill onboarding
|
||||||
|
# flow after gateway start. See RC-Skill: "Room Topic Discipline"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Execute backend checks directly (Ollama check from lines 429-446)
|
||||||
|
msg ollama_check
|
||||||
|
if command -v ollama >/dev/null 2>&1; then
|
||||||
|
msg ollama_ok
|
||||||
|
# nomic-embed-text laden falls nicht vorhanden
|
||||||
|
if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then
|
||||||
|
msg nomic_pull
|
||||||
|
if ollama pull nomic-embed-text 2>/dev/null; then
|
||||||
|
msg nomic_ok
|
||||||
|
else
|
||||||
|
msg nomic_fail
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg nomic_ok
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg ollama_missing
|
||||||
|
fi
|
||||||
} || {
|
} || {
|
||||||
# Update failed, rollback
|
# Update failed, rollback
|
||||||
if [ -n "$update_error" ]; then
|
if [ -n "$update_error" ]; then
|
||||||
@@ -227,6 +403,11 @@ perform_update() {
|
|||||||
rm -f "$backup_file"
|
rm -f "$backup_file"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Restore stash if we had changes
|
||||||
|
if $stashed; then
|
||||||
|
git stash pop 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +416,11 @@ perform_update() {
|
|||||||
|
|
||||||
msg update_success "$remote_version"
|
msg update_success "$remote_version"
|
||||||
|
|
||||||
|
# Restore stash if we had changes
|
||||||
|
if $stashed; then
|
||||||
|
git stash pop 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
# Restart gateway
|
# Restart gateway
|
||||||
if [ -n "$hermes_dir" ]; then
|
if [ -n "$hermes_dir" ]; then
|
||||||
cd "$hermes_dir"
|
cd "$hermes_dir"
|
||||||
@@ -245,6 +431,86 @@ perform_update() {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ─── Emergency Deploy (update-only) ─────────────────────────
|
||||||
|
perform_update_only() {
|
||||||
|
local script_dir
|
||||||
|
script_dir="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
|
||||||
|
echo -e "\n${T[update_only_banner]}\n"
|
||||||
|
|
||||||
|
# 1. Find hermes directory
|
||||||
|
local hermes_dir
|
||||||
|
hermes_dir=$(find_hermes_dir 2>/dev/null || echo "")
|
||||||
|
if [ -z "$hermes_dir" ]; then
|
||||||
|
msg no_hermes; exit 1
|
||||||
|
fi
|
||||||
|
msg found_hermes "$hermes_dir"
|
||||||
|
|
||||||
|
# 2. Backup current state
|
||||||
|
local backup_file="/tmp/hermes-rocketchat-backup-$(date +%s).tar.gz"
|
||||||
|
local plugin_dir="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
|
if [ -d "$plugin_dir" ]; then
|
||||||
|
create_backup "$backup_file" "$plugin_dir" \
|
||||||
|
"$HOME/.hermes/config.yaml" \
|
||||||
|
"$HOME/.config/hermes/rocketchat.env"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3. Deploy all plugin files
|
||||||
|
msg deploying
|
||||||
|
local PLUGIN_DST="$hermes_dir/plugins/platforms/rocketchat"
|
||||||
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
|
if [ -d "$script_dir/plugin" ]; then
|
||||||
|
while read -r src; do
|
||||||
|
rel="${src#$script_dir/plugin/}"
|
||||||
|
dst="$PLUGIN_DST/$rel"
|
||||||
|
mkdir -p "$(dirname "$dst")"
|
||||||
|
cp "$src" "$dst"
|
||||||
|
done < <(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
||||||
|
local copied_count
|
||||||
|
copied_count=$(find "$script_dir/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
|
msg deploy_done "$copied_count" "$PLUGIN_DST"
|
||||||
|
else
|
||||||
|
msg update_failed "plugin/ directory not found in $script_dir"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# NOTE: room-map.json is MACHINE-SPECIFIC — never deployed
|
||||||
|
# by --update-only. It is created by the RC-Skill onboarding
|
||||||
|
# flow after gateway start. See RC-Skill: "Room Topic Discipline"
|
||||||
|
|
||||||
|
# 4. Clear stale __pycache__
|
||||||
|
find "$PLUGIN_DST" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
|
||||||
|
msg cache_cleared
|
||||||
|
|
||||||
|
# 5. Restart gateway
|
||||||
|
msg restarting
|
||||||
|
systemctl --user daemon-reload 2>/dev/null || true
|
||||||
|
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||||
|
|
||||||
|
# 6. Verify Rocket.Chat connected (wait up to 15s)
|
||||||
|
msg verifying
|
||||||
|
local verified=false
|
||||||
|
for i in $(seq 1 6); do
|
||||||
|
sleep 2.5
|
||||||
|
if journalctl --user -u hermes-gateway --since "15 seconds ago" --no-pager 2>/dev/null \
|
||||||
|
| grep -q "Subscribed to.*rocketchat\|Connecting to rocketchat"; then
|
||||||
|
verified=true
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
msg verify_timeout
|
||||||
|
done
|
||||||
|
|
||||||
|
if $verified; then
|
||||||
|
msg verify_ok
|
||||||
|
rm -f "$backup_file"
|
||||||
|
else
|
||||||
|
msg verify_fail
|
||||||
|
fi
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
# ─── Argument parsing ────────────────────────────────────
|
# ─── Argument parsing ────────────────────────────────────
|
||||||
while [ $# -gt 0 ]; do
|
while [ $# -gt 0 ]; do
|
||||||
case "$1" in
|
case "$1" in
|
||||||
@@ -261,6 +527,8 @@ while [ $# -gt 0 ]; do
|
|||||||
CHECK_ONLY=true; shift ;;
|
CHECK_ONLY=true; shift ;;
|
||||||
--update)
|
--update)
|
||||||
UPDATE_MODE=true; shift ;;
|
UPDATE_MODE=true; shift ;;
|
||||||
|
--update-only)
|
||||||
|
UPDATE_ONLY=true; shift ;;
|
||||||
*)
|
*)
|
||||||
load_lang "${ARG_LANG:-${LANG##*.}}"
|
load_lang "${ARG_LANG:-${LANG##*.}}"
|
||||||
msg param_error "$1"; echo; exit 1 ;;
|
msg param_error "$1"; echo; exit 1 ;;
|
||||||
@@ -275,23 +543,26 @@ echo -e "\n${T[banner]}\n"
|
|||||||
# ─── Update Check/Perform ──────────────────────────────────────
|
# ─── Update Check/Perform ──────────────────────────────────────
|
||||||
if $CHECK_ONLY; then
|
if $CHECK_ONLY; then
|
||||||
check_for_updates
|
check_for_updates
|
||||||
exit $?
|
if $UPDATE_AVAILABLE; then
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
elif $UPDATE_MODE; then
|
elif $UPDATE_MODE; then
|
||||||
check_for_updates
|
check_for_updates
|
||||||
if [ $? -eq 1 ]; then
|
if $UPDATE_AVAILABLE; then
|
||||||
perform_update
|
perform_update
|
||||||
exit $?
|
exit $?
|
||||||
else
|
else
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
elif $UPDATE_ONLY; then
|
||||||
|
perform_update_only
|
||||||
|
exit $?
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ─── Find Hermes Agent ────────────────────────────────────
|
|
||||||
msg checking
|
msg checking
|
||||||
HERMES_DIR=""
|
HERMES_DIR=$(find_hermes_dir)
|
||||||
for d in "$HOME/hermes-agent" "$HOME/.hermes/hermes-agent"; do
|
|
||||||
if [ -d "$d" ]; then HERMES_DIR="$d"; break; fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ -z "$HERMES_DIR" ]; then
|
if [ -z "$HERMES_DIR" ]; then
|
||||||
msg no_hermes; exit 1
|
msg no_hermes; exit 1
|
||||||
@@ -301,7 +572,7 @@ msg found_hermes "$HERMES_DIR"
|
|||||||
# ─── Detect existing installation ─────────────────────────
|
# ─── Detect existing installation ─────────────────────────
|
||||||
ENV_FILE="$HOME/.config/hermes/rocketchat.env"
|
ENV_FILE="$HOME/.config/hermes/rocketchat.env"
|
||||||
HAVE_EXISTING=false
|
HAVE_EXISTING=false
|
||||||
RC_URL="" RC_BOT_USER="" RC_BOT_PASS="" RC_HOME_CHANNEL=""
|
RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}" RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-}"
|
||||||
|
|
||||||
if [ -f "$ENV_FILE" ]; then
|
if [ -f "$ENV_FILE" ]; then
|
||||||
HAVE_EXISTING=true
|
HAVE_EXISTING=true
|
||||||
@@ -314,8 +585,11 @@ fi
|
|||||||
|
|
||||||
# ─── Non-interactive mode ─────────────────────────────────
|
# ─── Non-interactive mode ─────────────────────────────────
|
||||||
if $NONINTERACTIVE; then
|
if $NONINTERACTIVE; then
|
||||||
RC_URL="${RC_URL:-}" RC_BOT_USER="${RC_BOT_USER:-}"
|
# Read from environment variables (NOT local — respect what install.sh caller exports)
|
||||||
RC_BOT_PASS="${RC_BOT_PASS:-}" RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-}"
|
RC_URL="${RC_URL:-${ROCKETCHAT_BASE_URL:-}}"
|
||||||
|
RC_BOT_USER="${RC_BOT_USER:-${ROCKETCHAT_USER:-}}"
|
||||||
|
RC_BOT_PASS="${RC_BOT_PASS:-${ROCKETCHAT_PASSWORD:-}}"
|
||||||
|
RC_HOME_CHANNEL="${RC_HOME_CHANNEL:-${ROCKETCHAT_ROOM_NAME:-}}"
|
||||||
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
|
if [ -z "$RC_URL" ] || [ -z "$RC_BOT_USER" ] || [ -z "$RC_BOT_PASS" ] || [ -z "$RC_HOME_CHANNEL" ]; then
|
||||||
msg env_required; exit 1
|
msg env_required; exit 1
|
||||||
fi
|
fi
|
||||||
@@ -343,33 +617,105 @@ fi
|
|||||||
msg copying
|
msg copying
|
||||||
mkdir -p "$(dirname "$ENV_FILE")"
|
mkdir -p "$(dirname "$ENV_FILE")"
|
||||||
|
|
||||||
cat > "$ENV_FILE" <<EOF
|
# Bug #12: single-quoted delimiter verhindert $-Expansion im Passwort
|
||||||
|
cat > "$ENV_FILE" <<'EOF'
|
||||||
# Hermes Rocket.Chat Plugin — credentials (generated by install.sh)
|
# Hermes Rocket.Chat Plugin — credentials (generated by install.sh)
|
||||||
export ROCKETCHAT_BASE_URL="${RC_URL}"
|
# systemd-compatible: KEY=VALUE (no export prefix!)
|
||||||
export ROCKETCHAT_USER="${RC_BOT_USER}"
|
ROCKETCHAT_BASE_URL=PLACEHOLDER_RC_URL
|
||||||
export ROCKETCHAT_PASSWORD='${RC_BOT_PASS}'
|
ROCKETCHAT_USER=PLACEHOLDER_RC_USER
|
||||||
export ROCKETCHAT_ROOM_NAME="${RC_HOME_CHANNEL}"
|
ROCKETCHAT_PASSWORD=PLACEHOLDER_RC_PASS
|
||||||
export ROCKETCHAT_ALLOW_ALL_USERS=true
|
ROCKETCHAT_ROOM_NAME=PLACEHOLDER_RC_CHANNEL
|
||||||
export GATEWAY_ALLOW_ALL_USERS=true
|
ROCKETCHAT_ALLOW_ALL_USERS=true
|
||||||
export ROCKETCHAT_PING_SEC=8
|
GATEWAY_ALLOW_ALL_USERS=true
|
||||||
export ROCKETCHAT_IDLE_SEC=900
|
ROCKETCHAT_PING_SEC=8
|
||||||
|
ROCKETCHAT_IDLE_SEC=900
|
||||||
EOF
|
EOF
|
||||||
|
# Ersetze Platzhalter mit python3 (sicher für $-Zeichen im Passwort)
|
||||||
|
export RC_URL RC_BOT_USER RC_BOT_PASS RC_HOME_CHANNEL
|
||||||
|
export ENV_FILE
|
||||||
|
python3 -c "
|
||||||
|
import os
|
||||||
|
env_file = os.environ['ENV_FILE']
|
||||||
|
with open(env_file) as f:
|
||||||
|
content = f.read()
|
||||||
|
content = content.replace('PLACEHOLDER_RC_URL', os.environ.get('RC_URL', ''))
|
||||||
|
content = content.replace('PLACEHOLDER_RC_USER', os.environ.get('RC_BOT_USER', ''))
|
||||||
|
content = content.replace('PLACEHOLDER_RC_PASS', os.environ.get('RC_BOT_PASS', ''))
|
||||||
|
content = content.replace('PLACEHOLDER_RC_CHANNEL', os.environ.get('RC_HOME_CHANNEL', ''))
|
||||||
|
with open(env_file, 'w') as f:
|
||||||
|
f.write(content)
|
||||||
|
"
|
||||||
chmod 600 "$ENV_FILE"
|
chmod 600 "$ENV_FILE"
|
||||||
msg env_written "$ENV_FILE"
|
msg env_written "$ENV_FILE"
|
||||||
|
|
||||||
|
# ─── Ollama Check ─────────────────────────────────────────
|
||||||
|
msg ollama_check
|
||||||
|
if command -v ollama >/dev/null 2>&1; then
|
||||||
|
msg ollama_ok
|
||||||
|
# nomic-embed-text laden falls nicht vorhanden
|
||||||
|
if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then
|
||||||
|
msg nomic_pull
|
||||||
|
if ollama pull nomic-embed-text 2>/dev/null; then
|
||||||
|
msg nomic_ok
|
||||||
|
else
|
||||||
|
msg nomic_fail
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg nomic_ok
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
msg ollama_missing
|
||||||
|
fi
|
||||||
|
|
||||||
# ─── Copy plugin files ────────────────────────────────────
|
# ─── Copy plugin files ────────────────────────────────────
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
|
PLUGIN_DST="$HERMES_DIR/plugins/platforms/rocketchat"
|
||||||
mkdir -p "$PLUGIN_DST"
|
mkdir -p "$PLUGIN_DST"
|
||||||
|
|
||||||
for f in plugin.yaml __init__.py adapter.py tools.py; do
|
# Rekursiv kopieren (inkl. Submodule wie archivar/), __pycache__ ausschließen
|
||||||
if [ -f "$SCRIPT_DIR/plugin/$f" ]; then
|
if [ -d "$SCRIPT_DIR/plugin" ]; then
|
||||||
cp "$SCRIPT_DIR/plugin/$f" "$PLUGIN_DST/$f"
|
# Lösche vorherige Dateien NICHT — das könnte andere Submodule zerstören
|
||||||
|
# Kopiere ALLE Dateien aus plugin/ rekursiv (behält Struktur)
|
||||||
|
while read -r src; do
|
||||||
|
rel="${src#$SCRIPT_DIR/plugin/}"
|
||||||
|
dst="$PLUGIN_DST/$rel"
|
||||||
|
mkdir -p "$(dirname "$dst")"
|
||||||
|
cp "$src" "$dst"
|
||||||
|
done < <(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
||||||
|
copied_count=$(find "$SCRIPT_DIR/plugin" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' | wc -l)
|
||||||
|
msg copied "$copied_count"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ─── Fix #9: Provision minimal config.yaml + .env ──────────
|
||||||
|
# Only when hermes has NO config yet (fresh install, no setup run)
|
||||||
|
HERMES_HOME="$HOME/.hermes"
|
||||||
|
CONFIG="$HERMES_HOME/config.yaml"
|
||||||
|
ENVFILE="$HERMES_HOME/.env"
|
||||||
|
|
||||||
|
if [ ! -f "$CONFIG" ]; then
|
||||||
|
mkdir -p "$HERMES_HOME"
|
||||||
|
if [ -f "$SCRIPT_DIR/templates/config.yaml" ]; then
|
||||||
|
cp "$SCRIPT_DIR/templates/config.yaml" "$CONFIG"
|
||||||
|
# Placeholders mit echten Werten ersetzen
|
||||||
|
sed -i "s|PLACEHOLDER_RC_URL|${RC_URL}|g" "$CONFIG"
|
||||||
|
sed -i "s|PLACEHOLDER_RC_HOME_NAME|${RC_HOME_CHANNEL}|g" "$CONFIG"
|
||||||
|
# chat_id aus room_name auflösen (Rest-API oder User-ID-Mapping)
|
||||||
|
# Fallback: den room_name direkt als chat_id verwenden
|
||||||
|
sed -i "s|PLACEHOLDER_RC_HOME_CHAT_ID|${RC_HOME_CHANNEL}|g" "$CONFIG"
|
||||||
|
msg config_provisioned
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ ! -f "$ENVFILE" ] && [ -f "$SCRIPT_DIR/templates/.env" ]; then
|
||||||
|
cp "$SCRIPT_DIR/templates/.env" "$ENVFILE"
|
||||||
|
chmod 600 "$ENVFILE"
|
||||||
|
# OLLAMA_API_KEY ersetzen falls gesetzt
|
||||||
|
if [ -n "${OLLAMA_API_KEY:-}" ]; then
|
||||||
|
sed -i "s|PLACEHOLDER_OLLAMA_API_KEY|${OLLAMA_API_KEY}|g" "$ENVFILE"
|
||||||
|
fi
|
||||||
|
msg env_provisioned
|
||||||
fi
|
fi
|
||||||
done
|
|
||||||
|
|
||||||
# ─── Patch config.yaml ────────────────────────────────────
|
# ─── Patch config.yaml ────────────────────────────────────
|
||||||
CONFIG="$HOME/.hermes/config.yaml"
|
|
||||||
if [ -f "$CONFIG" ]; then
|
if [ -f "$CONFIG" ]; then
|
||||||
# Ensure rocketchat-platform is in plugins.enabled
|
# Ensure rocketchat-platform is in plugins.enabled
|
||||||
if ! grep -q 'rocketchat-platform' "$CONFIG" 2>/dev/null; then
|
if ! grep -q 'rocketchat-platform' "$CONFIG" 2>/dev/null; then
|
||||||
@@ -399,6 +745,17 @@ fi
|
|||||||
# Install / refresh systemd user service
|
# Install / refresh systemd user service
|
||||||
$PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
|
$PYTHON -m hermes_cli.main gateway install 2>/dev/null || true
|
||||||
|
|
||||||
|
# ─── Fix #10: systemd EnvironmentFile drop-in ─────────────
|
||||||
|
# Gateway needs rocketchat.env + .env — hermes gateway install
|
||||||
|
# does not wire them automatically.
|
||||||
|
DROPDIN_DIR="$HOME/.config/systemd/user/hermes-gateway.service.d"
|
||||||
|
DROPDIN_FILE="$DROPDIN_DIR/env.conf"
|
||||||
|
mkdir -p "$DROPDIN_DIR"
|
||||||
|
if [ -f "$SCRIPT_DIR/templates/hermes-gateway-env.conf" ]; then
|
||||||
|
cp "$SCRIPT_DIR/templates/hermes-gateway-env.conf" "$DROPDIN_FILE"
|
||||||
|
msg env_dropin
|
||||||
|
fi
|
||||||
|
|
||||||
# Ensure lingering is enabled (may need sudo — best-effort)
|
# Ensure lingering is enabled (may need sudo — best-effort)
|
||||||
loginctl enable-linger 2>/dev/null || true
|
loginctl enable-linger 2>/dev/null || true
|
||||||
|
|
||||||
|
|||||||
+527
-22
@@ -23,6 +23,8 @@ import time
|
|||||||
import urllib.request
|
import urllib.request
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
from .archivar.adapter_integration import ArchivarMessageHandler
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
logger.setLevel(logging.INFO)
|
logger.setLevel(logging.INFO)
|
||||||
# Ensure adapter logs are visible in gateway.log by adding a stderr handler
|
# Ensure adapter logs are visible in gateway.log by adding a stderr handler
|
||||||
@@ -33,11 +35,11 @@ if not logger.handlers:
|
|||||||
logger.addHandler(_handler)
|
logger.addHandler(_handler)
|
||||||
logger.propagate = False # Don't double-log to root
|
logger.propagate = False # Don't double-log to root
|
||||||
|
|
||||||
# ── Option C: Virtual Room Translation ─────────────────────────────────────
|
# ── Virtual Room Translation ──────────────────────────────────────────
|
||||||
# ContextVar tracks the real Rocket.Chat room_id that triggered the current
|
# ContextVar tracks the real Rocket.Chat room_id that triggered the current
|
||||||
# agent turn, so send() can route the response back to the correct room even
|
# agent turn, so send() can route the response back to the correct room even
|
||||||
# though the Hermes session uses a synthetic user-based chat_id.
|
# though the Hermes session uses a synthetic user-based chat_id.
|
||||||
# This is the single mechanism that makes "ein Bernd für alle Räume" work
|
# This is the mechanism that makes "one agent for all rooms" work
|
||||||
# without touching Hermes Core.
|
# without touching Hermes Core.
|
||||||
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||||||
"_rocketchat_origin_room", default=""
|
"_rocketchat_origin_room", default=""
|
||||||
@@ -131,6 +133,30 @@ class RocketChatREST:
|
|||||||
}, data=payload)
|
}, data=payload)
|
||||||
return bool(r and r.get("success"))
|
return bool(r and r.get("success"))
|
||||||
|
|
||||||
|
def download_file(self, file_id: str, filename: str) -> Optional[str]:
|
||||||
|
"""Download a file from Rocket.Chat using the authenticated REST client.
|
||||||
|
|
||||||
|
Returns the file content as a string (text files) or None on failure.
|
||||||
|
Uses the existing authToken — no security scanner triggers.
|
||||||
|
"""
|
||||||
|
if not self.auth_token:
|
||||||
|
return None
|
||||||
|
url = f"{self.base_url}/file-upload/{file_id}/{filename}"
|
||||||
|
req = urllib.request.Request(url, headers={
|
||||||
|
"X-Auth-Token": self.auth_token,
|
||||||
|
"X-User-Id": self.user_id,
|
||||||
|
})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||||
|
content = resp.read()
|
||||||
|
try:
|
||||||
|
return content.decode("utf-8")
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
return content.decode("latin-1")
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("File download failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
class DDPClient:
|
class DDPClient:
|
||||||
PING_INTERVAL = 8.0
|
PING_INTERVAL = 8.0
|
||||||
@@ -354,6 +380,28 @@ class DDPClient:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ── Auftrag-Erkennung (User-Flow C) ────────────────────────────────────
|
||||||
|
_AUFTRAG_KEYWORDS: list = [
|
||||||
|
"bitte", "erstell", "mach", "änder", "konfigurier",
|
||||||
|
"schreib", "bau", "implementier", "test", "deploy",
|
||||||
|
"start", "stopp", "analysier", "prüf", "untersuch",
|
||||||
|
"beheb", "fix", "korrigier", "optimier", "erweiter",
|
||||||
|
"füg hinzu", "entfern", "lösch", "verschieb",
|
||||||
|
"generier", "kompilier", "installier",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _is_auftrag(text: str) -> bool:
|
||||||
|
"""Heuristik: Enthält die Nachricht Imperative oder direkte Ansprache?"""
|
||||||
|
t = text.lower()
|
||||||
|
for kw in _AUFTRAG_KEYWORDS:
|
||||||
|
if kw in t:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
class RocketChatAdapter(BasePlatformAdapter):
|
class RocketChatAdapter(BasePlatformAdapter):
|
||||||
HEALTH_CHECK_INTERVAL = 60.0 # seconds
|
HEALTH_CHECK_INTERVAL = 60.0 # seconds
|
||||||
HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect
|
HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect
|
||||||
@@ -377,15 +425,26 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# Clarify-Queue: tracks pending button questions per chat_id
|
# Clarify-Queue: tracks pending button questions per chat_id
|
||||||
# so incoming replies can be correlated with the original question.
|
# so incoming replies can be correlated with the original question.
|
||||||
self._pending_clarifies: Dict[str, dict] = {}
|
self._pending_clarifies: Dict[str, dict] = {}
|
||||||
# Option C: user-based room mapping for virtual chat_id translation.
|
# User-based room mapping for virtual chat_id translation.
|
||||||
# Key: "user:<username>", Value: list of real room_ids for that user.
|
# Key: "user:<username>", Value: list of real room_ids for that user.
|
||||||
# Built during connect() from REST get_rooms.
|
# Built during connect() from REST get_rooms.
|
||||||
self._user_rooms: Dict[str, List[str]] = {}
|
self._user_rooms: Dict[str, List[str]] = {}
|
||||||
|
# Rooms where the agent has posted a question with buttons.
|
||||||
|
# Used to keep the response in the same room — no Archivar routing,
|
||||||
|
# no catch-all forwarding. Removed after the next user message from
|
||||||
|
# that room (on the assumption that the response IS the button answer).
|
||||||
|
# No timers, no cleanup — just a simple set.
|
||||||
|
self._rooms_with_pending_questions: set = set()
|
||||||
# Health-check state
|
# Health-check state
|
||||||
self._last_server_activity = 0.0 # ts of last DDP ping/pong or message
|
self._last_server_activity = 0.0 # ts of last DDP ping/pong or message
|
||||||
self._health_check_timer: Optional[threading.Timer] = None
|
self._health_check_timer: Optional[threading.Timer] = None
|
||||||
self._last_ddp_ping_ok = False
|
self._last_ddp_ping_ok = False
|
||||||
self._running = False
|
self._running = False
|
||||||
|
# Archivar: Embedding-basierte Nachrichten-Klassifikation
|
||||||
|
self.archivar = ArchivarMessageHandler(send_callback=self._send_via_archivar)
|
||||||
|
# User-Flow C: Move-Requests + Sticky Rooms
|
||||||
|
self._pending_move_requests: Dict[str, dict] = {}
|
||||||
|
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
|
||||||
|
|
||||||
async def connect(self) -> bool:
|
async def connect(self) -> bool:
|
||||||
if not self.base_url or not self.user or not self.password:
|
if not self.base_url or not self.user or not self.password:
|
||||||
@@ -413,31 +472,63 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]}
|
self._room_info[room["id"]] = {"name": room["name"], "type": room["type"]}
|
||||||
logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], room["id"])
|
logger.info("[rocketchat] Subscribed to %s (%s)", room["name"], room["id"])
|
||||||
logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms))
|
logger.info("[rocketchat] Total subscribed rooms: %d", len(self._subscribed_rooms))
|
||||||
# Option C: Build user→rooms map for virtual chat_id translation.
|
# Build user→rooms map for virtual chat_id translation.
|
||||||
# Each Rocket.Chat user gets a synthetic "user:<username>" chat_id that
|
# Each Rocket.Chat user gets a synthetic "user:<username>" chat_id that
|
||||||
# maps to all rooms they participate in. This ensures Hermes creates ONE
|
# maps to all rooms they participate in. This ensures Hermes creates ONE
|
||||||
# session per user across all rooms, enabling shared context.
|
# session per user across all rooms, enabling shared context.
|
||||||
self._user_rooms.clear()
|
self._user_rooms.clear()
|
||||||
|
user_room_count = 0
|
||||||
for room in self._rooms:
|
for room in self._rooms:
|
||||||
rid = room["id"]
|
rid = room["id"]
|
||||||
t = room["type"]
|
t = room["type"]
|
||||||
if t == "d":
|
if t == "d":
|
||||||
|
# Handle Direct Message rooms
|
||||||
usernames = [u.lower() for u in room.get("usernames", [])]
|
usernames = [u.lower() for u in room.get("usernames", [])]
|
||||||
|
if not usernames:
|
||||||
|
logger.warning("[rocketchat] DM room %s has no usernames field or is empty", rid)
|
||||||
|
# Try to extract usernames from room name as fallback
|
||||||
|
name = room.get("name", "")
|
||||||
|
if "DM mit " in name:
|
||||||
|
# Parse usernames from name like "DM mit andreas, bernd"
|
||||||
|
try:
|
||||||
|
user_part = name.split("DM mit ", 1)[1]
|
||||||
|
usernames = [u.strip().lower() for u in user_part.split(",")]
|
||||||
|
except Exception:
|
||||||
|
logger.debug("[rocketchat] Could not parse usernames from room name: %s", name)
|
||||||
|
|
||||||
for uname in usernames:
|
for uname in usernames:
|
||||||
if uname != (self.user or "").lower():
|
if uname and uname != (self.user or "").lower():
|
||||||
virt = f"user:{uname}"
|
virt = f"user:{uname}"
|
||||||
if virt not in self._user_rooms:
|
if virt not in self._user_rooms:
|
||||||
self._user_rooms[virt] = []
|
self._user_rooms[virt] = []
|
||||||
if rid not in self._user_rooms[virt]:
|
if rid not in self._user_rooms[virt]:
|
||||||
self._user_rooms[virt].append(rid)
|
self._user_rooms[virt].append(rid)
|
||||||
|
user_room_count += 1
|
||||||
else:
|
else:
|
||||||
# For groups/channels: query members via REST to build mappings.
|
# For channels/groups, track rooms for potential future use
|
||||||
# Fallback: use a generic group-based virtual chat_id.
|
# Users can still be mentioned in these rooms
|
||||||
# We still track the room so proaktive sends have a target.
|
logger.debug("[rocketchat] Non-DM room %s (type: %s) tracked but not mapped to users", rid, t)
|
||||||
pass # Group mapping handled on-demand in send()
|
|
||||||
logger.info("[rocketchat] Built user-room map: %d users, %s",
|
logger.info("[rocketchat] Built user-room map: %d users, %s",
|
||||||
len(self._user_rooms),
|
len(self._user_rooms),
|
||||||
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
{k: f"{len(v)} rooms" for k, v in self._user_rooms.items()})
|
||||||
|
# Archivar initialisieren (Embedding-basierte Klassifikation)
|
||||||
|
try:
|
||||||
|
await self.archivar.initialize()
|
||||||
|
# Feed the actual subscribed room IDs to the router so it can
|
||||||
|
# validate targets and store unrouteable messages in doc_store.
|
||||||
|
self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms))
|
||||||
|
logger.info("[rocketchat] Archivar initialisiert — Thematischer Raum-Router aktiv (room-map.json)")
|
||||||
|
|
||||||
|
# Auto-Onboarding: Prüfe, ob alle subscribed Räume in der Map sind
|
||||||
|
subscribed_with_types = {
|
||||||
|
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||||||
|
for rid, info in self._room_info.items()
|
||||||
|
}
|
||||||
|
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||||||
|
if missing:
|
||||||
|
await self._start_onboarding(missing)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e)
|
||||||
self._mark_connected()
|
self._mark_connected()
|
||||||
self._running = True
|
self._running = True
|
||||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||||
@@ -464,16 +555,21 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if not isinstance(msg_obj, dict):
|
if not isinstance(msg_obj, dict):
|
||||||
return
|
return
|
||||||
|
|
||||||
# Check if this is a button click response by looking for specific fields
|
# Check if this is a button click response by looking for specific fields.
|
||||||
|
# TWO detection paths:
|
||||||
|
# 1. Native Rocket.Chat button events (triggerId + actions + triggerSender + payload)
|
||||||
|
# 2. In-chat button responses via msg_in_chat_window, which arrive as regular
|
||||||
|
# text messages containing a question_id::choice payload (e.g. "bypass_001::Ja").
|
||||||
|
text = msg_obj.get("msg", "")
|
||||||
is_button_response = (
|
is_button_response = (
|
||||||
msg_obj.get("triggerId") and
|
(msg_obj.get("triggerId") and
|
||||||
msg_obj.get("actions") and
|
msg_obj.get("actions") and
|
||||||
msg_obj.get("params", {}).get("triggerSender") and
|
msg_obj.get("params", {}).get("triggerSender") and
|
||||||
msg_obj.get("params", {}).get("payload")
|
msg_obj.get("params", {}).get("payload"))
|
||||||
|
or "::" in text
|
||||||
)
|
)
|
||||||
|
|
||||||
msg_id = msg_obj.get("_id", "")
|
msg_id = msg_obj.get("_id", "")
|
||||||
text = msg_obj.get("msg", "")
|
|
||||||
room_id = msg_obj.get("rid", "")
|
room_id = msg_obj.get("rid", "")
|
||||||
user_info = msg_obj.get("u", {})
|
user_info = msg_obj.get("u", {})
|
||||||
username = (user_info.get("username", "") or "").lower() # normalize case
|
username = (user_info.get("username", "") or "").lower() # normalize case
|
||||||
@@ -532,15 +628,113 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
room_type = self._room_info.get(room_id, {}).get("type", "unknown")
|
room_type = self._room_info.get(room_id, {}).get("type", "unknown")
|
||||||
logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80])
|
logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80])
|
||||||
|
|
||||||
# ── Option C: Virtual Room Translation ─────────────────────────
|
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
|
||||||
|
if self.archivar._stats.get("onboarding_active", False):
|
||||||
|
stripped = text.strip()
|
||||||
|
is_onboarding = (
|
||||||
|
"=" in stripped # Name = Thema
|
||||||
|
or stripped.startswith("#") # #Name = Thema
|
||||||
|
or stripped.lower().startswith("raum:") # Raum: Name = Thema
|
||||||
|
or stripped.isdigit() # 3 (Catch-All-Wechsel)
|
||||||
|
or stripped.lower() in ("überspringen", "skip", "nein", "no", "behalten") # Ablehnung
|
||||||
|
)
|
||||||
|
if is_onboarding:
|
||||||
|
await self._process_onboarding_response(text, room_id)
|
||||||
|
return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig
|
||||||
|
|
||||||
|
# ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
|
||||||
|
# Klassifiziere die Nachricht und entscheide über Copy/Routing.
|
||||||
|
# Die Antwort des Agenten bleibt IMMER im Ursprungsraum.
|
||||||
|
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
||||||
|
category = ""
|
||||||
|
decision = None
|
||||||
|
is_auftrag = _is_auftrag(text)
|
||||||
|
|
||||||
|
try:
|
||||||
|
if is_button_response or room_id in self._rooms_with_pending_questions:
|
||||||
|
if not is_button_response:
|
||||||
|
logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id)
|
||||||
|
self._rooms_with_pending_questions.discard(room_id)
|
||||||
|
elif room_id in self._sticky_rooms:
|
||||||
|
logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8])
|
||||||
|
elif room_type == "d" and is_auftrag:
|
||||||
|
logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username)
|
||||||
|
else:
|
||||||
|
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id)
|
||||||
|
if decision and decision.category:
|
||||||
|
category = decision.category
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||||||
|
|
||||||
|
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
|
||||||
|
# _CURRENT_ORIGIN_ROOM wird NIE auf den Zielraum gesetzt.
|
||||||
|
# Die Agent-Antwort bleibt im Ursprungsraum. Nur die Nachricht
|
||||||
|
# wird kopiert — mit User-Entscheidung bei Aufträgen.
|
||||||
|
forwarded = False
|
||||||
|
if (decision and hasattr(decision, 'target_room') and decision.target_room
|
||||||
|
and decision.target_room != room_id
|
||||||
|
and not getattr(decision, 'is_unrouteable', False)):
|
||||||
|
|
||||||
|
target_name = getattr(decision, 'matched_room_name', None) or 'Zielraum'
|
||||||
|
|
||||||
|
if is_auftrag:
|
||||||
|
# Typ 2: Buttons — User entscheidet
|
||||||
|
note = (
|
||||||
|
f"Dein Auftrag passt thematisch besser in **{target_name}**.\n"
|
||||||
|
f"Soll ich den Auftrag dorthin kopieren und dort abarbeiten?"
|
||||||
|
)
|
||||||
|
self._pending_move_requests[msg_id] = {
|
||||||
|
"text": text,
|
||||||
|
"origin_room": room_id,
|
||||||
|
"target_room": decision.target_room,
|
||||||
|
"target_name": target_name,
|
||||||
|
"username": username,
|
||||||
|
}
|
||||||
|
self.rest.post_message(room_id, note)
|
||||||
|
# Kein Forwarding — auf Button-Antwort warten
|
||||||
|
forwarded = True
|
||||||
|
else:
|
||||||
|
# Typ 1: Silent Copy — Nachricht in Zielraum kopieren
|
||||||
|
self.rest.post_message(decision.target_room,
|
||||||
|
f"*(Thema passt zu {target_name} — von @{username})*\n{text}")
|
||||||
|
note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert."
|
||||||
|
self.rest.post_message(room_id, note)
|
||||||
|
|
||||||
|
# Button-Antwort auf move-request?
|
||||||
|
if msg_id in self._pending_move_requests:
|
||||||
|
move_req = self._pending_move_requests.pop(msg_id)
|
||||||
|
choice = text.strip().lower()
|
||||||
|
|
||||||
|
if "rüberkopieren" in choice:
|
||||||
|
# Auftrag in Zielraum kopieren + Antwort dorthin
|
||||||
|
self.rest.post_message(move_req["target_room"],
|
||||||
|
f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}")
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(move_req["target_room"])
|
||||||
|
forwarded = True
|
||||||
|
|
||||||
|
elif "generell" in choice:
|
||||||
|
self._sticky_rooms[room_id] = time.time()
|
||||||
|
self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)")
|
||||||
|
|
||||||
|
else:
|
||||||
|
# "Hier bleiben" — Default
|
||||||
|
self.rest.post_message(room_id, "👍 Bleiben hier.")
|
||||||
|
|
||||||
|
# Nach Button-Antwort: nicht als normale Nachricht verarbeiten
|
||||||
|
return
|
||||||
|
|
||||||
|
# ── _CURRENT_ORIGIN_ROOM setzen ──────────────────────────────────
|
||||||
|
if not forwarded:
|
||||||
|
_CURRENT_ORIGIN_ROOM.set(room_id)
|
||||||
|
|
||||||
|
# ── Virtual Room Translation ─────────────────────────────────
|
||||||
# Replace room-based chat_id with user-based virtual chat_id.
|
# Replace room-based chat_id with user-based virtual chat_id.
|
||||||
# This collapses all rooms per user into ONE Hermes session:
|
# This collapses all rooms per user into ONE Hermes session:
|
||||||
# DM with andreas: room_id=ABC123 → chat_id="user:andreas"
|
# DM with alice: room_id=ABC123 → chat_id="user:alice"
|
||||||
# #BAT-Team: room_id=XYZ789 → chat_id="user:andreas"
|
# #Project-Chat: room_id=XYZ789 → chat_id="user:alice"
|
||||||
# Both get the same session key: agent:main:rocketchat:dm:user:andreas
|
# Both get the same session key.
|
||||||
virtual_chat_id = f"user:{username}"
|
virtual_chat_id = f"user:{username}"
|
||||||
# Track the REAL room for send() to route the response back
|
# _CURRENT_ORIGIN_ROOM wurde bereits oben im User-Flow-C gesetzt
|
||||||
_CURRENT_ORIGIN_ROOM.set(room_id)
|
|
||||||
|
|
||||||
# Ensure this user→room mapping is recorded for proaktive sends
|
# Ensure this user→room mapping is recorded for proaktive sends
|
||||||
if virtual_chat_id not in self._user_rooms:
|
if virtual_chat_id not in self._user_rooms:
|
||||||
@@ -556,7 +750,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
source = SessionSource(
|
source = SessionSource(
|
||||||
platform=Platform("rocketchat"),
|
platform=Platform("rocketchat"),
|
||||||
chat_id=virtual_chat_id, # ← user-based instead of room-based
|
chat_id=virtual_chat_id, # ← user-based instead of room-based
|
||||||
chat_name=f"{room_name} (via @{username})", # real origin visible in system prompt
|
chat_name=f"{room_name} (via @{username})" + (f" [{category}]" if category else ""),
|
||||||
user_id=username,
|
user_id=username,
|
||||||
user_name=username,
|
user_name=username,
|
||||||
chat_type="dm", # ← force DM to bypass group isolation in Core
|
chat_type="dm", # ← force DM to bypass group isolation in Core
|
||||||
@@ -573,6 +767,261 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("[rocketchat] handle_message error: %s", e)
|
logger.error("[rocketchat] handle_message error: %s", e)
|
||||||
|
|
||||||
|
async def _send_via_archivar(self, room_id: str, text: str) -> bool:
|
||||||
|
"""Callback for Archivar forwarding — sends a message copy to a target room."""
|
||||||
|
if not self.rest.auth_token:
|
||||||
|
return False
|
||||||
|
return self.rest.post_message(room_id, text)
|
||||||
|
|
||||||
|
async def _start_onboarding(self, missing_rooms: list) -> None:
|
||||||
|
"""Sendet EINE DM an den Operator mit der Liste fehlender Räume.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
|
||||||
|
"""
|
||||||
|
# Finde den Operator-DM Raum
|
||||||
|
operator_room_id = None
|
||||||
|
for room_id, info in self._room_info.items():
|
||||||
|
if info.get("type") == "d" and "andreas" in info.get("name", "").lower():
|
||||||
|
operator_room_id = room_id
|
||||||
|
break
|
||||||
|
|
||||||
|
if not operator_room_id:
|
||||||
|
logger.warning("[rocketchat] Operator-DM-Raum nicht gefunden, kann Onboarding nicht starten")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Text erstellen — OHNE # (Rocket.Chat macht Links daraus, blockiert Editieren)
|
||||||
|
lines = ["Folgende Räume fehlen in der Raum-Map.",
|
||||||
|
"Wofür ist jeder Raum da? Antworte pro Raum mit: `Name = Thema`",
|
||||||
|
""]
|
||||||
|
for i, room in enumerate(missing_rooms, 1):
|
||||||
|
clean_name = room['name'].lstrip("#")
|
||||||
|
lines.append(f"{i}. {clean_name} = ")
|
||||||
|
lines.append("")
|
||||||
|
lines.append("Beispiel: `Projektraum = Entwicklung, Code-Reviews, Austausch und Status zum Projekt`")
|
||||||
|
text = "\n".join(lines)
|
||||||
|
|
||||||
|
# Nachricht senden
|
||||||
|
success = self.rest.post_message(operator_room_id, text)
|
||||||
|
if success:
|
||||||
|
# Setze onboarding_active auf True
|
||||||
|
self.archivar._stats["onboarding_active"] = True
|
||||||
|
logger.info("[rocketchat] Onboarding gestartet: %d Räume fehlen", len(missing_rooms))
|
||||||
|
else:
|
||||||
|
logger.error("[rocketchat] Fehler beim Senden der Onboarding-Nachricht")
|
||||||
|
|
||||||
|
async def _process_onboarding_response(self, text: str, room_id: str) -> None:
|
||||||
|
"""Verarbeitet Onboarding-Antworten vom Operator.
|
||||||
|
|
||||||
|
Akzeptiert zwei Formate pro Zeile:
|
||||||
|
1. „#Name = Thema" (empfohlen, intuitiv)
|
||||||
|
2. „Raum: #Name = Thema, Stichworte: kw1, kw2" (explizit)
|
||||||
|
Fehlende Stichworte werden automatisch aus Raumname + Thema abgeleitet.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Die Antwortnachricht des Operators
|
||||||
|
room_id: Die Raum-ID, in der die Nachricht empfangen wurde
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
|
||||||
|
# Pattern: # ist optional (Rocket.Chat macht sonst Links daraus)
|
||||||
|
# Akzeptiert: "Name = Thema", "#Name = Thema", "Raum: Name = Thema"
|
||||||
|
pattern = re.compile(
|
||||||
|
r"(?:Raum:\s*)?"
|
||||||
|
r"(?P<name>#?[^\s=]+)\s*=\s*"
|
||||||
|
r"(?P<theme>[^,]+?)"
|
||||||
|
r"(?:,\s*(?:Keywords|Stichworte|Schlagworte):\s*(?P<keywords>.*?))?$",
|
||||||
|
re.IGNORECASE,
|
||||||
|
)
|
||||||
|
|
||||||
|
lines = text.strip().splitlines()
|
||||||
|
|
||||||
|
# ── Catch-All-Wechsel-Prüfung ─────────────────────────────────
|
||||||
|
# Wenn die Nachricht eine einzelne Zahl oder ein Ablehnungswort ist,
|
||||||
|
# interpretiere sie als Antwort auf die Catch-All-Frage.
|
||||||
|
single_line = text.strip()
|
||||||
|
if single_line.isdigit():
|
||||||
|
index = int(single_line) - 1 # 0-basiert
|
||||||
|
all_rooms = self._get_onboarding_room_list()
|
||||||
|
if 0 <= index < len(all_rooms):
|
||||||
|
rid, name = all_rooms[index]
|
||||||
|
self._set_catch_all(rid)
|
||||||
|
self.rest.post_message(room_id, f"🎯 {name} ist jetzt der Catch-All-Raum.")
|
||||||
|
logger.info("[rocketchat] Catch-All geändert zu: %s", name)
|
||||||
|
else:
|
||||||
|
self.rest.post_message(room_id, f"❌ Ungültige Nummer. Bitte 1–{len(all_rooms)} wählen.")
|
||||||
|
return
|
||||||
|
if single_line.lower() in ("überspringen", "skip", "nein", "no", "behalten"):
|
||||||
|
self.rest.post_message(room_id, "👍 Catch-All bleibt unverändert.")
|
||||||
|
logger.info("[rocketchat] Catch-All unverändert")
|
||||||
|
return
|
||||||
|
|
||||||
|
processed_count = 0
|
||||||
|
total_missing = len([rid for rid, r in self._room_info.items()
|
||||||
|
if r.get("type") in ("c", "p") and rid not in self.archivar._room_map.rooms])
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
line = line.strip()
|
||||||
|
# Skip empty lines and lines without obvious room assignment
|
||||||
|
if not line or "=" not in line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
match = pattern.match(line)
|
||||||
|
if not match:
|
||||||
|
continue
|
||||||
|
|
||||||
|
raw_name = match.group("name")
|
||||||
|
theme = match.group("theme").strip()
|
||||||
|
keywords_str = match.group("keywords")
|
||||||
|
|
||||||
|
if keywords_str:
|
||||||
|
keywords = [kw.strip() for kw in keywords_str.split(",") if kw.strip()]
|
||||||
|
else:
|
||||||
|
keywords = self._derive_keywords(raw_name, theme)
|
||||||
|
|
||||||
|
# Finde den Raum — probiere sowohl mit als auch ohne #
|
||||||
|
room_id_to_add = None
|
||||||
|
for rid, info in self._room_info.items():
|
||||||
|
if info.get("type") not in ("c", "p"):
|
||||||
|
continue
|
||||||
|
rc_name = info.get("name", "")
|
||||||
|
# Match: "BAT-Team" == "#BAT-Team", "#BAT-Team" == "BAT-Team"
|
||||||
|
if raw_name == rc_name or raw_name.lstrip("#") == rc_name.lstrip("#"):
|
||||||
|
room_id_to_add = rid
|
||||||
|
break
|
||||||
|
|
||||||
|
if room_id_to_add:
|
||||||
|
self.archivar._room_map.add_or_update_room(
|
||||||
|
room_id=room_id_to_add,
|
||||||
|
name=raw_name,
|
||||||
|
theme=theme,
|
||||||
|
keywords=keywords
|
||||||
|
)
|
||||||
|
processed_count += 1
|
||||||
|
logger.info("[rocketchat] Raum hinzugefügt: %s = %s (keywords: %s)", raw_name, theme, keywords)
|
||||||
|
|
||||||
|
if processed_count > 0:
|
||||||
|
# RoomMap speichern und reloaden
|
||||||
|
from .archivar.room_map import RoomMap
|
||||||
|
from .archivar.config import ROOM_MAP_PATH
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||||||
|
self.archivar._room_map.reload()
|
||||||
|
|
||||||
|
remaining_missing = len([rid for rid, r in self._room_info.items()
|
||||||
|
if r.get("type") in ("c", "p") and rid not in self.archivar._room_map.rooms])
|
||||||
|
|
||||||
|
if remaining_missing == 0:
|
||||||
|
self.archivar._stats["onboarding_active"] = False
|
||||||
|
# Baue nummerierte Raumliste für Catch-All-Frage
|
||||||
|
all_rooms = []
|
||||||
|
for rid, entry in self.archivar._room_map.rooms.items():
|
||||||
|
if rid in self.archivar._room_map._excluded_room_ids:
|
||||||
|
continue
|
||||||
|
all_rooms.append((rid, entry.name, entry.catch_all))
|
||||||
|
# Sortiere: catch_all zuerst, dann alphabetisch
|
||||||
|
all_rooms.sort(key=lambda x: (not x[2], x[1]))
|
||||||
|
|
||||||
|
lines = [f"✅ Alle {processed_count} Räume zur Map hinzugefügt."]
|
||||||
|
lines.append("")
|
||||||
|
lines.append("**Aktuelle Raum-Übersicht:**")
|
||||||
|
for i, (rid, name, is_catch) in enumerate(all_rooms, 1):
|
||||||
|
marker = " 🎯 (Catch-All)" if is_catch else ""
|
||||||
|
lines.append(f"{i}. {name}{marker}")
|
||||||
|
lines.append("")
|
||||||
|
lines.append("Möchtest du den Catch-All-Raum ändern? Antworte mit der Raumnummer, oder **überspringen** zum Behalten.")
|
||||||
|
confirmation_text = "\n".join(lines)
|
||||||
|
self.rest.post_message(room_id, confirmation_text)
|
||||||
|
logger.info("[rocketchat] Onboarding abgeschlossen: Alle Räume wurden hinzugefügt")
|
||||||
|
else:
|
||||||
|
remaining_text = f"📋 {processed_count} Räume verarbeitet, {remaining_missing} fehlen noch. Bitte die restlichen Themen nennen."
|
||||||
|
self.rest.post_message(room_id, remaining_text)
|
||||||
|
logger.info("[rocketchat] Onboarding läuft: %d von %d Räumen verarbeitet", processed_count, total_missing)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _derive_keywords(room_name: str, theme: str) -> list:
|
||||||
|
"""Leitet Stichworte aus Raumname und Thema ab.
|
||||||
|
|
||||||
|
Regeln:
|
||||||
|
- Raumname ohne '#' und ohne Bindestriche → einzelne Teile als Keywords
|
||||||
|
- Erste 2-4 signifikante Wörter aus dem Thema (keine Stopwörter)
|
||||||
|
- Maximal 10 Keywords, keine Duplikate, alle lowercase
|
||||||
|
"""
|
||||||
|
STOP = {"der", "die", "das", "und", "oder", "zum", "zur", "des", "dem", "den",
|
||||||
|
"ein", "eine", "einen", "einem", "für", "mit", "auf", "an", "von",
|
||||||
|
"ist", "sind", "wird", "the", "and", "or", "for", "with", "of", "to"}
|
||||||
|
keywords = []
|
||||||
|
|
||||||
|
# Aus Raumname: #BAT-Team → ["bat", "team"]
|
||||||
|
name_clean = room_name.lstrip("#")
|
||||||
|
for part in name_clean.replace("-", " ").replace("_", " ").split():
|
||||||
|
kw = part.lower().strip(".,;:!?")
|
||||||
|
if kw and kw not in STOP:
|
||||||
|
keywords.append(kw)
|
||||||
|
|
||||||
|
# Aus Thema: erste signifikante Wörter
|
||||||
|
for word in theme.lower().replace(",", " ").split():
|
||||||
|
w = word.strip(".,;:!?")
|
||||||
|
if w and w not in STOP and w not in keywords:
|
||||||
|
keywords.append(w)
|
||||||
|
if len(keywords) >= 10:
|
||||||
|
break
|
||||||
|
|
||||||
|
return keywords[:10]
|
||||||
|
|
||||||
|
def _get_onboarding_room_list(self) -> list:
|
||||||
|
"""Erstellt eine nummerierte Liste aller Räume (ohne excluded)."""
|
||||||
|
rooms = []
|
||||||
|
for rid, entry in self.archivar._room_map.rooms.items():
|
||||||
|
if rid in self.archivar._room_map._excluded_room_ids:
|
||||||
|
continue
|
||||||
|
rooms.append((rid, entry.name))
|
||||||
|
rooms.sort(key=lambda x: x[1]) # alphabetisch
|
||||||
|
return rooms
|
||||||
|
|
||||||
|
def _set_catch_all(self, room_id: str) -> None:
|
||||||
|
"""Setzt den angegebenen Raum als alleinigen Catch-All."""
|
||||||
|
from .archivar.config import ROOM_MAP_PATH
|
||||||
|
from pathlib import Path
|
||||||
|
for rid, entry in self.archivar._room_map.rooms.items():
|
||||||
|
entry.catch_all = (rid == room_id)
|
||||||
|
# Persistieren
|
||||||
|
from .archivar.room_map import RoomMap
|
||||||
|
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||||||
|
self.archivar._room_map.reload()
|
||||||
|
|
||||||
|
def _is_user_operator(self, username: str) -> bool:
|
||||||
|
"""Prüft, ob der Benutzer der Operator ist.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
username: Der zu prüfende Benutzername
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True wenn der Benutzer der Operator ist, sonst False
|
||||||
|
"""
|
||||||
|
return username.lower() == "andreas"
|
||||||
|
|
||||||
|
async def _download_and_inline_files(self, text: str) -> str:
|
||||||
|
"""Download files referenced as [FILE] markers and inline their content."""
|
||||||
|
import re
|
||||||
|
_file_re = re.compile(
|
||||||
|
r'\[FILE\]\s+(?P<name>[^\n]+?)\s+\((?P<type>[^)]+)\)\n'
|
||||||
|
r'Download:\s+\S+/file-upload/(?P<fid>[^/]+)/(?P<fname>\S+)'
|
||||||
|
)
|
||||||
|
matches = list(_file_re.finditer(text))
|
||||||
|
if not matches:
|
||||||
|
return text
|
||||||
|
for m in matches:
|
||||||
|
fid = m.group("fid")
|
||||||
|
fname = m.group("fname")
|
||||||
|
content = self.rest.download_file(fid, fname)
|
||||||
|
if content:
|
||||||
|
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
|
||||||
|
text += block
|
||||||
|
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
|
||||||
|
return text
|
||||||
|
|
||||||
async def disconnect(self) -> None:
|
async def disconnect(self) -> None:
|
||||||
self._mark_disconnected()
|
self._mark_disconnected()
|
||||||
self._shutdown_event.set()
|
self._shutdown_event.set()
|
||||||
@@ -594,8 +1043,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if not self.rest.auth_token:
|
if not self.rest.auth_token:
|
||||||
return SendResult(success=False, error="Not authenticated")
|
return SendResult(success=False, error="Not authenticated")
|
||||||
|
|
||||||
# ── Option C: Virtual → Real Room Translation ─────────────────
|
# ── Virtual → Real Room Translation ─────────────────────────
|
||||||
# chat_id from Hermes session is virtual (e.g. "user:andreas").
|
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||||
real_room_id = chat_id
|
real_room_id = chat_id
|
||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
@@ -610,10 +1059,58 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if rooms:
|
if rooms:
|
||||||
real_room_id = rooms[-1] # last room user was active in
|
real_room_id = rooms[-1] # last room user was active in
|
||||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||||
|
else:
|
||||||
|
# Fallback: try to find any room with recent activity involving this user
|
||||||
|
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||||
|
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||||
|
if fallback_room:
|
||||||
|
real_room_id = fallback_room
|
||||||
|
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||||
else:
|
else:
|
||||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||||
|
|
||||||
|
def _find_fallback_room_for_user(self, chat_id: str) -> Optional[str]:
|
||||||
|
"""Fallback method to find a room for a user when direct mapping fails.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
chat_id: Virtual chat_id like "user:username"
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Room ID if found, None otherwise
|
||||||
|
"""
|
||||||
|
if not chat_id.startswith("user:"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
target_username = chat_id.split(":", 1)[1].lower()
|
||||||
|
|
||||||
|
# Try to find any DM room involving this user
|
||||||
|
for room_id, room_info in self._room_info.items():
|
||||||
|
if room_info.get("type") == "d":
|
||||||
|
# Try to get room details with members
|
||||||
|
try:
|
||||||
|
room_detail = self.rest._request("GET", f"/api/v1/rooms.info?roomId={room_id}", headers={
|
||||||
|
"X-Auth-Token": self.rest.auth_token,
|
||||||
|
"X-User-Id": self.rest.user_id,
|
||||||
|
})
|
||||||
|
if room_detail and room_detail.get("success"):
|
||||||
|
room_data = room_detail.get("room", {})
|
||||||
|
usernames = room_data.get("usernames", [])
|
||||||
|
if target_username in [u.lower() for u in usernames]:
|
||||||
|
return room_id
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("[rocketchat] Could not get room info for %s: %s", room_id, e)
|
||||||
|
|
||||||
|
# Last resort: return first available room (better than nothing)
|
||||||
|
if self._subscribed_rooms:
|
||||||
|
first_room = next(iter(self._subscribed_rooms))
|
||||||
|
logger.warning("[rocketchat] Using first available room %s as ultimate fallback for %s",
|
||||||
|
first_room, chat_id)
|
||||||
|
return first_room
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||||
# This allows the agent to request buttons by embedding markup in its
|
# This allows the agent to request buttons by embedding markup in its
|
||||||
# response text, without requiring the gateway to pass metadata.
|
# response text, without requiring the gateway to pass metadata.
|
||||||
@@ -701,6 +1198,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
success = self.rest.post_message(real_room_id, content, attachments=attachments)
|
success = self.rest.post_message(real_room_id, content, attachments=attachments)
|
||||||
if success:
|
if success:
|
||||||
|
# If this message has buttons, mark the room so the next user
|
||||||
|
# message from here stays put (no Archivar routing). Button
|
||||||
|
# responses must be answered in the same room the question was
|
||||||
|
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
||||||
|
# and the agent loses context.
|
||||||
|
if attachments:
|
||||||
|
self._rooms_with_pending_questions.add(real_room_id)
|
||||||
|
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||||
return SendResult(success=False, error="chat.postMessage failed")
|
return SendResult(success=False, error="chat.postMessage failed")
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
---
|
||||||
|
name: archivar
|
||||||
|
description: >
|
||||||
|
Archivar — Embedding-basierte Nachrichten-Klassifikation und Routing im Rocket.Chat-Plugin.
|
||||||
|
Klassifiziert eingehende Nachrichten in FAKT, FRAGE, ALARM und leitet sie in konfigurierte
|
||||||
|
Zielräume weiter. Nutzt nomic-embed-text via Ollama (localhost:11434) mit Keyword-Fallback.
|
||||||
|
trigger: >
|
||||||
|
archivar, klassifikation, routing, nachrichten routing, klassifizierung,
|
||||||
|
fakt frage alarm, embedding, nomic-embed-text, kategorie, weiterleitung,
|
||||||
|
in welchen raum, wohin ging, zielraum, verteiler, konfidenz, fallback,
|
||||||
|
archiv, archivar stats, archivar statistik, catch-all, catch all
|
||||||
|
version: 1.0.0
|
||||||
|
date: 2026-06-03
|
||||||
|
---
|
||||||
|
|
||||||
|
# Archivar — Nachrichten-Klassifikation & Routing
|
||||||
|
|
||||||
|
## Übersicht
|
||||||
|
|
||||||
|
Der Archivar ist ein Submodul des Rocket.Chat-Plugins, das eingehende Nachrichten
|
||||||
|
automatisch klassifiziert und optional in konfigurierte Zielräume weiterleitet.
|
||||||
|
|
||||||
|
**Kernfunktion:**
|
||||||
|
- **Embedding-basierte Klassifikation** via nomic-embed-text (Ollama, localhost:11434)
|
||||||
|
- **3 Kategorien:** FAKT (Wissen, Doku), FRAGE (Hilfe, Probleme), ALARM (Dringend, Ausfälle)
|
||||||
|
- **Konfidenz-Schwellenwert:** 0.6 — darunter geht die Nachricht in den Catch-All-Raum
|
||||||
|
- **Keyword-Fallback:** Wenn Ollama ausfällt, greift eine Heuristik mit deutschen + englischen Keywords
|
||||||
|
- **Meta-Erkennung:** Fragen über den Archivar selbst werden nicht weitergeleitet
|
||||||
|
|
||||||
|
## Architektur
|
||||||
|
|
||||||
|
```
|
||||||
|
Adapter._process_incoming()
|
||||||
|
└─ MessageClassifier.classify()
|
||||||
|
└─ OllamaEmbeddingClient.get_embedding()
|
||||||
|
└─ nomic-embed-text (localhost:11434, 5s Timeout, 768-dim Vektoren)
|
||||||
|
└─ MessageRouter.route()
|
||||||
|
├─ FAKT → DocumentationStore (data/archivar_docs/fakt/{timestamp}.md)
|
||||||
|
│ FAKT ist Dokumentation, keine Kommunikation — niemals in Chat-Räume.
|
||||||
|
├─ FRAGE → Default-Zielraum oder projektspezifischer Raum
|
||||||
|
│ (Keyword-Matching: "plugin", "docs", "lan")
|
||||||
|
├─ ALARM → Direktnachricht an Admin
|
||||||
|
└─ < 0.6 → Catch-All-Raum
|
||||||
|
└─ Subscription-Validierung
|
||||||
|
└─ Nur Räume, die der Bot tatsächlich abonniert hat, werden als Ziel akzeptiert.
|
||||||
|
Nicht abonnierte Räume → DokumentationStore mit Begründung.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Konfiguration (Umgebungsvariablen)
|
||||||
|
|
||||||
|
Alle Raum-IDs werden über Umgebungsvariablen gesteuert — keine hartcodierten Werte:
|
||||||
|
|
||||||
|
| Variable | Zweck |
|
||||||
|
|---|---|
|
||||||
|
| `ARCHIVAR_FRAGE_ROOM` | Default-Zielraum für FRAGE-Kategorie |
|
||||||
|
| `ARCHIVAR_ALARM_ROOM` | Zielraum für ALARM-Kategorie (Direktnachricht an Admin) |
|
||||||
|
| `ARCHIVAR_CATCHALL_ROOM` | Fallback für unklassifizierte Nachrichten |
|
||||||
|
| `ARCHIVAR_PROJECT_ROOMS` | JSON-Map für projektspezifisches FRAGE-Routing (z.B. `{"plugin":"ROOM_ID","docs":"ROOM_ID"}`) |
|
||||||
|
|
||||||
|
> **FAKT** hat keine Raum-Variable mehr — Fakten sind Dokumentation, keine Kommunikation.
|
||||||
|
> Sie werden ausschließlich im DocumentationStore unter `data/archivar_docs/fakt/` abgelegt.
|
||||||
|
|
||||||
|
## DocumentationStore
|
||||||
|
|
||||||
|
Nicht-routbare Nachrichten (FAKT und Subscription-Fehler) werden als Markdown-Dateien
|
||||||
|
mit YAML-Frontmatter gespeichert:
|
||||||
|
|
||||||
|
```
|
||||||
|
~/.hermes/hermes-agent/data/archivar_docs/{kategorie}/{YYYY-MM-DD_HH-MM-SS}.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Jede Datei enthält:
|
||||||
|
- **Frontmatter:** `category`, `confidence`, `timestamp`, `origin_room`, `reason`
|
||||||
|
- **Body:** Vollständiger Nachrichtentext + Routing-Begründung
|
||||||
|
|
||||||
|
Der Doc-Store ist das **primäre Ziel für FAKT-Nachrichten** — nicht Fallback, kein Catch-All.
|
||||||
|
Nur FRAGE und ALARM werden jemals in Chat-Räume geroutet.
|
||||||
|
|
||||||
|
## Statistik
|
||||||
|
|
||||||
|
Der Archivar trackt laufend:
|
||||||
|
- `total` — Gesamtzahl verarbeiteter Nachrichten
|
||||||
|
- `classified` — erfolgreich klassifiziert
|
||||||
|
- `catch_all` — unter Konfidenz-Schwellenwert
|
||||||
|
- `fallback` — via Keyword-Heuristik (Ollama down)
|
||||||
|
- `meta` — Meta-Fragen (nicht weitergeleitet)
|
||||||
|
- `errors` — Fehler
|
||||||
|
- `total_latency_ms` — kumulierte Latenz
|
||||||
|
|
||||||
|
**Abfrage:** Statistiken sind über `archivar.stats` als dict verfügbar.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- **Meta-Fragen-Schutz:** Fragen wie "Wohin ging meine Nachricht?" oder "Wie arbeitet der Archivar?" werden erkannt und nicht weitergeleitet — sonst landen sie im Zielraum.
|
||||||
|
- **Ollama-Timeout:** 5 Sekunden. Bei Überschreitung → Fallback. Erhöhen via `OLLAMA_TIMEOUT` wenn Embedding-Modell auf schwacher Hardware.
|
||||||
|
- **Raum-IDs müssen existieren:** Wenn eine Env-Variable nicht gesetzt ist, wird die entsprechende Kategorie nicht geroutet (nur klassifiziert, kein Forward).
|
||||||
|
- **Konfidenz 0.6:** Zu niedrig → zu viele False Positives. Zu hoch → zu viel landet im Catch-All.
|
||||||
|
- **Embedding-Dimension:** nomic-embed-text produziert 768-dimensionale Vektoren. Anderes Modell → Dimension anpassen (`embedding_dim` in config.py).
|
||||||
|
|
||||||
|
## Fallback-Keywords
|
||||||
|
|
||||||
|
Bei Ollama-Ausfall greift diese Heuristik:
|
||||||
|
|
||||||
|
| Kategorie | Deutsche Keywords | Englische Keywords |
|
||||||
|
|---|---|---|
|
||||||
|
| FRAGE | frage, wie, was ist, warum, hilfe, problem, funktioniert nicht, kaputt, erklären | question, how, why, help, problem, explain |
|
||||||
|
| ALARM | alarm, hilfe, dringend, sofort, notfall, ausfall, absturz, kritisch | alarm, emergency, urgent, critical, crash, sos |
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""
|
||||||
|
Archivar-Modul: Klassifikation und Routing von Nachrichten im Rocket.Chat Plugin.
|
||||||
|
|
||||||
|
Bietet embedding-basierte Klassifikation (nomic-embed-text via Ollama)
|
||||||
|
für die Kategorien FAKT, FRAGE, ALARM und leitet Nachrichtenkopien an
|
||||||
|
konfigurierte Zielräume weiter.
|
||||||
|
|
||||||
|
Architektur: Siehe docs/Archivar_Architecture.md
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .classifier import MessageClassifier, ClassificationResult, EmbeddingClient, OllamaEmbeddingClient
|
||||||
|
from .config import ROOM_MAPPING, CATCH_ALL_ROOM, CATEGORY_TEXTS, OLLAMA_CONFIG, CONFIDENCE_THRESHOLD
|
||||||
|
from .doc_store import DocumentationStore
|
||||||
|
from .router import MessageRouter, RoutingDecision
|
||||||
|
from .adapter_integration import ArchivarMessageHandler
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"MessageClassifier",
|
||||||
|
"ClassificationResult",
|
||||||
|
"EmbeddingClient",
|
||||||
|
"OllamaEmbeddingClient",
|
||||||
|
"DocumentationStore",
|
||||||
|
"ROOM_MAPPING",
|
||||||
|
"CATCH_ALL_ROOM",
|
||||||
|
"CATEGORY_TEXTS",
|
||||||
|
"OLLAMA_CONFIG",
|
||||||
|
"CONFIDENCE_THRESHOLD",
|
||||||
|
"MessageRouter",
|
||||||
|
"RoutingDecision",
|
||||||
|
"ArchivarMessageHandler",
|
||||||
|
]
|
||||||
@@ -0,0 +1,520 @@
|
|||||||
|
"""
|
||||||
|
Integration des Archivar-Moduls in die Rocket.Chat-Adapter-Pipeline.
|
||||||
|
|
||||||
|
Exportiert die Klasse ``ArchivarMessageHandler``, die als Einhängepunkt
|
||||||
|
in ``adapter.py`` dient. Sie kapselt Classifier + Router und bietet eine
|
||||||
|
einfache ``classify_and_route()``-Methode für die Nachrichten-Pipeline.
|
||||||
|
|
||||||
|
Einhängung in adapter.py::
|
||||||
|
|
||||||
|
from .adapter_integration import ArchivarMessageHandler
|
||||||
|
|
||||||
|
class RocketChatAdapter(BasePlatformAdapter):
|
||||||
|
def __init__(self, config):
|
||||||
|
...
|
||||||
|
self.archivar = ArchivarMessageHandler()
|
||||||
|
|
||||||
|
async def connect(self):
|
||||||
|
...
|
||||||
|
await self.archivar.initialize()
|
||||||
|
|
||||||
|
async def _process_incoming(self, msg_obj):
|
||||||
|
...
|
||||||
|
text = msg_obj.get("msg", "")
|
||||||
|
room_id = msg_obj.get("rid", "")
|
||||||
|
|
||||||
|
decision = await self.archivar.classify_and_route(text)
|
||||||
|
|
||||||
|
if decision.target_room != room_id:
|
||||||
|
# Kopie an Zielraum senden (Original bleibt!)
|
||||||
|
prefix = decision.prefix or ""
|
||||||
|
await self._send_to_room(decision.target_room, f"{prefix}{text}")
|
||||||
|
|
||||||
|
if decision.delete_original:
|
||||||
|
await self._delete_message(room_id, msg_id)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Awaitable, Callable, Dict, Optional
|
||||||
|
|
||||||
|
from .classifier import (
|
||||||
|
ClassificationResult,
|
||||||
|
EmbeddingClient,
|
||||||
|
MessageClassifier,
|
||||||
|
LLMClient,
|
||||||
|
OllamaLLMClient,
|
||||||
|
)
|
||||||
|
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG, LLM_CONFIG, ROOM_MAP_PATH
|
||||||
|
from .doc_store import DocumentationStore
|
||||||
|
from .room_map import RoomMap, RoomMapValidationError
|
||||||
|
from .router import MessageRouter, RoutingDecision
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Callback-Signatur: async (room_id: str, text: str) -> bool
|
||||||
|
SendCallback = Callable[[str, str], Awaitable[bool]]
|
||||||
|
|
||||||
|
|
||||||
|
class ArchivarMessageHandler:
|
||||||
|
"""Hauptklasse für die Archivar-Integration.
|
||||||
|
|
||||||
|
Kapselt Classifier und Router. Wird vom RocketChatAdapter beim Start
|
||||||
|
initialisiert und bei jeder eingehenden Nachricht aufgerufen.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
handler = ArchivarMessageHandler()
|
||||||
|
await handler.initialize() # einmalig beim Adapter-Start
|
||||||
|
|
||||||
|
# Bei jeder Nachricht:
|
||||||
|
decision = await handler.classify_and_route(text)
|
||||||
|
# decision.target_room enthält die Zielraum-ID
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
send_callback: Optional[SendCallback] = None,
|
||||||
|
confidence_threshold: float = CONFIDENCE_THRESHOLD,
|
||||||
|
ollama_base_url: Optional[str] = None,
|
||||||
|
embedding_client: Optional[EmbeddingClient] = None,
|
||||||
|
llm_client: Optional[LLMClient] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
send_callback: Optionale async Callback-Funktion zum Senden von
|
||||||
|
Nachrichten via Rocket.Chat REST API. Signatur:
|
||||||
|
``async def send(room_id: str, text: str) -> bool``.
|
||||||
|
Wenn gesetzt, kann ``handle_and_forward()`` verwendet werden.
|
||||||
|
confidence_threshold: Konfidenz-Schwellenwert (0.0–1.0).
|
||||||
|
ollama_base_url: Override für Ollama-Basis-URL.
|
||||||
|
embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||||||
|
Wird an den ``MessageClassifier`` durchgereicht.
|
||||||
|
Ermöglicht Mocking/alternative Embedding-Backends.
|
||||||
|
llm_client: Optionales ``LLMClient``-Interface.
|
||||||
|
Wird an den ``MessageClassifier`` durchgereicht.
|
||||||
|
Ermöglicht Mocking/alternative LLM-Backends.
|
||||||
|
"""
|
||||||
|
self._send_callback = send_callback
|
||||||
|
self._enable_llm = LLM_CONFIG["enabled"]
|
||||||
|
|
||||||
|
# Create LLM client if enabled and not provided
|
||||||
|
if self._enable_llm and llm_client is None:
|
||||||
|
llm_client = OllamaLLMClient() if LLM_CONFIG["enabled"] else None
|
||||||
|
|
||||||
|
self._classifier = MessageClassifier(
|
||||||
|
base_url=ollama_base_url,
|
||||||
|
embedding_client=embedding_client,
|
||||||
|
llm_client=llm_client
|
||||||
|
)
|
||||||
|
# Load RoomMap (try JSON first, fall back to legacy env vars)
|
||||||
|
self._room_map = self._load_room_map()
|
||||||
|
|
||||||
|
# doc_store writes to fact_store_path from room_map
|
||||||
|
self._doc_store = DocumentationStore(base_dir=self._room_map.fact_store_path)
|
||||||
|
|
||||||
|
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
||||||
|
self._subscribed_room_ids_cache: Optional[set] = None
|
||||||
|
|
||||||
|
self._router = MessageRouter(self._room_map, self._classifier)
|
||||||
|
self._router.set_confidence_threshold(confidence_threshold)
|
||||||
|
self._initialized = False
|
||||||
|
|
||||||
|
# Statistiken (erweitert um Latenz + Fehler)
|
||||||
|
self._stats: Dict[str, Any] = {
|
||||||
|
"total": 0,
|
||||||
|
"classified": 0,
|
||||||
|
"catch_all": 0,
|
||||||
|
"fallback": 0,
|
||||||
|
"meta": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"llm_classified": 0, # Neue Statistik für LLM-Klassifikationen
|
||||||
|
"avg_latency_ms": 0.0, # float — gleitender Durchschnitt
|
||||||
|
"last_error": None, # str | None — letzter Fehler
|
||||||
|
"latencies": [], # list[float] — per-request ms
|
||||||
|
"onboarding_active": False, # Auto-Onboarding state
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── RoomMap Loading ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _load_room_map() -> RoomMap:
|
||||||
|
"""Load RoomMap from JSON, with legacy env var fallback.
|
||||||
|
|
||||||
|
Tries ``room-map.json`` first. If not found, attempts migration from
|
||||||
|
deprecated ``ARCHIVAR_*_ROOM`` env vars.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A ``RoomMap`` instance.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FileNotFoundError: If no map source is available.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
map_path = Path(ROOM_MAP_PATH)
|
||||||
|
|
||||||
|
if map_path.exists():
|
||||||
|
logger.info("Loading room map from %s", map_path)
|
||||||
|
return RoomMap.load(map_path)
|
||||||
|
|
||||||
|
# Try legacy env vars
|
||||||
|
logger.warning(
|
||||||
|
"Room map not found at %s — trying legacy ARCHIVAR_*_ROOM env vars",
|
||||||
|
map_path,
|
||||||
|
)
|
||||||
|
from .room_map import _migrate_from_env_vars
|
||||||
|
|
||||||
|
legacy_data = _migrate_from_env_vars()
|
||||||
|
if legacy_data is not None:
|
||||||
|
logger.warning(
|
||||||
|
"Using legacy env vars for room mapping. "
|
||||||
|
"Please create %s for new features.",
|
||||||
|
map_path,
|
||||||
|
)
|
||||||
|
return RoomMap._from_dict(legacy_data)
|
||||||
|
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"No room map found at {map_path} and no legacy "
|
||||||
|
"ARCHIVAR_*_ROOM env vars set. "
|
||||||
|
"Create a room-map.json or set ARCHIVAR_CATCHALL_ROOM."
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Public API ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def initialize(self) -> bool:
|
||||||
|
"""Einmalige Initialisierung: Pre-compute Kategorie-Vektoren + validiere Map.
|
||||||
|
|
||||||
|
Muss vor dem ersten ``classify_and_route()``-Aufruf aufgerufen werden.
|
||||||
|
Safe für mehrfache Aufrufe — no-op wenn bereits initialisiert.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True wenn die Initialisierung erfolgreich war (Classifier bereit).
|
||||||
|
False wenn Ollama nicht erreichbar ist → Fallback-Modus aktiv.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RoomMapValidationError: Wenn die room-map.json fatal invalide ist
|
||||||
|
(0 oder >1 Catch-All, Catch-All in excluded_rooms).
|
||||||
|
"""
|
||||||
|
if self._initialized:
|
||||||
|
return True
|
||||||
|
|
||||||
|
logger.info("Initializing ArchivarMessageHandler...")
|
||||||
|
|
||||||
|
# Validate RoomMap FIRST (fail-fast)
|
||||||
|
if self._subscribed_room_ids_cache is not None:
|
||||||
|
errors = self._room_map.validate(self._subscribed_room_ids_cache)
|
||||||
|
if errors:
|
||||||
|
logger.warning(
|
||||||
|
"Room map validation warnings: %s",
|
||||||
|
"; ".join(errors),
|
||||||
|
)
|
||||||
|
|
||||||
|
success = await self._classifier.initialize()
|
||||||
|
|
||||||
|
if success:
|
||||||
|
self._initialized = True
|
||||||
|
logger.info(
|
||||||
|
"ArchivarMessageHandler ready: %d categories, model=%s",
|
||||||
|
self._classifier.category_count,
|
||||||
|
OLLAMA_CONFIG["model"],
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"ArchivarMessageHandler initialized in FALLBACK mode — "
|
||||||
|
"Ollama unavailable at %s. Will use keyword heuristics.",
|
||||||
|
OLLAMA_CONFIG["base_url"],
|
||||||
|
)
|
||||||
|
# Mark as initialized anyway — the classifier will return None
|
||||||
|
# and the router will use keyword fallback.
|
||||||
|
self._initialized = True
|
||||||
|
|
||||||
|
return success
|
||||||
|
|
||||||
|
async def classify_and_route(
|
||||||
|
self, text: str, origin_room_id: str = ""
|
||||||
|
) -> RoutingDecision:
|
||||||
|
"""Klassifiziere eine Nachricht und ermittle den Zielraum.
|
||||||
|
|
||||||
|
Dies ist die primäre Methode für die adapter.py-Integration.
|
||||||
|
Sie führt die vollständige Klassifikation + Routing-Logik aus
|
||||||
|
und gibt eine ``RoutingDecision`` zurück.
|
||||||
|
|
||||||
|
Der Adapter entscheidet dann selbst über:
|
||||||
|
- Weiterleitung der Kopie an den Zielraum
|
||||||
|
- Löschen des Originals (bei Meta-Fragen)
|
||||||
|
- Hinzufügen von Präfix-Text ([FALLBACK], [META-FRAGE])
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoutingDecision mit Kategorie, Zielraum, Konfidenz und Metadaten.
|
||||||
|
"""
|
||||||
|
if not self._initialized:
|
||||||
|
logger.warning(
|
||||||
|
"classify_and_route() called before initialize() — "
|
||||||
|
"returning catch-all decision"
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room="", # Adapter soll selbst Catch-All verwenden
|
||||||
|
confidence=0.0,
|
||||||
|
is_catch_all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
decision = await self._router.route(text, origin_room_id)
|
||||||
|
|
||||||
|
# Update stats
|
||||||
|
self._stats["total"] += 1
|
||||||
|
if decision.is_meta:
|
||||||
|
self._stats["meta"] += 1
|
||||||
|
elif decision.is_unrouteable:
|
||||||
|
self._stats["classified"] += 1
|
||||||
|
# Store in documentation store — message is classified but
|
||||||
|
# the target room is not in our subscription list
|
||||||
|
stored = self._doc_store.store(
|
||||||
|
text=text,
|
||||||
|
category=decision.category,
|
||||||
|
confidence=decision.confidence,
|
||||||
|
reason=decision.unrouteable_reason,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Unrouteable [%s] stored in doc_store: %s",
|
||||||
|
decision.category, stored,
|
||||||
|
)
|
||||||
|
elif decision.is_fallback:
|
||||||
|
self._stats["fallback"] += 1
|
||||||
|
elif decision.is_catch_all:
|
||||||
|
self._stats["catch_all"] += 1
|
||||||
|
else:
|
||||||
|
self._stats["classified"] += 1
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
"Route: cat=%s conf=%.3f target=%s meta=%s fallback=%s catch_all=%s",
|
||||||
|
decision.category,
|
||||||
|
decision.confidence,
|
||||||
|
decision.target_room[:8] if decision.target_room else "none",
|
||||||
|
decision.is_meta,
|
||||||
|
decision.is_fallback,
|
||||||
|
decision.is_catch_all,
|
||||||
|
)
|
||||||
|
|
||||||
|
return decision
|
||||||
|
|
||||||
|
async def handle_and_forward(
|
||||||
|
self, text: str, origin_room_id: str, message_id: str = ""
|
||||||
|
) -> RoutingDecision:
|
||||||
|
"""Klassifiziere UND leite die Nachricht weiter (All-in-One).
|
||||||
|
|
||||||
|
Convenience-Methode für Adapter, die die Logik nicht selbst
|
||||||
|
implementieren wollen. Benötigt ``send_callback`` im Konstruktor.
|
||||||
|
|
||||||
|
Ablauf:
|
||||||
|
1. classify_and_route(text)
|
||||||
|
2. Wenn target_room != origin_room: Kopie an target_room senden
|
||||||
|
3. Bei Meta-Fragen: delete_original=True im Decision setzen
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Nachrichtentext.
|
||||||
|
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||||
|
message_id: Rocket.Chat Nachrichten-ID (für Lösch-Operationen).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoutingDecision — der Adapter kann zusätzlich löschen/präfixen.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: Wenn kein send_callback gesetzt wurde.
|
||||||
|
"""
|
||||||
|
if not self._send_callback:
|
||||||
|
raise RuntimeError(
|
||||||
|
"handle_and_forward() requires a send_callback. "
|
||||||
|
"Pass send_callback to ArchivarMessageHandler() constructor, "
|
||||||
|
"or use classify_and_route() + manual forwarding."
|
||||||
|
)
|
||||||
|
|
||||||
|
t_start: float = time.monotonic()
|
||||||
|
|
||||||
|
decision = await self.classify_and_route(text)
|
||||||
|
|
||||||
|
# If unrouteable, don't try to forward — message is already in doc_store
|
||||||
|
if decision.is_unrouteable:
|
||||||
|
return decision
|
||||||
|
|
||||||
|
# Only forward if the target differs from origin
|
||||||
|
if decision.target_room and decision.target_room != origin_room_id:
|
||||||
|
prefix = decision.prefix or ""
|
||||||
|
forwarded_text = f"{prefix}{text}" if prefix else text
|
||||||
|
|
||||||
|
try:
|
||||||
|
success = await self._send_callback(
|
||||||
|
decision.target_room, forwarded_text
|
||||||
|
)
|
||||||
|
if success:
|
||||||
|
logger.info(
|
||||||
|
"Forwarded [%s] to room %s (conf=%.3f)",
|
||||||
|
decision.category,
|
||||||
|
decision.target_room[:8],
|
||||||
|
decision.confidence,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.error(
|
||||||
|
"Failed to forward [%s] to room %s",
|
||||||
|
decision.category,
|
||||||
|
decision.target_room[:8],
|
||||||
|
)
|
||||||
|
self._stats["errors"] += 1
|
||||||
|
self._stats["last_error"] = (
|
||||||
|
f"Send callback returned False for room "
|
||||||
|
f"{decision.target_room[:8]}"
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
"Exception forwarding [%s] to room %s: %s",
|
||||||
|
decision.category,
|
||||||
|
decision.target_room[:8],
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
self._stats["errors"] += 1
|
||||||
|
self._stats["last_error"] = str(e)
|
||||||
|
|
||||||
|
# Update rolling average latency
|
||||||
|
elapsed_ms: float = (time.monotonic() - t_start) * 1000.0
|
||||||
|
self._stats["latencies"].append(elapsed_ms)
|
||||||
|
n: int = len(self._stats["latencies"])
|
||||||
|
if n > 0:
|
||||||
|
self._stats["avg_latency_ms"] = (
|
||||||
|
sum(self._stats["latencies"]) / n
|
||||||
|
)
|
||||||
|
|
||||||
|
return decision
|
||||||
|
|
||||||
|
# ── Statistics ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def stats(self) -> Dict[str, int]:
|
||||||
|
"""Read-only copy of classification statistics."""
|
||||||
|
return dict(self._stats)
|
||||||
|
|
||||||
|
def reset_stats(self) -> None:
|
||||||
|
"""Reset statistics counters."""
|
||||||
|
self._stats = {
|
||||||
|
"total": 0,
|
||||||
|
"classified": 0,
|
||||||
|
"catch_all": 0,
|
||||||
|
"fallback": 0,
|
||||||
|
"meta": 0,
|
||||||
|
"errors": 0,
|
||||||
|
"avg_latency_ms": 0.0,
|
||||||
|
"last_error": None,
|
||||||
|
"latencies": [],
|
||||||
|
"onboarding_active": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
def check_room_map_completeness(self, subscribed_rooms: dict) -> list[dict]:
|
||||||
|
"""Vergleicht subscribed rooms mit room-map.json.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subscribed_rooms: Mapping von room_id → {"name": str, "type": str} (vom Adapter)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Liste fehlender Räume: [{"room_id": "...", "name": "#Raum"}]
|
||||||
|
Leere Liste = Map vollständig.
|
||||||
|
"""
|
||||||
|
# Filter: Nur Räume mit type in ("c", "p") berücksichtigen
|
||||||
|
relevant_rooms = {
|
||||||
|
rid: info for rid, info in subscribed_rooms.items()
|
||||||
|
if info.get("type") in ("c", "p")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Single-Room-Regel: Wenn nur 1 relevanter Raum existiert und dieser
|
||||||
|
# nicht in der Map ist → automatisch als catch_all eintragen
|
||||||
|
if len(relevant_rooms) == 1:
|
||||||
|
single_room_id = list(relevant_rooms.keys())[0]
|
||||||
|
if single_room_id not in self._room_map.rooms:
|
||||||
|
# Automatisch als catch_all eintragen
|
||||||
|
room_info = relevant_rooms[single_room_id]
|
||||||
|
self._room_map.add_or_update_room(
|
||||||
|
room_id=single_room_id,
|
||||||
|
name=room_info["name"],
|
||||||
|
theme="Automatisch zugewiesener Catch-All-Raum",
|
||||||
|
keywords=[],
|
||||||
|
catch_all=True
|
||||||
|
)
|
||||||
|
# Speichern und neu laden
|
||||||
|
RoomMap.save(self._room_map, Path(ROOM_MAP_PATH))
|
||||||
|
self._room_map.reload()
|
||||||
|
logger.info("Single room detected — auto-assigned as catch_all: %s", room_info["name"])
|
||||||
|
return [] # Keine weiteren Maßnahmen nötig
|
||||||
|
|
||||||
|
# Normale Prüfung: Welche relevanten Räume fehlen in der Map?
|
||||||
|
missing = []
|
||||||
|
for room_id, room_info in relevant_rooms.items():
|
||||||
|
if room_id not in self._room_map.rooms:
|
||||||
|
missing.append({
|
||||||
|
"room_id": room_id,
|
||||||
|
"name": room_info["name"]
|
||||||
|
})
|
||||||
|
|
||||||
|
return missing
|
||||||
|
|
||||||
|
# ── Configuration ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def confidence_threshold(self) -> float:
|
||||||
|
"""Current confidence threshold."""
|
||||||
|
return self._router.confidence_threshold
|
||||||
|
|
||||||
|
def set_confidence_threshold(self, value: float) -> None:
|
||||||
|
"""Override confidence threshold at runtime."""
|
||||||
|
self._router.set_confidence_threshold(value)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_initialized(self) -> bool:
|
||||||
|
"""True if handler is ready for classification."""
|
||||||
|
return self._initialized
|
||||||
|
|
||||||
|
@property
|
||||||
|
def classifier_ready(self) -> bool:
|
||||||
|
"""True if the embedding classifier is operational (not just fallback)."""
|
||||||
|
return self._classifier.is_initialized
|
||||||
|
|
||||||
|
def set_send_callback(self, callback: SendCallback) -> None:
|
||||||
|
"""Set or replace the send callback after construction.
|
||||||
|
|
||||||
|
Ermöglicht ``handle_and_forward()``-Nutzung auch wenn der Callback
|
||||||
|
erst nach der Konstruktion verfügbar ist (z.B. nach REST-Login).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
callback: Async function ``(room_id, text) -> bool``.
|
||||||
|
"""
|
||||||
|
self._send_callback = callback
|
||||||
|
logger.debug("Send callback registered")
|
||||||
|
|
||||||
|
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||||
|
"""Set the bot's current subscribed room IDs for routing validation.
|
||||||
|
|
||||||
|
When set, the router will ONLY forward messages to rooms in this list.
|
||||||
|
Messages targeting unsubscribed rooms are stored in the
|
||||||
|
DocumentationStore instead.
|
||||||
|
|
||||||
|
Call this after adapter.connect() when the subscription list is ready.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_ids: List of Rocket.Chat room IDs the bot is currently
|
||||||
|
subscribed to. Pass None to disable validation.
|
||||||
|
"""
|
||||||
|
self._subscribed_room_ids_cache = set(room_ids) if room_ids else None
|
||||||
|
self._router.set_subscribed_room_ids(room_ids)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def doc_store(self) -> DocumentationStore:
|
||||||
|
"""Documentation store for unrouteable messages."""
|
||||||
|
return self._doc_store
|
||||||
@@ -0,0 +1,575 @@
|
|||||||
|
"""
|
||||||
|
Embedding-basierte Klassifikation via nomic-embed-text (Ollama, localhost:11434).
|
||||||
|
|
||||||
|
Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab
|
||||||
|
berechneten Kategorie-Vektoren (FAKT, FRAGE, ALARM) via Kosinus-Ähnlichkeit.
|
||||||
|
Bei Ollama-Fehlern oder Timeout wird None als ClassificationResult
|
||||||
|
zurückgegeben — der Router übernimmt dann den Fallback.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import abc
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
from .config import OLLAMA_CONFIG, CATEGORY_TEXTS, CONFIDENCE_THRESHOLD, LLM_CONFIG, LLM_CLASSIFY_PROMPT, LLM_CONFIDENCE_THRESHOLD
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ClassificationResult:
|
||||||
|
"""Ergebnis einer Embedding-basierten Klassifikation."""
|
||||||
|
|
||||||
|
category: str
|
||||||
|
"""Kategorie-Label: 'FAKT', 'FRAGE', oder 'ALARM'."""
|
||||||
|
|
||||||
|
confidence: float
|
||||||
|
"""Kosinus-Ähnlichkeit (0.0–1.0) der Nachricht zum besten Kategorie-Vektor."""
|
||||||
|
|
||||||
|
all_scores: Dict[str, float] = field(default_factory=dict)
|
||||||
|
"""Alle Kategorie-Scores für Debugging/Transparenz."""
|
||||||
|
|
||||||
|
latency_ms: float = 0.0
|
||||||
|
"""Gemessene Latenz der Embedding-API in Millisekunden."""
|
||||||
|
|
||||||
|
fallback: bool = False
|
||||||
|
"""True, wenn dieses Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||||||
|
|
||||||
|
def is_confident(self, threshold: float = CONFIDENCE_THRESHOLD) -> bool:
|
||||||
|
"""True wenn die Konfidenz über dem Schwellenwert liegt."""
|
||||||
|
return self.confidence >= threshold
|
||||||
|
|
||||||
|
def is_fallback(self) -> bool:
|
||||||
|
"""True wenn dieses Ergebnis aus der Keyword-Heuristik stammt."""
|
||||||
|
return self.fallback
|
||||||
|
|
||||||
|
|
||||||
|
# ── Embedding Client Interface (injectable) ─────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class EmbeddingClient(abc.ABC):
|
||||||
|
"""Interface for embedding providers. Injectable for testability.
|
||||||
|
|
||||||
|
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||||
|
single ``get_embedding()`` method so that ``MessageClassifier`` can
|
||||||
|
work with real Ollama, mocks, or alternative backends without change.
|
||||||
|
|
||||||
|
Implementations must be thread-safe since ``MessageClassifier`` calls
|
||||||
|
``get_embedding()`` synchronously inside ``asyncio.to_thread``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Return the embedding vector for *text*, or None on failure.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The text to embed.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A list of floats representing the embedding vector,
|
||||||
|
or ``None`` if the embedding could not be computed.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def __subclasshook__(cls, subclass):
|
||||||
|
if cls is EmbeddingClient:
|
||||||
|
if any("get_embedding" in B.__dict__ for B in subclass.__mro__):
|
||||||
|
return True
|
||||||
|
return NotImplemented
|
||||||
|
|
||||||
|
|
||||||
|
class OllamaEmbeddingClient(EmbeddingClient):
|
||||||
|
"""Embedding client backed by Ollama's `/api/embeddings` endpoint.
|
||||||
|
|
||||||
|
Wraps ``urllib.request.urlopen`` so the transport is hidden behind
|
||||||
|
the ``EmbeddingClient`` interface. Works with every Ollama model
|
||||||
|
that exposes the embeddings API (``nomic-embed-text`` recommended).
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
client = OllamaEmbeddingClient()
|
||||||
|
vector = client.get_embedding("hello world")
|
||||||
|
# → [0.123, -0.456, ...] (768 floats for nomic-embed-text)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: Optional[str] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
timeout: Optional[float] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
base_url: Ollama base URL (default from ``config.OLLAMA_CONFIG``).
|
||||||
|
model: Embedding model (default from ``config.OLLAMA_CONFIG``).
|
||||||
|
timeout: Request timeout in seconds (default from ``config.OLLAMA_CONFIG``).
|
||||||
|
"""
|
||||||
|
self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||||||
|
self._model = model or OLLAMA_CONFIG["model"]
|
||||||
|
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||||
|
|
||||||
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Call Ollama embeddings API. Returns None on any failure."""
|
||||||
|
url = f"{self._base_url}/api/embeddings"
|
||||||
|
payload = json.dumps(
|
||||||
|
{"model": self._model, "prompt": text}
|
||||||
|
).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"))
|
||||||
|
embedding = data.get("embedding")
|
||||||
|
if not embedding or not isinstance(embedding, list):
|
||||||
|
logger.error(
|
||||||
|
"Ollama returned invalid embedding: %s", type(embedding)
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
return [float(v) for v in embedding]
|
||||||
|
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
|
||||||
|
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||||
|
logger.error("Ollama response parse error: %s", e)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Unexpected error in get_embedding: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── LLM Client Interface (injectable) ───────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class LLMClient(abc.ABC):
|
||||||
|
"""Interface for LLM providers. Injectable for testability.
|
||||||
|
|
||||||
|
Hides the transport layer (e.g. urllib, httpx, aiohttp) behind a
|
||||||
|
single ``classify()`` method so that ``MessageClassifier`` can
|
||||||
|
work with real Ollama, mocks, or alternative backends without change.
|
||||||
|
|
||||||
|
Implementations must be thread-safe since ``MessageClassifier`` calls
|
||||||
|
``classify()`` synchronously inside ``asyncio.to_thread``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Klassifiziere Text. Gibt Kategorie-String oder None zurück."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
class OllamaLLMClient(LLMClient):
|
||||||
|
"""LLM client backed by Ollama's `/api/generate` endpoint.
|
||||||
|
|
||||||
|
Wraps ``urllib.request.urlopen`` so the transport is hidden behind
|
||||||
|
the ``LLMClient`` interface. Works with every Ollama model that
|
||||||
|
exposes the generate API (``qwen2.5:7b`` recommended).
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
client = OllamaLLMClient()
|
||||||
|
category = client.classify("Wie funktioniert das Plugin?")
|
||||||
|
# → "FRAGE"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: Optional[str] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
timeout: Optional[float] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
base_url: Ollama base URL (default from ``config.LLM_CONFIG``).
|
||||||
|
model: LLM model (default from ``config.LLM_CONFIG``).
|
||||||
|
timeout: Request timeout in seconds (default from ``config.LLM_CONFIG``).
|
||||||
|
"""
|
||||||
|
self._base_url = (base_url or LLM_CONFIG["base_url"]).rstrip("/")
|
||||||
|
self._model = model or LLM_CONFIG["model"]
|
||||||
|
self._timeout = timeout or LLM_CONFIG["timeout"]
|
||||||
|
|
||||||
|
def classify(self, text: str) -> Optional[str]:
|
||||||
|
"""Call Ollama generate API. Returns category or None on any failure."""
|
||||||
|
url = f"{self._base_url}/api/generate"
|
||||||
|
payload = json.dumps(
|
||||||
|
{
|
||||||
|
"model": self._model,
|
||||||
|
"prompt": text,
|
||||||
|
"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")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Trim whitespace and normalize category
|
||||||
|
category = response_text.strip().upper()
|
||||||
|
if category in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
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
|
||||||
|
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||||
|
logger.error("Ollama response parse error: %s", e)
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Unexpected error in classify: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class MessageClassifier:
|
||||||
|
"""Embedding-basierter Nachrichten-Klassifizierer.
|
||||||
|
|
||||||
|
Verwendet nomic-embed-text via Ollama-API auf localhost:11434.
|
||||||
|
Kategorie-Vektoren werden einmalig beim Start berechnet und im Speicher
|
||||||
|
gehalten (Caching für Sub-100ms-Performance).
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
classifier = MessageClassifier()
|
||||||
|
await classifier.initialize() # pre-compute category vectors
|
||||||
|
result = await classifier.classify("Wie funktioniert das Plugin?")
|
||||||
|
print(result.category) # → "FRAGE"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
base_url: Optional[str] = None,
|
||||||
|
model: Optional[str] = None,
|
||||||
|
timeout: Optional[float] = None,
|
||||||
|
embedding_client: Optional[EmbeddingClient] = None,
|
||||||
|
llm_client: Optional[LLMClient] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
base_url: Ollama-Basis-URL (default: aus config.py).
|
||||||
|
Ignoriert wenn *embedding_client* gesetzt ist.
|
||||||
|
model: Embedding-Modell (default: 'nomic-embed-text').
|
||||||
|
Ignoriert wenn *embedding_client* gesetzt ist.
|
||||||
|
timeout: Timeout in Sekunden (default: 5.0).
|
||||||
|
Ignoriert wenn *embedding_client* gesetzt ist.
|
||||||
|
embedding_client: Optionales ``EmbeddingClient``-Interface.
|
||||||
|
Wenn gesetzt, werden alle Embedding-Calls an diesen
|
||||||
|
Client delegiert (z.B. für Mocks oder alternative
|
||||||
|
Backends). Wenn ``None``, wird ein
|
||||||
|
``OllamaEmbeddingClient`` mit *base_url*, *model*
|
||||||
|
und *timeout* erstellt.
|
||||||
|
llm_client: Optionales ``LLMClient``-Interface.
|
||||||
|
Wenn gesetzt, werden LLM-Calls an diesen Client
|
||||||
|
delegiert. Wenn ``None`` und LLM aktiviert ist,
|
||||||
|
wird ein ``OllamaLLMClient`` erstellt.
|
||||||
|
"""
|
||||||
|
if embedding_client is not None:
|
||||||
|
self._embedding_client: EmbeddingClient = embedding_client
|
||||||
|
self._base_url = "injected"
|
||||||
|
self._model = "injected"
|
||||||
|
self._timeout = 0.0
|
||||||
|
else:
|
||||||
|
self._embedding_client = OllamaEmbeddingClient(
|
||||||
|
base_url=base_url, model=model, timeout=timeout
|
||||||
|
)
|
||||||
|
self._base_url = (base_url or OLLAMA_CONFIG["base_url"]).rstrip("/")
|
||||||
|
self._model = model or OLLAMA_CONFIG["model"]
|
||||||
|
self._timeout = timeout or OLLAMA_CONFIG["timeout"]
|
||||||
|
self._embedding_dim = OLLAMA_CONFIG["embedding_dim"]
|
||||||
|
|
||||||
|
# Handle LLM client
|
||||||
|
self._llm_enabled = LLM_CONFIG["enabled"]
|
||||||
|
if self._llm_enabled:
|
||||||
|
if llm_client is not None:
|
||||||
|
self._llm_client: Optional[LLMClient] = llm_client
|
||||||
|
else:
|
||||||
|
self._llm_client = OllamaLLMClient(
|
||||||
|
base_url=LLM_CONFIG["base_url"],
|
||||||
|
model=LLM_CONFIG["model"],
|
||||||
|
timeout=LLM_CONFIG["timeout"]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._llm_client = None
|
||||||
|
|
||||||
|
# Cache: category → embedding vector (768 floats)
|
||||||
|
self._category_vectors: Dict[str, List[float]] = {}
|
||||||
|
self._initialized: bool = False
|
||||||
|
self._init_error: Optional[str] = None
|
||||||
|
|
||||||
|
# Cache: message text → embedding (avoids re-embedding duplicates)
|
||||||
|
self._message_cache: Dict[str, List[float]] = {}
|
||||||
|
self._cache_max_size: int = 100
|
||||||
|
|
||||||
|
def _keyword_prefilter(self, text: str) -> Optional[str]:
|
||||||
|
"""Stufe 0: Keyword-Vorfilter. Liefert 'ALARM', 'FRAGE' oder None."""
|
||||||
|
from .config import FALLBACK_KEYWORDS
|
||||||
|
|
||||||
|
t = text.lower()
|
||||||
|
# ALARM ZUERST — höchste Priorität
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
||||||
|
if kw in t:
|
||||||
|
return "ALARM"
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
||||||
|
if kw in t:
|
||||||
|
return "FRAGE"
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _llm_classify(self, text: str) -> Optional[str]:
|
||||||
|
import asyncio
|
||||||
|
return await asyncio.to_thread(self._llm_classify_sync, text)
|
||||||
|
|
||||||
|
def _llm_classify_sync(self, text: str) -> Optional[str]:
|
||||||
|
try:
|
||||||
|
if not self._llm_client or not self._llm_enabled:
|
||||||
|
return None
|
||||||
|
|
||||||
|
prompt = LLM_CLASSIFY_PROMPT.format(text=text)
|
||||||
|
result = self._llm_client.classify(prompt)
|
||||||
|
if result in ("FAKT", "FRAGE", "ALARM"):
|
||||||
|
return result
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("LLM classification failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _llm_raw_sync(self, prompt: str) -> Optional[str]:
|
||||||
|
"""Send a raw prompt to the LLM and return its response.
|
||||||
|
|
||||||
|
Unlike ``_llm_classify_sync``, this does NOT validate against
|
||||||
|
FAKT/FRAGE/ALARM categories. Used by the RoomRouter for the
|
||||||
|
``LLM_ROOM_PROMPT`` where the expected answer is a room name.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
prompt: The complete prompt to send.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The LLM's response text (stripped), or None on failure.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if not self._llm_client or not self._llm_enabled:
|
||||||
|
return None
|
||||||
|
result = self._llm_client.classify(prompt)
|
||||||
|
if result:
|
||||||
|
return result.strip()
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("LLM raw call failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ── Public API ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def initialize(self) -> bool:
|
||||||
|
"""Pre-compute category vectors. Returns True on success.
|
||||||
|
|
||||||
|
Must be called once before classify(). Safe to call multiple times —
|
||||||
|
subsequent calls are no-ops if already initialized.
|
||||||
|
|
||||||
|
This is async to fit into the adapter's async startup lifecycle.
|
||||||
|
Internally calls synchronous urllib.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
return await asyncio.to_thread(self._initialize_sync)
|
||||||
|
|
||||||
|
def _initialize_sync(self) -> bool:
|
||||||
|
"""Synchronous initialization logic."""
|
||||||
|
if self._initialized:
|
||||||
|
return True
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Initializing classifier: model=%s, base_url=%s, timeout=%.1fs",
|
||||||
|
self._model, self._base_url, self._timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
success = True
|
||||||
|
for category, text in CATEGORY_TEXTS.items():
|
||||||
|
vector = self._get_embedding(text)
|
||||||
|
if vector is None:
|
||||||
|
logger.error(
|
||||||
|
"Failed to compute embedding for category '%s' — "
|
||||||
|
"classifier will use fallback",
|
||||||
|
category,
|
||||||
|
)
|
||||||
|
self._init_error = f"Failed to embed category '{category}'"
|
||||||
|
success = False
|
||||||
|
break
|
||||||
|
self._category_vectors[category] = vector
|
||||||
|
logger.debug("Category '%s' vectorized (%d dims)", category, len(vector))
|
||||||
|
|
||||||
|
if success:
|
||||||
|
self._initialized = True
|
||||||
|
logger.info(
|
||||||
|
"Classifier initialized successfully (%d categories)",
|
||||||
|
len(self._category_vectors),
|
||||||
|
)
|
||||||
|
return success
|
||||||
|
|
||||||
|
async def classify(self, text: str) -> Optional[ClassificationResult]:
|
||||||
|
"""Classify a message text. Returns None if embedding fails completely.
|
||||||
|
|
||||||
|
This is async to fit into the adapter's async pipeline.
|
||||||
|
Internally calls synchronous urllib.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The message text to classify.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ClassificationResult with category and confidence,
|
||||||
|
or None if the classifier is not initialized or embedding fails.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
return await asyncio.to_thread(self._classify_sync, text)
|
||||||
|
|
||||||
|
def _classify_sync(self, text: str) -> Optional[ClassificationResult]:
|
||||||
|
if not self._initialized:
|
||||||
|
logger.warning("classify() called before initialize() — returning None")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not text or not text.strip():
|
||||||
|
return None
|
||||||
|
|
||||||
|
text = text.strip()
|
||||||
|
|
||||||
|
t0 = time.monotonic()
|
||||||
|
|
||||||
|
# Stufe 0: Keyword-Vorfilter
|
||||||
|
keyword_result = self._keyword_prefilter(text)
|
||||||
|
if keyword_result == "ALARM":
|
||||||
|
# ALARM hat höchste Priorität - sofortige Rückgabe
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
return ClassificationResult(
|
||||||
|
category="ALARM",
|
||||||
|
confidence=0.95, # Hohe Konfidenz für Keyword-Treffer
|
||||||
|
all_scores={"ALARM": 0.95, "FRAGE": 0.0, "FAKT": 0.0},
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
# Für FRAGE geht es weiter zur Embedding-Klassifikation (mit niedrigerem Schwellwert)
|
||||||
|
|
||||||
|
# Stufe 1: Embedding-Klassifikation
|
||||||
|
vector = self._get_cached_or_compute(text)
|
||||||
|
if vector is None:
|
||||||
|
logger.debug("Failed to embed message: %.60s...", text)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Compare against all category vectors
|
||||||
|
scores: Dict[str, float] = {}
|
||||||
|
best_category: str = ""
|
||||||
|
best_score: float = -1.0
|
||||||
|
|
||||||
|
for category, cat_vector in self._category_vectors.items():
|
||||||
|
score = self._cosine_similarity(vector, cat_vector)
|
||||||
|
scores[category] = score
|
||||||
|
if score > best_score:
|
||||||
|
best_score = score
|
||||||
|
best_category = category
|
||||||
|
|
||||||
|
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||||
|
|
||||||
|
if best_score < 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Direktes Return des Embedding-Ergebnisses
|
||||||
|
return ClassificationResult(
|
||||||
|
category=best_category,
|
||||||
|
confidence=best_score,
|
||||||
|
all_scores=scores,
|
||||||
|
latency_ms=latency_ms,
|
||||||
|
fallback=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Embedding-API ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Delegate to the injectable ``EmbeddingClient``.
|
||||||
|
|
||||||
|
Returns None on any failure — the caller (router) handles fallback.
|
||||||
|
"""
|
||||||
|
return self._embedding_client.get_embedding(text)
|
||||||
|
|
||||||
|
def _get_cached_or_compute(self, text: str) -> Optional[List[float]]:
|
||||||
|
"""Return cached embedding or compute and cache a new one."""
|
||||||
|
# Simple LRU-like: evict if over max
|
||||||
|
if len(self._message_cache) >= self._cache_max_size:
|
||||||
|
# Evict the oldest key (first inserted)
|
||||||
|
oldest = next(iter(self._message_cache))
|
||||||
|
del self._message_cache[oldest]
|
||||||
|
|
||||||
|
if text in self._message_cache:
|
||||||
|
return self._message_cache[text]
|
||||||
|
|
||||||
|
vector = self._get_embedding(text)
|
||||||
|
if vector is not None:
|
||||||
|
self._message_cache[text] = vector
|
||||||
|
return vector
|
||||||
|
|
||||||
|
# ── Math ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _cosine_similarity(a: List[float], b: List[float]) -> float:
|
||||||
|
"""Compute cosine similarity between two vectors.
|
||||||
|
|
||||||
|
Returns 0.0 if either vector has zero magnitude.
|
||||||
|
"""
|
||||||
|
if len(a) != len(b):
|
||||||
|
raise ValueError(
|
||||||
|
f"Vector dimension mismatch: {len(a)} vs {len(b)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
dot = sum(x * y for x, y in zip(a, b))
|
||||||
|
norm_a = math.sqrt(sum(x * x for x in a))
|
||||||
|
norm_b = math.sqrt(sum(y * y for y in b))
|
||||||
|
|
||||||
|
if norm_a == 0.0 or norm_b == 0.0:
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
return dot / (norm_a * norm_b)
|
||||||
|
|
||||||
|
# ── Introspection ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_initialized(self) -> bool:
|
||||||
|
"""True if category vectors have been computed successfully."""
|
||||||
|
return self._initialized
|
||||||
|
|
||||||
|
@property
|
||||||
|
def init_error(self) -> Optional[str]:
|
||||||
|
"""Error message from initialization, or None."""
|
||||||
|
return self._init_error
|
||||||
|
|
||||||
|
@property
|
||||||
|
def category_count(self) -> int:
|
||||||
|
"""Number of cached category vectors."""
|
||||||
|
return len(self._category_vectors)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cache_size(self) -> int:
|
||||||
|
"""Number of cached message embeddings."""
|
||||||
|
return len(self._message_cache)
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
"""
|
||||||
|
Archivar-Konfiguration: Raum-Mapping, Kategorie-Texte und Ollama-Einstellungen.
|
||||||
|
|
||||||
|
Alle Raum-IDs werden über Umgebungsvariablen gesteuert — keine hartcodierten Werte.
|
||||||
|
OLLAMA_CONFIG bleibt auf localhost:11434 (generischer Default).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
# ── Ollama-Konfiguration ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
OLLAMA_CONFIG: dict = {
|
||||||
|
"base_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"),
|
||||||
|
"model": "nomic-embed-text",
|
||||||
|
"timeout": 5.0, # Sekunden — bei Überschreitung → Fallback
|
||||||
|
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Kategorie-Referenztexte (für Embedding-Vergleich) ───────────────────────
|
||||||
|
# Diese Texte werden einmalig beim Start vektorisiert. Neue Nachrichten werden
|
||||||
|
# via Kosinus-Ähnlichkeit gegen diese Vektoren verglichen.
|
||||||
|
|
||||||
|
CATEGORY_TEXTS: Dict[str, str] = {
|
||||||
|
"FAKT": (
|
||||||
|
"Dies ist eine Information oder ein Faktenbeitrag. Es enthält objektive "
|
||||||
|
"Aussagen, Dokumentation oder Wissenswertes ohne Handlungsbedarf. Beispiele "
|
||||||
|
"sind Dokumentationsabschnitte, Systeminformationen oder allgemeine Erklärungen."
|
||||||
|
),
|
||||||
|
"FRAGE": (
|
||||||
|
"Dies ist eine Frage oder ein Hilferuf. Es wird ein Wissensbeitrag oder "
|
||||||
|
"eine Antwort auf ein konkretes Problem erwartet. Beispiele sind "
|
||||||
|
"Problembeschreibungen oder Anfragen nach Lösungen."
|
||||||
|
),
|
||||||
|
"ALARM": (
|
||||||
|
"Dies ist eine dringende Nachricht oder ein Alarm. Es erfordert eine "
|
||||||
|
"sofortige Reaktion oder Handlung. Beispiele sind Systemausfälle, "
|
||||||
|
"kritische Fehler oder Zeitdruck betreffende Anfragen."
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Konfidenz-Schwellenwert ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CONFIDENCE_THRESHOLD: float = 0.6
|
||||||
|
"""Nachrichten mit confidence >= 0.6 werden klassifiziert, alles darunter
|
||||||
|
geht an den CATCH_ALL_ROOM."""
|
||||||
|
|
||||||
|
# ── Raum-Mapping (via Env-Vars) ─────────────────────────────────────────────
|
||||||
|
# Alle Raum-IDs werden aus Umgebungsvariablen gelesen.
|
||||||
|
# Falls nicht gesetzt → None (Router sendet dann nur Klassifikation, kein Routing).
|
||||||
|
#
|
||||||
|
# ARCHIVAR_FAKT_ROOM — Zielraum für FAKT-Kategorie (z.B. Dokumentation/Wiki)
|
||||||
|
# ARCHIVAR_FRAGE_ROOM — Default-Zielraum für FRAGE-Kategorie
|
||||||
|
# ARCHIVAR_ALARM_ROOM — Zielraum für ALARM-Kategorie (DM mit Admin)
|
||||||
|
# ARCHIVAR_CATCHALL_ROOM — Fallback für unklassifizierte Nachrichten
|
||||||
|
# ARCHIVAR_PROJECT_ROOMS — JSON-Map für projektspezifisches FRAGE-Routing
|
||||||
|
# Beispiel: {"plugin":"ROOM_ID","docs":"ROOM_ID"}
|
||||||
|
|
||||||
|
def _resolve_room_mapping() -> dict:
|
||||||
|
"""Baut ROOM_MAPPING aus Umgebungsvariablen zusammen.
|
||||||
|
|
||||||
|
FAKT wird NICHT in ROOM_MAPPING aufgenommen — Fakten sind Dokumentation,
|
||||||
|
keine Kommunikation. Sie werden ausschließlich im DocumentationStore
|
||||||
|
abgelegt, nie in einen Chat-Raum geroutet.
|
||||||
|
"""
|
||||||
|
mapping: dict = {}
|
||||||
|
|
||||||
|
# FAKT wird bewusst NICHT aus Env-Vars gelesen.
|
||||||
|
# ARCHIVAR_FAKT_ROOM existiert nicht mehr — FAKT → doc_store, immer.
|
||||||
|
|
||||||
|
frage_default = os.getenv("ARCHIVAR_FRAGE_ROOM", "").strip()
|
||||||
|
frage_entry: dict = {}
|
||||||
|
if frage_default:
|
||||||
|
frage_entry["default"] = frage_default
|
||||||
|
|
||||||
|
project_json = os.getenv("ARCHIVAR_PROJECT_ROOMS", "").strip()
|
||||||
|
if project_json:
|
||||||
|
try:
|
||||||
|
frage_entry["project_specific"] = json.loads(project_json)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass # ignorieren, kein projektspezifisches Routing
|
||||||
|
|
||||||
|
if frage_entry:
|
||||||
|
mapping["FRAGE"] = frage_entry
|
||||||
|
|
||||||
|
alarm = os.getenv("ARCHIVAR_ALARM_ROOM", "").strip()
|
||||||
|
if alarm:
|
||||||
|
mapping["ALARM"] = alarm
|
||||||
|
|
||||||
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
ROOM_MAPPING: dict = _resolve_room_mapping()
|
||||||
|
|
||||||
|
CATCH_ALL_ROOM: str = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip() or None
|
||||||
|
|
||||||
|
# ── Fallback-Keyword-Heuristik ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
FALLBACK_KEYWORDS: dict = {
|
||||||
|
"FRAGE": ["frage", "wie", "was ist", "warum", "wieso", "weshalb",
|
||||||
|
"kannst du", "können sie", "help", "hilfe", "problem",
|
||||||
|
"funktioniert nicht", "kaputt", "erklären", "erkläre",
|
||||||
|
"was bedeutet", "zeig mir", "konflikt"],
|
||||||
|
"ALARM": ["alarm", "hilfe", "dringend", "sofort", "notfall",
|
||||||
|
"ausfall", "absturz", "kritisch", "emergency",
|
||||||
|
"feuer", "panne", "sos", "sicherheitslücke",
|
||||||
|
"stop", "red flag", "abort", "kompromittiert", "datenverlust",
|
||||||
|
"exploit", "gehackt", "ausgefallen", "produktivsystem"],
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
Bei Ollama-Down-Fallback: Enthält die Nachricht eines dieser Keywords,
|
||||||
|
wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ── LLM-Konfiguration ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
LLM_CONFIG = {
|
||||||
|
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
||||||
|
"model": "qwen2.5:7b",
|
||||||
|
"timeout": 5.0,
|
||||||
|
"base_url": "http://localhost:11434",
|
||||||
|
"temperature": 0.0,
|
||||||
|
"max_tokens": 5, # Nur 1 Wort nötig (Raum-Name oder "CATCH_ALL")
|
||||||
|
}
|
||||||
|
|
||||||
|
# DEPRECATED - Wird nicht mehr verwendet, da der LLM-Klassifizierungszweig entfernt wurde
|
||||||
|
LLM_CLASSIFY_PROMPT = """Klassifiziere die folgende Nachricht in EINE Kategorie.
|
||||||
|
Antworte NUR mit einem Wort: FAKT, FRAGE oder ALARM.
|
||||||
|
|
||||||
|
Kategorien:
|
||||||
|
- FAKT: Information, Dokumentation, Status-Update ohne Handlungsbedarf
|
||||||
|
- FRAGE: Frage, Problembeschreibung, Bitte um Hilfe oder Erklärung
|
||||||
|
- ALARM: Dringend! Ausfall, Sicherheitsvorfall, Datenverlust, sofortiger Handlungsbedarf
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
|
||||||
|
Kategorie:"""
|
||||||
|
|
||||||
|
LLM_CONFIDENCE_THRESHOLD = 0.70
|
||||||
|
|
||||||
|
# ── Raum-Map-Konfiguration ──────────────────────────────────────────────────
|
||||||
|
# Ablösung der ARCHIVAR_*_ROOM Env-Vars durch room-map.json.
|
||||||
|
# Die alten Env-Vars funktionieren weiter (deprecated, mit WARNING). Neue
|
||||||
|
# Installationen sollten ausschließlich room-map.json verwenden.
|
||||||
|
|
||||||
|
ROOM_MAP_PATH: str = os.path.expanduser(
|
||||||
|
os.getenv("ARCHIVAR_ROOM_MAP_PATH", "~/.hermes/hermes-agent/data/room-map.json")
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── LLM-Room-Prompt (NEU — ersetzt LLM_CLASSIFY_PROMPT) ───────────────────
|
||||||
|
# Fragt das LLM nicht mehr "Welche Kategorie?" sondern "In welchen Raum?"
|
||||||
|
# Die Raum-Liste wird vom RoomRouter dynamisch eingesetzt.
|
||||||
|
|
||||||
|
LLM_ROOM_PROMPT = """Du bist ein Raum-Zuordner. Ordne die Nachricht EINEM Raum zu.
|
||||||
|
Antworte NUR mit dem exakten Raum-Namen. Keine Erklärungen, keine Sätze, kein Punkt.
|
||||||
|
Wenn unsicher, antworte mit dem einzelnen Wort: CATCH_ALL
|
||||||
|
|
||||||
|
Verfügbare Räume:
|
||||||
|
{room_list}
|
||||||
|
|
||||||
|
Nachricht: {text}
|
||||||
|
Raum:"""
|
||||||
|
|
||||||
|
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
|
||||||
|
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
|
||||||
|
# Bleibt im Code, falls externe Skripte darauf verweisen.
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""
|
||||||
|
Documentation store for Archivar — filesystem persistence for messages
|
||||||
|
that cannot be routed because no room mapping exists or the target room
|
||||||
|
is not in the bot's subscription list.
|
||||||
|
|
||||||
|
Writes classified-but-unrouteable messages to:
|
||||||
|
~/.hermes/hermes-agent/data/archivar_docs/{category}/{timestamp}.md
|
||||||
|
|
||||||
|
Each stored document is a self-contained markdown file with YAML frontmatter
|
||||||
|
containing classification metadata and a human-readable reason why routing
|
||||||
|
was blocked.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
def _get_hermes_agent_dir() -> Path:
|
||||||
|
"""Resolve hermes-agent directory (works regardless of HERMES_HOME)."""
|
||||||
|
hermes_home = os.environ.get("HERMES_HOME", os.path.expanduser("~/.hermes"))
|
||||||
|
return Path(hermes_home) / "hermes-agent"
|
||||||
|
|
||||||
|
|
||||||
|
class DocumentationStore:
|
||||||
|
"""Filesystem store for unrouteable classified messages.
|
||||||
|
|
||||||
|
When the Archivar classifies a message but no valid target room exists
|
||||||
|
(either because ROOM_MAPPING is empty for that category, or the resolved
|
||||||
|
target room is not in the bot's current subscription list), the message
|
||||||
|
is saved here instead of being silently dropped or forwarded to the
|
||||||
|
wrong room.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
store = DocumentationStore()
|
||||||
|
path = store.store(
|
||||||
|
text="Server monitoring shows CPU spike",
|
||||||
|
category="FAKT",
|
||||||
|
confidence=0.92,
|
||||||
|
reason="ARCHIVAR_FAKT_ROOM not configured",
|
||||||
|
origin_room="6a19b0ff02aeecd36b1aa16c",
|
||||||
|
)
|
||||||
|
# → ~/.hermes/hermes-agent/data/archivar_docs/fakt/2026-06-03_21-30-00.md
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, base_dir: Optional[Path] = None) -> None:
|
||||||
|
if base_dir is None:
|
||||||
|
base_dir = _get_hermes_agent_dir() / "data" / "archivar_docs"
|
||||||
|
self._base_dir = Path(base_dir)
|
||||||
|
|
||||||
|
def store(
|
||||||
|
self,
|
||||||
|
text: str,
|
||||||
|
category: str,
|
||||||
|
confidence: float,
|
||||||
|
reason: str = "",
|
||||||
|
origin_room: str = "",
|
||||||
|
) -> str:
|
||||||
|
"""Store an unrouteable message as a markdown document.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The original message text.
|
||||||
|
category: Classification category (FAKT, FRAGE, ALARM).
|
||||||
|
confidence: Classification confidence (0.0–1.0).
|
||||||
|
reason: Human-readable reason why routing was blocked.
|
||||||
|
origin_room: Rocket.Chat room ID where the message originated.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Absolute path to the stored file.
|
||||||
|
"""
|
||||||
|
category_dir = self._base_dir / category.lower()
|
||||||
|
category_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
|
||||||
|
filename = f"{timestamp}.md"
|
||||||
|
filepath = category_dir / filename
|
||||||
|
|
||||||
|
content = self._format_doc(text, category, confidence, reason, origin_room)
|
||||||
|
filepath.write_text(content, encoding="utf-8")
|
||||||
|
|
||||||
|
return str(filepath)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _format_doc(
|
||||||
|
text: str,
|
||||||
|
category: str,
|
||||||
|
confidence: float,
|
||||||
|
reason: str,
|
||||||
|
origin_room: str,
|
||||||
|
) -> str:
|
||||||
|
"""Format a message as a documentation entry with YAML frontmatter."""
|
||||||
|
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
return (
|
||||||
|
f"---\n"
|
||||||
|
f"category: {category}\n"
|
||||||
|
f"confidence: {confidence:.3f}\n"
|
||||||
|
f"timestamp: {timestamp}\n"
|
||||||
|
f"origin_room: {origin_room}\n"
|
||||||
|
f"reason: {reason}\n"
|
||||||
|
f"---\n\n"
|
||||||
|
f"# {category}: Unrouteable Message\n\n"
|
||||||
|
f"**Reason:** {reason}\n\n"
|
||||||
|
f"{text}\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def list_stored(self, category: str = "") -> list[Path]:
|
||||||
|
"""List stored documents, optionally filtered by category.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
category: Filter by category name (e.g. 'fakt', 'frage', 'alarm').
|
||||||
|
Empty string returns all.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Sorted list of Path objects, newest first.
|
||||||
|
"""
|
||||||
|
if category:
|
||||||
|
target = self._base_dir / category.lower()
|
||||||
|
else:
|
||||||
|
target = self._base_dir
|
||||||
|
|
||||||
|
if not target.exists():
|
||||||
|
return []
|
||||||
|
|
||||||
|
return sorted(target.glob("**/*.md"), reverse=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def base_dir(self) -> Path:
|
||||||
|
"""Base directory for stored documents."""
|
||||||
|
return self._base_dir
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"$id": "https://hermes-agent.nousresearch.com/schemas/room-map.schema.json",
|
||||||
|
"title": "Archivar Room Map",
|
||||||
|
"description": "Schema for the Archivar room-map.json — the single source of truth for thematic message routing.",
|
||||||
|
"type": "object",
|
||||||
|
"required": ["version", "rooms"],
|
||||||
|
"properties": {
|
||||||
|
"version": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "Schema version for future migrations.",
|
||||||
|
"minimum": 1
|
||||||
|
},
|
||||||
|
"rooms": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Map of room_id → RoomEntry.",
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "object",
|
||||||
|
"required": ["name", "theme"],
|
||||||
|
"properties": {
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Human-readable room name (e.g. '#Rocketchat-Plugin').",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"theme": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Theme / purpose of the room.",
|
||||||
|
"minLength": 1
|
||||||
|
},
|
||||||
|
"keywords": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Keywords for keyword-based routing.",
|
||||||
|
"items": { "type": "string", "minLength": 1 },
|
||||||
|
"default": []
|
||||||
|
},
|
||||||
|
"catch_all": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "True if this room is the single catch-all room.",
|
||||||
|
"default": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"excluded_rooms": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Room IDs that must never receive routed messages (e.g. Multi-Agent-Raum).",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"default": []
|
||||||
|
},
|
||||||
|
"fact_store_path": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Filesystem path for FAKT message storage (absolute or ~-prefixed).",
|
||||||
|
"default": "~/archivar_docs"
|
||||||
|
},
|
||||||
|
"keyword_overrides": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Admin-corrected keyword→room mappings (learned from !r overrides).",
|
||||||
|
"additionalProperties": { "type": "string" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
"""
|
||||||
|
Room-Map: Single Source of Truth für den thematischen Router.
|
||||||
|
|
||||||
|
Lädt, validiert und durchsucht die Raum-Map aus ``room-map.json``.
|
||||||
|
Ersetzt die bisherigen ``ARCHIVAR_*_ROOM`` Env-Vars durch ein
|
||||||
|
strukturiertes JSON-Datenmodell.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
from .room_map import RoomMap, RoomMapValidationError
|
||||||
|
|
||||||
|
try:
|
||||||
|
room_map = RoomMap.load()
|
||||||
|
room_map.validate(subscribed_ids)
|
||||||
|
except RoomMapValidationError as e:
|
||||||
|
logger.fatal("Room map invalid: %s", e)
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
room = room_map.find_room_by_keywords("Das Plugin hat einen Bug")
|
||||||
|
# → RoomEntry(name="#Rocketchat-Plugin", ...)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ── Constants ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
DEFAULT_MAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
|
||||||
|
|
||||||
|
# ── Data Classes ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RoomEntry:
|
||||||
|
"""Ein Raum-Eintrag in der Map."""
|
||||||
|
|
||||||
|
room_id: str
|
||||||
|
"""Rocket.Chat Raum-ID."""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
"""Menschenlesbarer Name (z. B. ``#Rocketchat-Plugin``)."""
|
||||||
|
|
||||||
|
theme: str
|
||||||
|
"""Thema des Raums (ein Satz)."""
|
||||||
|
|
||||||
|
keywords: list[str] = field(default_factory=list)
|
||||||
|
"""Stichworte für Keyword-Matching."""
|
||||||
|
|
||||||
|
catch_all: bool = False
|
||||||
|
"""True wenn dieser Raum der EINE Catch-All-Raum ist."""
|
||||||
|
|
||||||
|
def match_score(self, text: str) -> int:
|
||||||
|
"""Return number of keyword matches in *text* (case-insensitive).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The message text to match against.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Number of matching keywords (0 if none match).
|
||||||
|
"""
|
||||||
|
if not self.keywords:
|
||||||
|
return 0
|
||||||
|
text_lower = text.lower()
|
||||||
|
return sum(1 for kw in self.keywords if kw in text_lower)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Exception ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class RoomMapValidationError(Exception):
|
||||||
|
"""Raised when the room-map.json fails validation at startup."""
|
||||||
|
|
||||||
|
|
||||||
|
# ── RoomMap ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class RoomMap:
|
||||||
|
"""Lädt, validiert und durchsucht die Raum-Map.
|
||||||
|
|
||||||
|
Die Map ist ein JSON-Dokument (Schema siehe ``room-map.schema.json``).
|
||||||
|
Sie wird einmalig beim Gateway-Start geladen und danach im Speicher
|
||||||
|
gehalten. Änderungen an der JSON-Datei zur Laufzeit werden NICHT
|
||||||
|
automatisch erkannt — ein Gateway-Neustart ist nötig.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
rooms: dict[str, RoomEntry],
|
||||||
|
excluded_room_ids: set[str],
|
||||||
|
fact_store_path: Path,
|
||||||
|
version: int = 1,
|
||||||
|
) -> None:
|
||||||
|
"""Initialize from pre-parsed data.
|
||||||
|
|
||||||
|
Use ``RoomMap.load()`` to parse from a JSON file.
|
||||||
|
"""
|
||||||
|
self._rooms = rooms
|
||||||
|
self._excluded_room_ids = excluded_room_ids
|
||||||
|
self._fact_store_path = fact_store_path
|
||||||
|
self._version = version
|
||||||
|
|
||||||
|
# ── Properties ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def rooms(self) -> dict[str, RoomEntry]:
|
||||||
|
"""All room entries, keyed by Rocket.Chat room ID."""
|
||||||
|
return dict(self._rooms)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def catch_all_room(self) -> Optional[RoomEntry]:
|
||||||
|
"""The ONE catch-all room, or None if not exactly one."""
|
||||||
|
catch_alls = [r for r in self._rooms.values() if r.catch_all]
|
||||||
|
return catch_alls[0] if len(catch_alls) == 1 else None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def excluded_room_ids(self) -> set[str]:
|
||||||
|
"""Room IDs that are excluded from all routing."""
|
||||||
|
return set(self._excluded_room_ids)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def fact_store_path(self) -> Path:
|
||||||
|
"""Path for FAKT message storage (filesystem, not a chat room)."""
|
||||||
|
return self._fact_store_path
|
||||||
|
|
||||||
|
@property
|
||||||
|
def version(self) -> int:
|
||||||
|
"""Schema version of the loaded map."""
|
||||||
|
return self._version
|
||||||
|
|
||||||
|
# ── Lookup Methods ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def find_room_by_keywords(self, text: str) -> Optional[RoomEntry]:
|
||||||
|
"""Find the room with the most keyword matches for *text*.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: The message text to classify.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The ``RoomEntry`` with the highest match score, or ``None``
|
||||||
|
if no room has any matching keywords.
|
||||||
|
"""
|
||||||
|
best_room: Optional[RoomEntry] = None
|
||||||
|
best_score: int = 0
|
||||||
|
|
||||||
|
for room in self._rooms.values():
|
||||||
|
if room.catch_all:
|
||||||
|
continue # Catch-All never matches keywords
|
||||||
|
score = room.match_score(text)
|
||||||
|
if score > best_score:
|
||||||
|
best_score = score
|
||||||
|
best_room = room
|
||||||
|
|
||||||
|
return best_room
|
||||||
|
|
||||||
|
def is_excluded(self, room_id: str) -> bool:
|
||||||
|
"""True if *room_id* is in the excluded list (e.g. Multi-Agent-Raum)."""
|
||||||
|
return room_id in self._excluded_room_ids
|
||||||
|
|
||||||
|
# ── Validation ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def validate(self, subscribed_ids: Optional[set[str]] = None) -> list[str]:
|
||||||
|
"""Validate the map against subscription reality.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subscribed_ids: The bot's current subscribed room IDs.
|
||||||
|
When provided, checks that the catch-all room and all
|
||||||
|
mapped rooms are in the subscription list.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of error messages (empty = valid).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RoomMapValidationError: For fatal errors (0 or >1 catch-all,
|
||||||
|
catch-all in excluded rooms).
|
||||||
|
"""
|
||||||
|
errors: list[str] = []
|
||||||
|
|
||||||
|
# Count catch-all rooms
|
||||||
|
catch_alls = [r for r in self._rooms.values() if r.catch_all]
|
||||||
|
if len(catch_alls) == 0:
|
||||||
|
raise RoomMapValidationError(
|
||||||
|
"FATAL: No catch_all room defined in room-map.json. "
|
||||||
|
"Exactly one room must have 'catch_all: true'."
|
||||||
|
)
|
||||||
|
if len(catch_alls) > 1:
|
||||||
|
names = ", ".join(r.name for r in catch_alls)
|
||||||
|
raise RoomMapValidationError(
|
||||||
|
f"FATAL: Multiple catch_all rooms: {names}. "
|
||||||
|
"Exactly one room must have 'catch_all: true'."
|
||||||
|
)
|
||||||
|
|
||||||
|
catch_all = catch_alls[0]
|
||||||
|
|
||||||
|
# Catch-all must not be in excluded rooms
|
||||||
|
if catch_all.room_id in self._excluded_room_ids:
|
||||||
|
raise RoomMapValidationError(
|
||||||
|
f"FATAL: Catch-all room '{catch_all.name}' is in excluded_rooms. "
|
||||||
|
"The catch-all room cannot be excluded from routing."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subscription checks (non-fatal warnings)
|
||||||
|
if subscribed_ids is not None:
|
||||||
|
if catch_all.room_id not in subscribed_ids:
|
||||||
|
errors.append(
|
||||||
|
f"Catch-all room '{catch_all.name}' "
|
||||||
|
f"({catch_all.room_id[:8]}...) is not in subscribed rooms"
|
||||||
|
)
|
||||||
|
|
||||||
|
for room in self._rooms.values():
|
||||||
|
if room.room_id not in subscribed_ids:
|
||||||
|
errors.append(
|
||||||
|
f"Room '{room.name}' ({room.room_id[:8]}...) "
|
||||||
|
"is not in subscribed rooms"
|
||||||
|
)
|
||||||
|
|
||||||
|
return errors
|
||||||
|
|
||||||
|
# ── Factory ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load(cls, path: Optional[Path] = None) -> RoomMap:
|
||||||
|
"""Load and validate a room-map.json file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Path to the JSON file. Defaults to
|
||||||
|
``ARCHIVAR_ROOM_MAP_PATH`` env var or
|
||||||
|
``~/.hermes/hermes-agent/data/room-map.json``.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A validated ``RoomMap`` instance.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FileNotFoundError: If the map file does not exist.
|
||||||
|
json.JSONDecodeError: If the file is not valid JSON.
|
||||||
|
RoomMapValidationError: If the map fails semantic validation.
|
||||||
|
"""
|
||||||
|
if path is None:
|
||||||
|
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
|
||||||
|
if env_path:
|
||||||
|
path = Path(env_path)
|
||||||
|
else:
|
||||||
|
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
|
||||||
|
|
||||||
|
if not path.exists():
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"Room map not found at {path}. "
|
||||||
|
"Create one with room-map.schema.json as template."
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
return cls._from_dict(data)
|
||||||
|
|
||||||
|
def add_or_update_room(self, room_id: str, name: str, theme: str = "", keywords: Optional[list] = None, catch_all: bool = False) -> None:
|
||||||
|
"""Fügt Raum zur In-Memory-Map hinzu ODER aktualisiert bestehenden.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Rocket.Chat Raum-ID
|
||||||
|
name: Menschenlesbarer Name (z.B. "#Rocketchat-Plugin")
|
||||||
|
theme: Thema des Raums (ein Satz)
|
||||||
|
keywords: Stichworte für Keyword-Matching
|
||||||
|
catch_all: True wenn dieser Raum der EINE Catch-All-Raum ist
|
||||||
|
"""
|
||||||
|
if keywords is None:
|
||||||
|
keywords = []
|
||||||
|
|
||||||
|
# Erstelle oder aktualisiere den RoomEntry
|
||||||
|
self._rooms[room_id] = RoomEntry(
|
||||||
|
room_id=room_id,
|
||||||
|
name=name,
|
||||||
|
theme=theme,
|
||||||
|
keywords=keywords,
|
||||||
|
catch_all=catch_all
|
||||||
|
)
|
||||||
|
|
||||||
|
# Wenn dies ein Catch-All-Raum ist, stellen wir sicher, dass es nur einen gibt
|
||||||
|
if catch_all:
|
||||||
|
for rid, room in self._rooms.items():
|
||||||
|
if rid != room_id and room.catch_all:
|
||||||
|
# Entferne catch_all von anderen Räumen
|
||||||
|
room.catch_all = False
|
||||||
|
|
||||||
|
def reload(self, path: Optional[Path] = None) -> None:
|
||||||
|
"""Lädt room-map.json neu von Disk.
|
||||||
|
|
||||||
|
Aktualisiert die In-Memory-Repräsentation.
|
||||||
|
Kein Gateway-Neustart nötig.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
|
||||||
|
"""
|
||||||
|
if path is None:
|
||||||
|
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
|
||||||
|
if env_path:
|
||||||
|
path = Path(env_path)
|
||||||
|
else:
|
||||||
|
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
|
||||||
|
|
||||||
|
if path.exists():
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
# Parse die neue Daten und aktualisiere die Instanz
|
||||||
|
new_map = self._from_dict(data)
|
||||||
|
self._rooms = new_map._rooms
|
||||||
|
self._excluded_room_ids = new_map._excluded_room_ids
|
||||||
|
self._fact_store_path = new_map._fact_store_path
|
||||||
|
self._version = new_map._version
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def save(room_map: 'RoomMap', path: Optional[Path] = None) -> None:
|
||||||
|
"""Speichert die RoomMap in eine JSON-Datei.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_map: Die zu speichernde RoomMap-Instanz
|
||||||
|
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
|
||||||
|
"""
|
||||||
|
if path is None:
|
||||||
|
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
|
||||||
|
if env_path:
|
||||||
|
path = Path(env_path)
|
||||||
|
else:
|
||||||
|
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
|
||||||
|
|
||||||
|
# Erstelle das Verzeichnis falls es nicht existiert
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# Konvertiere die Map in ein serialisierbares Dict
|
||||||
|
data = {
|
||||||
|
"version": room_map._version,
|
||||||
|
"rooms": {},
|
||||||
|
"excluded_rooms": list(room_map._excluded_room_ids),
|
||||||
|
"fact_store_path": str(room_map._fact_store_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
for room_id, room_entry in room_map._rooms.items():
|
||||||
|
data["rooms"][room_id] = {
|
||||||
|
"name": room_entry.name,
|
||||||
|
"theme": room_entry.theme,
|
||||||
|
"keywords": room_entry.keywords,
|
||||||
|
"catch_all": room_entry.catch_all
|
||||||
|
}
|
||||||
|
|
||||||
|
# Schreibe die Datei
|
||||||
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _from_dict(cls, data: dict) -> RoomMap:
|
||||||
|
"""Parse a deserialized map dict into a ``RoomMap`` instance."""
|
||||||
|
version = data.get("version", 1)
|
||||||
|
|
||||||
|
# Parse rooms
|
||||||
|
rooms: dict[str, RoomEntry] = {}
|
||||||
|
for room_id, room_data in data.get("rooms", {}).items():
|
||||||
|
rooms[room_id] = RoomEntry(
|
||||||
|
room_id=room_id,
|
||||||
|
name=room_data.get("name", room_id),
|
||||||
|
theme=room_data.get("theme", ""),
|
||||||
|
keywords=room_data.get("keywords", []),
|
||||||
|
catch_all=room_data.get("catch_all", False),
|
||||||
|
)
|
||||||
|
|
||||||
|
excluded = set(data.get("excluded_rooms", []))
|
||||||
|
fact_store = Path(
|
||||||
|
os.path.expanduser(data.get("fact_store_path", "~/archivar_docs"))
|
||||||
|
)
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
rooms=rooms,
|
||||||
|
excluded_room_ids=excluded,
|
||||||
|
fact_store_path=fact_store,
|
||||||
|
version=version,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Migration from Legacy Env Vars ────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _migrate_from_env_vars() -> Optional[dict]:
|
||||||
|
"""Build a temporary map dict from deprecated ARCHIVAR_*_ROOM env vars.
|
||||||
|
|
||||||
|
Logs a WARNING that the env var approach is deprecated and the user
|
||||||
|
should migrate to room-map.json.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A dict suitable for ``RoomMap._from_dict()``, or ``None`` if
|
||||||
|
no legacy env vars are set.
|
||||||
|
"""
|
||||||
|
fakt = os.getenv("ARCHIVAR_FAKT_ROOM", "").strip()
|
||||||
|
frage = os.getenv("ARCHIVAR_FRAGE_ROOM", "").strip()
|
||||||
|
alarm = os.getenv("ARCHIVAR_ALARM_ROOM", "").strip()
|
||||||
|
catchall = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip()
|
||||||
|
project_json = os.getenv("ARCHIVAR_PROJECT_ROOMS", "").strip()
|
||||||
|
|
||||||
|
has_any = any([fakt, frage, alarm, catchall, project_json])
|
||||||
|
if not has_any:
|
||||||
|
return None
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"Using deprecated ARCHIVAR_*_ROOM env vars. "
|
||||||
|
"Please migrate to room-map.json. "
|
||||||
|
"See docs/archivar-architektur.md for migration guide."
|
||||||
|
)
|
||||||
|
|
||||||
|
rooms: dict[str, dict] = {}
|
||||||
|
|
||||||
|
# Catch-all room
|
||||||
|
if catchall:
|
||||||
|
rooms[catchall] = {
|
||||||
|
"name": "Catch-All (legacy)",
|
||||||
|
"theme": "Legacy catch-all from ARCHIVAR_CATCHALL_ROOM",
|
||||||
|
"keywords": [],
|
||||||
|
"catch_all": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
# ALARM room
|
||||||
|
if alarm and alarm != catchall:
|
||||||
|
rooms[alarm] = {
|
||||||
|
"name": "ALARM Room (legacy)",
|
||||||
|
"theme": "Legacy alarm room from ARCHIVAR_ALARM_ROOM",
|
||||||
|
"keywords": ["alarm", "dringend", "sofort", "kritisch", "ausfall"],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
# FAKT room (legacy — now goes to doc_store, but keep for migration)
|
||||||
|
if fakt and fakt != catchall and fakt != alarm:
|
||||||
|
rooms[fakt] = {
|
||||||
|
"name": "FAKT Room (legacy)",
|
||||||
|
"theme": "Legacy fakt room from ARCHIVAR_FAKT_ROOM",
|
||||||
|
"keywords": ["dokumentation", "fakt", "info"],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
# FRAGE room(s)
|
||||||
|
if frage and frage != catchall:
|
||||||
|
rooms[frage] = {
|
||||||
|
"name": "FRAGE Room (legacy)",
|
||||||
|
"theme": "Legacy frage room from ARCHIVAR_FRAGE_ROOM",
|
||||||
|
"keywords": ["frage", "hilfe", "problem"],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Project-specific rooms
|
||||||
|
if project_json:
|
||||||
|
try:
|
||||||
|
projects = json.loads(project_json)
|
||||||
|
for proj_key, proj_room_id in projects.items():
|
||||||
|
if proj_room_id not in rooms:
|
||||||
|
rooms[proj_room_id] = {
|
||||||
|
"name": f"Project: {proj_key} (legacy)",
|
||||||
|
"theme": f"Legacy project room for {proj_key}",
|
||||||
|
"keywords": [proj_key],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.warning("Failed to parse ARCHIVAR_PROJECT_ROOMS JSON")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"version": 1,
|
||||||
|
"rooms": rooms,
|
||||||
|
"excluded_rooms": [],
|
||||||
|
"fact_store_path": os.path.expanduser("~/archivar_docs"),
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
"""
|
||||||
|
Routing-Logik für klassifizierte Nachrichten.
|
||||||
|
|
||||||
|
Ermittelt den Zielraum basierend auf Klassifikationsergebnis, Konfidenzschwelle
|
||||||
|
und Fallback-Strategie. Unterstützt projektspezifisches Routing für FRAGE-Kategorie
|
||||||
|
und Meta-Fragen-Erkennung.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
from .classifier import ClassificationResult, MessageClassifier
|
||||||
|
from .config import (
|
||||||
|
CONFIDENCE_THRESHOLD,
|
||||||
|
FALLBACK_KEYWORDS,
|
||||||
|
OLLAMA_CONFIG,
|
||||||
|
LLM_ROOM_PROMPT,
|
||||||
|
ROOM_MAP_PATH,
|
||||||
|
)
|
||||||
|
from .room_map import RoomMap, RoomEntry
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Meta-Fragen-Erkennung ───────────────────────────────────────────────────
|
||||||
|
# Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als
|
||||||
|
# FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind.
|
||||||
|
# Solche Nachrichten werden erkannt, aus dem Originalraum gelöscht und mit einem
|
||||||
|
# Hinweis in der Kopie versehen.
|
||||||
|
|
||||||
|
_META_PATTERNS: List[re.Pattern] = [
|
||||||
|
re.compile(r"(?:wohin|an wen|welcher raum|welchem raum|welchen raum|in welch)\s+(?:wurde|geht|ging|landet)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"warum\s+(?:wurde|ist)\s+(?:meine\s+)?(?:nachricht|frage)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:archivar|klassifi(?:zier|kation)|routing|weiterleitung)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:was|wie)\s+(?:macht|arbeitet|funktioniert)\s+(?:der\s+)?archivar",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:klasse|kategorie)\s+(?:meiner\s+)?(?:nachricht|würde|wurde)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:in welch(?:er|em|en|e)?)\s+(?:kategorie|klasse|raum)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
re.compile(r"(?:who|which room|where).*(?:message|routed|sent)",
|
||||||
|
re.IGNORECASE),
|
||||||
|
]
|
||||||
|
|
||||||
|
# ── Projekt-Keywords für FRAGE-Routing ──────────────────────────────────────
|
||||||
|
# DEPRECATED: Keywords leben jetzt in RoomEntry.keywords der room-map.json.
|
||||||
|
# Diese Liste bleibt für Abwärtskompatibilität, wird aber nicht mehr vom
|
||||||
|
# RoomRouter verwendet. Neue Installationen nutzen ausschließlich RoomMap.
|
||||||
|
|
||||||
|
_PROJECT_KEYWORDS: Dict[str, List[str]] = {
|
||||||
|
"plugin": [
|
||||||
|
"plugin", "adapter", "rocketchat", "gateway", "webhook",
|
||||||
|
"archivar", "module", "schnittstelle",
|
||||||
|
],
|
||||||
|
"lan": [
|
||||||
|
"lan", "netzwerk", "router", "switch", "vlan", "dns",
|
||||||
|
"dhcp", "ip-adresse", "subnetz", "firewall", "wlan",
|
||||||
|
"ethernet", "kabel", "patchpanel", "zugangspunkt",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RoutingDecision:
|
||||||
|
"""Entscheidung, wohin eine Nachricht weitergeleitet wird."""
|
||||||
|
|
||||||
|
category: str
|
||||||
|
"""Klassifikations-Kategorie: 'FAKT', 'FRAGE', 'ALARM'."""
|
||||||
|
|
||||||
|
target_room: str
|
||||||
|
"""Rocket.Chat Raum-ID des Zielraums."""
|
||||||
|
|
||||||
|
confidence: float
|
||||||
|
"""Konfidenz der Klassifikation (0.0–1.0)."""
|
||||||
|
|
||||||
|
is_catch_all: bool = False
|
||||||
|
"""True, wenn die Nachricht wegen zu niedriger Konfidenz an Catch-All ging."""
|
||||||
|
|
||||||
|
is_fallback: bool = False
|
||||||
|
"""True, wenn das Ergebnis aus der Keyword-Heuristik stammt (Ollama down)."""
|
||||||
|
|
||||||
|
is_meta: bool = False
|
||||||
|
"""True, wenn die Nachricht als Meta-Frage erkannt wurde."""
|
||||||
|
|
||||||
|
is_unrouteable: bool = False
|
||||||
|
"""True, wenn der Zielraum nicht in den subscribed rooms des Bots ist
|
||||||
|
und die Nachricht stattdessen im DocumentationStore abgelegt wird."""
|
||||||
|
|
||||||
|
unrouteable_reason: str = ""
|
||||||
|
"""Grund, warum kein Routing möglich war (nur bei is_unrouteable=True)."""
|
||||||
|
|
||||||
|
prefix: str = ""
|
||||||
|
"""Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK])."""
|
||||||
|
|
||||||
|
delete_original: bool = False
|
||||||
|
"""True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll."""
|
||||||
|
|
||||||
|
project: Optional[str] = None
|
||||||
|
"""Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None."""
|
||||||
|
|
||||||
|
matched_room_name: Optional[str] = None
|
||||||
|
"""Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde."""
|
||||||
|
|
||||||
|
all_scores: Dict[str, float] = field(default_factory=dict)
|
||||||
|
"""Alle Kategorie-Scores für Debugging/Logging."""
|
||||||
|
|
||||||
|
|
||||||
|
class MessageRouter:
|
||||||
|
"""Thematischer Router: Nachricht → Zielraum.
|
||||||
|
|
||||||
|
Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung.
|
||||||
|
Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch
|
||||||
|
``RoomMap`` abgelöst.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
room_map = RoomMap.load()
|
||||||
|
classifier = MessageClassifier()
|
||||||
|
await classifier.initialize()
|
||||||
|
|
||||||
|
router = MessageRouter(room_map, classifier)
|
||||||
|
router.set_subscribed_room_ids(["6a19...", "6a1f..."])
|
||||||
|
decision = await router.route("Wie konfiguriere ich das Plugin?", "6a1f...")
|
||||||
|
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin)
|
||||||
|
# decision.matched_room_name → "#Rocketchat-Plugin"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
room_map: RoomMap,
|
||||||
|
classifier: MessageClassifier,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
room_map: A loaded and validated ``RoomMap`` instance.
|
||||||
|
classifier: An (initialized) ``MessageClassifier``.
|
||||||
|
"""
|
||||||
|
self._room_map = room_map
|
||||||
|
self._classifier = classifier
|
||||||
|
self._confidence_threshold = CONFIDENCE_THRESHOLD
|
||||||
|
self._subscribed_room_ids: Optional[set] = None
|
||||||
|
|
||||||
|
# ── Public API ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
|
||||||
|
"""Klassifiziere und route eine Nachricht.
|
||||||
|
|
||||||
|
Der vollständige Routing-Flow:
|
||||||
|
1. origin_room_id in excluded_rooms? → IGNORE (silent)
|
||||||
|
2. Keyword-Match in RoomEntry.keywords → Zielraum
|
||||||
|
3. Keyword-Override-Match → Override-Raum (höchste Prio)
|
||||||
|
4. Embedding-Klassifikation via Classifier
|
||||||
|
5. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?")
|
||||||
|
6. Kein Treffer → catch_all_room
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RoutingDecision mit Zielraum, Kategorie und Metadaten.
|
||||||
|
"""
|
||||||
|
if not text or not text.strip():
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=0.0,
|
||||||
|
is_catch_all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
text = text.strip()
|
||||||
|
|
||||||
|
# ── Schritt 0: Excluded rooms check ──────────────────────────
|
||||||
|
if origin_room_id and self._room_map.is_excluded(origin_room_id):
|
||||||
|
logger.debug(
|
||||||
|
"Message from excluded room %s — ignoring", origin_room_id[:8]
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=0.0,
|
||||||
|
is_catch_all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 1: Meta-Fragen-Erkennung ──────────────────────────
|
||||||
|
if self._is_meta_question(text):
|
||||||
|
logger.info("Meta-question detected: %.80s...", text)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FRAGE",
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=1.0,
|
||||||
|
is_meta=True,
|
||||||
|
delete_original=True,
|
||||||
|
prefix="[META-FRAGE] ",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 1.5: Keyword-Match (aus RoomMap) ──────────────────
|
||||||
|
matched_room = self._room_map.find_room_by_keywords(text)
|
||||||
|
if matched_room is not None:
|
||||||
|
logger.debug(
|
||||||
|
"Keyword match: '%s' → %s", text[:80], matched_room.name
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="FRAGE",
|
||||||
|
target_room=matched_room.room_id,
|
||||||
|
confidence=0.95,
|
||||||
|
matched_room_name=matched_room.name,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 2: Embedding-basierte Klassifikation ───────────────
|
||||||
|
result: Optional[ClassificationResult] = None
|
||||||
|
|
||||||
|
if self._classifier.is_initialized:
|
||||||
|
result = await self._classifier.classify(text)
|
||||||
|
|
||||||
|
# ── Schritt 3: Fallback bei Classifier-Versagen ────────────────
|
||||||
|
if result is None:
|
||||||
|
logger.info(
|
||||||
|
"Classifier unavailable — using keyword fallback for: %.80s...",
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
category, is_fallback = self._keyword_classify(text)
|
||||||
|
return RoutingDecision(
|
||||||
|
category=category,
|
||||||
|
target_room=self._resolve_room(category),
|
||||||
|
confidence=0.0,
|
||||||
|
is_fallback=is_fallback,
|
||||||
|
prefix="[FALLBACK] " if is_fallback else "",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 4: Konfidenz-Prüfung ───────────────────────────────
|
||||||
|
if not result.is_confident(self._confidence_threshold):
|
||||||
|
logger.debug(
|
||||||
|
"Low confidence (%.3f < %.1f) for category '%s' — routing to catch-all",
|
||||||
|
result.confidence, self._confidence_threshold, result.category,
|
||||||
|
)
|
||||||
|
return RoutingDecision(
|
||||||
|
category=result.category,
|
||||||
|
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||||
|
confidence=result.confidence,
|
||||||
|
is_catch_all=True,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Schritt 5: FAKT = Dokumentation, niemals Kommunikation ────
|
||||||
|
if result.category == "FAKT":
|
||||||
|
decision = RoutingDecision(
|
||||||
|
category="FAKT",
|
||||||
|
target_room="", # No room — goes to doc_store
|
||||||
|
confidence=result.confidence,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
)
|
||||||
|
decision.is_unrouteable = True
|
||||||
|
decision.unrouteable_reason = (
|
||||||
|
"FAKT messages are documentation, not communication — "
|
||||||
|
"stored in doc_store, never forwarded to chat rooms"
|
||||||
|
)
|
||||||
|
logger.info("FAKT → doc_store: %.80s...", text)
|
||||||
|
return decision
|
||||||
|
|
||||||
|
# ── Schritt 6: LLM-Room-Lookup (für FRAGE) ────────────────────
|
||||||
|
if result.category == "FRAGE":
|
||||||
|
llm_room = self._llm_room_lookup(text)
|
||||||
|
if llm_room is not None:
|
||||||
|
target_room = llm_room.room_id
|
||||||
|
matched_name = llm_room.name
|
||||||
|
else:
|
||||||
|
target_room = self._resolve_room("FRAGE")
|
||||||
|
matched_name = None
|
||||||
|
|
||||||
|
decision = RoutingDecision(
|
||||||
|
category="FRAGE",
|
||||||
|
target_room=target_room,
|
||||||
|
confidence=result.confidence,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
matched_room_name=matched_name,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# ALARM → catch_all_room (Admin-DM)
|
||||||
|
decision = RoutingDecision(
|
||||||
|
category=result.category,
|
||||||
|
target_room=self._resolve_room(result.category),
|
||||||
|
confidence=result.confidence,
|
||||||
|
all_scores=result.all_scores,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Subscription-Validierung ──────────────────────────────────
|
||||||
|
self._check_unrouteable(decision)
|
||||||
|
return decision
|
||||||
|
|
||||||
|
def _check_unrouteable(self, decision: RoutingDecision) -> None:
|
||||||
|
"""Validate target_room against subscribed IDs.
|
||||||
|
|
||||||
|
If the target room is not in the bot's subscription list, mark the
|
||||||
|
decision as unrouteable so the caller can store the message in the
|
||||||
|
DocumentationStore instead of forwarding it.
|
||||||
|
"""
|
||||||
|
reason = self._validate_target_room(decision.category, decision.target_room)
|
||||||
|
if reason:
|
||||||
|
decision.is_unrouteable = True
|
||||||
|
decision.unrouteable_reason = reason
|
||||||
|
logger.warning(
|
||||||
|
"Unrouteable [%s]: %s", decision.category, reason
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── Room Resolution ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _resolve_room(self, category: str) -> str:
|
||||||
|
"""Resolve the target room ID for a category.
|
||||||
|
|
||||||
|
Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars.
|
||||||
|
ALARM routes to catch_all_room. FRAGE uses the catch_all as fallback.
|
||||||
|
"""
|
||||||
|
catch_all = self._room_map.catch_all_room
|
||||||
|
if catch_all is None:
|
||||||
|
logger.error("No catch_all room configured — cannot route category '%s'", category)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
if category == "ALARM":
|
||||||
|
return catch_all.room_id
|
||||||
|
|
||||||
|
# For FRAGE: use catch_all as default (LLM will refine in route())
|
||||||
|
return catch_all.room_id
|
||||||
|
|
||||||
|
def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]:
|
||||||
|
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
|
||||||
|
|
||||||
|
Baut eine Raum-Liste aus der RoomMap und nutzt den LLM_ROOM_PROMPT
|
||||||
|
für kontextbasiertes Routing. Der Classifier muss LLM-fähig sein
|
||||||
|
(``ARCHIVAR_ENABLE_LLM=1``).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Der Nachrichtentext.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Den gematchten ``RoomEntry``, oder ``None`` bei Fehler/kein Match.
|
||||||
|
"""
|
||||||
|
# Build room list for LLM prompt
|
||||||
|
room_list_parts = []
|
||||||
|
for room in self._room_map.rooms.values():
|
||||||
|
if room.catch_all:
|
||||||
|
continue
|
||||||
|
room_list_parts.append(
|
||||||
|
f"- {room.name}: {room.theme} (Keywords: {', '.join(room.keywords[:5])})"
|
||||||
|
)
|
||||||
|
room_list_parts.append(
|
||||||
|
f"- CATCH_ALL: {self._room_map.catch_all_room.name if self._room_map.catch_all_room else 'Admin DM'}"
|
||||||
|
)
|
||||||
|
room_list = "\n".join(room_list_parts)
|
||||||
|
|
||||||
|
prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text)
|
||||||
|
|
||||||
|
# Try LLM classification (raw mode — expects room name, not category)
|
||||||
|
llm_result = self._classifier._llm_raw_sync(prompt)
|
||||||
|
if llm_result is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Parse LLM response — could be a room name or "CATCH_ALL"
|
||||||
|
response = llm_result.strip()
|
||||||
|
|
||||||
|
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Try to match response to a room name
|
||||||
|
response_lower = response.lower()
|
||||||
|
for room in self._room_map.rooms.values():
|
||||||
|
if response_lower == room.name.lower():
|
||||||
|
return room
|
||||||
|
if response_lower in room.name.lower():
|
||||||
|
return room
|
||||||
|
|
||||||
|
logger.debug("LLM returned unknown room: %s", response)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ── Route Validation ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
# ── Meta-Question Detection ────────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _is_meta_question(text: str) -> bool:
|
||||||
|
"""Check if a message is a meta-question about the Archivar system.
|
||||||
|
|
||||||
|
Meta-questions ask about the classification/routing system itself.
|
||||||
|
They should NOT be forwarded as regular questions.
|
||||||
|
"""
|
||||||
|
for pattern in _META_PATTERNS:
|
||||||
|
if pattern.search(text):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
# ── Fallback: Keyword-Heuristik ────────────────────────────────────
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _keyword_classify(text: str) -> Tuple[str, bool]:
|
||||||
|
"""Classify using keyword heuristics when Ollama is unavailable.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(category, is_fallback) — is_fallback is always True here.
|
||||||
|
"""
|
||||||
|
text_lower = text.lower()
|
||||||
|
|
||||||
|
# Check ALARM keywords first (highest priority)
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("ALARM", []):
|
||||||
|
if kw in text_lower:
|
||||||
|
return "ALARM", True
|
||||||
|
|
||||||
|
# Check FRAGE keywords
|
||||||
|
for kw in FALLBACK_KEYWORDS.get("FRAGE", []):
|
||||||
|
if kw in text_lower:
|
||||||
|
return "FRAGE", True
|
||||||
|
|
||||||
|
# Default: FAKT
|
||||||
|
return "FAKT", True
|
||||||
|
|
||||||
|
# ── Configuration ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def confidence_threshold(self) -> float:
|
||||||
|
"""Current confidence threshold."""
|
||||||
|
return self._confidence_threshold
|
||||||
|
|
||||||
|
def set_confidence_threshold(self, value: float) -> None:
|
||||||
|
"""Override the confidence threshold at runtime.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
value: New threshold (0.0–1.0).
|
||||||
|
"""
|
||||||
|
if not 0.0 <= value <= 1.0:
|
||||||
|
raise ValueError(f"Confidence threshold must be in [0.0, 1.0], got {value}")
|
||||||
|
self._confidence_threshold = value
|
||||||
|
logger.info("Confidence threshold set to %.2f", value)
|
||||||
|
|
||||||
|
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||||
|
"""Set the bot's current subscribed room IDs for validation.
|
||||||
|
|
||||||
|
When set, the router will ONLY route to rooms that are in this list.
|
||||||
|
Messages targeting unsubscribed rooms are marked as ``is_unrouteable``
|
||||||
|
and should be stored in the DocumentationStore instead.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_ids: List of Rocket.Chat room IDs the bot is subscribed to.
|
||||||
|
Pass None or empty list to disable validation.
|
||||||
|
"""
|
||||||
|
if room_ids:
|
||||||
|
self._subscribed_room_ids = set(room_ids)
|
||||||
|
logger.debug(
|
||||||
|
"Router subscribed IDs set: %d rooms", len(self._subscribed_room_ids)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._subscribed_room_ids = None
|
||||||
|
|
||||||
|
def _validate_target_room(self, category: str, room_id: str) -> str:
|
||||||
|
"""Validate target room against subscribed IDs.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Empty string if valid. Human-readable reason if blocked.
|
||||||
|
"""
|
||||||
|
if not room_id:
|
||||||
|
return f"no room configured for category '{category}'"
|
||||||
|
|
||||||
|
if self._subscribed_room_ids is None:
|
||||||
|
return "" # validation disabled
|
||||||
|
|
||||||
|
if room_id not in self._subscribed_room_ids:
|
||||||
|
return (
|
||||||
|
f"target room {room_id[:8]}... for category '{category}' "
|
||||||
|
f"is not in bot's subscription list "
|
||||||
|
f"({len(self._subscribed_room_ids)} subscribed rooms)"
|
||||||
|
)
|
||||||
|
|
||||||
|
return ""
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
"""Tests für die Auto-Onboarding-Funktion des Archivar-Moduls."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
# Füge das plugin-Verzeichnis zum Python-Pfad hinzu
|
||||||
|
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||||
|
|
||||||
|
from archivar.adapter_integration import ArchivarMessageHandler
|
||||||
|
from archivar.room_map import RoomMap, RoomEntry
|
||||||
|
|
||||||
|
|
||||||
|
class TestAutoOnboarding(unittest.TestCase):
|
||||||
|
"""Testfälle für die Auto-Onboarding-Funktion."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
"""Set up test fixtures before each test method."""
|
||||||
|
# Erstelle eine temporäre room-map.json für Tests
|
||||||
|
self.temp_dir = tempfile.TemporaryDirectory()
|
||||||
|
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
|
||||||
|
|
||||||
|
# Mock-Daten für die RoomMap
|
||||||
|
self.test_data = {
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {
|
||||||
|
"catchall_room_id": {
|
||||||
|
"name": "#CatchAll",
|
||||||
|
"theme": "Catch-all room for everything else",
|
||||||
|
"keywords": [],
|
||||||
|
"catch_all": True
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"excluded_rooms": [],
|
||||||
|
"fact_store_path": str(self.temp_path.parent / "docs")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Schreibe die Testdaten in die temporäre Datei
|
||||||
|
with open(self.temp_path, 'w') as f:
|
||||||
|
json.dump(self.test_data, f)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
"""Tear down test fixtures after each test method."""
|
||||||
|
self.temp_dir.cleanup()
|
||||||
|
|
||||||
|
@patch('archivar.adapter_integration.ROOM_MAP_PATH')
|
||||||
|
def test_single_room_auto_catch_all(self, mock_room_map_path):
|
||||||
|
"""Testet die Single-Room-Regel: 1 relevanter Raum → automatisch catch_all."""
|
||||||
|
mock_room_map_path.return_value = str(self.temp_path)
|
||||||
|
|
||||||
|
# Erstelle einen ArchivarMessageHandler
|
||||||
|
handler = ArchivarMessageHandler()
|
||||||
|
|
||||||
|
# Mock die _load_room_map Methode, um unsere Testdaten zu verwenden
|
||||||
|
with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(self.test_data)):
|
||||||
|
handler._room_map = handler._load_room_map()
|
||||||
|
|
||||||
|
# Simuliere subscribed_rooms mit nur einem relevanten Raum
|
||||||
|
subscribed_rooms = {
|
||||||
|
"single_room_id": {"name": "#SingleRoom", "type": "c"}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Führe die Prüfung aus
|
||||||
|
missing = handler.check_room_map_completeness(subscribed_rooms)
|
||||||
|
|
||||||
|
# Es sollten keine fehlenden Räume gemeldet werden (Single-Room-Regel)
|
||||||
|
self.assertEqual(len(missing), 0)
|
||||||
|
|
||||||
|
# Der Raum sollte automatisch als catch_all hinzugefügt worden sein
|
||||||
|
self.assertIn("single_room_id", handler._room_map.rooms)
|
||||||
|
self.assertTrue(handler._room_map.rooms["single_room_id"].catch_all)
|
||||||
|
|
||||||
|
@patch('archivar.adapter_integration.ROOM_MAP_PATH')
|
||||||
|
def test_multi_room_onboarding_triggered(self, mock_room_map_path):
|
||||||
|
"""Testet dass Onboarding bei mehreren fehlenden Räumen ausgelöst wird."""
|
||||||
|
mock_room_map_path.return_value = str(self.temp_path)
|
||||||
|
|
||||||
|
# Erstelle einen ArchivarMessageHandler
|
||||||
|
handler = ArchivarMessageHandler()
|
||||||
|
|
||||||
|
# Mock die _load_room_map Methode, um unsere Testdaten zu verwenden
|
||||||
|
with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(self.test_data)):
|
||||||
|
handler._room_map = handler._load_room_map()
|
||||||
|
|
||||||
|
# Simuliere subscribed_rooms mit mehreren relevanten Räumen
|
||||||
|
subscribed_rooms = {
|
||||||
|
"room1_id": {"name": "#Room1", "type": "c"},
|
||||||
|
"room2_id": {"name": "#Room2", "type": "p"}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Führe die Prüfung aus
|
||||||
|
missing = handler.check_room_map_completeness(subscribed_rooms)
|
||||||
|
|
||||||
|
# Es sollten 2 fehlende Räume gemeldet werden
|
||||||
|
self.assertEqual(len(missing), 2)
|
||||||
|
self.assertEqual(missing[0]["room_id"], "room1_id")
|
||||||
|
self.assertEqual(missing[1]["room_id"], "room2_id")
|
||||||
|
|
||||||
|
@patch('archivar.adapter_integration.ROOM_MAP_PATH')
|
||||||
|
def test_dm_rooms_ignored(self, mock_room_map_path):
|
||||||
|
"""Testet dass DM-Räume ignoriert werden (außer Operator-DM)."""
|
||||||
|
mock_room_map_path.return_value = str(self.temp_path)
|
||||||
|
|
||||||
|
# Erstelle einen ArchivarMessageHandler
|
||||||
|
handler = ArchivarMessageHandler()
|
||||||
|
|
||||||
|
# Mock die _load_room_map Methode, um unsere Testdaten zu verwenden
|
||||||
|
with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(self.test_data)):
|
||||||
|
handler._room_map = handler._load_room_map()
|
||||||
|
|
||||||
|
# Simuliere subscribed_rooms mit DM-Räumen
|
||||||
|
subscribed_rooms = {
|
||||||
|
"dm1_id": {"name": "DM mit Bernd", "type": "d"},
|
||||||
|
"dm2_id": {"name": "DM mit Bernd, Thomas", "type": "d"},
|
||||||
|
"channel_id": {"name": "#Channel", "type": "c"}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Führe die Prüfung aus
|
||||||
|
missing = handler.check_room_map_completeness(subscribed_rooms)
|
||||||
|
|
||||||
|
# Nur der Channel sollte als fehlend gemeldet werden, nicht die DMs
|
||||||
|
self.assertEqual(len(missing), 1)
|
||||||
|
self.assertEqual(missing[0]["room_id"], "channel_id")
|
||||||
|
|
||||||
|
@patch('archivar.adapter_integration.ROOM_MAP_PATH')
|
||||||
|
def test_map_already_complete_no_action(self, mock_room_map_path):
|
||||||
|
"""Testet dass nichts passiert wenn die Map bereits vollständig ist."""
|
||||||
|
mock_room_map_path.return_value = str(self.temp_path)
|
||||||
|
|
||||||
|
# Erstelle Testdaten mit bereits vorhandenen Räumen
|
||||||
|
test_data_with_rooms = {
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {
|
||||||
|
"catchall_room_id": {
|
||||||
|
"name": "#CatchAll",
|
||||||
|
"theme": "Catch-all room for everything else",
|
||||||
|
"keywords": [],
|
||||||
|
"catch_all": True
|
||||||
|
},
|
||||||
|
"room1_id": {
|
||||||
|
"name": "#Room1",
|
||||||
|
"theme": "First test room",
|
||||||
|
"keywords": ["test"],
|
||||||
|
"catch_all": False
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"excluded_rooms": [],
|
||||||
|
"fact_store_path": str(self.temp_path.parent / "docs")
|
||||||
|
}
|
||||||
|
|
||||||
|
# Erstelle einen ArchivarMessageHandler
|
||||||
|
handler = ArchivarMessageHandler()
|
||||||
|
|
||||||
|
# Mock die _load_room_map Methode, um unsere Testdaten zu verwenden
|
||||||
|
with patch.object(handler, '_load_room_map', return_value=RoomMap._from_dict(test_data_with_rooms)):
|
||||||
|
handler._room_map = handler._load_room_map()
|
||||||
|
|
||||||
|
# Simuliere subscribed_rooms mit Räumen, die bereits in der Map sind
|
||||||
|
subscribed_rooms = {
|
||||||
|
"room1_id": {"name": "#Room1", "type": "c"}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Führe die Prüfung aus
|
||||||
|
missing = handler.check_room_map_completeness(subscribed_rooms)
|
||||||
|
|
||||||
|
# Es sollten keine fehlenden Räume gemeldet werden
|
||||||
|
self.assertEqual(len(missing), 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,379 @@
|
|||||||
|
"""
|
||||||
|
Tests für das RoomMap-Datenmodell.
|
||||||
|
|
||||||
|
Prüft:
|
||||||
|
- Laden und Validieren von room-map.json
|
||||||
|
- Keyword-Matching
|
||||||
|
- Validierungsfehler (0/2 Catch-All, excluded_rooms)
|
||||||
|
- Legacy-Env-Var-Migration
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Ensure the archivar package is importable
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.room_map import (
|
||||||
|
RoomMap,
|
||||||
|
RoomEntry,
|
||||||
|
RoomMapValidationError,
|
||||||
|
_migrate_from_env_vars,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _make_map_json(rooms: list[dict] | None = None, excluded: list[str] | None = None) -> str:
|
||||||
|
"""Create a minimal valid room-map.json as a string."""
|
||||||
|
data: dict = {
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {},
|
||||||
|
"excluded_rooms": excluded or [],
|
||||||
|
"fact_store_path": "/tmp/test_docs",
|
||||||
|
}
|
||||||
|
for room in (rooms or []):
|
||||||
|
data["rooms"][room["room_id"]] = {
|
||||||
|
"name": room["name"],
|
||||||
|
"theme": room.get("theme", ""),
|
||||||
|
"keywords": room.get("keywords", []),
|
||||||
|
"catch_all": room.get("catch_all", False),
|
||||||
|
}
|
||||||
|
return json.dumps(data)
|
||||||
|
|
||||||
|
|
||||||
|
def _tmp_map(content: str) -> Path:
|
||||||
|
"""Write content to a temp file and return its Path."""
|
||||||
|
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
|
||||||
|
tmp.write(content)
|
||||||
|
tmp.close()
|
||||||
|
return Path(tmp.name)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Basic Loading ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapLoad:
|
||||||
|
"""RoomMap.load() — basic loading."""
|
||||||
|
|
||||||
|
def test_load_valid_map(self):
|
||||||
|
"""Load a map with 3 rooms, 1 catch-all, 1 excluded."""
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Dev", "theme": "dev room", "keywords": ["code", "bug"]},
|
||||||
|
{"room_id": "r2", "name": "#Ops", "theme": "ops room", "keywords": ["server", "docker"]},
|
||||||
|
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
excluded=["rx99"],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
rm = RoomMap.load(path)
|
||||||
|
assert rm.version == 1
|
||||||
|
assert len(rm.rooms) == 3
|
||||||
|
assert rm.catch_all_room is not None
|
||||||
|
assert rm.catch_all_room.room_id == "r3"
|
||||||
|
assert "rx99" in rm.excluded_room_ids
|
||||||
|
assert str(rm.fact_store_path) == "/tmp/test_docs"
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_load_empty_rooms(self):
|
||||||
|
"""Map with no rooms — should load but fail validation."""
|
||||||
|
json_str = _make_map_json(rooms=[])
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
rm = RoomMap.load(path)
|
||||||
|
assert len(rm.rooms) == 0
|
||||||
|
# Validation should raise
|
||||||
|
with pytest.raises(RoomMapValidationError, match="No catch_all"):
|
||||||
|
rm.validate()
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_load_file_not_found(self):
|
||||||
|
"""Missing file should raise FileNotFoundError."""
|
||||||
|
with pytest.raises(FileNotFoundError):
|
||||||
|
RoomMap.load(Path("/tmp/nonexistent_room_map_2026.json"))
|
||||||
|
|
||||||
|
|
||||||
|
# ── Keyword Matching ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapKeywords:
|
||||||
|
"""RoomMap.find_room_by_keywords() tests."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def room_map(self) -> RoomMap:
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Plugin", "theme": "plugin dev", "keywords": ["plugin", "adapter", "gateway"]},
|
||||||
|
{"room_id": "r2", "name": "#BAT", "theme": "trading", "keywords": ["bat", "trading", "docker"]},
|
||||||
|
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
return RoomMap.load(path)
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_keyword_match_plugin(self, room_map):
|
||||||
|
"""Plugin keywords should match #Plugin room."""
|
||||||
|
result = room_map.find_room_by_keywords("Das Plugin hat einen Gateway-Bug")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Plugin"
|
||||||
|
|
||||||
|
def test_keyword_match_bat(self, room_map):
|
||||||
|
"""BAT keywords should match #BAT room."""
|
||||||
|
result = room_map.find_room_by_keywords("Das Docker-Image für Trading ist kaputt")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#BAT"
|
||||||
|
|
||||||
|
def test_keyword_multiple_matches(self, room_map):
|
||||||
|
"""Most matching keywords wins."""
|
||||||
|
# "gateway" matches both Plugin and BAT, but "plugin" gives Plugin an edge
|
||||||
|
result = room_map.find_room_by_keywords("gateway plugin trading")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Plugin" # plugin + gateway = 2 vs trading = 1
|
||||||
|
|
||||||
|
def test_no_keyword_match(self, room_map):
|
||||||
|
"""No keywords should return None."""
|
||||||
|
result = room_map.find_room_by_keywords("Hallo wie gehts")
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_catch_all_never_matches_keywords(self, room_map):
|
||||||
|
"""Catch-all room has no keywords, never returned."""
|
||||||
|
result = room_map.find_room_by_keywords("irgendwas")
|
||||||
|
assert result is None # Not the catch-all
|
||||||
|
|
||||||
|
def test_keyword_case_insensitive(self, room_map):
|
||||||
|
"""Keywords are case-insensitive."""
|
||||||
|
result = room_map.find_room_by_keywords("PLUGIN ADAPTER")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Plugin"
|
||||||
|
|
||||||
|
|
||||||
|
# ── Exclusion ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapExclusion:
|
||||||
|
"""Room exclusion tests."""
|
||||||
|
|
||||||
|
def test_excluded_room(self):
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Bot-Room", "theme": "multi-agent", "keywords": []},
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
excluded=["r1"],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
rm = RoomMap.load(path)
|
||||||
|
assert rm.is_excluded("r1") is True
|
||||||
|
assert rm.is_excluded("admin") is False
|
||||||
|
assert rm.is_excluded("nonexistent") is False
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Validation ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomMapValidation:
|
||||||
|
"""RoomMap.validate() tests."""
|
||||||
|
|
||||||
|
def _load(self, rooms: list[dict], excluded: list[str] | None = None) -> RoomMap:
|
||||||
|
json_str = _make_map_json(rooms=rooms, excluded=excluded)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
return RoomMap.load(path)
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_no_catch_all(self):
|
||||||
|
"""0 catch-all rooms → RoomMapValidationError."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#A", "theme": "A"},
|
||||||
|
{"room_id": "r2", "name": "#B", "theme": "B"},
|
||||||
|
])
|
||||||
|
with pytest.raises(RoomMapValidationError, match="No catch_all"):
|
||||||
|
rm.validate()
|
||||||
|
|
||||||
|
def test_two_catch_all(self):
|
||||||
|
"""2 catch-all rooms → RoomMapValidationError."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#A", "theme": "A", "keywords": [], "catch_all": True},
|
||||||
|
{"room_id": "r2", "name": "#B", "theme": "B", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
with pytest.raises(RoomMapValidationError, match="Multiple catch_all"):
|
||||||
|
rm.validate()
|
||||||
|
|
||||||
|
def test_catch_all_in_excluded(self):
|
||||||
|
"""Catch-all in excluded_rooms → RoomMapValidationError."""
|
||||||
|
rm = self._load(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Excluded", "theme": "bad", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
excluded=["r1"],
|
||||||
|
)
|
||||||
|
with pytest.raises(RoomMapValidationError, match="excluded_rooms"):
|
||||||
|
rm.validate()
|
||||||
|
|
||||||
|
def test_valid_map_with_subscriptions(self):
|
||||||
|
"""Valid map with subscribed room IDs — no errors."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
errors = rm.validate(subscribed_ids={"r1", "admin"})
|
||||||
|
assert errors == []
|
||||||
|
|
||||||
|
def test_room_not_subscribed_warning(self):
|
||||||
|
"""Room not in subscribed_ids → non-fatal warning."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
errors = rm.validate(subscribed_ids={"admin"}) # r1 not subscribed
|
||||||
|
assert len(errors) >= 1
|
||||||
|
assert any("not in subscribed" in e for e in errors)
|
||||||
|
|
||||||
|
def test_catch_all_not_subscribed_warning(self):
|
||||||
|
"""Catch-all not in subscribed_ids → warning (not fatal)."""
|
||||||
|
rm = self._load([
|
||||||
|
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
])
|
||||||
|
errors = rm.validate(subscribed_ids={"r999"})
|
||||||
|
assert len(errors) >= 1
|
||||||
|
assert any("catch_all room" in e.lower() for e in errors)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Migration from Legacy Env Vars ─────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestMigrationFromEnvVars:
|
||||||
|
"""_migrate_from_env_vars() tests."""
|
||||||
|
|
||||||
|
def teardown_method(self):
|
||||||
|
"""Clean up env vars after each test."""
|
||||||
|
for key in list(os.environ):
|
||||||
|
if key.startswith("ARCHIVAR_"):
|
||||||
|
del os.environ[key]
|
||||||
|
|
||||||
|
def test_no_env_vars(self):
|
||||||
|
"""No legacy env vars → None."""
|
||||||
|
assert _migrate_from_env_vars() is None
|
||||||
|
|
||||||
|
def test_with_catchall_only(self):
|
||||||
|
"""ARCHIVAR_CATCHALL_ROOM set → catch-all in migrated map."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall"
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
assert "room_catchall" in result["rooms"]
|
||||||
|
assert result["rooms"]["room_catchall"]["catch_all"] is True
|
||||||
|
|
||||||
|
def test_with_multiple_rooms(self):
|
||||||
|
"""Multiple legacy vars → all rooms in migrated map."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall"
|
||||||
|
os.environ["ARCHIVAR_ALARM_ROOM"] = "room_alarm"
|
||||||
|
os.environ["ARCHIVAR_FRAGE_ROOM"] = "room_frage"
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
assert len(result["rooms"]) >= 3
|
||||||
|
|
||||||
|
def test_alarm_same_as_catchall_not_duplicated(self):
|
||||||
|
"""If ALARM_ROOM == CATCHALL_ROOM, don't create duplicate."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "same_room"
|
||||||
|
os.environ["ARCHIVAR_ALARM_ROOM"] = "same_room"
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
# Should only have one entry for "same_room" with catch_all=True
|
||||||
|
assert "same_room" in result["rooms"]
|
||||||
|
assert result["rooms"]["same_room"]["catch_all"] is True
|
||||||
|
|
||||||
|
def test_project_rooms(self):
|
||||||
|
"""ARCHIVAR_PROJECT_ROOMS JSON → project rooms in migrated map."""
|
||||||
|
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_admin"
|
||||||
|
os.environ["ARCHIVAR_PROJECT_ROOMS"] = '{"plugin": "r_plugin", "bat": "r_bat"}'
|
||||||
|
result = _migrate_from_env_vars()
|
||||||
|
assert result is not None
|
||||||
|
assert "r_plugin" in result["rooms"]
|
||||||
|
assert "r_bat" in result["rooms"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── RoomEntry ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRoomEntry:
|
||||||
|
"""RoomEntry dataclass tests."""
|
||||||
|
|
||||||
|
def test_match_score(self):
|
||||||
|
entry = RoomEntry(
|
||||||
|
room_id="r1", name="#Dev", theme="dev",
|
||||||
|
keywords=["plugin", "gateway", "adapter"],
|
||||||
|
)
|
||||||
|
assert entry.match_score("Das Plugin braucht einen Gateway-Fix") == 2
|
||||||
|
assert entry.match_score("Der Adapter ist kaputt") == 1
|
||||||
|
assert entry.match_score("Hallo Welt") == 0
|
||||||
|
|
||||||
|
def test_match_score_no_keywords(self):
|
||||||
|
entry = RoomEntry(
|
||||||
|
room_id="admin", name="DM Admin", theme="admin",
|
||||||
|
keywords=[], catch_all=True,
|
||||||
|
)
|
||||||
|
assert entry.match_score("irgendwas") == 0
|
||||||
|
|
||||||
|
def test_match_score_case_insensitive(self):
|
||||||
|
entry = RoomEntry(
|
||||||
|
room_id="r1", name="#Dev", theme="dev",
|
||||||
|
keywords=["Plugin", "GATEWAY"],
|
||||||
|
)
|
||||||
|
assert entry.match_score("plugin gateway") == 2
|
||||||
|
|
||||||
|
|
||||||
|
# ── LLM Lookup Tests ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestLLMLookup:
|
||||||
|
"""LLM-based lookup tests."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def room_map(self) -> RoomMap:
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Plugin", "theme": "plugin dev", "keywords": ["plugin", "adapter", "gateway"]},
|
||||||
|
{"room_id": "r2", "name": "#BAT", "theme": "trading", "keywords": ["bat", "trading", "docker"]},
|
||||||
|
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
try:
|
||||||
|
return RoomMap.load(path)
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_llm_lookup_route_to_plugin(self, room_map):
|
||||||
|
"""LLM should route plugin-related query to #Plugin room."""
|
||||||
|
# This simulates the LLM-based routing that would happen in router.py
|
||||||
|
# For now, we're just testing that the room map structure supports it
|
||||||
|
result = room_map.find_room_by_keywords("Wie implementiere ich einen neuen Plugin-Adapter?")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#Plugin"
|
||||||
|
|
||||||
|
def test_llm_lookup_route_to_bat(self, room_map):
|
||||||
|
"""LLM should route trading-related query to #BAT room."""
|
||||||
|
# This simulates the LLM-based routing that would happen in router.py
|
||||||
|
# For now, we're just testing that the room map structure supports it
|
||||||
|
result = room_map.find_room_by_keywords("Wie funktioniert das BAT Trading-Signal?")
|
||||||
|
assert result is not None
|
||||||
|
assert result.name == "#BAT"
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""
|
||||||
|
Integration tests für den Router.
|
||||||
|
|
||||||
|
Prüft:
|
||||||
|
- Embedding-basiertes Routing
|
||||||
|
- LLM-basiertes Fallback-Routing (simuliert)
|
||||||
|
- Integration mit room-map.json
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Ensure the archivar package is importable
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.router import MessageRouter
|
||||||
|
from plugin.archivar.room_map import RoomMap
|
||||||
|
from plugin.archivar.classifier import MessageClassifier, EmbeddingClient
|
||||||
|
|
||||||
|
|
||||||
|
# ── Mocks ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class MockEmbeddingClient(EmbeddingClient):
|
||||||
|
"""Mock embedding client for testing."""
|
||||||
|
|
||||||
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||||
|
# Return a fixed embedding vector for testing
|
||||||
|
# In a real implementation, this would call an embedding API
|
||||||
|
return [0.1] * 768 # nomic-embed-text produces 768-dimensional vectors
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
def _make_map_json(rooms: list[dict] | None = None, excluded: list[str] | None = None) -> str:
|
||||||
|
"""Create a minimal valid room-map.json as a string."""
|
||||||
|
data: dict = {
|
||||||
|
"version": 1,
|
||||||
|
"rooms": {},
|
||||||
|
"excluded_rooms": excluded or [],
|
||||||
|
"fact_store_path": "/tmp/test_docs",
|
||||||
|
}
|
||||||
|
for room in (rooms or []):
|
||||||
|
data["rooms"][room["room_id"]] = {
|
||||||
|
"name": room["name"],
|
||||||
|
"theme": room.get("theme", ""),
|
||||||
|
"keywords": room.get("keywords", []),
|
||||||
|
"catch_all": room.get("catch_all", False),
|
||||||
|
}
|
||||||
|
return json.dumps(data)
|
||||||
|
|
||||||
|
|
||||||
|
def _tmp_map(content: str) -> Path:
|
||||||
|
"""Write content to a temp file and return its Path."""
|
||||||
|
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
|
||||||
|
tmp.write(content)
|
||||||
|
tmp.close()
|
||||||
|
return Path(tmp.name)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Integration Tests ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class TestRouterIntegration:
|
||||||
|
"""MessageRouter integration tests."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def router(self) -> MessageRouter:
|
||||||
|
# Create a room map for testing
|
||||||
|
json_str = _make_map_json(
|
||||||
|
rooms=[
|
||||||
|
{"room_id": "r1", "name": "#Plugin", "theme": "plugin dev", "keywords": ["plugin", "adapter", "gateway"]},
|
||||||
|
{"room_id": "r2", "name": "#BAT", "theme": "trading", "keywords": ["bat", "trading", "docker"]},
|
||||||
|
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
path = _tmp_map(json_str)
|
||||||
|
|
||||||
|
try:
|
||||||
|
room_map = RoomMap.load(path)
|
||||||
|
# Create a mock classifier
|
||||||
|
mock_client = MockEmbeddingClient()
|
||||||
|
classifier = MessageClassifier(embedding_client=mock_client)
|
||||||
|
router = MessageRouter(room_map, classifier)
|
||||||
|
return router
|
||||||
|
finally:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def test_route_to_plugin_room(self, router):
|
||||||
|
"""Embedding-basiertes Routing sollte Plugin-Nachrichten an #Plugin senden."""
|
||||||
|
message = "Wie implementiere ich einen neuen Plugin-Adapter für Rocket.Chat?"
|
||||||
|
|
||||||
|
# For this test, we're checking that the router can be instantiated and used
|
||||||
|
# The actual routing logic is tested in room_map tests
|
||||||
|
assert router is not None
|
||||||
|
assert router._room_map is not None
|
||||||
|
|
||||||
|
def test_route_to_bat_room(self, router):
|
||||||
|
"""Embedding-basiertes Routing sollte Trading-Nachrichten an #BAT senden."""
|
||||||
|
message = "Wie funktioniert das BAT Trading-Signal und wie kann ich es optimieren?"
|
||||||
|
|
||||||
|
# For this test, we're checking that the router can be instantiated and used
|
||||||
|
# The actual routing logic is tested in room_map tests
|
||||||
|
assert router is not None
|
||||||
|
assert router._room_map is not None
|
||||||
+7
-17
@@ -1,22 +1,12 @@
|
|||||||
name: rocketchat-platform
|
name: rocketchat-platform
|
||||||
|
label: Rocket.Chat
|
||||||
kind: platform
|
kind: platform
|
||||||
version: 1.0.0
|
version: 1.0.0
|
||||||
description: >
|
description: >
|
||||||
Rocket.Chat gateway adapter for Hermes Agent.
|
Rocket.Chat gateway adapter for Hermes Agent.
|
||||||
Connects to a self-hosted Rocket.Chat server via WebSocket/DDP for
|
Connects via DDP (WebSocket) to a self-hosted Rocket.Chat server,
|
||||||
real-time message streaming and presence, and REST API for sending replies.
|
monitors subscribed rooms, and routes messages through the Hermes
|
||||||
Supports channels, private groups, and direct messages.
|
agent. Includes the Archivar classification subsystem for automatic
|
||||||
author: Hermes Community
|
message routing (FAKT → doc_store, FRAGE → project room, ALARM → DM)
|
||||||
requires_env:
|
plus Button-interaction support and file upload/download.
|
||||||
- ROCKETCHAT_BASE_URL
|
author: Entwicklerteam
|
||||||
- ROCKETCHAT_USER
|
|
||||||
- ROCKETCHAT_PASSWORD
|
|
||||||
- name: ROCKETCHAT_ROOM_ID
|
|
||||||
description: "Default room/channel ID to subscribe (optional if auto-discovery enabled)"
|
|
||||||
required: false
|
|
||||||
- name: ROCKETCHAT_ALLOW_ALL_USERS
|
|
||||||
description: "Set to 'true' to allow all users (default: false = allowlist)"
|
|
||||||
required: false
|
|
||||||
- name: ROCKETCHAT_ALLOWED_USERS
|
|
||||||
description: "Comma-separated list of allowed Rocket.Chat usernames"
|
|
||||||
required: false
|
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Hermes Agent — API key (generated by Rocket.Chat Plugin installer)
|
||||||
|
# Set OLLAMA_API_KEY env var before running install.sh --non-interactive
|
||||||
|
OLLAMA_API_KEY=PLACEH..._KEY
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Hermes Agent — minimal working configuration
|
||||||
|
# Generated by Rocket.Chat Plugin installer
|
||||||
|
# Expand with: hermes setup
|
||||||
|
|
||||||
|
model:
|
||||||
|
default: deepseek-v4-pro
|
||||||
|
provider: ollama-cloud
|
||||||
|
base_url: https://ollama.com/v1
|
||||||
|
|
||||||
|
providers: {}
|
||||||
|
|
||||||
|
toolsets:
|
||||||
|
- hermes-cli
|
||||||
|
|
||||||
|
plugins:
|
||||||
|
enabled:
|
||||||
|
- rocketchat-platform
|
||||||
|
|
||||||
|
agent:
|
||||||
|
max_turns: 90
|
||||||
|
gateway_timeout: 1800
|
||||||
|
|
||||||
|
terminal:
|
||||||
|
backend: local
|
||||||
|
|
||||||
|
display:
|
||||||
|
language: de
|
||||||
|
|
||||||
|
gateway:
|
||||||
|
enabled: true
|
||||||
|
platforms:
|
||||||
|
rocketchat:
|
||||||
|
enabled: true
|
||||||
|
extra:
|
||||||
|
base_url: PLACEHOLDER_RC_URL
|
||||||
|
home_channel:
|
||||||
|
platform: rocketchat
|
||||||
|
chat_id: PLACEHOLDER_RC_HOME
|
||||||
|
name: PLACEHOLDER_RC_HOME_NAME
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Rocket.Chat Plugin — environment file hook for hermes-gateway
|
||||||
|
# Generated by install.sh — do not edit manually
|
||||||
|
[Service]
|
||||||
|
EnvironmentFile=%h/.config/hermes/rocketchat.env
|
||||||
|
EnvironmentFile=%h/.hermes/.env
|
||||||
Reference in New Issue
Block a user