Compare commits
151 Commits
v2.1.0
...
17e6670358
| Author | SHA1 | Date | |
|---|---|---|---|
| 17e6670358 | |||
| c3a66239fd | |||
| c850ca1ba7 | |||
| 1157c73d65 | |||
| 5a9cf5f160 | |||
| 8b67e03f7e | |||
| 1ade5549b3 | |||
| 9488f44d88 | |||
| 85713a7e29 | |||
| 4f9054fea1 | |||
| 8760d29036 | |||
| 9be9e616d1 | |||
| bc7b05d768 | |||
| 6f47885b1c | |||
| 572bc89205 | |||
| 54de0d1b69 | |||
| 868ee153ac | |||
| 40563864ac | |||
| 5c8026c0f0 | |||
| 52dd470e00 | |||
| a442e42b4e | |||
| 4d6fae6bf7 | |||
| cd7fae1ad0 | |||
| ba2ba33616 | |||
| 5abab32d0f | |||
| 8e7dfa5ccb | |||
| 658f1ba8a0 | |||
| 1ad9155a24 | |||
| 4596ffba2a | |||
| 2599a574e1 | |||
| ac1751e9ce | |||
| 34087299e8 | |||
| 0e13e4b30d | |||
| d005eb769d | |||
| 97d59f5272 | |||
| 60665c5fd4 | |||
| 8d6deb7f2d | |||
| 3fe2dd832e | |||
| 27b117e151 | |||
| c590b8a53a | |||
| ea96ebbde7 | |||
| a3875f5fbf | |||
| 7776e26fb2 | |||
| d54c9a8896 | |||
| 0b4ff2169e | |||
| 03d3bb44df | |||
| 43d14b2d58 | |||
| 4fff5980c7 | |||
| 134c21a218 | |||
| 1f7054eab8 | |||
| a1fc4cc9b5 | |||
| aa50857193 | |||
| 00d6ca4e75 | |||
| 92697b5fff | |||
| 948666fcdd | |||
| 2eb723fb63 | |||
| 6e02a12431 | |||
| b05b1ab1ec | |||
| 48fb292fe0 | |||
| 1f7d09a7fd | |||
| c6b82cc33c | |||
| 80842a365e | |||
| 186308c983 | |||
| 44121da702 | |||
| 170f7e6096 | |||
| 0a7702475f | |||
| 4bb1ccbc82 | |||
| f27de836dc | |||
| 2b53537638 | |||
| 6b97ccfad9 | |||
| 9177c99088 | |||
| 017dc2b69c | |||
| 53dd436a86 | |||
| 281c2af9dd | |||
| 7e6e9fb15d | |||
| 53ffcf9b4d | |||
| 213831757a | |||
| 6eda62b94c | |||
| 6348578678 | |||
| a261c771fc | |||
| c23127c9c5 | |||
| 58749914fc | |||
| dba856ffab | |||
| b11c2c9fe7 | |||
| 87f95b818f | |||
| 5e8e9c9a9c | |||
| 92bdb396a9 | |||
| 50e7639aec | |||
| 43ef3e6a91 | |||
| e7e6b66ba2 | |||
| b21a8bec19 | |||
| 2fe574cf71 | |||
| 09c327b5a1 | |||
| 0f8dc06f15 | |||
| ffb7cafff6 | |||
| 62c996c4da | |||
| f47ffc93f4 | |||
| e7ed81c189 | |||
| 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.
|
||||
+124
-163
@@ -1,63 +1,77 @@
|
||||
# Hermes Rocket.Chat Plugin — Community Release
|
||||
# Hermes Agent × Rocket.Chat — Your AI Assistant, Now in Every Room
|
||||
|
||||
> **Nützliches Add-on für [Hermes Agent](https://hermes-agent.nousresearch.com/)**
|
||||
> Verbindet Hermes Agent mit einem selbst-gehosteten Rocket.Chat-Server.
|
||||
**Connect your Hermes Agent to a self-hosted Rocket.Chat server and talk to it from any channel, group, or DM — with native buttons, smart room routing, and file sharing.**
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ HAFTUNGSAUSSCHLUSS
|
||||
## What This Plugin Does
|
||||
|
||||
**DIESES PLUGIN WIRD OHNE JEGLICHE GEWÄHRLEISTUNG BEREITGESTELLT.**
|
||||
You run [Hermes Agent](https://github.com/NousResearch/hermes-agent) — a personal AI agent that remembers across sessions, delegates to subagents, and drives a real terminal and browser. Normally you talk to it through a CLI or TUI.
|
||||
|
||||
- Die Nutzung erfolgt **ausschließlich auf eigene Gefahr**.
|
||||
- Der Autor übernimmt **keinerlei Haftung** für Schäden, Datenverluste, Sicherheitsvorfälle, fehlerhafte Konfigurationen oder sonstige Nachteile, die aus der Installation oder Nutzung dieses Plugins entstehen können.
|
||||
- Dieses Plugin ist ein **inoffizielles Community-Projekt**. Es steht in keiner Verbindung zu Rocket.Chat (Rocket.Chat Technologies Corp.) oder Nous Research.
|
||||
- Vor dem Produktiveinsatz sind **eigene Sicherheitsprüfungen und Tests** zwingend erforderlich.
|
||||
- Das Plugin wird unter der [Unlicense](LICENSE) veröffentlicht — es kommt **wie gesehen ("as-is")**, ohne Mängelgewähr und ohne Support-Garantie.
|
||||
This plugin connects Hermes to **Rocket.Chat**, so you can talk to your agent from **any room** on your self-hosted chat server. One agent, all rooms, one memory.
|
||||
|
||||
**Wer dieses Plugin installiert oder einsetzt, erklärt sich mit diesen Bedingungen einverstanden.**
|
||||
### The Experience
|
||||
|
||||
```
|
||||
You (in #devops): "What's the status of the BAT stack?"
|
||||
Agent (in #devops): "5/5 containers UP. API :3001, Web :3003, DB healthy.
|
||||
Gateway connected to rocketchat.thomander.de."
|
||||
|
||||
You (in DM): "StartObsidian"
|
||||
Agent (in DM): "Vault clean. No new FAKT files. Last daily: 08.06.
|
||||
BAT: 5/5 UP, RC-Plugin: Archivar v3 deployed."
|
||||
|
||||
You (in #general): "Deploy the new adapter fix"
|
||||
Agent (in #general): "Dein Auftrag passt thematisch besser in #rocketchat-plugin."
|
||||
[✅Ja] [📍Hier] [📌Generell]
|
||||
```
|
||||
|
||||
The agent knows what happened in ALL rooms. It routes tasks to the right room. It asks before moving things. And you always click buttons — never type numbers.
|
||||
|
||||
---
|
||||
|
||||
## Was ist das?
|
||||
## Key Features
|
||||
|
||||
Dieses Plugin verwandelt Hermes Agent in einen **nativen Rocket.Chat-Benutzer** — mit Echtzeit-Nachrichten über das Hermes Gateway, Präsenz-Status und interaktiven Buttons.
|
||||
### 🎯 Button-Garantie (Button Guarantee)
|
||||
|
||||
**Das Besondere:** Ein einziger Agent kann in beliebig vielen Räumen gleichzeitig präsent sein — Kanäle, Gruppen, DMs — und behält trotzdem den Überblick. Inhalte landen automatisch im richtigen Raum, Themen bleiben sauber getrennt, und nichts geht im Multi-Room-Chaos unter.
|
||||
**Every user interaction uses native Rocket.Chat buttons.** No raw text input, no "type 1/2/3", no confusion.
|
||||
|
||||
- **Eingehend**: WebSocket/DDP (`stream-room-messages`) für sofortige Nachrichten
|
||||
- **Ausgehend**: REST-API für Antworten, Buttons, Dateien
|
||||
- **Gateway-nativ**: Registriert sich als `rocketchat-platform` im Hermes Gateway — kein Standalone-Daemon mehr
|
||||
- **Multi-Room-fähig**: Ein Agent-Session für alle Räume mit geteiltem Kontext
|
||||
- Built-in templates: Yes/No, Confirm/Cancel, OK, Multi-Choice
|
||||
- Custom buttons with emoji labels: `✅Ja`, `❌Nein`, `🟡Später`
|
||||
- Structured payloads: `question_id::choice` — the agent always knows what you clicked
|
||||
- REST-first: native buttons always tried first; text fallback only on HTTP error
|
||||
|
||||
### 🧭 Smart Room Routing (Archivar v4)
|
||||
|
||||
The agent understands **where messages belong** — and routes them there, with your permission.
|
||||
|
||||
- **2-stage pipeline:** Embedding pre-filter (nomic-embed-text, <100ms) → LLM room router (qwen2.5:7b, ~2.4s)
|
||||
- **LLM-based room router** — The LLM receives the full message + room list with keywords and returns the target room ID directly. No intent categories, no fuzzy matching.
|
||||
- **Keywords as anchors** — Room-specific keywords in the LLM prompt give precise hints. "RC" at the end of a sentence is recognized.
|
||||
- **Move-Requests with buttons:** When a task belongs elsewhere, you get ✅Ja / 📍Hier — clickable options, never text prompts
|
||||
- **Zero token cost for routing** — The entire routing process runs on local models. Your primary LLM never spends tokens on figuring out where to reply.
|
||||
- **Timeout & fallback:** 10s LLM timeout → automatic CATCH_ALL. **No answer is not an option.**
|
||||
- **Butler principle:** The agent suggests, you decide. Nothing is silently rerouted.
|
||||
|
||||
### 🆕 Auto-Onboarding
|
||||
|
||||
Add the bot to a new room and it introduces itself, asks for a room name and topic, and configures routing automatically. No manual config files.
|
||||
|
||||
### 📚 Knowledge Integration
|
||||
|
||||
Pure facts and documentation are automatically saved to your Obsidian Vault — not dumped in chat rooms. Your morning `StartObsidian` routine processes them into themed documents.
|
||||
|
||||
### 📎 File Attachments
|
||||
|
||||
Upload files to rooms, download files users attach, browse room file lists — all with native Rocket.Chat rendering.
|
||||
|
||||
### 🌐 Multi-Room, One Memory
|
||||
|
||||
The agent maintains a single context across all rooms. Knowledge from `#devops` is available in `#general`. You never have to re-explain.
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | Beschreibung |
|
||||
|---------|-------------|
|
||||
| 🚀 Echtzeit-Streaming | DDP/WebSocket für instant eingehende Nachrichten |
|
||||
| 🟢 Präsenz | Grüner Online-Status im Rocket.Chat |
|
||||
| 🌐 Multi-Room | Ein Agent über alle Räume — Kanäle, Gruppen, DMs. Geteilter Kontext, kein Kontext-Verlust beim Raumwechsel |
|
||||
| 🧭 Smart Room Routing | Der Agent lernt beim ersten Start, welche Themen in welchen Raum gehören. Kein manuelles Konfigurieren — ein kurzes Interview, danach landet alles automatisch am richtigen Ort |
|
||||
| ✍️ Markdown | Fett, kursiv, `Code`, Blöcke, Links |
|
||||
| 🔘 Interaktive Buttons | Ja/Nein, Bestätigen/Abbrechen, Mehrfachauswahl |
|
||||
| 🔌 7 REST-Tools | `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send`, `rocketchat_upload`, `rocketchat_download`, `rocketchat_files` |
|
||||
| 📎 Datei-Anhänge | Upload, Download, Datei-Listing — nativ im Rocket.Chat gerendert |
|
||||
| 🌍 Bilingual | Installer auf Deutsch & Englisch (`--lang de|en`), Agent erkennt Systemsprache automatisch |
|
||||
| 📦 Zero-Dependency | Nutzt ausschließlich Python-Standardbibliothek |
|
||||
|
||||
---
|
||||
|
||||
## Schnellstart
|
||||
|
||||
### 1. Voraussetzungen
|
||||
|
||||
- Hermes Agent installiert ([Setup-Guide](https://hermes-agent.nousresearch.com/docs))
|
||||
- Laufender Rocket.Chat-Server (v5+ empfohlen)
|
||||
- Bot-Benutzer auf Rocket.Chat mit Login-Daten
|
||||
|
||||
### 2. Plugin herunterladen & installieren
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
git clone https://gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin.git
|
||||
@@ -65,147 +79,94 @@ cd Hermes_rocket.chat_Plugin
|
||||
./install.sh
|
||||
```
|
||||
|
||||
Der Installer führt interaktiv durch:
|
||||
- Rocket.Chat Server URL
|
||||
- **Bot Username** (der Bot-Account auf dem Server)
|
||||
- Bot Passwort
|
||||
- Home Channel (Name oder ID)
|
||||
The installer walks you through:
|
||||
1. Rocket.Chat server URL
|
||||
2. Bot username and password
|
||||
3. Home channel
|
||||
|
||||
Bei bestehender Installation werden alle Werte angezeigt und können bestätigt (ENTER) oder geändert werden.
|
||||
|
||||
**Optionen:**
|
||||
**That's it.** The gateway restarts, the bot appears online (green dot), and you can start talking.
|
||||
|
||||
```bash
|
||||
./install.sh --help # Alle Optionen anzeigen
|
||||
./install.sh --lang en # Englisch
|
||||
./install.sh --lang de # Deutsch (Standard)
|
||||
./install.sh --non-interactive # Batch-Mode (RC_URL, RC_BOT_USER, RC_BOT_PASS, RC_HOME_CHANNEL)
|
||||
```
|
||||
# Update without reconfiguring
|
||||
./install.sh --update-only
|
||||
|
||||
### 3. Pairing
|
||||
|
||||
Nach der Installation gibt der Gateway einen **Pairing-Code** aus. Diesen im Home-Channel eingeben, um den Bot zu aktivieren. (Identisch zum Telegram-Integrations-Pattern.)
|
||||
|
||||
---
|
||||
|
||||
## Architektur
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌─────────────────┐
|
||||
│ Hermes Agent│ Hermes Gateway │ Rocket.Chat │
|
||||
│ (Plugin) │◄── DDP/WebSocket ──────►│ Server │
|
||||
│ │◄── REST API ──────►│ (v5+) │
|
||||
└─────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
**Plugin-Dateien:**
|
||||
|
||||
| Datei | Größe | Funktion |
|
||||
|-------|-------|----------|
|
||||
| `plugin/adapter.py` | ~27 KB | DDP-Client, Session-Handling, Nachrichten-Parsing, Reconnect, Button-Rendering |
|
||||
| `plugin/__init__.py` | ~4,5 KB | Plugin-Registrierung, Interaction Templates |
|
||||
| `plugin/tools.py` | ~43 KB | 7 Rocket.Chat REST-Tools für Agent-Kontext |
|
||||
| `plugin/plugin.yaml` | 0,8 KB | Metadaten, Env-Vars |
|
||||
|
||||
---
|
||||
|
||||
## Button-Templates
|
||||
|
||||
| Template | Nutzung |
|
||||
|----------|---------|
|
||||
| `yes_no` | ✅ Ja / ❌ Nein |
|
||||
| `confirm_cancel` | ✅ Bestätigen / 🚫 Abbrechen |
|
||||
| `ok` | 👍 OK |
|
||||
| `multi_choice_3` | 1. Links / 2. Rechts / 3. Zwei Runden |
|
||||
| `custom` | Beliebige Labels via `custom_buttons` |
|
||||
|
||||
**Button-Label-Regeln:**
|
||||
- Desktop-App schneidet bei **~5–7 Zeichen** ab
|
||||
- **NIEMALS Underscores (`_`)** in Button-Texten — zerstört Rendering
|
||||
- Leerzeichen sind erlaubt: `1. Links`
|
||||
- Pattern: Lange Optionen im Text, Buttons mit Kurzreferenz (`1. Links`, `2. Rechts`)
|
||||
|
||||
Details: [docs/BUTTON_GUIDE.md](docs/BUTTON_GUIDE.md)
|
||||
|
||||
---
|
||||
|
||||
## Konfiguration (Referenz)
|
||||
|
||||
`install.sh` schreibt automatisch. Manuelle Referenz:
|
||||
|
||||
```yaml
|
||||
# ~/.hermes/config.yaml
|
||||
plugins:
|
||||
enabled:
|
||||
- rocketchat-platform
|
||||
|
||||
gateway:
|
||||
platforms:
|
||||
rocketchat:
|
||||
enabled: true
|
||||
extra:
|
||||
base_url: "https://rocketchat.example.com"
|
||||
home_channel:
|
||||
platform: rocketchat
|
||||
chat_id: "69f4e..."
|
||||
name: "ki-assistent"
|
||||
|
||||
toolsets:
|
||||
- rocketchat
|
||||
```
|
||||
|
||||
```bash
|
||||
# ~/.config/hermes/rocketchat.env (chmod 600)
|
||||
ROCKETCHAT_BASE_URL=https://rocketchat.example.com
|
||||
ROCKETCHAT_USER=botuser
|
||||
ROCKETCHAT_PASSWORD=...
|
||||
ROCKETCHAT_ALLOW_ALL_USERS=true
|
||||
GATEWAY_ALLOW_ALL_USERS=true
|
||||
# Non-interactive (CI/CD, scripts)
|
||||
./install.sh --non-interactive
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Aktueller Status
|
||||
## Requirements
|
||||
|
||||
- **Version**: 2.3.0
|
||||
- **Stabilität**: Produktiv im Einsatz (seit Mai 2026)
|
||||
- **Getestet mit**: Rocket.Chat v5.x, Hermes Agent Gateway
|
||||
- **Lizenz**: [Unlicense](LICENSE) — Public Domain
|
||||
- **Hermes Agent** installed and running
|
||||
- **Self-hosted Rocket.Chat** (v5+)
|
||||
- A **bot user account** on your Rocket.Chat server
|
||||
- Python 3.10+ (comes with Hermes)
|
||||
|
||||
**Optional but recommended:**
|
||||
- `nomic-embed-text` via Ollama — enables embedding-based room routing
|
||||
- `qwen2.5:7b` via Ollama — enables LLM-based routing for borderline cases
|
||||
|
||||
---
|
||||
|
||||
## Changelog
|
||||
## Why This Exists
|
||||
|
||||
### v2.3.0 (30. Mai 2026)
|
||||
- **Attachment-Tools:** `rocketchat_upload`, `rocketchat_download`, `rocketchat_files`
|
||||
- **Upload-Fix:** 2-Step-Flow für RC 8.4.1 — `rooms.media` + `chat.postMessage` mit `title_link`
|
||||
- **DDP-Adapter:** Erkennt eingehende Attachments automatisch (`file`/`attachments` im Event)
|
||||
Hermes Agent is powerful — but the CLI isn't where conversations happen. Teams live in Rocket.Chat. This plugin brings your AI assistant to where you already are.
|
||||
|
||||
### v2.2.0 (30. Mai 2026)
|
||||
- **Room Topic Discipline:** Agent trennt Inhalte strikt nach Raum-Thema
|
||||
- **Catch-All-Raum:** Interaktive Erstinitialisierung bei >1 Raum
|
||||
**Use cases:**
|
||||
- **DevOps team:** Ask the agent for container status, deploy fixes, check logs — from your team channel
|
||||
- **Personal assistant:** Morning briefing (`StartObsidian`), knowledge capture, task routing
|
||||
- **Project management:** Multi-room coordination — the agent knows what's happening across all project channels
|
||||
- **Self-hosted everything:** No cloud dependencies. Your agent, your chat server, your data.
|
||||
|
||||
### v2.1.0 (29. Mai 2026)
|
||||
- **Cross-Room Session Sharing:** Ein Agent über alle Räume, gemeinsamer Kontext. Zero Core Changes — rein plugin-basiert
|
||||
---
|
||||
|
||||
### v2.0.0 (Mai 2026)
|
||||
- Gateway-natives Plugin (kein Standalone-Daemon mehr)
|
||||
- `tools.py`: 4 Rocket.Chat REST-Tools für Agent-Kontext
|
||||
- Neuer bilingualer `install.sh` (DE/EN, `--help`, `--non-interactive`, Re-Install-Erkennung)
|
||||
- "Bot Username"-Prompt statt "Username"
|
||||
- `BasePlatformAdapter`-Vererbung, DDP `added`-Events, case-insensitive Filter
|
||||
## Current Status
|
||||
|
||||
### v1.0.0 (Mai 2026)
|
||||
- Initialer Standalone-Daemon-Release
|
||||
**Active development — production-ready core, expanding features.**
|
||||
|
||||
| Feature | Status |
|
||||
|---------|--------|
|
||||
| Real-time DDP messaging | ✅ Stable |
|
||||
| 7 REST API tools | ✅ Stable |
|
||||
| Interactive buttons | ✅ Stable |
|
||||
| Button-Garantie | ✅ Enforced |
|
||||
| Archivar v4 room routing | ✅ Deployed (2026-06-14) |
|
||||
| Auto-onboarding | ✅ Stable |
|
||||
| FAKT → Obsidian Vault | ✅ Stable |
|
||||
| File upload/download/list | ✅ Stable |
|
||||
| `install.sh` one-click setup | ✅ Stable |
|
||||
|
||||
**In progress:** `install.sh` deployment path alignment.
|
||||
|
||||
---
|
||||
|
||||
## Links
|
||||
|
||||
- **Hermes Agent**: https://hermes-agent.nousresearch.com/
|
||||
- **Rocket.Chat**: https://www.rocket.chat/
|
||||
- **Dieses Repo**: https://gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin
|
||||
- **Repository:** [gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin](https://gitea.myowntools.org/andreas/Hermes_rocket.chat_Plugin)
|
||||
- **Hermes Agent:** [github.com/NousResearch/hermes-agent](https://github.com/NousResearch/hermes-agent)
|
||||
- **Rocket.Chat:** [rocket.chat](https://rocket.chat)
|
||||
- **License:** Public Domain (Unlicense)
|
||||
|
||||
---
|
||||
|
||||
> *Erstellt von der Hermes Agent Community — für die Rocket.Chat Community.*
|
||||
## FAQ
|
||||
|
||||
**Q: Does this work with Rocket.Chat SaaS (cloud.rocket.chat)?**
|
||||
A: It's designed for self-hosted instances. SaaS may work but hasn't been tested — the plugin needs WebSocket/DDP access which SaaS tiers may restrict.
|
||||
|
||||
**Q: Can multiple users talk to the same bot?**
|
||||
A: Yes — the bot listens in all subscribed rooms. One agent session handles all users. Each user's rooms are collapsed into a virtual `user:username` session so the agent maintains per-user context.
|
||||
|
||||
**Q: Does the bot need admin permissions?**
|
||||
A: No. A regular user with `bot` role is sufficient. The bot needs `create-d`, `create-p`, and `upload-file` permissions (standard for bot role).
|
||||
|
||||
**Q: What happens if the gateway restarts?**
|
||||
A: The bot reconnects automatically. The room-map.json persists. There's a known Discovery Bug where Rocket.Chat may not reconnect after SIGTERM — workaround is clearing state files before restart. The Archivar v4 initializes immediately after reconnect with the operating stage log: `Archivar Stufe 1: Embedding-Vorfilter + LLM-Raum-Router aktiv (5 Räume)`.
|
||||
|
||||
**Q: Is this an official Nous Research product?**
|
||||
A: No — it's a community plugin maintained independently. Public Domain license.
|
||||
|
||||
---
|
||||
|
||||
*Built with ❤️ for the self-hosting community. Zero external dependencies. Pure Python + WebSocket.*
|
||||
|
||||
@@ -6,18 +6,67 @@
|
||||
**⚠️ Community Add-on — not an official Nous Research product.**
|
||||
This plugin is maintained independently. Use at your own risk. See [LICENSE](LICENSE).
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
### Core Messaging
|
||||
- 🟢 **Real-time messaging** via DDP/WebSocket (`stream-room-messages`)
|
||||
- 💬 **Interactive buttons** — Native Rocket.Chat attachments with `question_id::choice` correlation
|
||||
- 🔌 **7 REST tools** — `rocketchat_rooms`, `rocketchat_users`, `rocketchat_dm`, `rocketchat_send`, `rocketchat_upload`, `rocketchat_download`, `rocketchat_files`
|
||||
- 🧭 **Smart Room Routing** — Automatically learns which topics belong in which rooms. Keeps conversations organized across channels, groups, and DMs. One agent, many rooms, zero confusion.
|
||||
- 📎 **File Attachments** — Upload, download, and list files with native Rocket.Chat rendering
|
||||
- 🌐 **Multi-Room Presence** — One agent session across all rooms. Shared context, clean delivery.
|
||||
- 🟢 **Online presence** — Green dot via DDP `UserPresence`
|
||||
- ♻️ **Auto-reconnect** with exponential backoff
|
||||
- 🌍 **Bilingual installer** — German & English (`--lang de|en`)
|
||||
|
||||
### Interactive Buttons (Button-Garantie)
|
||||
- 💬 **Native Rocket.Chat Action Buttons** — All user interactions use clickable buttons, never raw text input
|
||||
- 🎯 **Button-Garantie (Button Guarantee):** REST-Path first, text fallback only on HTTP error. Every clarify prompt, every move request, every multi-choice question uses native buttons
|
||||
- 📋 **Built-in templates:** `yes_no`, `confirm_cancel`, `ok`, `multi_choice_3`, `custom`
|
||||
- 🔗 **`question_id::choice` correlation** — Button clicks return structured payloads the agent can resolve
|
||||
- 📏 **Desktop-safe labels** — Emoji+text pattern (✅Ja, ❌Nein) with ~7 char truncation awareness
|
||||
|
||||
### Smart Room Routing (Archivar v4)
|
||||
- 🧭 **LLM-based room router** — Determines the TARGET ROOM directly, not an intent category. The LLM receives the full message text + room list with keywords and returns the room ID.
|
||||
- ⚡ **2-stage pipeline:** Embedding pre-filter (nomic-embed-text, <100ms) → LLM room router (qwen2.5:7b, ~2.4s median)
|
||||
- 🎯 **Keywords as anchors** — Room-specific keywords in the LLM prompt give precise hints. "RC" at the end of a sentence is recognized.
|
||||
- 🛡️ **Butler principle** — Before routing: Move-Request button (✅Ja / 📍Hier). The human decides, never the machine.
|
||||
- 💰 **Zero DeepSeek tokens for routing** — The entire routing process runs on local models (nomic-embed-text + qwen2.5:7b). DeepSeek only receives the final answer context.
|
||||
- ⏱️ **Timeout & fallback:** 10s LLM timeout (covers cold starts up to 7.8s). Fallback: CATCH_ALL room. **No answer is not an option.**
|
||||
- 🏠 **Catch-All room** — Unclassified messages land in a designated fallback room, not lost
|
||||
- 📊 **Operating stage log:** `Archivar Stufe 1: Embedding-Vorfilter + LLM-Raum-Router aktiv (5 Räume)`
|
||||
|
||||
### Auto-Onboarding
|
||||
- 🆕 **New rooms auto-detected** — When the bot is added to a new channel/group/DM, it starts an onboarding interview
|
||||
- 📝 **Room-map.json** — Persistent room configuration (names, topics, keywords, sticky status)
|
||||
- 🔑 **`#Name =` parser** — Users set room names inline during onboarding
|
||||
|
||||
### Knowledge Integration (FAKT)
|
||||
- 📚 **FAKT → Obsidian Vault** — Pure facts (documentation, not communication) are automatically saved to the user's Obsidian Vault inbox
|
||||
- 🗂️ **`StartObsidian` workflow** — Morning routine processes FAKT files into themed documents via WikiLinks
|
||||
- 🚫 **No chat-room pollution** — Facts never appear in chat rooms; they go straight to the knowledge base
|
||||
|
||||
### File Attachments
|
||||
- 📎 **Upload** (`rocketchat_upload`) — Send files to any room with native Rocket.Chat rendering
|
||||
- 📥 **Download** (`rocketchat_download`) — Retrieve files users attach to messages
|
||||
- 📋 **List** (`rocketchat_files`) — Browse all files in a room
|
||||
|
||||
### REST Tools (7 total)
|
||||
| Tool | Function |
|
||||
|------|----------|
|
||||
| `rocketchat_rooms` | List, create, archive, delete rooms; invite/kick users; fetch history |
|
||||
| `rocketchat_users` | List all users, get user info, search by name |
|
||||
| `rocketchat_dm` | Open or send direct messages |
|
||||
| `rocketchat_send` | Send messages with optional interactive buttons |
|
||||
| `rocketchat_upload` | Upload files with message and description |
|
||||
| `rocketchat_download` | Download files by ID |
|
||||
| `rocketchat_files` | List files in a room with pagination |
|
||||
|
||||
### Multi-Room Architecture
|
||||
- 🌐 **One agent, all rooms, one memory** — The agent maintains a single context across all subscribed rooms
|
||||
- 🧠 **Shared session** — Knowledge from one room is available in all others
|
||||
- 🎯 **Virtual chat IDs** — `user:alice` collapses all of Alice's rooms into one Hermes session
|
||||
- 🔀 **Butler principle** — The agent suggests, the human decides. Nothing is silently rerouted
|
||||
|
||||
---
|
||||
|
||||
## Quick Install
|
||||
|
||||
```bash
|
||||
@@ -41,23 +90,38 @@ The installer will ask for:
|
||||
./install.sh --lang en # English
|
||||
./install.sh --lang de # German (default)
|
||||
./install.sh --non-interactive # Batch mode (reads from env vars)
|
||||
./install.sh --update-only # Update plugin files without reconfiguring
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Rocket.Chat Server
|
||||
↕ WebSocket/DDP + REST
|
||||
Hermes Gateway (plugin)
|
||||
├── adapter.py — DDP client, message routing, button handling
|
||||
├── __init__.py — Plugin registration, button builders
|
||||
├── tools.py — 7 REST API tools
|
||||
└── archivar/ — Smart room routing subsystem
|
||||
├── classifier.py — Embedding pre-filter (nomic-embed-text)
|
||||
├── router.py — LLM-based room router (qwen2.5:7b)
|
||||
├── config.py — LLM_ROOM_PROMPT, thresholds, room-map
|
||||
├── room_map.py — Room-map.json loader + keyword matching
|
||||
├── doc_store.py — FAKT → Obsidian Vault integration
|
||||
└── adapter_integration.py — Archivar ↔ Adapter bridge
|
||||
↕
|
||||
Hermes Agent ← → LLM inference
|
||||
```
|
||||
|
||||
The plugin registers as `rocketchat-platform` in Hermes' bundled plugin path (`hermes-agent/plugins/platforms/rocketchat/`).
|
||||
The plugin registers as `rocketchat-platform` in Hermes' plugin path. **Deployment note:** The gateway loads from `~/.hermes/hermes-agent/plugins/platforms/rocketchat/`. The `install.sh` copies files there. A secondary path at `/usr/local/lib/hermes-agent/plugins/platforms/rocketchat/` exists for system-wide installs but is not the active path for user-level gateway runs.
|
||||
|
||||
---
|
||||
|
||||
## Interactive Buttons
|
||||
|
||||
The plugin supports native Rocket.Chat buttons. The agent sends them via `send_message` with metadata:
|
||||
The plugin supports native Rocket.Chat Action Buttons. The agent sends them via `send_message` with metadata:
|
||||
|
||||
```python
|
||||
send_message(
|
||||
@@ -67,40 +131,152 @@ send_message(
|
||||
"template": "custom",
|
||||
"question_id": "confirm_42",
|
||||
"button_title": "Choose:",
|
||||
"custom_buttons": ["✅ Yes", "❌ No"]
|
||||
"custom_buttons": ["✅Ja", "❌Nein"]
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
User click returns: `confirm_42::✅ Yes`
|
||||
User click returns: `confirm_42::✅Ja`
|
||||
|
||||
**Button label rules:**
|
||||
- Max ~7 visible characters on desktop (mobile shows full text)
|
||||
- **NO underscores** — breaks Rocket.Chat rendering
|
||||
- Spaces allowed: `1. Left`, `2. Right`
|
||||
- Prefix with number/keyword for distinguishability
|
||||
### Built-in Templates
|
||||
|
||||
| Template | Buttons | Use Case |
|
||||
|----------|---------|----------|
|
||||
| `yes_no` | ✅Ja / ❌Nein | Binary decisions |
|
||||
| `confirm_cancel` | ✅Bestätigen / 🚫Abbrechen | Destructive actions |
|
||||
| `ok` | 👍OK | Acknowledgement |
|
||||
| `multi_choice_3` | 1. Links / 2. Rechts / 3. Zwei Runden | Directional choices |
|
||||
| `custom` | User-defined | Any multi-choice scenario |
|
||||
|
||||
### Button Label Rules
|
||||
|
||||
1. **NO underscores (`_`)** — destroys button rendering completely
|
||||
2. **Desktop truncation at ~7 chars** — first 7 characters must be distinguishable
|
||||
3. **Mobile shows full text** — but design for desktop-first
|
||||
4. **Spaces ARE allowed** — `1. Links` works; `1._Links` breaks
|
||||
5. **Emoji+Text pattern preferred:** `✅Ja`, `❌Nein`, `🟡Später`
|
||||
|
||||
See [docs/BUTTON_GUIDE.md](docs/BUTTON_GUIDE.md) for full details.
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Set in `~/.config/hermes/rocketchat.env` (generated by install.sh):
|
||||
Set in `~/.hermes/.env` (generated by install.sh):
|
||||
|
||||
```bash
|
||||
ROCKETCHAT_BASE_URL=https://rocketchat.example.com
|
||||
ROCKETCHAT_BASE_URL=rocketchat.thomander.de # WITHOUT https:// prefix!
|
||||
ROCKETCHAT_USER=botuser
|
||||
ROCKETCHAT_PASSWORD=...
|
||||
ROCKETCHAT_ROOM_NAME=ki-assistent
|
||||
ROCKETCHAT_ALLOW_ALL_USERS=true
|
||||
GATEWAY_ALLOW_ALL_USERS=true
|
||||
```
|
||||
|
||||
> ⚠️ **Important:** `ROCKETCHAT_BASE_URL` must NOT include the protocol (`https://`). The DDP client prepends `wss://` automatically. Including `https://` causes `getaddrinfo ENOTFOUND https` and the gateway will crash-loop.
|
||||
|
||||
### Optional: Archivar LLM Stage
|
||||
|
||||
```bash
|
||||
ARCHIVAR_ENABLE_LLM=1 # Enable LLM stage for borderline classifications
|
||||
```
|
||||
|
||||
Requires `qwen2.5:7b` pulled via Ollama (~4.7 GB). Without this, the Archivar runs in 2-stage mode (Keyword + Embedding only).
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
- Hermes Agent installed
|
||||
- Self-hosted Rocket.Chat server (V5+)
|
||||
- Bot user account on the Rocket.Chat server
|
||||
- Hermes Agent installed and running
|
||||
- Self-hosted Rocket.Chat server (v5+)
|
||||
- Bot user account on the Rocket.Chat server with `bot` role
|
||||
- Python 3.10+ (hermes-agent venv)
|
||||
- **Optional:** `nomic-embed-text` via Ollama for embedding-based routing
|
||||
- **Optional:** `qwen2.5:7b` via Ollama for LLM-based routing (set `ARCHIVAR_ENABLE_LLM=1`)
|
||||
|
||||
---
|
||||
|
||||
## Room Routing — How It Works
|
||||
|
||||
### The Archivar (v4)
|
||||
|
||||
The Archivar is a **thematic room router**, not a category classifier. It answers: "Which room does this message belong in?" — not "Is this a fact, question, or alarm?"
|
||||
|
||||
**2-stage pipeline:**
|
||||
|
||||
| Stage | Method | Speed | Role |
|
||||
|-------|--------|-------|------|
|
||||
| 0 | Embedding pre-filter (nomic-embed-text, 768-dim) | <100ms | Binary: Smalltalk → stay. Everything else → LLM router |
|
||||
| 1 | LLM room router (qwen2.5:7b) | ~2.4s median | Full message + room list + keywords → room ID |
|
||||
|
||||
**The LLM receives:**
|
||||
- The complete message text
|
||||
- All available rooms with their IDs, names, and keywords
|
||||
- Keywords act as anchors — "RC" at the end of a sentence is recognized
|
||||
|
||||
**The LLM returns:** A single room ID (or `CATCH_ALL`). No categories, no fuzzy matching.
|
||||
|
||||
**Routing decisions:**
|
||||
|
||||
| Scenario | Behavior |
|
||||
|----------|----------|
|
||||
| **Smalltalk / greeting** | Embedding pre-filter catches it → stays in origin room |
|
||||
| **Clear topic match** | LLM returns room ID → Move-Request button (✅Ja / 📍Hier) |
|
||||
| **User clicks ✅Ja** | Message copied to target room. Agent answers there. |
|
||||
| **User clicks 📍Hier** | No routing. Answer stays in origin room. |
|
||||
| **No clear match** | LLM returns CATCH_ALL → falls to designated catch-all room |
|
||||
| **LLM timeout (10s)** | Automatic fallback to CATCH_ALL. **No answer is not an option.** |
|
||||
|
||||
### Zero Token Cost for Routing
|
||||
|
||||
The entire routing process runs on **local models** (nomic-embed-text + qwen2.5:7b). Your primary LLM (DeepSeek, Claude, etc.) receives only the final answer context — it never spends tokens on figuring out where to reply.
|
||||
|
||||
### Butler Principle
|
||||
|
||||
The agent **suggests**, the human **decides**. Before any routing, a Move-Request button appears. Nothing is silently rerouted.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Cause | Fix |
|
||||
|---------|-------|-----|
|
||||
| Gateway shows `No adapter available for rocketchat` | Plugin loading failed — missing `plugin.yaml` or `__init__.py` in plugin path, or ImportError in plugin code | Check `~/.hermes/hermes-agent/plugins/platforms/rocketchat/` has both files. Clear `__pycache__`. Check `journalctl --user -u hermes-gateway` for import errors. |
|
||||
| Gateway loses Rocket.Chat after restart (Discovery Bug) | `gateway_state.json` corruption after SIGTERM | `rm ~/.hermes/gateway_state.json ~/.hermes/.gateway_state_*.tmp && systemctl --user reset-failed hermes-gateway && systemctl --user start hermes-gateway` |
|
||||
| Gateway crash-loops after restart | Auto-resume of interrupted sessions | Same fix as Discovery Bug — clearing state files also clears interrupted session markers |
|
||||
| `getaddrinfo ENOTFOUND https` | `ROCKETCHAT_BASE_URL` contains `https://` prefix | Remove the protocol: `rocketchat.thomander.de` (not `https://rocketchat.thomander.de`) |
|
||||
| Buttons show as text options instead of native buttons | Old plugin version in `~/.hermes/...` path, or stale `__pycache__` | `cp` updated `adapter.py` to `~/.hermes/hermes-agent/plugins/platforms/rocketchat/`, clear `__pycache__`, restart gateway |
|
||||
| `Built user-room map: 0 users` after restart | Timing: user-map built before DDP fully connected | Usually self-heals on next message. If persistent, restart gateway with state-file cleanup. |
|
||||
| `install.sh --update-only` deploys to wrong path | `install.sh` targets `/usr/local/lib/...` but gateway loads from `~/.hermes/...` | Manually `cp` to `~/.hermes/hermes-agent/plugins/platforms/rocketchat/` after install. Don is fixing `install.sh`. |
|
||||
| Plugin import fails after code changes | Stale `.pyc` bytecode in `__pycache__/` | `find ~/.hermes/hermes-agent/plugins/platforms/rocketchat -name '__pycache__' -type d -exec rm -rf {} +` |
|
||||
|
||||
---
|
||||
|
||||
## Known Limitations
|
||||
|
||||
- **Desktop button truncation:** Rocket.Chat desktop app truncates button labels at ~7 characters. Use short emoji+text labels.
|
||||
- **Gateway Discovery Bug:** After SIGTERM, the gateway may lose the Rocket.Chat platform. Workaround: clear state files before restart. Root cause in Hermes Core — not fixable in the plugin.
|
||||
- **`install.sh` path mismatch:** Currently deploys to `/usr/local/lib/...` but the user-level gateway loads from `~/.hermes/...`. Manual `cp` needed after `--update-only`. Being fixed.
|
||||
- **User-Map timing:** After cold start, user-room map may show 0 users briefly. Self-heals on first message.
|
||||
- **No multi-user bot support:** One bot user = one agent session. Multiple bot users on the same server are not tested.
|
||||
|
||||
---
|
||||
|
||||
## Project Status
|
||||
|
||||
**Active development.** Current focus: Archivar v4 stabilization, install.sh path fix.
|
||||
|
||||
| Component | Status |
|
||||
|-----------|--------|
|
||||
| DDP/WebSocket messaging | ✅ Production |
|
||||
| REST API tools (7) | ✅ Production |
|
||||
| Interactive buttons | ✅ Production |
|
||||
| Archivar v4 (LLM room router) | ✅ Deployed (2026-06-14) |
|
||||
| Button-Garantie | ✅ Enforced (2026-06-12) |
|
||||
| Move-Request buttons | ✅ Native (2026-06-12) |
|
||||
| Auto-Onboarding | ✅ Production |
|
||||
| FAKT → Obsidian Vault | ✅ Production |
|
||||
| File attachments | ✅ Production |
|
||||
| `install.sh` path fix | 🔧 In progress (Don) |
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ The agent uses `send_message` with a `metadata` dict. The adapter converts this
|
||||
|
||||
```python
|
||||
send_message(
|
||||
target="rocketchat:protonbridge",
|
||||
target="rocketchat:my-room",
|
||||
text="Should I proceed?",
|
||||
metadata={
|
||||
"template": "custom",
|
||||
@@ -90,7 +90,7 @@ Without it, a late click on an old button creates silent context errors. Always
|
||||
```python
|
||||
# Step 1: Choose format
|
||||
send_message(
|
||||
target="rocketchat:protonbridge",
|
||||
target="rocketchat:my-room",
|
||||
text="Which export format?",
|
||||
metadata={
|
||||
"template": "custom",
|
||||
@@ -103,7 +103,7 @@ send_message(
|
||||
|
||||
# Step 2: Choose destination
|
||||
send_message(
|
||||
target="rocketchat:protonbridge",
|
||||
target="rocketchat:my-room",
|
||||
text="Where to send the CSV?",
|
||||
metadata={
|
||||
"template": "custom",
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
## Problem
|
||||
|
||||
Hermes erzeugt pro Rocket.Chat-Raum eine eigene Session. Andreas' DM und der
|
||||
#BAT-Team-Raum hatten zwei unabhängige Bernd-Instanzen — doppeltes
|
||||
Hermes erzeugt pro Rocket.Chat-Raum eine eigene Session. Die Admin-DM und der
|
||||
#Support-Team-Raum hatten zwei unabhängige Instanzen — doppeltes
|
||||
Informations-Management, kein gemeinsamer Kontext.
|
||||
|
||||
## Lösung: Virtuelle Raum-Übersetzung (Plugin-only)
|
||||
@@ -16,7 +16,7 @@ user-basierten virtuellen Chat-IDs. Keine Hermes-Core-Änderungen.
|
||||
### Datenfluss
|
||||
|
||||
```
|
||||
EINGANG: RC-Raum (DM / #BAT-Team)
|
||||
EINGANG: RC-Raum (DM / #Support-Team)
|
||||
↓
|
||||
_adapter._process_incoming():
|
||||
room_id → user:<username> als chat_id
|
||||
@@ -24,9 +24,9 @@ _adapter._process_incoming():
|
||||
chat_type=dm (umgeht group isolation in Core)
|
||||
↓
|
||||
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():
|
||||
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,107 @@
|
||||
# Archivar-Lernsystem — Nutzer-Anleitung
|
||||
|
||||
> **Stand:** 13. Juni 2026 | **Version:** 1.0
|
||||
> **Gilt für:** Rocket.Chat Plugin mit Archivar v3
|
||||
|
||||
## Was lernt der Archivar?
|
||||
|
||||
Der Archivar merkt sich, **welche Begriffe (Keywords) zu welchem Raum gehören** — und er lernt das aus deinen Entscheidungen. Jedes Mal, wenn du auf einen Button klickst, aktualisiert er die Gewichte in seiner internen Datenbank (`archivar_state.json`).
|
||||
|
||||
**Ziel:** Der Archivar soll mit der Zeit immer besser wissen, wohin eine Nachricht gehört — ohne dich jedes Mal fragen zu müssen.
|
||||
|
||||
---
|
||||
|
||||
## Die zwei Frage-Typen
|
||||
|
||||
Der Archivar stellt dir zwei Arten von Rückfragen. Beide trainieren das System — aber auf unterschiedliche Weise.
|
||||
|
||||
### 1. Move-Request: „Wohin soll ich den Auftrag verschieben?"
|
||||
|
||||
**Wann erscheint sie?** Wenn du einen Arbeitsauftrag schreibst, der thematisch besser in einen anderen Projektraum passt. Der Archivar hat Keywords erkannt, die auf einen anderen Raum hindeuten.
|
||||
|
||||
**Deine Optionen und was sie bewirken:**
|
||||
|
||||
| Button | Bedeutung | Lerneffekt |
|
||||
|---|---|---|
|
||||
| **1️⃣ Rüber** | Auftrag in den Zielraum kopieren, ich antworte dort | ✅ **Bestätigung:** Die erkannten Keywords gehören WIRKLICH zum Zielraum. Gewicht steigt. |
|
||||
| **2️⃣ Hier** | Auftrag bleibt hier, ich kümmere mich drum | ⚠️ **Korrektur:** Die Keywords gehören DOCH eher hierher. Gewicht für Zielraum sinkt leicht. |
|
||||
| **3️⃣ Nein** | Raum wird bis zum nächsten Neustart nicht mehr automatisch geroutet | 🛑 **Stopp:** Dieser Raum soll GAR NICHT automatisch geroutet werden. Gewicht für Zielraum sinkt stark. |
|
||||
|
||||
**Faustregel:**
|
||||
- Klick **1️⃣ Rüber**, wenn der Vorschlag perfekt passt
|
||||
- Klick **2️⃣ Hier**, wenn der Auftrag zwar thematisch passt, aber du ihn lieber hier behältst
|
||||
- Klick **3️⃣ Nein**, wenn der Archivar sich grundsätzlich irrt und diesen Raum in Ruhe lassen soll
|
||||
|
||||
### 2. Clarify: „Ich möchte mir das für die Zukunft richtig merken. Welche Absicht ist mit der Nachricht verbunden?"
|
||||
|
||||
**Wann erscheint sie?** Wenn der Archivar unsicher ist — er kann nicht eindeutig entscheiden, ob deine Nachricht eine Frage, Smalltalk oder ein Auftrag ist. Die Konfidenz liegt zwischen 60% und 90%.
|
||||
|
||||
**Deine Optionen und was sie bewirken:**
|
||||
|
||||
| Button | Bedeutung | Lerneffekt |
|
||||
|---|---|---|
|
||||
| **📝 Direkte Frage** | Du hast eine Frage gestellt, kein Auftrag | 🏠 **Hier bleiben:** Nachrichten in diesem Raum werden nicht geroutet. Die unsicheren Keywords werden diesem Raum zugeordnet. |
|
||||
| **💬 Smalltalk** | Plauderei, keine Arbeitsabsicht | 🏠 **Hier bleiben:** Wie Direkte Frage — Raum wird als „always stay" markiert. |
|
||||
| **📋 Arbeitsauftrag** | Du willst, dass etwas erledigt wird | 🔀 **Routing erlaubt:** Der Archivar darf für diesen Raum weiter routen. Keywords werden dem Zielraum zugeordnet. |
|
||||
|
||||
**Faustregel:**
|
||||
- Klick **📝 Frage** oder **💬 Smalltalk**, wenn du einfach nur redest — der Archivar soll dich hier in Ruhe lassen
|
||||
- Klick **📋 Auftrag**, wenn du wirklich willst, dass etwas passiert — der Archivar darf Vorschläge machen
|
||||
|
||||
---
|
||||
|
||||
## Was passiert mit den Gewichten?
|
||||
|
||||
Jeder Klick verändert die Keyword-Gewichte in `archivar_state.json`. Das System arbeitet mit einer **Lernrate**:
|
||||
|
||||
- **Tag 1–7:** Lernrate 0,2 (schnelles Lernen — das System ist neu)
|
||||
- **Tag 8+:** Lernrate 0,1 (konservatives Lernen — das System hat Erfahrung)
|
||||
|
||||
**Bei „confirm" (1️⃣ Rüber, 📋 Auftrag):**
|
||||
- Gewicht für den Zielraum steigt: `neu = alt + (1 - alt) × Lernrate`
|
||||
- Gewichte für andere Räume sinken proportional
|
||||
- Maximum: 0,95
|
||||
|
||||
**Bei „stay" (2️⃣ Hier, 📝 Frage, 💬 Smalltalk):**
|
||||
- Gewicht für den Zielraum sinkt leicht
|
||||
- Gewichte für andere Räume steigen proportional
|
||||
- Minimum: 0,05
|
||||
|
||||
**Bei „never" (3️⃣ Nein):**
|
||||
- Gewicht für den Zielraum sinkt stark (doppelte Lernrate)
|
||||
- Der Raum wird zusätzlich „sticky" — keine automatischen Routings bis zum nächsten Gateway-Neustart
|
||||
|
||||
**Langfristige Effekte:**
|
||||
- **Promotion:** 3 Bestätigungen + Gewicht ≥ 0,85 → Keyword wird von „context" zu „100%-Keyword" hochgestuft (ein Treffer reicht dann für sofortigen Match)
|
||||
- **Degradation:** 2× „never" oder 4× „stay" → 100%-Keyword wird zurück nach „context" gestuft
|
||||
- **Decay:** 30 Tage ohne Aktivität → -10%, 90 Tage → -30%
|
||||
|
||||
---
|
||||
|
||||
## Wie sehe ich den Lernfortschritt?
|
||||
|
||||
Die Gewichte werden in `archivar_state.json` gespeichert (Pfad: `~/.hermes/hermes-agent/data/archivar_state.json`).
|
||||
|
||||
**Direkte Einsicht (für Fortgeschrittene):**
|
||||
```bash
|
||||
cat ~/.hermes/hermes-agent/data/archivar_state.json | python3 -m json.tool | grep -A5 '"keyword_weights"'
|
||||
```
|
||||
|
||||
**Indirekte Beobachtung (im Alltag):**
|
||||
- Der Archivar fragt **seltener** → die Gewichte sind stabil, das System ist sicher
|
||||
- Der Archivar fragt **häufiger** → neue Keywords, das System lernt aktiv
|
||||
- Move-Requests treffen **öfter ins Schwarze** → die Keyword-Zuordnung ist präzise
|
||||
|
||||
---
|
||||
|
||||
## Praktische Tipps
|
||||
|
||||
1. **Sei konsequent in den ersten Tagen.** Die Lernrate ist anfangs hoch (0,2) — deine ersten Entscheidungen prägen das System stark. Klick bewusst.
|
||||
|
||||
2. **„Nein" sparsam einsetzen.** 3️⃣ Nein setzt den Raum auf „sticky" — der Archivar ignoriert ihn komplett. Nutze es nur, wenn der Archivar sich grundsätzlich irrt. Für „passt nicht ganz" reicht 2️⃣ Hier.
|
||||
|
||||
3. **Clarify-Fragen ernst nehmen.** Die 📝/💬/📋-Entscheidung bestimmt, ob ein Raum überhaupt geroutet wird. Ein Raum, den du als „Frage/Smalltalk" markierst, wird nie automatisch geroutet — auch wenn später echte Aufträge kommen.
|
||||
|
||||
4. **Geduld haben.** Das System braucht 3–5 Interaktionen pro Keyword, um sicher zu werden. Nach 7 Tagen schaltet es auf konservatives Lernen um — dann sind die Gewichte weitgehend stabil.
|
||||
|
||||
5. **Gateway-Neustart = Reset der Sticky-Räume.** Die 3️⃣ Nein-Sperre gilt nur bis zum nächsten Gateway-Neustart. Danach fragt der Archivar wieder. Für dauerhafte Sperren: Raum in der `room-map.json` auf `catch_all: false` + `excluded_rooms` setzen.
|
||||
@@ -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
|
||||
@@ -0,0 +1,224 @@
|
||||
# Archivar v3 - Architekturskizze
|
||||
|
||||
## Übersicht
|
||||
|
||||
Archivar v3 ist ein kompletter Architektur-Reset des Nachrichtenklassifizierungs- und Routing-Systems für Hermes. Die neue Architektur basiert auf fünf grundlegenden Prinzipien, die von Andreas am 11.06.2026 genehmigt wurden.
|
||||
|
||||
## Architekturprinzipien
|
||||
|
||||
1. **Default = Bleiben** — Routing nur bei >90% Intent-Confidence. Smalltalk/Direktfragen bleiben IMMER im Channel. Bei 60-90%: LLM-Klärung mit nativen RC Action-Buttons.
|
||||
2. **Bidirektionales Routing** — Wenn umgezogen wird: Quellkanal bekommt "📋 Bearbeite ich in [Ziel]" + Link. Antwort im Zielraum. Nach Abschluss: Summary zurück in Quellkanal.
|
||||
3. **Buttons sind Pflicht** — Move-Request ausschließlich via native RC Action-Buttons (REST). Text-Fallback nur bei REST-Fehler mit Log-Warnung.
|
||||
4. **Zustand pro Raum** — "Generell hier bleiben" persistiert in room_state.json über Gateway-Neustarts.
|
||||
|
||||
## Komponenten-Diagramm
|
||||
|
||||
```
|
||||
+------------------+ +---------------------+ +----------------------+
|
||||
| | | | | |
|
||||
| User Nachricht |---->| Intent-Erkenner |---->| Confidence-Framework |
|
||||
| | | | | |
|
||||
+------------------+ +---------------------+ +----------------------+
|
||||
|
|
||||
v
|
||||
+------------------+ +---------------------+ +----------------------+
|
||||
| | | | | |
|
||||
| Persistenz- |<----| Bidirektionales |<----| Button-Garantie |
|
||||
| Layer | | Routing | | |
|
||||
+------------------+ +---------------------+ +----------------------+
|
||||
| ^
|
||||
v |
|
||||
+------------------+
|
||||
| |
|
||||
| Zielraum |
|
||||
| |
|
||||
+------------------+
|
||||
```
|
||||
|
||||
## Datenfluss
|
||||
|
||||
```
|
||||
User-Nachricht
|
||||
|
|
||||
v
|
||||
+-----------------+
|
||||
| Intent-Erkenner |
|
||||
| - direct_question|
|
||||
| - smalltalk |
|
||||
| - work_order |
|
||||
| - ambiguous |
|
||||
+-----------------+
|
||||
|
|
||||
v
|
||||
+---------------------+
|
||||
| Confidence-Framework|
|
||||
| - Keyword-Match |
|
||||
| - Embedding-Ähnlichk|
|
||||
| - LLM-Verifikation |
|
||||
+---------------------+
|
||||
|
|
||||
v
|
||||
+---------------------+ +------------------+
|
||||
| | | |
|
||||
| Routing-Entscheidung|--> | Button-Garantie |
|
||||
| - >90%: auto-move | | - REST-Pfad |
|
||||
| - 60-90%: Klärung | | - Text-Fallback |
|
||||
| - <60%: bleiben | | |
|
||||
+---------------------+ +------------------+
|
||||
|
|
||||
v
|
||||
+---------------------+
|
||||
| Bidirektionales |
|
||||
| Routing |
|
||||
| - Quellkanal-Info |
|
||||
| - Zielkanal-Move |
|
||||
| - Summary zurück |
|
||||
+---------------------+
|
||||
|
|
||||
v
|
||||
+---------------------+
|
||||
| Persistenz-Layer |
|
||||
| - room_state.json |
|
||||
| - Zustand speichern |
|
||||
+---------------------+
|
||||
```
|
||||
|
||||
## Neue Komponenten
|
||||
|
||||
### 1. Intent-Erkenner
|
||||
|
||||
**Verantwortung:** Klassifizierung eingehender Nachrichten nach Intention
|
||||
|
||||
**Ausgabe:**
|
||||
- `direct_question` - Direkte Fragen an Hermes
|
||||
- `smalltalk` - Smalltalk und allgemeine Konversation
|
||||
- `work_order` - Arbeitsaufträge und Anfragen zur Bearbeitung
|
||||
- `ambiguous` - Mehrdeutige Nachrichten, die Klärung benötigen
|
||||
|
||||
**Änderungen:**
|
||||
- Neue `CATEGORY_TEXTS` in `config.py` mit Referenztexten für jeden Intent-Typ
|
||||
- `direct_question` und `smalltalk` werden niemals geroutet
|
||||
- `work_order` wird nur bei >90% Confidence geroutet
|
||||
- `ambiguous` (60-90% Confidence) benötigt LLM-Klärung mit Buttons
|
||||
|
||||
### 2. Confidence-Framework
|
||||
|
||||
**Verantwortung:** Berechnung und Bewertung der Klassifizierungsgenauigkeit
|
||||
|
||||
**Stufen:**
|
||||
1. **Keyword-Match** (0-50% Basis-Score) - Schnelle Vorfilterung
|
||||
2. **Embedding-Ähnlichkeit** (0-80%) - Semantische Analyse
|
||||
3. **LLM-Verifikation** (nur bei ambiguous, finaler Score) - Kontextuelle Bewertung
|
||||
|
||||
**Schwellenwerte:**
|
||||
- 90%+ für automatisches Routing
|
||||
- 60-90% für LLM-Klärung mit Buttons
|
||||
- <60% keine Weiterleitung, Nachricht bleibt im Ursprungsraum
|
||||
|
||||
### 3. Bidirektionales Routing
|
||||
|
||||
**Verantwortung:** Koordination des Nachrichtentransfers zwischen Räumen
|
||||
|
||||
**Ablauf:**
|
||||
1. Quellkanal-Post: "📋 Bearbeite ich in #ziel — [Link]"
|
||||
2. Vollständige Nachricht + Kontext im Zielkanal
|
||||
3. Agent-Antwort im Zielkanal
|
||||
4. Nach Abschluss: Summary zurück in Quellkanal
|
||||
|
||||
**Erweiterung von RoutingDecision:**
|
||||
- `source_room_notification` - Benachrichtigung im Ursprungsraum
|
||||
- `return_summary_to_source` - Zusammenfassung nach Abschluss
|
||||
|
||||
### 4. Persistenz-Layer
|
||||
|
||||
**Verantwortung:** Speicherung von Routing-Entscheidungen über Neustarts hinweg
|
||||
|
||||
**Klasse:** `ArchivarState`
|
||||
|
||||
**Schema:**
|
||||
```json
|
||||
{
|
||||
"rooms": {
|
||||
"<room_id>": {
|
||||
"stay_decision": "always"|"ask"|"never_route",
|
||||
"decided_at": "ISO-Zeitstempel",
|
||||
"decided_by": "Benutzername"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Verhalten:**
|
||||
- Laden bei Gateway-Start (`Adapter.__init__`)
|
||||
- Speichern bei jeder User-Entscheidung
|
||||
- Separater Pfad von `gateway_state.json`
|
||||
|
||||
### 5. Button-Garantie
|
||||
|
||||
**Verantwortung:** Sicherstellung der nativen Rocket.Chat Action-Buttons für Klärungsanfragen
|
||||
|
||||
**Flow:** `send_clarify()`
|
||||
- **REST-Pfad Vorrang:** `rocketchat_send` mit `button_template`
|
||||
- **Text-Fallback:** Nur bei HTTP-Fehler
|
||||
- **Logging:** Warnung bei Fallback-Nutzung
|
||||
|
||||
**Deployment-Test:** Don verifiziert auf frischer Debian-Installation
|
||||
|
||||
## Interface-Änderungen
|
||||
|
||||
### Neue Module/Klassen
|
||||
|
||||
1. **IntentClassifier** - Neue Klasse für Intent-Klassifizierung
|
||||
2. **ConfidenceEngine** - Neue Klasse für Confidence-Berechnung
|
||||
3. **BidirectionalRouter** - Erweiterte Routing-Logik
|
||||
4. **ArchivarState** - Persistenz-Layer für Raum-Zustände
|
||||
5. **ButtonEnforcer** - Garantie für native RC-Buttons
|
||||
|
||||
### Geänderte Module
|
||||
|
||||
1. **config.py**
|
||||
- Neue `CATEGORY_TEXTS` mit Intent-Typen
|
||||
- Neue Konfiguration für Button-Templates
|
||||
- Neue Pfade für Persistenz-Dateien
|
||||
|
||||
2. **router.py**
|
||||
- Erweitertes `RoutingDecision`-Objekt
|
||||
- Integration des bidirektionalen Routings
|
||||
- Verwendung des neuen Confidence-Frameworks
|
||||
|
||||
3. **classifier.py**
|
||||
- Komplett überarbeitet für Intent-Klassifizierung
|
||||
- Integration des Confidence-Frameworks
|
||||
- Neue Ausgabetypen statt FAKT/FRAGE/ALARM
|
||||
|
||||
### Unveränderte Module
|
||||
|
||||
1. **gateway.py** - Grundlegende Gateway-Funktionalität bleibt bestehen
|
||||
2. **rocketchat_client.py** - REST-API-Client bleibt weitgehend unverändert
|
||||
3. **logger.py** - Logging-Infrastruktur bleibt bestehen
|
||||
|
||||
## Migration vom IST-Zustand
|
||||
|
||||
### Aktuelle Probleme (IST-Zustand)
|
||||
|
||||
1. **classifier.py** (575 LOC):
|
||||
- Nur 3 Kategorien: FAKT/FRAGE/ALARM
|
||||
- Kein Intent-Konzept
|
||||
- Keine Smalltalk/Question-Unterscheidung
|
||||
|
||||
2. **router.py** (478 LOC):
|
||||
- Kein bidirektionales Routing
|
||||
- Kein Persistenz-Layer
|
||||
- Raum-basiert statt Intent-basiert
|
||||
|
||||
3. **config.py** (169 LOC):
|
||||
- Eingeschränkte Kategorien
|
||||
- Kein Intent-Kontext im Raum-Prompt
|
||||
|
||||
### Vorteile der neuen Architektur
|
||||
|
||||
1. **Präzisere Klassifizierung** durch Intent-basierte Ansätze
|
||||
2. **Transparenz** durch bidirektionales Routing
|
||||
3. **Benutzerfreundlichkeit** durch native Buttons
|
||||
4. **Persistenz** von Entscheidungen über Neustarts
|
||||
5. **Sicherheit** durch höhere Confidence-Schwellen
|
||||
@@ -0,0 +1,144 @@
|
||||
# Q-Gate Code-Review: Archivar v3 Implementierung
|
||||
|
||||
**Reviewer:** Rainer (Architekt)
|
||||
**Datum:** 11.06.2026
|
||||
**Bewertete Commits:** 92bdb39, 5e8e9c9, 87f95b8, b11c2c9, dba856f
|
||||
|
||||
## F1: Architektur-Konformität
|
||||
|
||||
**BESTANDEN** — Die Implementierung entspricht vollständig der Architekturskizze in docs/archivar-v3-architektur.md.
|
||||
|
||||
### Überprüfte Komponenten:
|
||||
|
||||
✅ **Intent-Erkenner mit 4 Typen**
|
||||
- Implementiert in `classifier.py` als `IntentClassifier`
|
||||
- Unterstützt alle vier Typen: `direct_question`, `smalltalk`, `work_order`, `ambiguous`
|
||||
|
||||
✅ **Confidence-Framework 3-stufig mit korrekten Schwellen**
|
||||
- Implementiert in `classifier.py`
|
||||
- Korrekte Schwellenwerte: 90% für Auto-Routing, 60-90% für Klärung
|
||||
- Konfiguration in `config.py` mit `CONFIDENCE_THRESHOLDS`
|
||||
|
||||
✅ **Bidirektionales Routing mit Quellkanal-Info + Summary**
|
||||
- Implementiert in `router.py` als `BidirectionalRouter`
|
||||
- Erweitertes `RoutingDecision`-Objekt mit `source_room_notification`
|
||||
- `move_message()` Methode implementiert in `adapter_integration.py`
|
||||
|
||||
✅ **Persistenz-Layer mit room_state.json**
|
||||
- Implementiert in `archivar_state.py` als `ArchivarState`
|
||||
- Speichert Raum-Zustände in JSON-Datei
|
||||
- Konfiguration in `config.py` mit `ARCHIVAR_STATE_PATH`
|
||||
|
||||
✅ **Button-Garantie mit REST-first**
|
||||
- Implementiert in `adapter_integration.py` mit `_send_clarify()`
|
||||
- REST-Pfad als Vorrang, Text-Fallback nur bei Fehler
|
||||
- Button-Templates in `config.py`
|
||||
|
||||
## F2: Code-Qualität
|
||||
|
||||
**BESTANDEN** — Sehr gute Code-Qualität mit sauberer Python-Implementierung.
|
||||
|
||||
### Überprüfte Module:
|
||||
|
||||
✅ **classifier.py: should_route() Logik korrekt**
|
||||
- `direct_question` und `smalltalk` → `False` (bleiben im Raum)
|
||||
- `work_order` nur bei >90% Confidence → `True`
|
||||
- `ambiguous` → `False` (benötigt Klärung)
|
||||
|
||||
✅ **router.py: RoutingDecision korrekt erweitert**
|
||||
- Neue Felder: `stay_in_room`, `needs_clarification`, `source_room_notification`
|
||||
- `should_route()` Methode korrekt implementiert
|
||||
- `move_message()` Methode vorhanden
|
||||
|
||||
✅ **archivar_state.py: load/save atomar**
|
||||
- Atomare Operationen mit Fehlerbehandlung
|
||||
- Robuste JSON-Serialisierung
|
||||
- Fehlerbehandlung bei Dateioperationen
|
||||
|
||||
## F3: Regression
|
||||
|
||||
**BESTANDEN** — Keine Regressionen in bestehender Funktionalität.
|
||||
|
||||
### Überprüfte Aspekte:
|
||||
|
||||
✅ **Alte FAKT/FRAGE/ALARM-Kategorien entfernt**
|
||||
- Vollständiger Wechsel zu Intent-basiertem Ansatz
|
||||
- Keine Referenzen mehr auf alte Kategorien
|
||||
|
||||
✅ **Bestehende Tests aktualisiert**
|
||||
- `test_router.py` angepasst an neue Klassen (`IntentClassifier`, `BidirectionalRouter`)
|
||||
- `test_room_map.py` unverändert und weiterhin gültig
|
||||
- `test_auto_onboarding.py` weiterhin gültig
|
||||
|
||||
✅ **room_map.py unverändert**
|
||||
- Kernfunktionalität bleibt bestehen
|
||||
- Keine Breaking Changes
|
||||
|
||||
## F4: Interface-Kompatibilität
|
||||
|
||||
**BESTANDEN** — Alle neuen Interfaces sind korrekt integriert.
|
||||
|
||||
### Überprüfte Aspekte:
|
||||
|
||||
✅ **adapter_integration.py korrekt integriert**
|
||||
- Verwendet neue Klassen (`IntentClassifier`, `BidirectionalRouter`)
|
||||
- `ArchivarState` Integration vorhanden
|
||||
- Button-Support implementiert
|
||||
|
||||
✅ **Import-Pfade stimmen**
|
||||
- Alle relativen Importe korrekt
|
||||
- Keine zirkulären Abhängigkeiten
|
||||
- Konsistente Modulstruktur
|
||||
|
||||
## F5: Fehlerbehandlung
|
||||
|
||||
**BESTANDEN** — Robuste Fehlerbehandlung in allen Komponenten.
|
||||
|
||||
### Überprüfte Aspekte:
|
||||
|
||||
✅ **Ollama-Down → Fallback**
|
||||
- Keyword-basierte Fallback-Klassifikation implementiert
|
||||
- Graceful Degradation bei Embedding-API-Ausfall
|
||||
|
||||
✅ **JSON-Korruption → Recovery**
|
||||
- Try-Catch-Blöcke bei JSON-Operationen
|
||||
- Fehlerbehandlung bei Persistenz-Layer
|
||||
|
||||
✅ **Timeout → Graceful Degradation**
|
||||
- Timeout-Konfiguration in `OLLAMA_CONFIG`
|
||||
- Fallback bei Überschreitung der Timeout-Grenze
|
||||
|
||||
## F6: Deployment-Fähigkeit
|
||||
|
||||
**BESTANDEN** — Implementierung ist deployment-fähig.
|
||||
|
||||
### Überprüfte Aspekte:
|
||||
|
||||
✅ **Alle neuen Dateien unter plugin/archivar/**
|
||||
- `archivar_state.py` korrekt platziert
|
||||
- Alle neuen Module im richtigen Verzeichnis
|
||||
|
||||
✅ **Keine Stray-Dateien im Repo-Root**
|
||||
- Alle Dateien in korrekter Verzeichnisstruktur
|
||||
- Keine unerwarteten Dateien im Repository-Root
|
||||
|
||||
✅ **install.sh kopiert neue Dateien mit**
|
||||
- Rekursive Kopierung inkl. aller Submodule
|
||||
- `__pycache__` ausgeschlossen
|
||||
|
||||
## Gesamturteil
|
||||
|
||||
**FREIGABE** — Die Archivar v3 Implementierung ist vollständig und entspricht allen Anforderungen der Architekturskizze. Die Code-Qualität ist hoch, und es wurden keine Regressionen festgestellt. Die Implementierung ist bereit für das Deployment.
|
||||
|
||||
### Besondere Stärken:
|
||||
|
||||
1. **Klare Trennung der Verantwortlichkeiten** — Jede Komponente hat eine klar definierte Aufgabe
|
||||
2. **Robuste Fehlerbehandlung** — Umfassende Behandlung von Edge Cases
|
||||
3. **Gute Testabdeckung** — Bestehende Tests wurden angepasst und neue Funktionen sind testbar
|
||||
4. **Konsistente API** — Einheitliche Schnittstellen und Namensgebung
|
||||
|
||||
### Empfehlungen für zukünftige Verbesserungen:
|
||||
|
||||
1. **Erweiterte Tests für neue Komponenten** — Integrationstests für `ArchivarState` und `BidirectionalRouter`
|
||||
2. **Performance-Monitoring** — Hinzufügen von Metriken für die neue Persistenz-Schicht
|
||||
3. **Dokumentation** — Erweiterte Dokumentation der neuen Intent-Kategorien für Endbenutzer
|
||||
@@ -0,0 +1,212 @@
|
||||
# Architekturskizze: Zweistufiges Keyword-Evidenz-System
|
||||
|
||||
## Überblick
|
||||
|
||||
Das zweistufige Keyword-Evidenz-System trennt eindeutige Keywords (100% Evidenz) von mehrdeutigen Keywords (<100% Evidenz), um die Routing-Genauigkeit zu verbessern und manuelle Pflege zu reduzieren.
|
||||
|
||||
## 1. Neue room-map.json-Struktur
|
||||
|
||||
Die bestehende flache `keywords`-Liste wird in zwei separate Listen aufgeteilt:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"6a19b0ff02aeecd36b1aa16c": {
|
||||
"name": "#Rocketchat-Plugin",
|
||||
"theme": "Hermes Plugin Rocketchat, RC, rocket.chat, Austausch und Status zum Projekt Rocketchat",
|
||||
"keywords_100": ["rocketchat", "rc", "ddp", "websocket", "adapter", "install.sh", "hermes"],
|
||||
"keywords_context": ["plugin", "gateway", "deployment", "button", "sync"],
|
||||
"catch_all": false
|
||||
},
|
||||
"69f8beaef06dba03be82f9fc": {
|
||||
"name": "#Protonbridge-Plugin",
|
||||
"theme": "Hermes Plugin Protonbridge, Proton Mail Bridge, Austausch und Status zum Projekt Protonbridge",
|
||||
"keywords_100": ["protonbridge", "proton", "mail", "bridge", "email", "smtp", "imap"],
|
||||
"keywords_context": ["plugin", "deployment"],
|
||||
"catch_all": false
|
||||
},
|
||||
"6a049d493a62ef8f1ead2320": {
|
||||
"name": "#BAT-Team",
|
||||
"theme": "Trading-Plattform, Multi-Agent-System, Bot-Agenten-Team, Krypto-Analysen, Wyckoff-Methodik, Boot-Window, Entwicklung und Betrieb der BAT-Trading-Plattform",
|
||||
"keywords_100": ["bat", "bat-team", "trading", "krypto", "wyckoff", "boot-window", "börse", "exchange", "analyst", "control-tower"],
|
||||
"keywords_context": ["gateway"],
|
||||
"catch_all": false
|
||||
},
|
||||
"6a1c56d4b73efec2bebec2db": {
|
||||
"name": "#LAN-Dokumentation",
|
||||
"theme": "HomeLab, home lab, Dokumentation des LAN, Austausch und Status zum Projekt LAN-Dokumentation",
|
||||
"keywords_100": ["lan", "dokumentation", "homelab", "netzwerk", "router", "switch", "subnetz", "proxmox", "heimnetz", "ip-adresse"],
|
||||
"keywords_context": [],
|
||||
"catch_all": false
|
||||
},
|
||||
"69f4e777f06dba03be82dce7": {
|
||||
"name": "DM mit Andreas",
|
||||
"theme": "Direktnachrichten — Catch-All für alle Themen ohne eigenen Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": true
|
||||
}
|
||||
},
|
||||
"excluded_rooms": [
|
||||
"6a049d493a62ef8f1ead2320",
|
||||
"6a1c56d4b73efec2bebec2db",
|
||||
"69f8beaef06dba03be82f9fc",
|
||||
"6a19b0ff02aeecd36b1aa16c",
|
||||
"6a0f4b2991db1dbf570a5442",
|
||||
"6a21495ede3de7118e84d82e"
|
||||
],
|
||||
"fact_store_path": "/data/Wissensdatenbank/0100 Inbox"
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Keyword-Matcher Algorithmus
|
||||
|
||||
Der neue Matcher verarbeitet Keywords in zwei Stufen:
|
||||
|
||||
### Stufe 1: 100% Evidenz Keywords
|
||||
|
||||
```python
|
||||
def find_room_by_keywords(self, text: str, min_score: int = 2, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
|
||||
"""Find the room with the most keyword matches for *text*."""
|
||||
|
||||
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
|
||||
text_lower = text.lower()
|
||||
for room in self._rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
|
||||
# Prüfe ob 100% Keywords matchen
|
||||
if any(kw in text_lower for kw in room.keywords_100):
|
||||
return room
|
||||
|
||||
# Stufe 2: Origin-Priorität mit kontextabhängigen Keywords
|
||||
if origin_room_id is not None and origin_room_id in self._rooms:
|
||||
origin_room = self._rooms[origin_room_id]
|
||||
if not origin_room.catch_all:
|
||||
# Prüfe kontextabhängige Keywords im Ursprungsraum
|
||||
context_score = sum(1 for kw in origin_room.keywords_context if kw in text_lower)
|
||||
if context_score >= min_score:
|
||||
return origin_room
|
||||
|
||||
# Stufe 3: Globaler Scan mit kontextabhängigen Keywords
|
||||
best_room: Optional[RoomEntry] = None
|
||||
best_score: int = 0
|
||||
|
||||
for room in self._rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
|
||||
# Prüfe kontextabhängige Keywords
|
||||
context_score = sum(1 for kw in room.keywords_context if kw in text_lower)
|
||||
if context_score > best_score:
|
||||
best_score = context_score
|
||||
best_room = room
|
||||
|
||||
if best_room is not None and best_score >= min_score:
|
||||
return best_room
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
## 3. Selbstlernendes System (Optional)
|
||||
|
||||
### Datenstruktur
|
||||
|
||||
In `archivar_state.json` wird eine neue Sektion für Keyword-Gewichte hinzugefügt:
|
||||
|
||||
```json
|
||||
{
|
||||
"rooms": {
|
||||
"6a19b0ff02aeecd36b1aa16c": {
|
||||
"stay_decision": "ask",
|
||||
"decided_at": "2026-06-12T10:30:00",
|
||||
"decided_by": "Andreas"
|
||||
}
|
||||
},
|
||||
"keyword_weights": {
|
||||
"plugin": {
|
||||
"6a19b0ff02aeecd36b1aa16c": 0.7, # #Rocketchat-Plugin
|
||||
"69f8beaef06dba03be82f9fc": 0.3 # #Protonbridge-Plugin
|
||||
},
|
||||
"gateway": {
|
||||
"6a19b0ff02aeecd36b1aa16c": 0.6, # #Rocketchat-Plugin
|
||||
"6a049d493a62ef8f1ead2320": 0.4 # #BAT-Team
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Lernalgorithmus
|
||||
|
||||
1. **Ereignis**: Andreas klickt "✅Ja" (rüberkopieren) im Kontext eines Keywords
|
||||
2. **Gewichtsanpassung**:
|
||||
- Erhöhe Gewicht für das aktuelle Zimmer um 0.1
|
||||
- Dämpfung: Maximalgewicht 0.9, Mindestgewicht 0.1
|
||||
- Verteile das reduzierte Gewicht gleichmäßig auf andere Zimmer
|
||||
3. **Schwellwert**: Nach 3 Bestätigungen wird das Keyword in `keywords_100` verschoben
|
||||
|
||||
### Persistenz
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class KeywordWeights:
|
||||
"""Gewichte für kontextabhängige Keywords."""
|
||||
|
||||
weights: Dict[str, Dict[str, float]] = field(default_factory=dict)
|
||||
# keyword → {room_id → weight}
|
||||
|
||||
class ArchivarState:
|
||||
# ... bestehende Methoden ...
|
||||
|
||||
def get_keyword_weight(self, keyword: str, room_id: str) -> float:
|
||||
"""Hole das Gewicht für ein Keyword in einem Raum."""
|
||||
return self._keyword_weights.get(keyword, {}).get(room_id, 0.0)
|
||||
|
||||
def update_keyword_weight(self, keyword: str, room_id: str, positive: bool) -> bool:
|
||||
"""Aktualisiere das Gewicht basierend auf Benutzerfeedback."""
|
||||
# Implementierung des Lernalgorithmus
|
||||
pass
|
||||
```
|
||||
|
||||
## 4. Migrationspfad
|
||||
|
||||
### Phase 1: Abwärtskompatibel
|
||||
|
||||
- Bestehende `keywords`-Liste wird als `keywords_context` interpretiert
|
||||
- Neue `keywords_100` bleibt leer
|
||||
- Version bleibt auf 1, neue Felder werden ignoriert
|
||||
|
||||
### Phase 2: Upgrade
|
||||
|
||||
- Automatische Migration bei Erkennung von Version 1
|
||||
- Manuelles Review zur Klassifizierung von Keywords
|
||||
- Version auf 2 erhöhen
|
||||
|
||||
## 5. Betroffene Dateien
|
||||
|
||||
### Geänderte Dateien:
|
||||
- `room_map.py` - Keyword-Matcher Logik
|
||||
- `archivar_state.py` - Keyword-Gewichte Persistenz
|
||||
- `room-map.json` - Neue Struktur (abwärtskompatibel)
|
||||
|
||||
### Neue Dateien:
|
||||
- `keyword_weights.json` (optional) - Separate Datei für Keyword-Gewichte
|
||||
|
||||
## 6. Pitfalls und Lösungen
|
||||
|
||||
### Abwärtskompatibilität
|
||||
- **Problem**: Bestehende Installationen brechen
|
||||
- **Lösung**: Versionierung und automatische Migration
|
||||
|
||||
### Lernrate
|
||||
- **Problem**: Zu schnelles oder zu langsames Lernen
|
||||
- **Lösung**: Gedämpfte Lernrate mit Min/Max-Begrenzungen
|
||||
|
||||
### Manuelle Overrides
|
||||
- **Problem**: Gelernte Gewichte überschreiben manuelle Entscheidungen
|
||||
- **Lösung**: Manuelle Entscheidungen haben immer Vorrang
|
||||
|
||||
### Performance
|
||||
- **Problem**: Komplexere Matching-Logik verlangsamt den Matcher
|
||||
- **Lösung**: Caching und optimierte Datenstrukturen
|
||||
@@ -0,0 +1,55 @@
|
||||
# Architekturskizze: Origin-Priorität im Keyword-Matcher
|
||||
|
||||
## 1. Problemstellung
|
||||
|
||||
Der aktuelle Keyword-Matcher `find_room_by_keywords()` in `room_map.py` führt einen flachen globalen Scan über alle Räume durch, ohne den Ursprungsraum der Nachricht zu berücksichtigen. Dies führt zu Fehl-Routings, wenn Keywords in mehreren Räumen vorkommen.
|
||||
|
||||
### Beispiel
|
||||
Das Wort "plugin" ist Keyword sowohl in #Rocketchat-Plugin als auch in #Protonbridge-Plugin. Wenn jemand im Protonbridge-Raum "Wie geht's mit dem Plugin?" schreibt, matcht der Matcher beide Räume. Bei Gleichstand wird arbiträr der erste Raum im Dictionary ausgewählt, was zur Folge haben kann, dass die Nachricht fälschlicherweise in #Rocketchat-Plugin geroutet wird, obwohl sie im Protonbridge-Raum verfasst wurde.
|
||||
|
||||
## 2. Lösungsansatz: Origin-First-Prinzip
|
||||
|
||||
Das neue Prinzip folgt der Logik: "Wo sind wir gerade?" - der Ursprungsraum hat Priorität.
|
||||
|
||||
### Algorithmus
|
||||
1. **Origin-Check**: Wenn ein Ursprungsraum angegeben ist, prüfe zuerst, ob dieser Raum Keywords matcht
|
||||
2. **Origin-Match**: Wenn der Ursprungsraum mindestens den Mindestscore erreicht, wird dieser Raum ausgewählt
|
||||
3. **Global-Fallback**: Nur wenn der Ursprungsraum keinen ausreichenden Match liefert, wird der globale Scan durchgeführt
|
||||
4. **Best-Room-Selektion**: Aus den globalen Matches wird wie bisher der Raum mit dem höchsten Score ausgewählt
|
||||
|
||||
## 3. Benötigte Änderungen
|
||||
|
||||
### room_map.py
|
||||
- Erweitern der Methode `find_room_by_keywords()` um einen neuen Parameter `origin_room_id: Optional[str] = None`
|
||||
- Implementierung der Origin-Priorität Logik vor dem globalen Scan
|
||||
|
||||
### router.py
|
||||
- Anpassung des Aufrufs von `find_room_by_keywords()` um den `room_id` des Ursprungsraums zu übergeben
|
||||
|
||||
### Tests
|
||||
- Erstellen neuer Testfälle für das Origin-Priorität-Verhalten
|
||||
- Anpassen bestehender Tests an die neue Signatur
|
||||
|
||||
## 4. Signatur-Änderung
|
||||
|
||||
```python
|
||||
def find_room_by_keywords(self, text: str, min_score: int = 2, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
|
||||
```
|
||||
|
||||
## 5. Pitfalls und Sonderfälle
|
||||
|
||||
### Excluded Rooms
|
||||
Wenn der Ursprungsraum ein excluded_room ist (z.B. BAT-Team, RC-Plugin), greift der Archivar nicht. Der Origin-Check ist nur für nicht-excluded Räume relevant.
|
||||
|
||||
### Catch-All als Ursprung
|
||||
Wenn der Ursprungsraum ein Catch-All-Raum ist, muss immer global gescannt werden, da Catch-All-Räume keine Keywords besitzen.
|
||||
|
||||
### Abwärtskompatibilität
|
||||
Der neue Parameter `origin_room_id` muss optional mit Default=None sein, um die Abwärtskompatibilität zu gewährleisten. Bestehende Aufrufer ohne den Parameter dürfen weiterhin funktionieren.
|
||||
|
||||
### Testabdeckung
|
||||
Es müssen neue Tests hinzugefügt werden, um verschiedene Szenarien abzudecken:
|
||||
- Nachricht aus normalem Raum mit Keyword-Match im Ursprungsraum
|
||||
- Nachricht aus normalem Raum ohne Keyword-Match im Ursprungsraum (Global-Fallback)
|
||||
- Nachricht aus Catch-All-Raum
|
||||
- Nachricht aus excluded_room
|
||||
@@ -0,0 +1,296 @@
|
||||
# Vertiefte Architekturskizze: Selbstlernendes Keyword-Gewicht-System (Teil 2)
|
||||
|
||||
## Überblick
|
||||
|
||||
Das selbstlernende Keyword-Gewicht-System ist Teil 2 des zweistufigen Evidenz-Systems. Es basiert auf den bereits implementierten `keywords_100` (100% Evidenz) und `keywords_context` (<100% Evidenz) und lernt aus den Entscheidungen der Benutzer, um die Routing-Genauigkeit kontinuierlich zu verbessern.
|
||||
|
||||
## 1. Präziser Lernalgorithmus
|
||||
|
||||
### 1.1 Grundlegender Lernmechanismus
|
||||
|
||||
Der Lernalgorithmus passt die Gewichte basierend auf Benutzerfeedback an. Jedes Keyword in `keywords_context` hat für jeden Raum ein Gewicht zwischen 0.0 und 1.0.
|
||||
|
||||
### 1.2 Gewichtsanpassungsformel
|
||||
|
||||
Bei positivem Feedback (✅Ja):
|
||||
```
|
||||
neues_gewicht = altes_gewicht + (1 - altes_gewicht) * lernrate
|
||||
anderes_gewicht = anderes_gewicht - (anderes_gewicht * lernrate / (anzahl_andere_räume))
|
||||
```
|
||||
|
||||
Bei negativem Feedback (📍Hier oder 📌Generell):
|
||||
```
|
||||
neues_gewicht = altes_gewicht - altes_gewicht * lernrate
|
||||
anderes_gewicht = anderes_gewicht + ((1 - anderes_gewicht) * lernrate / (anzahl_andere_räume))
|
||||
```
|
||||
|
||||
### 1.3 Lernrate und Begrenzungen
|
||||
|
||||
- **Lernrate**: 0.1 (konfigurierbar)
|
||||
- **Maximalgewicht**: 0.95
|
||||
- **Minimalgewicht**: 0.05
|
||||
- **Glättung**: Gewichte werden exponentiell gedämpft, um Extremwerte zu vermeiden
|
||||
|
||||
### 1.4 Sticky-Room Konzept
|
||||
|
||||
Für "📌Generell" (nie routen) wird ein Sticky-Room erstellt:
|
||||
- Ein virtueller Raum mit ID "sticky_room"
|
||||
- Keywords mit Gewicht 0.0 in diesem Raum
|
||||
- Verhindert Routing zu ausgeschlossenen Räumen
|
||||
|
||||
## 2. Drei Feedback-Typen mit unterschiedlicher Wirkung
|
||||
|
||||
### 2.1 "✅Ja" (rüberkopieren) - Starkes positives Signal
|
||||
|
||||
- **Wirkung**: Erhöht das Gewicht für den Zielraum signifikant
|
||||
- **Gewichtsanpassung**: +0.1 (gedämpft)
|
||||
- **Verteilung**: Reduziertes Gewicht wird gleichmäßig auf andere Räume verteilt
|
||||
- **Promotion**: Zählt als 1 Bestätigung für die Promotion-Schwelle
|
||||
|
||||
### 2.2 "📍Hier" (hier bleiben) - Schwaches negatives Signal
|
||||
|
||||
- **Wirkung**: Zeigt an, dass das Routing falsch war, aber das Keyword im Raum bleiben soll
|
||||
- **Gewichtsanpassung**: -0.05 (gedämpft)
|
||||
- **Verteilung**: Gewicht wird auf andere Räume verteilt, aber mit geringerer Rate
|
||||
- **Promotion**: Zählt als 0.5 negative Bestätigungen
|
||||
|
||||
### 2.3 "📌Generell" (nie routen) - Starkes negatives Signal + Sticky-Room
|
||||
|
||||
- **Wirkung**: Starkes negatives Signal, Keyword soll nie zu diesem Raum geroutet werden
|
||||
- **Gewichtsanpassung**: Setzt Gewicht auf 0.0 für diesen Raum
|
||||
- **Sticky-Room**: Erstellt/aktualisiert Sticky-Room Eintrag
|
||||
- **Promotion**: Verhindert Promotion, zählt als 2 negative Bestätigungen
|
||||
|
||||
## 3. Promotion-Schwelle
|
||||
|
||||
### 3.1 Kriterien für die Promotion
|
||||
|
||||
Ein Keyword aus `keywords_context` wird nach `keywords_100` verschoben, wenn:
|
||||
- **Positive Bestätigungen**: Mindestens 3 "✅Ja" Bestätigungen im gleichen Raum
|
||||
- **Konsistenz**: Keine "📍Hier" oder "📌Generell" Ablehnungen im gleichen Raum
|
||||
- **Gewichtsschwelle**: Gewicht ≥ 0.85 im Zielraum
|
||||
|
||||
### 3.2 Degradation (keywords_100 → context)
|
||||
|
||||
Ein Keyword aus `keywords_100` wird nach `keywords_context` zurückverschoben, wenn:
|
||||
- **Negative Bestätigungen**: 2 "📌Generell" Ablehnungen oder 4 "📍Hier" Ablehnungen
|
||||
- **Manuelle Intervention**: Explizites Zurückverschieben durch Administrator
|
||||
|
||||
### 3.3 Zeitbasierte Abwertung
|
||||
|
||||
- **Decay-Rate**: Nach 30 Tagen ohne Bestätigung wird das Gewicht um 10% reduziert
|
||||
- **Verfall**: Nach 90 Tagen ohne Bestätigung wird das Gewicht um 30% reduziert
|
||||
|
||||
## 4. Datenstruktur
|
||||
|
||||
### 4.1 JSON-Schema für keyword_weights in archivar_state.json
|
||||
|
||||
```json
|
||||
{
|
||||
"keyword_weights": {
|
||||
"plugin": {
|
||||
"6a19b0ff02aeecd36b1aa16c": {
|
||||
"weight": 0.7,
|
||||
"last_updated": "2026-06-12T10:30:00Z",
|
||||
"confirmation_count": 2,
|
||||
"rejection_count": 0,
|
||||
"last_confirmation": "2026-06-12T10:30:00Z"
|
||||
},
|
||||
"69f8beaef06dba03be82f9fc": {
|
||||
"weight": 0.3,
|
||||
"last_updated": "2026-06-10T14:15:00Z",
|
||||
"confirmation_count": 1,
|
||||
"rejection_count": 1,
|
||||
"last_confirmation": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"sticky_keywords": {
|
||||
"gateway": ["6a19b0ff02aeecd36b1aa16c"],
|
||||
"deployment": ["69f8beaef06dba03be82f9fc"]
|
||||
},
|
||||
"promotion_candidates": {
|
||||
"plugin": {
|
||||
"6a19b0ff02aeecd36b1aa16c": {
|
||||
"score": 2.5,
|
||||
"last_updated": "2026-06-12T10:30:00Z"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4.2 Felder und ihre Bedeutung
|
||||
|
||||
- **weight**: Aktuelles Gewicht des Keywords im Raum (0.0 - 1.0)
|
||||
- **last_updated**: Zeitstempel der letzten Gewichtsanpassung (ISO 8601)
|
||||
- **confirmation_count**: Anzahl der "✅Ja" Bestätigungen
|
||||
- **rejection_count**: Anzahl der "📍Hier"/"📌Generell" Ablehnungen
|
||||
- **last_confirmation**: Zeitstempel der letzten positiven Bestätigung
|
||||
- **sticky_keywords**: Liste von Keywords, die nie zu bestimmten Räumen geroutet werden
|
||||
- **promotion_candidates**: Keywords, die nahe an der Promotion-Schwelle sind
|
||||
|
||||
## 5. Manuelle Overrides
|
||||
|
||||
### 5.1 Speicherung von Overrides
|
||||
|
||||
Manuelle Overrides werden in einer separaten Sektion gespeichert:
|
||||
|
||||
```json
|
||||
{
|
||||
"manual_overrides": {
|
||||
"plugin": {
|
||||
"6a19b0ff02aeecd36b1aa16c": {
|
||||
"override_weight": 0.9,
|
||||
"override_reason": "Manuelle Anpassung durch Administrator",
|
||||
"override_date": "2026-06-12T11:00:00Z",
|
||||
"override_by": "admin_user"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 Vorrang von Overrides
|
||||
|
||||
- **Priorität 1**: Manuelle Overrides haben immer höchste Priorität
|
||||
- **Priorität 2**: Sticky-Room Einschränkungen
|
||||
- **Priorität 3**: Gelernte Gewichte
|
||||
|
||||
### 5.3 Umgang mit gelernten Keywords bei Overrides
|
||||
|
||||
Wenn ein Benutzer ein gelerntes Keyword manuell überschreibt:
|
||||
1. Das Override wird gespeichert
|
||||
2. Das gelernte Gewicht wird beibehalten, aber deaktiviert
|
||||
3. Eine Warnung wird im Log erzeugt
|
||||
4. Bei zukünftigen Bestätigungen wird das Override berücksichtigt
|
||||
|
||||
## 6. Cold-Start Verhalten
|
||||
|
||||
### 6.1 Verhalten bei frischem Archivar
|
||||
|
||||
Ein frischer Archivar ohne Gewichte verhält sich wie folgt:
|
||||
|
||||
1. **Fallback auf statische keywords_context**: Verwendet die bestehenden `keywords_context` mit gleichmäßiger Gewichtsverteilung
|
||||
2. **Initialgewichte**: Alle Keywords erhalten ein Startgewicht von 1.0 / Anzahl_der_Räume
|
||||
3. **Lernmodus**: Aktiviert das Lernen sofort nach der ersten Bestätigung
|
||||
|
||||
### 6.2 Bootstrap-Strategie
|
||||
|
||||
- **Tag 1-7**: Höhere Lernrate (0.2) für schnelles initiales Lernen
|
||||
- **Tag 8+**: Normale Lernrate (0.1)
|
||||
- **Fallback**: Bei weniger als 3 Räumen wird auf einfache Keyword-Matching-Logik zurückgegriffen
|
||||
|
||||
## 7. Edge Cases und Pitfalls
|
||||
|
||||
### 7.1 Overfitting
|
||||
|
||||
**Problem**: Das System lernt zu stark aus wenigen Beispielen
|
||||
**Lösung**:
|
||||
- Mindestanzahl von 3 Bestätigungen für Promotion
|
||||
- Zeitbasierte Abwertung von Gewichten
|
||||
- Glättungsfaktoren in der Lernformel
|
||||
|
||||
### 7.2 Falsches Lernen aus einmaligen Fehlklicks
|
||||
|
||||
**Problem**: Einzelne falsche Bestätigungen verfälschen die Gewichte
|
||||
**Lösung**:
|
||||
- Konfidenzbasierte Gewichtsanpassung (erfordert mehrere Bestätigungen)
|
||||
- "📍Hier" zählt nur als halbe negative Bestätigung
|
||||
- Manuelle Override-Möglichkeit für Administratoren
|
||||
|
||||
### 7.3 Speicherwachstum
|
||||
|
||||
**Problem**: Unkontrolliertes Wachstum der keyword_weights Datenstruktur
|
||||
**Lösung**:
|
||||
- Automatische Bereinigung von Keywords ohne Aktivität (>90 Tage)
|
||||
- Begrenzung der maximalen Anzahl gelernter Keywords pro Raum
|
||||
- Komprimierung von Gewichten mit geringem Einfluss (<0.1)
|
||||
|
||||
### 7.4 Konflikte zwischen Räumen
|
||||
|
||||
**Problem**: Mehrere Räume beanspruchen das gleiche Keyword
|
||||
**Lösung**:
|
||||
- Relative Gewichtung statt absoluter Gewichte
|
||||
- Konfliktauflösung basierend auf Gesamtkontext-Score
|
||||
- Manuelle Priorisierung durch Administratoren
|
||||
|
||||
### 7.5 Degradierende Lernrate
|
||||
|
||||
**Problem**: Das System hört auf zu lernen, wenn Gewichte extrem sind
|
||||
**Lösung**:
|
||||
- Exponentielle Dämpfung statt linearer Anpassung
|
||||
- Periodische Rekalibrierung der Gewichte
|
||||
- Einführung von "Refresher"-Bestätigungen
|
||||
|
||||
## 8. Implementierungsdetails
|
||||
|
||||
### 8.1 Datenstruktur für den ArchivarState
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class KeywordWeightEntry:
|
||||
weight: float
|
||||
last_updated: datetime
|
||||
confirmation_count: int
|
||||
rejection_count: int
|
||||
last_confirmation: Optional[datetime]
|
||||
|
||||
@dataclass
|
||||
class ManualOverride:
|
||||
override_weight: float
|
||||
override_reason: str
|
||||
override_date: datetime
|
||||
override_by: str
|
||||
|
||||
class ArchivarState:
|
||||
_keyword_weights: Dict[str, Dict[str, KeywordWeightEntry]]
|
||||
_sticky_keywords: Dict[str, List[str]] # keyword -> list of room_ids
|
||||
_manual_overrides: Dict[str, Dict[str, ManualOverride]]
|
||||
_promotion_candidates: Dict[str, Dict[str, Dict[str, Union[float, datetime]]]]
|
||||
```
|
||||
|
||||
### 8.2 Kernfunktionen des Lernalgorithmus
|
||||
|
||||
```python
|
||||
def update_keyword_weight(self, keyword: str, room_id: str, feedback_type: str) -> bool:
|
||||
"""
|
||||
Aktualisiert das Gewicht basierend auf Benutzerfeedback.
|
||||
|
||||
Args:
|
||||
keyword: Das betroffene Keyword
|
||||
room_id: Die Zielraum-ID
|
||||
feedback_type: "confirm", "stay", oder "never"
|
||||
|
||||
Returns:
|
||||
True wenn das Gewicht erfolgreich aktualisiert wurde
|
||||
"""
|
||||
pass
|
||||
|
||||
def calculate_room_score(self, keyword: str, room_id: str) -> float:
|
||||
"""
|
||||
Berechnet den Score für ein Keyword in einem Raum unter Berücksichtigung
|
||||
von Overrides, Sticky-Rooms und gelernten Gewichten.
|
||||
"""
|
||||
pass
|
||||
|
||||
def check_promotion_eligibility(self, keyword: str, room_id: str) -> bool:
|
||||
"""
|
||||
Prüft ob ein Keyword für die Promotion in keywords_100 berechtigt ist.
|
||||
"""
|
||||
pass
|
||||
```
|
||||
|
||||
## 9. Monitoring und Debugging
|
||||
|
||||
### 9.1 Lernfortschritt-Tracking
|
||||
|
||||
- Protokollierung aller Gewichtsänderungen
|
||||
- Statistiken über Bestätigungen/Ablehnungen
|
||||
- Performance-Metriken des Matchers
|
||||
|
||||
### 9.2 Debugging-Tools
|
||||
|
||||
- Gewichtsanzeige pro Keyword und Raum
|
||||
- Lernhistorie für einzelne Keywords
|
||||
- Override-Log zur Nachverfolgung manueller Änderungen
|
||||
@@ -0,0 +1,43 @@
|
||||
# Architektur: Agent-Modellgrößenprüfung für Multi-Room-Szenarien
|
||||
|
||||
## Zweck
|
||||
|
||||
Bei der Installation eines Multi-Room-Agents soll das installierte Agent-Modell auf seine Eignung für raumübergreifende Kontexthaltung geprüft werden. Modelle mit weniger als 80 Milliarden Parametern können diese Aufgabe nicht zuverlässig erfüllen. Die Prüfung soll während des Setups (`install.sh`) erfolgen und eine Warnung ausgeben, ohne den Installationsprozess zu blockieren.
|
||||
|
||||
## Einbettungspunkt
|
||||
|
||||
Die Prüfung wird in das `install.sh`-Skript integriert. Sie erfolgt nach erfolgreicher Installation, aber vor der abschließenden Freigabe der Installation. Der genaue Einbettungspunkt ist direkt nach der Erstkonfiguration des Agenten, aber vor dem Start des ersten Sitzungsprozesses.
|
||||
|
||||
## Heuristik
|
||||
|
||||
Die Modellgröße wird anhand des Namens in der `config.yaml` ermittelt. Es wird eine Heuristik angewendet, die auf bekannte Modellgrößen-Suffixe prüft:
|
||||
|
||||
- 4b, 7b, 12b → Warnung (kleine Modelle)
|
||||
- 32b → Warnung (mittelgroße Modelle)
|
||||
- 70b → Warnung (große Modelle)
|
||||
- 80b, 235b, 480b → OK (ausreichend für Multi-Room)
|
||||
|
||||
Die Heuristik ignoriert Classifier-Modelle und betrachtet ausschließlich das primäre Agent-Modell.
|
||||
|
||||
## Prompt-Text
|
||||
|
||||
Bei Erkennung eines ungeeigneten Modells wird folgender Text ausgegeben:
|
||||
|
||||
```
|
||||
WARNUNG: Das ausgewählte Agent-Modell ist möglicherweise nicht für Multi-Room-Szenarien geeignet.
|
||||
Erkanntes Modell: [modellname]
|
||||
Geschätzte Parameter: [größe]
|
||||
|
||||
Für zuverlässige raumübergreifende Kontexthaltung wird ein Modell mit mindestens 80B Parametern empfohlen.
|
||||
Sie können das Modell später mit 'hermes model' ändern.
|
||||
|
||||
Möchten Sie trotzdem fortfahren? (j/N):
|
||||
```
|
||||
|
||||
## Pitfalls
|
||||
|
||||
1. **Falsch-Positive**: Modellnamen ohne klare Größenangabe werden nicht bewertet, was zu unsichtbaren Problemen führen kann.
|
||||
2. **Heuristik-Grenzen**: Die Namensheuristik kann bei unkonventionellen Modellbezeichnungen versagen.
|
||||
3. **Benutzerfreundlichkeit**: Die Warnung sollte nicht zu aggressiv sein, da erfahrene Benutzer bewusst kleinere Modelle verwenden könnten.
|
||||
4. **Konfigurationspfade**: Unterschiedliche Profil-Konfigurationen könnten zu falschen Prüfergebnissen führen.
|
||||
5. **Fallback-Modelle**: Die Prüfung betrachtet nur das primäre Modell, nicht mögliche Fallback-Modelle.
|
||||
@@ -0,0 +1,109 @@
|
||||
# Move-Request Dialog - Button UX Verbesserung
|
||||
|
||||
## Übersicht
|
||||
|
||||
Verbesserung der Benutzerfreundlichkeit des Move-Request-Dialogs im Rocket.Chat-Plugin durch eine klare Beschreibung der Button-Funktionen vor den Schaltflächen.
|
||||
|
||||
## Aktueller Zustand
|
||||
|
||||
### Dialog-Text
|
||||
```
|
||||
Dein Auftrag passt thematisch besser in **{target_name}**.
|
||||
```
|
||||
|
||||
### Buttons
|
||||
- ✅Ja
|
||||
- 📍Hier
|
||||
- 📌Generell
|
||||
|
||||
### Probleme
|
||||
- "📌Generell" ist für Benutzer nicht verständlich
|
||||
- Keine Erklärung, was die Buttons tatsächlich bewirken
|
||||
- Benutzer müssen durch Ausprobieren erfahren, was passiert
|
||||
|
||||
## Verbesserter Zustand
|
||||
|
||||
### Dialog-Text (erweitert)
|
||||
```
|
||||
Dein Auftrag passt thematisch besser in **{target_name}**.
|
||||
|
||||
**Was soll ich tun?**
|
||||
|
||||
1️⃣ **Rüberkopieren** = Auftrag verschieben, ich antworte dort
|
||||
2️⃣ **Hier bleiben** = Auftrag bleibt hier, ich kümmere mich drum
|
||||
3️⃣ **Nicht mehr fragen** = Raum wird bis Neustart nicht mehr geroutet
|
||||
|
||||
Wohin soll ich den Auftrag verschieben?
|
||||
```
|
||||
|
||||
### Neue Buttons
|
||||
- 1️⃣ Rüber
|
||||
- 2️⃣ Hier
|
||||
- 3️⃣ Nein
|
||||
|
||||
### Begründung für neue Button-Labels
|
||||
- **Kürzer** (max. 7 Zeichen auf Desktop)
|
||||
- **Einheitlich** (alle numeriert)
|
||||
- **Verständlicher** ("Nein" statt "Generell")
|
||||
- **Konsistent** mit Numbered-Reference-Pattern
|
||||
|
||||
## Implementierungsdetails
|
||||
|
||||
### Empfangscode-Anpassungen
|
||||
|
||||
Der Code in `adapter.py` muss die neuen Button-Labels erkennen können:
|
||||
|
||||
```python
|
||||
# Neue Mapping-Logik
|
||||
if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren"):
|
||||
# Rüberkopieren
|
||||
elif choice in ("2", "2️⃣", "Hier", "hier"):
|
||||
# Hier bleiben
|
||||
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"):
|
||||
# Nicht mehr fragen / sticky_room setzen
|
||||
```
|
||||
|
||||
### Dateiänderungen
|
||||
|
||||
1. **plugin/adapter.py** (ca. Zeile 806)
|
||||
- Erweitern des `note`-Textes mit der Beschreibung
|
||||
- Anpassen der Button-Labels in der `buttons`-Liste
|
||||
|
||||
2. **plugin/adapter.py** (ca. Zeile 736)
|
||||
- Erweitern der Erkennungslogik für Button-Antworten
|
||||
|
||||
### Pitfalls und Constraints
|
||||
|
||||
#### Button-Truncation
|
||||
- Rocket.Chat kürzt Button-Texte nach ~7 Zeichen auf Desktop
|
||||
- Lösung: Kurze, prägnante Labels verwenden
|
||||
|
||||
#### Underscore-Verbot
|
||||
- Underscores werden in Button-Labels nicht korrekt dargestellt
|
||||
- Lösung: Verwendung von Emojis und Leerzeichen vermeiden
|
||||
|
||||
#### Trennzeichen-Konsistenz
|
||||
- Einheitliche Verwendung von:
|
||||
- Emojis für Nummerierung (1️⃣, 2️⃣, 3️⃣)
|
||||
- Klare Trennung zwischen Beschreibung und Buttons
|
||||
- Konsistente Terminologie in Text und Button-Labels
|
||||
|
||||
#### Abwärtskompatibilität
|
||||
- Alte numerische Antworten ("1", "2", "3") müssen weiterhin funktionieren
|
||||
- Alte Text-Antworten ("rüberkopieren", "hier bleiben", "generell") müssen weiterhin erkannt werden
|
||||
|
||||
## Sicherheitsaspekte
|
||||
|
||||
- Keine Änderungen an der Sicherheitslogik erforderlich
|
||||
- Bestehende Persistenz-Mechanismen bleiben unverändert
|
||||
- Button-Erkennung ist erweiterbar ohne Breaking Changes
|
||||
|
||||
## Testfälle
|
||||
|
||||
1. **Neuer Dialogtext wird korrekt angezeigt**
|
||||
2. **Neue Buttons werden korrekt gerendert**
|
||||
3. **Rüberkopieren-Button funktioniert**
|
||||
4. **Hier-bleiben-Button funktioniert**
|
||||
5. **Nicht-mehr-fragen-Button funktioniert**
|
||||
6. **Alte numerische Antworten funktionieren weiterhin**
|
||||
7. **Alte Text-Antworten funktionieren weiterhin**
|
||||
+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)
|
||||
**Catch-All:** DM andreas/Bernd (`69f4e777f06dba03be82dce7`)
|
||||
**Stand:** 03. Juni 2026 (anonymisiert für generische Verwendung)
|
||||
**Catch-All:** DM Admin (`<ADMIN_DM_ROOM_ID>`)
|
||||
|
||||
## Gemappte Räume
|
||||
## Gemappte Räume (Beispiele)
|
||||
|
||||
| Raum | Typ | Thema |
|
||||
|---|---|---|
|
||||
| `#BAT-Team` | channel | BAT-Trading-Plattform (Docker-Stack, Commits, Agent-Health, Entwicklerteam) |
|
||||
| `Rocketchat-Plugin` | group | Hermes Rocket.Chat Plugin (Gateway, Upload, Buttons, Adapter) |
|
||||
| `Protonbridge-Plugin` | group | ProtonMail-Bridge-Plugin (Mail, Bridge, SMTP) |
|
||||
| `DM andreas/Bernd` | dm | Allgemein, Meta, Strategie — **Catch-All** |
|
||||
| `DM mit Bernd, Thomas` | 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. |
|
||||
| `#Support-Team` | channel | Erst-Level-Support (Tickets, Bug-Reports, User-Feedback) |
|
||||
| `RC-Plugin-Dev` | group | Rocket.Chat Plugin-Entwicklung (Gateway, Upload, Buttons, Adapter) |
|
||||
| `Mail-Bridge-Plugin` | group | E-Mail-Bridge-Plugin (Mail, Bridge, SMTP) |
|
||||
| `DM Admin` | dm | Allgemein, Meta, Strategie — **Catch-All** |
|
||||
| `DM Team-Kollege` | dm | 🔇 Inaktiv — nur bei expliziter Aufforderung |
|
||||
| `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)
|
||||
|
||||
- `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
|
||||
|
||||
|
||||
Regular → Executable
+953
-52
File diff suppressed because it is too large
Load Diff
+9
-2
@@ -52,11 +52,16 @@ _TEMPLATE_MAP = {
|
||||
}
|
||||
|
||||
|
||||
def _build_custom_buttons(labels: list, prefix: str = "") -> list:
|
||||
def _build_custom_buttons(labels: list, prefix: str = "", style: str = "default") -> list:
|
||||
"""Build Rocket.Chat action buttons from plain label strings.
|
||||
|
||||
Rocket.Chat UI truncates button text after ~11-12 chars.
|
||||
Use short labels (emoji+text without spaces, or numbered refs).
|
||||
|
||||
Args:
|
||||
labels: Button display texts (keep short — emoji preferred)
|
||||
prefix: Payload prefix for correlation (e.g. "ONBOARD:<rid>")
|
||||
style: Rocket.Chat button style — "default" (grey) or "primary" (blue)
|
||||
"""
|
||||
buttons = []
|
||||
for idx, label in enumerate(labels):
|
||||
@@ -71,7 +76,7 @@ def _build_custom_buttons(labels: list, prefix: str = "") -> list:
|
||||
"text": display,
|
||||
"msg": msg_payload,
|
||||
"msg_in_chat_window": True,
|
||||
"style": "default",
|
||||
"style": style,
|
||||
})
|
||||
return buttons
|
||||
|
||||
@@ -97,6 +102,8 @@ def is_connected(config) -> bool:
|
||||
|
||||
def register(ctx):
|
||||
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
||||
_MULTIROOM = os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||
|
||||
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
||||
from .tools import register_tools
|
||||
|
||||
|
||||
+1503
-28
File diff suppressed because it is too large
Load Diff
@@ -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,35 @@
|
||||
"""
|
||||
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 IntentClassifier, ClassificationResult, EmbeddingClient, OllamaEmbeddingClient
|
||||
from .config import ROOM_MAPPING, CATCH_ALL_ROOM, CATEGORY_TEXTS, OLLAMA_CONFIG, CONFIDENCE_THRESHOLDS, ROOM_MAP_PATH, ARCHIVAR_STATE_PATH
|
||||
from .doc_store import DocumentationStore
|
||||
from .router import BidirectionalRouter, RoutingDecision
|
||||
from .adapter_integration import ArchivarMessageHandler
|
||||
from .archivar_state import ArchivarState
|
||||
|
||||
__all__ = [
|
||||
"IntentClassifier",
|
||||
"ClassificationResult",
|
||||
"EmbeddingClient",
|
||||
"OllamaEmbeddingClient",
|
||||
"DocumentationStore",
|
||||
"ROOM_MAPPING",
|
||||
"CATCH_ALL_ROOM",
|
||||
"CATEGORY_TEXTS",
|
||||
"OLLAMA_CONFIG",
|
||||
"CONFIDENCE_THRESHOLDS",
|
||||
"ROOM_MAP_PATH",
|
||||
"ARCHIVAR_STATE_PATH",
|
||||
"BidirectionalRouter",
|
||||
"RoutingDecision",
|
||||
"ArchivarMessageHandler",
|
||||
"ArchivarState",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,572 @@
|
||||
"""
|
||||
Persistenz-Layer für Archivar v3.
|
||||
|
||||
Speichert und lädt Raum-Zustände für das Routing-Verhalten.
|
||||
Die Zustände werden in einer JSON-Datei gespeichert und über Neustarts hinweg persistiert.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Optional, Union, List
|
||||
|
||||
# Use absolute import instead of relative import
|
||||
try:
|
||||
from config import ARCHIVAR_STATE_PATH
|
||||
except ImportError:
|
||||
# Fallback for testing
|
||||
ARCHIVAR_STATE_PATH = "~/.hermes/hermes-agent/data/archivar-state.json"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RoomState:
|
||||
"""Zustand eines Raums für das Archivar-Routing."""
|
||||
|
||||
stay_decision: str # "always"|"ask"|"never_route"
|
||||
decided_at: str # ISO-Zeitstempel
|
||||
decided_by: str # Benutzername
|
||||
|
||||
|
||||
@dataclass
|
||||
class KeywordWeightEntry:
|
||||
"""Eintrag für ein Keyword-Gewicht in einem Raum."""
|
||||
|
||||
weight: float
|
||||
last_updated: str # ISO-Zeitstempel
|
||||
confirmation_count: int
|
||||
rejection_count: int
|
||||
last_confirmation: Optional[str] # ISO-Zeitstempel oder None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ManualOverride:
|
||||
"""Manueller Override für ein Keyword-Gewicht."""
|
||||
|
||||
override_weight: float
|
||||
override_reason: str
|
||||
override_date: str # ISO-Zeitstempel
|
||||
override_by: str
|
||||
|
||||
|
||||
class ArchivarState:
|
||||
"""Persistenz-Layer für Archivar v3 Raum-Zustände."""
|
||||
|
||||
def __init__(self, state_file_path: Optional[str] = None) -> None:
|
||||
"""
|
||||
Args:
|
||||
state_file_path: Pfad zur JSON-Datei für den Zustand.
|
||||
Wenn None, wird der Standardpfad aus der Konfiguration verwendet.
|
||||
"""
|
||||
self._state_file_path = state_file_path or ARCHIVAR_STATE_PATH
|
||||
self._rooms: Dict[str, RoomState] = {}
|
||||
self._keyword_weights: Dict[str, Dict[str, KeywordWeightEntry]] = {}
|
||||
self._sticky_keywords: Dict[str, List[str]] = {} # keyword -> list of room_ids
|
||||
self._manual_overrides: Dict[str, Dict[str, ManualOverride]] = {}
|
||||
self._promotion_candidates: Dict[str, Dict[str, Dict[str, Union[float, str]]]] = {}
|
||||
self._loaded = False
|
||||
|
||||
def load(self) -> bool:
|
||||
"""Lade den Zustand aus der Datei.
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich geladen, False bei Fehler.
|
||||
"""
|
||||
try:
|
||||
# Stelle sicher, dass das Verzeichnis existiert
|
||||
os.makedirs(os.path.dirname(self._state_file_path), exist_ok=True)
|
||||
|
||||
if not os.path.exists(self._state_file_path):
|
||||
# Erstelle eine leere Datei wenn sie nicht existiert
|
||||
self._save_to_file({})
|
||||
logger.info("Created new archivar state file: %s", self._state_file_path)
|
||||
return True
|
||||
|
||||
with open(self._state_file_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
rooms_data = data.get("rooms", {})
|
||||
self._rooms = {}
|
||||
|
||||
for room_id, state_data in rooms_data.items():
|
||||
self._rooms[room_id] = RoomState(
|
||||
stay_decision=state_data["stay_decision"],
|
||||
decided_at=state_data["decided_at"],
|
||||
decided_by=state_data["decided_by"]
|
||||
)
|
||||
|
||||
# Lade Keyword-Gewichte
|
||||
keyword_weights_data = data.get("keyword_weights", {})
|
||||
self._keyword_weights = {}
|
||||
for keyword, rooms_data in keyword_weights_data.items():
|
||||
self._keyword_weights[keyword] = {}
|
||||
for room_id, weight_data in rooms_data.items():
|
||||
self._keyword_weights[keyword][room_id] = KeywordWeightEntry(
|
||||
weight=weight_data["weight"],
|
||||
last_updated=weight_data["last_updated"],
|
||||
confirmation_count=weight_data["confirmation_count"],
|
||||
rejection_count=weight_data["rejection_count"],
|
||||
last_confirmation=weight_data["last_confirmation"]
|
||||
)
|
||||
|
||||
# Lade Sticky-Keywords
|
||||
self._sticky_keywords = data.get("sticky_keywords", {})
|
||||
|
||||
# Lade manuelle Overrides
|
||||
manual_overrides_data = data.get("manual_overrides", {})
|
||||
self._manual_overrides = {}
|
||||
for keyword, rooms_data in manual_overrides_data.items():
|
||||
self._manual_overrides[keyword] = {}
|
||||
for room_id, override_data in rooms_data.items():
|
||||
self._manual_overrides[keyword][room_id] = ManualOverride(
|
||||
override_weight=override_data["override_weight"],
|
||||
override_reason=override_data["override_reason"],
|
||||
override_date=override_data["override_date"],
|
||||
override_by=override_data["override_by"]
|
||||
)
|
||||
|
||||
# Lade Promotion-Kandidaten
|
||||
self._promotion_candidates = data.get("promotion_candidates", {})
|
||||
|
||||
self._loaded = True
|
||||
logger.info("Loaded archivar state for %d rooms", len(self._rooms))
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Failed to load archivar state: %s", e)
|
||||
return False
|
||||
|
||||
def save(self) -> bool:
|
||||
"""Speichere den aktuellen Zustand in die Datei.
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich gespeichert, False bei Fehler.
|
||||
"""
|
||||
try:
|
||||
return self._save_to_file(self._to_dict())
|
||||
except Exception as e:
|
||||
logger.error("Failed to save archivar state: %s", e)
|
||||
return False
|
||||
|
||||
def _save_to_file(self, data: dict) -> bool:
|
||||
"""Speichere Daten in die Zustandsdatei."""
|
||||
try:
|
||||
# Stelle sicher, dass das Verzeichnis existiert
|
||||
os.makedirs(os.path.dirname(self._state_file_path), exist_ok=True)
|
||||
|
||||
with open(self._state_file_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
logger.debug("Saved archivar state to %s", self._state_file_path)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error("Failed to write archivar state file: %s", e)
|
||||
return False
|
||||
|
||||
def _to_dict(self) -> dict:
|
||||
"""Konvertiere den Zustand in ein serialisierbares Dictionary."""
|
||||
rooms_dict = {}
|
||||
for room_id, state in self._rooms.items():
|
||||
rooms_dict[room_id] = {
|
||||
"stay_decision": state.stay_decision,
|
||||
"decided_at": state.decided_at,
|
||||
"decided_by": state.decided_by
|
||||
}
|
||||
|
||||
# Konvertiere Keyword-Gewichte
|
||||
keyword_weights_dict = {}
|
||||
for keyword, rooms_data in self._keyword_weights.items():
|
||||
keyword_weights_dict[keyword] = {}
|
||||
for room_id, weight_entry in rooms_data.items():
|
||||
keyword_weights_dict[keyword][room_id] = {
|
||||
"weight": weight_entry.weight,
|
||||
"last_updated": weight_entry.last_updated,
|
||||
"confirmation_count": weight_entry.confirmation_count,
|
||||
"rejection_count": weight_entry.rejection_count,
|
||||
"last_confirmation": weight_entry.last_confirmation
|
||||
}
|
||||
|
||||
# Konvertiere manuelle Overrides
|
||||
manual_overrides_dict = {}
|
||||
for keyword, rooms_data in self._manual_overrides.items():
|
||||
manual_overrides_dict[keyword] = {}
|
||||
for room_id, override_entry in rooms_data.items():
|
||||
manual_overrides_dict[keyword][room_id] = {
|
||||
"override_weight": override_entry.override_weight,
|
||||
"override_reason": override_entry.override_reason,
|
||||
"override_date": override_entry.override_date,
|
||||
"override_by": override_entry.override_by
|
||||
}
|
||||
|
||||
return {
|
||||
"rooms": rooms_dict,
|
||||
"keyword_weights": keyword_weights_dict,
|
||||
"sticky_keywords": self._sticky_keywords,
|
||||
"manual_overrides": manual_overrides_dict,
|
||||
"promotion_candidates": self._promotion_candidates
|
||||
}
|
||||
|
||||
def get_room_state(self, room_id: str) -> Optional[RoomState]:
|
||||
"""Hole den Zustand für einen Raum.
|
||||
|
||||
Args:
|
||||
room_id: Die ID des Raums.
|
||||
|
||||
Returns:
|
||||
RoomState wenn vorhanden, sonst None.
|
||||
"""
|
||||
if not self._loaded:
|
||||
self.load()
|
||||
return self._rooms.get(room_id)
|
||||
|
||||
def set_room_state(self, room_id: str, decision: str, decided_by: str) -> bool:
|
||||
"""Setze den Zustand für einen Raum.
|
||||
|
||||
Args:
|
||||
room_id: Die ID des Raums.
|
||||
decision: Die Entscheidung ("always"|"ask"|"never_route").
|
||||
decided_by: Der Benutzer, der die Entscheidung getroffen hat.
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich gespeichert, False bei Fehler.
|
||||
"""
|
||||
if decision not in ("always", "ask", "never_route"):
|
||||
logger.error("Invalid stay decision: %s", decision)
|
||||
return False
|
||||
|
||||
state = RoomState(
|
||||
stay_decision=decision,
|
||||
decided_at=datetime.now().isoformat(),
|
||||
decided_by=decided_by
|
||||
)
|
||||
|
||||
self._rooms[room_id] = state
|
||||
|
||||
# Speichere sofort
|
||||
return self.save()
|
||||
|
||||
def should_stay_in_room(self, room_id: str) -> Optional[bool]:
|
||||
"""Prüfe ob Nachrichten im Raum bleiben sollten.
|
||||
|
||||
Args:
|
||||
room_id: Die ID des Raums.
|
||||
|
||||
Returns:
|
||||
True wenn Nachrichten immer im Raum bleiben sollen,
|
||||
False wenn sie nie geroutet werden sollen,
|
||||
None wenn die Entscheidung nicht getroffen wurde.
|
||||
"""
|
||||
state = self.get_room_state(room_id)
|
||||
if not state:
|
||||
return None
|
||||
|
||||
if state.stay_decision == "always":
|
||||
return True
|
||||
elif state.stay_decision == "never_route":
|
||||
return False
|
||||
else:
|
||||
return None # "ask" - Entscheidung pro Nachricht
|
||||
|
||||
def remove_room_state(self, room_id: str) -> bool:
|
||||
"""Entferne den Zustand für einen Raum.
|
||||
|
||||
Args:
|
||||
room_id: Die ID des Raums.
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich entfernt, False bei Fehler.
|
||||
"""
|
||||
if room_id in self._rooms:
|
||||
del self._rooms[room_id]
|
||||
return self.save()
|
||||
return True
|
||||
|
||||
@property
|
||||
def rooms(self) -> Dict[str, RoomState]:
|
||||
"""Gibt eine Kopie der aktuellen Räume zurück."""
|
||||
return self._rooms.copy()
|
||||
|
||||
@property
|
||||
def is_loaded(self) -> bool:
|
||||
"""True wenn der Zustand geladen wurde."""
|
||||
return self._loaded
|
||||
|
||||
# Neue Methoden für das selbstlernende Keyword-Gewicht-System
|
||||
|
||||
def update_keyword_weight(self, keyword: str, room_id: str, feedback_type: str) -> bool:
|
||||
"""
|
||||
Aktualisiert das Gewicht basierend auf Benutzerfeedback.
|
||||
|
||||
Args:
|
||||
keyword: Das betroffene Keyword
|
||||
room_id: Die Zielraum-ID
|
||||
feedback_type: "confirm", "stay", oder "never"
|
||||
|
||||
Returns:
|
||||
True wenn das Gewicht erfolgreich aktualisiert wurde
|
||||
"""
|
||||
try:
|
||||
# Initialisiere Einträge falls nicht vorhanden
|
||||
if keyword not in self._keyword_weights:
|
||||
self._keyword_weights[keyword] = {}
|
||||
|
||||
# Hole oder erstelle den Gewichtseintrag
|
||||
if room_id not in self._keyword_weights[keyword]:
|
||||
# Cold-Start: Initialgewicht basierend auf Anzahl der Räume
|
||||
# (wir nehmen an, dass mindestens 3 Räume existieren)
|
||||
initial_weight = 1.0 / 3.0
|
||||
self._keyword_weights[keyword][room_id] = KeywordWeightEntry(
|
||||
weight=initial_weight,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=0,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
)
|
||||
|
||||
entry = self._keyword_weights[keyword][room_id]
|
||||
|
||||
# Bestimme die Lernrate basierend auf der Anzahl der Bestätigungen
|
||||
# Tag 1-7: LEARNING_RATE = 0.2, Tag 8+: LEARNING_RATE = 0.1
|
||||
learning_rate = 0.2 if entry.confirmation_count < 7 else 0.1
|
||||
|
||||
# Hole die aktuelle Zeit
|
||||
now = datetime.now().isoformat()
|
||||
|
||||
# Hole alle Räume mit Gewichten für dieses Keyword (außer dem Zielraum)
|
||||
other_rooms = {rid: weight_entry for rid, weight_entry in self._keyword_weights[keyword].items()
|
||||
if rid != room_id}
|
||||
|
||||
if feedback_type == "confirm":
|
||||
# Positives Feedback (✅Ja / "confirm")
|
||||
# new_weight = old_weight + (1 - old_weight) * LEARNING_RATE
|
||||
new_weight = entry.weight + (1 - entry.weight) * learning_rate
|
||||
|
||||
# Begrenze das Gewicht auf maximal 0.95
|
||||
new_weight = min(new_weight, 0.95)
|
||||
|
||||
# Verteile reduziertes Gewicht auf andere Räume
|
||||
if other_rooms:
|
||||
weight_reduction = (1 - entry.weight) * learning_rate
|
||||
reduction_per_room = weight_reduction / len(other_rooms)
|
||||
|
||||
for other_room_id, other_entry in other_rooms.items():
|
||||
# other_weight = other_weight - (other_weight * LEARNING_RATE / num_other_rooms)
|
||||
reduced_weight = other_entry.weight - (other_entry.weight * learning_rate / len(other_rooms))
|
||||
# Begrenze das Gewicht auf minimal 0.05
|
||||
reduced_weight = max(reduced_weight, 0.05)
|
||||
|
||||
# Aktualisiere den Eintrag
|
||||
self._keyword_weights[keyword][other_room_id] = KeywordWeightEntry(
|
||||
weight=reduced_weight,
|
||||
last_updated=now,
|
||||
confirmation_count=other_entry.confirmation_count,
|
||||
rejection_count=other_entry.rejection_count,
|
||||
last_confirmation=other_entry.last_confirmation
|
||||
)
|
||||
|
||||
# Aktualisiere den Zielraum
|
||||
self._keyword_weights[keyword][room_id] = KeywordWeightEntry(
|
||||
weight=new_weight,
|
||||
last_updated=now,
|
||||
confirmation_count=entry.confirmation_count + 1,
|
||||
rejection_count=entry.rejection_count,
|
||||
last_confirmation=now
|
||||
)
|
||||
|
||||
elif feedback_type == "stay":
|
||||
# Schwach negatives Feedback (📍Hier / "stay")
|
||||
# new_weight = old_weight - old_weight * LEARNING_RATE * 0.5
|
||||
new_weight = entry.weight - entry.weight * learning_rate * 0.5
|
||||
|
||||
# Begrenze das Gewicht auf minimal 0.05
|
||||
new_weight = max(new_weight, 0.05)
|
||||
|
||||
# Verteile Gewicht auf andere Räume
|
||||
if other_rooms:
|
||||
weight_addition = (1 - entry.weight) * learning_rate * 0.5
|
||||
addition_per_room = weight_addition / len(other_rooms)
|
||||
|
||||
for other_room_id, other_entry in other_rooms.items():
|
||||
# other_weight = other_weight + ((1 - other_weight) * LEARNING_RATE * 0.5 / num_other_rooms)
|
||||
increased_weight = other_entry.weight + ((1 - other_entry.weight) * learning_rate * 0.5 / len(other_rooms))
|
||||
# Begrenze das Gewicht auf maximal 0.95
|
||||
increased_weight = min(increased_weight, 0.95)
|
||||
|
||||
# Aktualisiere den Eintrag
|
||||
self._keyword_weights[keyword][other_room_id] = KeywordWeightEntry(
|
||||
weight=increased_weight,
|
||||
last_updated=now,
|
||||
confirmation_count=other_entry.confirmation_count,
|
||||
rejection_count=other_entry.rejection_count,
|
||||
last_confirmation=other_entry.last_confirmation
|
||||
)
|
||||
|
||||
# Aktualisiere den Zielraum
|
||||
self._keyword_weights[keyword][room_id] = KeywordWeightEntry(
|
||||
weight=new_weight,
|
||||
last_updated=now,
|
||||
confirmation_count=entry.confirmation_count,
|
||||
rejection_count=entry.rejection_count + 1,
|
||||
last_confirmation=entry.last_confirmation
|
||||
)
|
||||
|
||||
elif feedback_type == "never":
|
||||
# Stark negatives Feedback (📌Generell / "never")
|
||||
# Setze Gewicht auf 0.0
|
||||
self._keyword_weights[keyword][room_id] = KeywordWeightEntry(
|
||||
weight=0.0,
|
||||
last_updated=now,
|
||||
confirmation_count=entry.confirmation_count,
|
||||
rejection_count=entry.rejection_count + 2, # Zählt als 2 negative Bestätigungen
|
||||
last_confirmation=entry.last_confirmation
|
||||
)
|
||||
|
||||
# Füge Keyword zu sticky_keywords für diesen Raum hinzu
|
||||
if keyword not in self._sticky_keywords:
|
||||
self._sticky_keywords[keyword] = []
|
||||
if room_id not in self._sticky_keywords[keyword]:
|
||||
self._sticky_keywords[keyword].append(room_id)
|
||||
|
||||
# Prüfe auf Promotion-Berechtigung
|
||||
self.check_promotion_eligibility(keyword, room_id)
|
||||
|
||||
# Speichere den aktualisierten Zustand
|
||||
return self.save()
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Failed to update keyword weight: %s", e)
|
||||
return False
|
||||
|
||||
def calculate_room_score(self, keyword: str, room_id: str) -> float:
|
||||
"""
|
||||
Berechnet den Score für ein Keyword in einem Raum unter Berücksichtigung
|
||||
von Overrides, Sticky-Rooms und gelernten Gewichten.
|
||||
|
||||
Args:
|
||||
keyword: Das zu bewertende Keyword
|
||||
room_id: Die Raum-ID
|
||||
|
||||
Returns:
|
||||
Der berechnete Score (0.0 - 1.0)
|
||||
"""
|
||||
# Prüfe manuelle Overrides (höchste Priorität)
|
||||
if keyword in self._manual_overrides and room_id in self._manual_overrides[keyword]:
|
||||
return self._manual_overrides[keyword][room_id].override_weight
|
||||
|
||||
# Prüfe Sticky-Rooms (Gewicht 0.0)
|
||||
if keyword in self._sticky_keywords and room_id in self._sticky_keywords[keyword]:
|
||||
return 0.0
|
||||
|
||||
# Verwende gelerntes Gewicht
|
||||
if keyword in self._keyword_weights and room_id in self._keyword_weights[keyword]:
|
||||
return self._keyword_weights[keyword][room_id].weight
|
||||
|
||||
# Default: Gleichverteilung basierend auf Anzahl der Räume
|
||||
# (angenommen mindestens 3 Räume)
|
||||
return 1.0 / 3.0
|
||||
|
||||
def check_promotion_eligibility(self, keyword: str, room_id: str) -> bool:
|
||||
"""
|
||||
Prüft ob ein Keyword für die Promotion in keywords_100 berechtigt ist.
|
||||
|
||||
Args:
|
||||
keyword: Das zu prüfende Keyword
|
||||
room_id: Die Raum-ID
|
||||
|
||||
Returns:
|
||||
True wenn das Keyword förderfähig ist, False sonst
|
||||
"""
|
||||
try:
|
||||
# Prüfe ob das Keyword existiert
|
||||
if keyword not in self._keyword_weights or room_id not in self._keyword_weights[keyword]:
|
||||
return False
|
||||
|
||||
entry = self._keyword_weights[keyword][room_id]
|
||||
|
||||
# Prüfe Kriterien für Promotion:
|
||||
# - Mindestens 3 confirmations
|
||||
# - Gewicht ≥ 0.85
|
||||
# - Keine rejections im gleichen Raum
|
||||
if (entry.confirmation_count >= 3 and
|
||||
entry.weight >= 0.85 and
|
||||
entry.rejection_count == 0):
|
||||
|
||||
# Trage in Promotion-Kandidaten ein
|
||||
if keyword not in self._promotion_candidates:
|
||||
self._promotion_candidates[keyword] = {}
|
||||
|
||||
self._promotion_candidates[keyword][room_id] = {
|
||||
"score": entry.confirmation_count + entry.weight, # Einfache Scoring-Formel
|
||||
"last_updated": datetime.now().isoformat()
|
||||
}
|
||||
|
||||
# Speichere den aktualisierten Zustand
|
||||
self.save()
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Failed to check promotion eligibility: %s", e)
|
||||
return False
|
||||
|
||||
def apply_decay(self) -> bool:
|
||||
"""
|
||||
Wendet zeitbasierte Abwertung (Decay) an.
|
||||
- 30 Tage: -10%
|
||||
- 90 Tage: -30%
|
||||
|
||||
Returns:
|
||||
True wenn Decay erfolgreich angewendet wurde, False bei Fehler
|
||||
"""
|
||||
try:
|
||||
now = datetime.now()
|
||||
updated = False
|
||||
|
||||
# Iteriere durch alle Keywords und Räume
|
||||
for keyword, rooms_data in self._keyword_weights.items():
|
||||
for room_id, entry in rooms_data.items():
|
||||
# Parse das last_updated Datum
|
||||
try:
|
||||
last_updated = datetime.fromisoformat(entry.last_updated)
|
||||
except ValueError:
|
||||
# Falls das Datum nicht geparst werden kann, überspringen
|
||||
continue
|
||||
|
||||
# Berechne die Zeitdifferenz in Tagen
|
||||
days_diff = (now - last_updated).days
|
||||
|
||||
# Wende Decay an, wenn nötig
|
||||
new_weight = entry.weight
|
||||
if days_diff >= 90:
|
||||
# 90 Tage: -30%
|
||||
new_weight = entry.weight * 0.7
|
||||
elif days_diff >= 30:
|
||||
# 30 Tage: -10%
|
||||
new_weight = entry.weight * 0.9
|
||||
|
||||
# Nur aktualisieren, wenn sich das Gewicht geändert hat
|
||||
if new_weight != entry.weight:
|
||||
self._keyword_weights[keyword][room_id] = KeywordWeightEntry(
|
||||
weight=new_weight,
|
||||
last_updated=entry.last_updated, # Datum bleibt unverändert
|
||||
confirmation_count=entry.confirmation_count,
|
||||
rejection_count=entry.rejection_count,
|
||||
last_confirmation=entry.last_confirmation
|
||||
)
|
||||
updated = True
|
||||
|
||||
# Speichere Änderungen, wenn welche vorgenommen wurden
|
||||
if updated:
|
||||
return self.save()
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Failed to apply decay: %s", e)
|
||||
return False
|
||||
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
Keyword-Booster für Archivar v5.
|
||||
|
||||
Verfeinert FAISS-Suchergebnisse durch Keyword-Analyse:
|
||||
- Eindeutige Keywords (nur in einem Raum) geben +0.10 Boost
|
||||
- Mehrere eindeutige Keywords geben zusätzlichen Boost (+0.05 pro weiterem Keyword)
|
||||
- Mehrdeutige Keywords sind neutral
|
||||
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords (+0.05 Boost)
|
||||
|
||||
Usage::
|
||||
|
||||
from .room_map import RoomMap
|
||||
from .booster import KeywordBooster
|
||||
|
||||
room_map = RoomMap.load()
|
||||
booster = KeywordBooster(room_map)
|
||||
|
||||
scores = [("room_a", 0.87), ("room_b", 0.85), ("room_c", 0.62)]
|
||||
text = "Das Plugin hat einen Bug im Router"
|
||||
boosted = booster.boost(text, scores)
|
||||
# → [("room_a", 0.97), ("room_b", 0.85), ("room_c", 0.62)]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Dict, List, Set, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class KeywordBooster:
|
||||
"""Keyword-basierter Score-Booster für RoomIndexManager.search()-Ergebnisse.
|
||||
|
||||
Baut aus einer geladenen RoomMap ein Mapping: keyword → set of room_ids.
|
||||
Wendet dann Boosts auf FAISS-Scores an basierend auf Keyword-Eindeutigkeit.
|
||||
"""
|
||||
|
||||
def __init__(self, room_map) -> None:
|
||||
"""Initialisiere den Booster mit einer geladenen RoomMap.
|
||||
|
||||
Args:
|
||||
room_map: Eine ``RoomMap``-Instanz (aus ``room_map.py``).
|
||||
"""
|
||||
self._room_map = room_map
|
||||
self._keyword_to_rooms: Dict[str, Set[str]] = {}
|
||||
self._build_mapping()
|
||||
|
||||
# ── Mapping ───────────────────────────────────────────────────────
|
||||
|
||||
def _build_mapping(self) -> None:
|
||||
"""Baut keyword → set(room_ids) aus allen keywords_100 + keywords_context."""
|
||||
self._keyword_to_rooms.clear()
|
||||
|
||||
for room_id, entry in self._room_map.rooms.items():
|
||||
if entry.catch_all:
|
||||
continue # Catch-All nimmt nicht an Keyword-Boosts teil
|
||||
|
||||
all_keywords: List[str] = []
|
||||
all_keywords.extend(entry.keywords_100)
|
||||
all_keywords.extend(entry.keywords_context)
|
||||
|
||||
for kw in all_keywords:
|
||||
kw_lower = kw.lower().strip()
|
||||
if not kw_lower:
|
||||
continue
|
||||
if kw_lower not in self._keyword_to_rooms:
|
||||
self._keyword_to_rooms[kw_lower] = set()
|
||||
self._keyword_to_rooms[kw_lower].add(room_id)
|
||||
|
||||
logger.debug(
|
||||
"KeywordBooster mapping built: %d keywords across %d rooms",
|
||||
len(self._keyword_to_rooms),
|
||||
len(self._room_map.rooms),
|
||||
)
|
||||
|
||||
# ── Public API ─────────────────────────────────────────────────────
|
||||
|
||||
def boost(
|
||||
self,
|
||||
text: str,
|
||||
scores: List[Tuple[str, float]],
|
||||
) -> List[Tuple[str, float]]:
|
||||
"""Wendet Keyword-Boosts auf FAISS-Scores an.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext (für Keyword-Extraktion).
|
||||
scores: Liste von ``(room_id, score)``-Tupeln aus
|
||||
``RoomIndexManager.search()``, absteigend nach Score sortiert.
|
||||
|
||||
Returns:
|
||||
Neue Liste von ``(room_id, adjusted_score)``-Tupeln,
|
||||
absteigend nach adjusted_score sortiert.
|
||||
"""
|
||||
if not scores:
|
||||
return []
|
||||
|
||||
# ── Score-Dict aufbauen ──────────────────────────────────
|
||||
score_dict: Dict[str, float] = {room_id: score for room_id, score in scores}
|
||||
|
||||
# ── Keywords im Text finden ───────────────────────────────
|
||||
text_lower = text.lower()
|
||||
matched_keywords: List[str] = [
|
||||
kw for kw in self._keyword_to_rooms if kw in text_lower
|
||||
]
|
||||
|
||||
if not matched_keywords:
|
||||
# Keine Keywords → Scores unverändert zurück
|
||||
return sorted(scores, key=lambda x: x[1], reverse=True)
|
||||
|
||||
# ── Boost-Phase: +0.10 für eindeutige Keywords ────────────
|
||||
for kw in matched_keywords:
|
||||
rooms = self._keyword_to_rooms[kw]
|
||||
if len(rooms) == 1:
|
||||
unique_room = next(iter(rooms))
|
||||
if unique_room in score_dict:
|
||||
score_dict[unique_room] += 0.10
|
||||
logger.debug(
|
||||
"Boost +0.10: keyword='%s' → room='%s' (unique)",
|
||||
kw,
|
||||
unique_room[:8],
|
||||
)
|
||||
|
||||
# ── Zusätzlicher Boost für mehrere eindeutige Keywords ────
|
||||
# Zähle eindeutige Keywords pro Raum und gib Bonus für hohe Anzahl
|
||||
unique_counts_per_room: Dict[str, int] = {}
|
||||
for kw in matched_keywords:
|
||||
rooms = self._keyword_to_rooms[kw]
|
||||
if len(rooms) == 1:
|
||||
unique_room = next(iter(rooms))
|
||||
if unique_room in score_dict:
|
||||
unique_counts_per_room[unique_room] = unique_counts_per_room.get(unique_room, 0) + 1
|
||||
|
||||
# Bonus: +0.05 für jeden weiteren unique Match über dem ersten
|
||||
for room_id, count in unique_counts_per_room.items():
|
||||
if count > 1:
|
||||
additional_boost = (count - 1) * 0.05
|
||||
score_dict[room_id] += additional_boost
|
||||
logger.debug(
|
||||
"Additional boost +%s: room='%s' has %d unique keywords",
|
||||
additional_boost,
|
||||
room_id[:8],
|
||||
count,
|
||||
)
|
||||
|
||||
# ── Nach Boost sortieren ──────────────────────────────────
|
||||
boosted = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
|
||||
|
||||
# ── Konfliktlösung: Top-2 Diff < 0.03 ────────────────────
|
||||
if len(boosted) >= 2:
|
||||
top1_room, top1_score = boosted[0]
|
||||
top2_room, top2_score = boosted[1]
|
||||
diff = top1_score - top2_score
|
||||
|
||||
if diff < 0.05:
|
||||
# Zähle eindeutige Keyword-Treffer für beide Räume
|
||||
unique_count_1 = self._count_unique_matches(text_lower, top1_room)
|
||||
unique_count_2 = self._count_unique_matches(text_lower, top2_room)
|
||||
|
||||
if unique_count_1 > unique_count_2:
|
||||
score_dict[top1_room] += 0.05
|
||||
logger.debug(
|
||||
"Conflict resolution: +0.05 for '%s' (%d unique vs %d)",
|
||||
top1_room[:8],
|
||||
unique_count_1,
|
||||
unique_count_2,
|
||||
)
|
||||
elif unique_count_2 > unique_count_1:
|
||||
score_dict[top2_room] += 0.05
|
||||
logger.debug(
|
||||
"Conflict resolution: +0.05 for '%s' (%d unique vs %d)",
|
||||
top2_room[:8],
|
||||
unique_count_2,
|
||||
unique_count_1,
|
||||
)
|
||||
# Bei Gleichstand: kein zusätzlicher Boost
|
||||
|
||||
# ── Finale Sortierung ─────────────────────────────────────
|
||||
return sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────
|
||||
|
||||
def _count_unique_matches(self, text_lower: str, room_id: str) -> int:
|
||||
"""Zählt wie viele eindeutige Keywords (nur in diesem Raum) im Text vorkommen.
|
||||
|
||||
Args:
|
||||
text_lower: Der Text in lowercase.
|
||||
room_id: Die zu prüfende Raum-ID.
|
||||
|
||||
Returns:
|
||||
Anzahl der eindeutigen Keyword-Treffer für diesen Raum.
|
||||
"""
|
||||
count = 0
|
||||
for kw, rooms in self._keyword_to_rooms.items():
|
||||
if len(rooms) == 1 and room_id in rooms and kw in text_lower:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
def reload(self) -> None:
|
||||
"""Baut das Keyword-Mapping neu (nach RoomMap.reload())."""
|
||||
self._build_mapping()
|
||||
@@ -0,0 +1,717 @@
|
||||
"""
|
||||
Embedding-basierte Intent-Klassifikation für Archivar v3.
|
||||
|
||||
Vergleicht den Embedding-Vektor einer eingehenden Nachricht mit vorab
|
||||
berechneten Kategorie-Vektoren (direct_question, smalltalk, work_order, ambiguous)
|
||||
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, Tuple
|
||||
|
||||
from .config import (
|
||||
OLLAMA_CONFIG,
|
||||
CATEGORY_TEXTS,
|
||||
CONFIDENCE_THRESHOLDS,
|
||||
LLM_CONFIG,
|
||||
LLM_CLASSIFY_PROMPT,
|
||||
LLM_CONFIDENCE_THRESHOLD,
|
||||
FALLBACK_KEYWORDS
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClassificationResult:
|
||||
"""Ergebnis einer Intent-Klassifikation."""
|
||||
|
||||
category: str
|
||||
"""Kategorie-Label: 'direct_question', 'smalltalk', 'work_order', oder 'ambiguous'."""
|
||||
|
||||
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)."""
|
||||
|
||||
llm_verified: bool = False
|
||||
"""True, wenn das Ergebnis durch LLM-Verifikation bestätigt wurde."""
|
||||
|
||||
def is_confident(self, threshold: float = CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]) -> bool:
|
||||
"""True wenn die Konfidenz über dem Schwellenwert für automatisches Routing liegt."""
|
||||
return self.confidence >= threshold
|
||||
|
||||
def needs_clarification(self) -> bool:
|
||||
"""True wenn die Konfidenz im Bereich 60-90% liegt und Klärung benötigt."""
|
||||
return (
|
||||
self.confidence >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||
self.confidence < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||
)
|
||||
|
||||
def should_route(self) -> bool:
|
||||
"""True wenn die Nachricht geroutet werden sollte.
|
||||
|
||||
- work_order mit >90% Konfidenz wird geroutet
|
||||
- direct_question und smalltalk werden nie geroutet
|
||||
- ambiguous benötigt Klärung
|
||||
"""
|
||||
if self.category in ("direct_question", "smalltalk"):
|
||||
return False
|
||||
if self.category == "work_order":
|
||||
return self.confidence >= CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||
if self.category == "ambiguous":
|
||||
return False # Benötigt Klärung
|
||||
return False
|
||||
|
||||
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 ``IntentClassifier`` can
|
||||
work with real Ollama, mocks, or alternative backends without change.
|
||||
|
||||
Implementations must be thread-safe since ``IntentClassifier`` 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 ``IntentClassifier`` can
|
||||
work with real Ollama, mocks, or alternative backends without change.
|
||||
|
||||
Implementations must be thread-safe since ``IntentClassifier`` 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."""
|
||||
...
|
||||
|
||||
@abc.abstractmethod
|
||||
def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
"""Verifiziere die Konfidenz mit dem LLM und gib (Kategorie, Konfidenz) zurück."""
|
||||
...
|
||||
|
||||
@abc.abstractmethod
|
||||
def generate(self, prompt: str) -> Optional[str]:
|
||||
"""Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung).
|
||||
|
||||
Wird vom Raum-Router verwendet, um die Zielraum-ID direkt vom LLM
|
||||
zu erhalten. Anders als ``classify()`` wird die Antwort NICHT gegen
|
||||
Intent-Kategorien validiert.
|
||||
|
||||
Args:
|
||||
prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT).
|
||||
|
||||
Returns:
|
||||
Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
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?")
|
||||
# → "direct_question"
|
||||
"""
|
||||
|
||||
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().lower()
|
||||
if category in ("direct_question", "smalltalk", "work_order", "ambiguous"):
|
||||
return category
|
||||
else:
|
||||
logger.warning("LLM returned invalid category: %s", category)
|
||||
return None
|
||||
except urllib.error.HTTPError as e:
|
||||
logger.warning("Ollama HTTP %d: %s", e.code, e.reason)
|
||||
return None
|
||||
except urllib.error.URLError as e:
|
||||
logger.warning("Ollama connection failed: %s", e)
|
||||
return None
|
||||
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
|
||||
|
||||
def verify_confidence(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
"""Verifiziere die Konfidenz mit dem LLM."""
|
||||
try:
|
||||
# Erstelle einen Prompt mit den Scores für die LLM-Verifikation
|
||||
scores_text = "\n".join([f"- {cat}: {score:.2f}" for cat, score in scores.items()])
|
||||
prompt = f"""Nachricht: {text}
|
||||
|
||||
Embedding-basierte Scores:
|
||||
{scores_text}
|
||||
|
||||
Welche Kategorie ist am wahrscheinlichsten? Antworte nur mit dem Kategorienamen:
|
||||
direct_question, smalltalk, work_order, oder ambiguous"""
|
||||
|
||||
category = self.classify(prompt)
|
||||
if category:
|
||||
# Setze eine hohe Konfidenz für LLM-verifizierte Ergebnisse
|
||||
return (category, 0.95)
|
||||
except Exception as e:
|
||||
logger.warning("LLM confidence verification failed: %s", e)
|
||||
return None
|
||||
|
||||
def generate(self, prompt: str) -> Optional[str]:
|
||||
"""Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung).
|
||||
|
||||
Sendet den Prompt an Ollama's /api/generate und gibt die Antwort
|
||||
unvalidiert zurück. Wird vom Raum-Router für LLM_ROOM_PROMPT verwendet.
|
||||
|
||||
Args:
|
||||
prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT).
|
||||
|
||||
Returns:
|
||||
Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
|
||||
"""
|
||||
url = f"{self._base_url}/api/generate"
|
||||
payload = json.dumps(
|
||||
{
|
||||
"model": self._model,
|
||||
"prompt": prompt,
|
||||
"stream": False,
|
||||
"options": {
|
||||
"temperature": LLM_CONFIG["temperature"],
|
||||
"num_predict": LLM_CONFIG["max_tokens"],
|
||||
}
|
||||
}
|
||||
).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url, data=payload, headers=headers, method="POST"
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
response_text = data.get("response", "")
|
||||
if not response_text:
|
||||
logger.error("Ollama returned empty response for generate()")
|
||||
return None
|
||||
return response_text.strip()
|
||||
except urllib.error.HTTPError as e:
|
||||
logger.warning("Ollama HTTP %d in generate(): %s", e.code, e.reason)
|
||||
return None
|
||||
except urllib.error.URLError as e:
|
||||
logger.warning("Ollama connection failed in generate(): %s", e)
|
||||
return None
|
||||
except (json.JSONDecodeError, TypeError, ValueError) as e:
|
||||
logger.error("Ollama response parse error in generate(): %s", e)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error("Unexpected error in generate(): %s", e)
|
||||
return None
|
||||
|
||||
|
||||
class IntentClassifier:
|
||||
"""Embedding-basierter Intent-Klassifizierer für Archivar v3.
|
||||
|
||||
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 = IntentClassifier()
|
||||
await classifier.initialize() # pre-compute category vectors
|
||||
result = await classifier.classify("Wie funktioniert das Plugin?")
|
||||
print(result.category) # → "direct_question"
|
||||
"""
|
||||
|
||||
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 Intent-Kategorie oder None."""
|
||||
t = text.lower()
|
||||
|
||||
# Prüfe zuerst auf direkte Matches
|
||||
for category, keywords in FALLBACK_KEYWORDS.items():
|
||||
if category == "ambiguous":
|
||||
continue # Ambiguous wird nicht über Keywords erkannt
|
||||
for kw in keywords:
|
||||
if kw in t:
|
||||
return category
|
||||
return None
|
||||
|
||||
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
import asyncio
|
||||
return await asyncio.to_thread(self._llm_classify_sync, text, scores)
|
||||
|
||||
def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
|
||||
try:
|
||||
if not self._llm_client or not self._llm_enabled:
|
||||
return None
|
||||
|
||||
return self._llm_client.verify_confidence(text, scores)
|
||||
except Exception as e:
|
||||
logger.warning("LLM classification failed: %s", e)
|
||||
return None
|
||||
|
||||
async def _llm_raw(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
|
||||
Intent-Kategorien. Uses ``LLMClient.generate()`` for free-form
|
||||
output. Used by the router for LLM_ROOM_PROMPT.
|
||||
|
||||
Wraps synchronous OllamaLLMClient.generate() in asyncio.to_thread().
|
||||
|
||||
Args:
|
||||
prompt: The complete prompt to send.
|
||||
|
||||
Returns:
|
||||
The LLM's response text (stripped), or None on failure.
|
||||
"""
|
||||
import asyncio
|
||||
try:
|
||||
if not self._llm_client or not self._llm_enabled:
|
||||
return None
|
||||
return await asyncio.to_thread(self._llm_client.generate, prompt)
|
||||
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 intent 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(
|
||||
"Intent 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:
|
||||
# Keyword-Treffer haben hohe Priorität
|
||||
latency_ms = (time.monotonic() - t0) * 1000.0
|
||||
confidence = 0.85 # Hohe Konfidenz für Keyword-Treffer
|
||||
|
||||
# Für ambiguous Ergebnisse setzen wir eine niedrigere Konfidenz
|
||||
if keyword_result == "ambiguous":
|
||||
confidence = 0.75
|
||||
|
||||
return ClassificationResult(
|
||||
category=keyword_result,
|
||||
confidence=confidence,
|
||||
all_scores={keyword_result: confidence},
|
||||
latency_ms=latency_ms,
|
||||
fallback=True,
|
||||
)
|
||||
|
||||
# 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
|
||||
|
||||
# Stufe 2: LLM-Verifikation bei ambiguous Ergebnissen
|
||||
llm_verified = False
|
||||
final_category = best_category
|
||||
final_score = best_score
|
||||
|
||||
# Wenn der Score im Klärungsbereich liegt, führe LLM-Verifikation durch
|
||||
if (
|
||||
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
|
||||
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||
):
|
||||
llm_result = self._llm_classify_sync(text, scores)
|
||||
if llm_result:
|
||||
final_category, final_score = llm_result
|
||||
llm_verified = True
|
||||
|
||||
# Direktes Return des Ergebnisses
|
||||
return ClassificationResult(
|
||||
category=final_category,
|
||||
confidence=final_score,
|
||||
all_scores=scores,
|
||||
latency_ms=latency_ms,
|
||||
fallback=False,
|
||||
llm_verified=llm_verified,
|
||||
)
|
||||
|
||||
# ── 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,265 @@
|
||||
"""
|
||||
Archivar-Konfiguration: Raum-Mapping, Kategorie-Texte und Ollama-Einstellungen.
|
||||
|
||||
Alle Raum-IDs werden über Umgebungsvariablen gesteuert — keine hartcodierten Werte.
|
||||
OLLAMA_CONFIG: Embeddings NUR von lokalem Ollama (ARCHIVAR_EMBEDDING_BASE_URL).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Dict
|
||||
|
||||
# ── Ollama-Konfiguration ────────────────────────────────────────────────────
|
||||
|
||||
OLLAMA_CONFIG: dict = {
|
||||
"base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", "http://localhost:11434"),
|
||||
"model": "nomic-embed-text",
|
||||
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s
|
||||
"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] = {
|
||||
"direct_question": (
|
||||
"Dies ist eine direkte Frage an den Assistenten. Es wird eine Antwort auf "
|
||||
"eine konkrete Frage erwartet. Beispiele sind 'Was ist die aktuelle Uhrzeit?', "
|
||||
"'Wie funktioniert das Archivsystem?' oder 'Kannst du mir helfen?'. "
|
||||
"Solche Nachrichten bleiben immer im aktuellen Raum."
|
||||
),
|
||||
"smalltalk": (
|
||||
"Dies ist Smalltalk oder allgemeine Konversation ohne konkreten Handlungsbedarf. "
|
||||
"Beispiele sind Begrüßungen, Smalltalk oder allgemeine Gespräche. "
|
||||
"Solche Nachrichten bleiben immer im aktuellen Raum."
|
||||
),
|
||||
"work_order": (
|
||||
"Dies ist ein Arbeitsauftrag oder eine Anfrage zur Bearbeitung. Es wird eine "
|
||||
"konkrete Aktion oder Bearbeitung erwartet. Beispiele sind 'Bitte dokumentiere ', "
|
||||
"'Erstelle einen Bericht zu' oder 'Überprüfe die Konfiguration von'. "
|
||||
"Solche Nachrichten können bei hoher Konfidenz geroutet werden."
|
||||
),
|
||||
"ambiguous": (
|
||||
"Diese Nachricht ist mehrdeutig und benötigt eine Klärung. Es ist unklar, "
|
||||
"ob es sich um eine direkte Frage, Smalltalk oder einen Arbeitsauftrag handelt. "
|
||||
"Solche Nachrichten benötigen eine LLM-Klärung mit nativen Action-Buttons."
|
||||
),
|
||||
}
|
||||
|
||||
# ── Konfidenz-Schwellenwerte ─────────────────────────────────────────────────
|
||||
|
||||
CONFIDENCE_THRESHOLDS: dict = {
|
||||
"AUTO_ROUTE": 0.9, # Ab 90% Konfidenz wird automatisch geroutet
|
||||
"CLARIFY_NEEDED": 0.6, # 60-90% Konfidenz benötigt Klärung mit Buttons
|
||||
"STAY_IN_ROOM": 0.6, # Unter 60% bleibt die Nachricht im Raum
|
||||
}
|
||||
|
||||
"""
|
||||
Nachrichten mit confidence >= 0.9 werden automatisch geroutet.
|
||||
Nachrichten mit confidence 0.6-0.9 benötigen eine Klärung mit Buttons.
|
||||
Nachrichten mit confidence < 0.6 bleiben im Ursprungsraum.
|
||||
"""
|
||||
|
||||
# ── Raum-Mapping (via Env-Vars) ─────────────────────────────────────────────
|
||||
# Alle Raum-IDs werden aus Umgebungsvariablen gelesen.
|
||||
# Falls nicht gesetzt → None (Router sendet dann nur Klassifikation, kein Routing).
|
||||
#
|
||||
# ARCHIVAR_WORK_ORDER_ROOM — Zielraum für work_order-Kategorie
|
||||
# ARCHIVAR_PROJECT_ROOMS — JSON-Map für projektspezifisches Routing
|
||||
# Beispiel: {"plugin":"ROOM_ID","docs":"ROOM_ID"}
|
||||
|
||||
def _resolve_room_mapping() -> dict:
|
||||
"""Baut ROOM_MAPPING aus Umgebungsvariablen zusammen.
|
||||
|
||||
work_order wird in ROOM_MAPPING aufgenommen — Arbeitsaufträge können geroutet werden.
|
||||
direct_question und smalltalk werden nicht geroutet, daher nicht in ROOM_MAPPING.
|
||||
"""
|
||||
mapping: dict = {}
|
||||
|
||||
# Nur work_order kann geroutet werden
|
||||
work_order_room = os.getenv("ARCHIVAR_WORK_ORDER_ROOM", "").strip()
|
||||
if work_order_room:
|
||||
mapping["work_order"] = work_order_room
|
||||
|
||||
project_json = os.getenv("ARCHIVAR_PROJECT_ROOMS", "").strip()
|
||||
if project_json:
|
||||
try:
|
||||
project_mapping = json.loads(project_json)
|
||||
if project_mapping:
|
||||
mapping["project_specific"] = project_mapping
|
||||
except json.JSONDecodeError:
|
||||
pass # ignorieren, kein projektspezifisches Routing
|
||||
|
||||
return mapping
|
||||
|
||||
|
||||
ROOM_MAPPING: dict = _resolve_room_mapping()
|
||||
|
||||
CATCH_ALL_ROOM: str = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip() or None
|
||||
|
||||
# ── Button-Konfiguration ─────────────────────────────────────────────────────
|
||||
|
||||
BUTTON_TEMPLATES: dict = {
|
||||
"clarify_intent": {
|
||||
"text": "Ich möchte mir das für die Zukunft richtig merken. Welche Absicht ist mit der Nachricht verbunden?",
|
||||
"actions": [
|
||||
{"text": "📝 Direkte Frage", "type": "direct_question"},
|
||||
{"text": "💬 Smalltalk", "type": "smalltalk"},
|
||||
{"text": "📋 Arbeitsauftrag", "type": "work_order"}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
"""
|
||||
Button-Templates für native Rocket.Chat Action-Buttons.
|
||||
Wird für die Klärung mehrdeutiger Nachrichten verwendet.
|
||||
"""
|
||||
|
||||
# ── Fallback-Keyword-Heuristik ──────────────────────────────────────────────
|
||||
|
||||
FALLBACK_KEYWORDS: dict = {
|
||||
"direct_question": ["frage", "was", "wie", "warum", "wieso", "weshalb",
|
||||
"kannst du", "können sie", "help", "hilfe", "erkläre",
|
||||
"erklären", "was bedeutet", "zeig mir"],
|
||||
"smalltalk": ["hallo", "hi", "grüß", "moin", "hey", "guten morgen",
|
||||
"guten tag", "guten abend", "tschüss", "bye", "ciao",
|
||||
"schön", "toll", "super", "cool", "danke", "danke dir",
|
||||
"freut mich", "geht so", "alles gut"],
|
||||
"work_order": ["bitte", "erstelle", "dokumentiere", "überprüfe",
|
||||
"erzeuge", "generiere", "mache", "erledige", "bearbeite",
|
||||
"erstellt", "dokumentiert", "überprüft", "erzeugt",
|
||||
"erledigt", "bearbeitet", "auftrag", "aufgabe",
|
||||
"arbeitsauftrag", "task", "todo", "bericht", "report"],
|
||||
"ambiguous": [], # Ambiguous wird nicht über Keywords erkannt
|
||||
}
|
||||
"""
|
||||
Bei Ollama-Down-Fallback: Enthält die Nachricht eines dieser Keywords,
|
||||
wird sie entsprechend klassifiziert. Alles andere → FAKT.
|
||||
"""
|
||||
|
||||
# ── LLM-Konfiguration ───────────────────────────────────────────────────────
|
||||
# ── LLM-Konfiguration ───────────────────────────────────────────────────────
|
||||
|
||||
LLM_CONFIG = {
|
||||
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
|
||||
"model": "qwen2.5:7b",
|
||||
"timeout": 30.0, # Iterative Optimierung: Start 30s (19.06.2026)
|
||||
"base_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"),
|
||||
"temperature": 0.0,
|
||||
"max_tokens": 30, # Raum-ID = 24 chars + Puffer
|
||||
}
|
||||
|
||||
LLM_CLASSIFY_PROMPT = """Klassifiziere die folgende Nachricht in EINE Kategorie.
|
||||
Antworte NUR mit einem Wort: direct_question, smalltalk, work_order oder ambiguous.
|
||||
|
||||
Kategorien:
|
||||
- direct_question: Direkte Frage an den Assistenten, erwartet Antwort
|
||||
- smalltalk: Allgemeine Konversation ohne Handlungsbedarf
|
||||
- work_order: Arbeitsauftrag oder Anfrage zur Bearbeitung
|
||||
- ambiguous: Mehrdeutig, benötigt Klärung
|
||||
|
||||
Nachricht: {text}
|
||||
|
||||
Kategorie:"""
|
||||
|
||||
LLM_CONFIDENCE_THRESHOLD = 0.90
|
||||
|
||||
# ── LLM-Room-Prompt (NEU — zentraler Raum-Router) ────────────────────────────
|
||||
# Fragt das LLM nach der Zielraum-ID. Keywords pro Raum geben dem LLM präzise
|
||||
# Anker — z.B. "RC" wird erkannt, auch wenn es erst am Satzende steht.
|
||||
# Ausgabe: Direkt die Raum-ID (keine Kategorien, kein Name-Matching).
|
||||
|
||||
LLM_ROOM_PROMPT = """Du bist ein Raum-Zuordner. Ordne die Nachricht EINEM Raum zu.
|
||||
Antworte mit der exakten Raum-ID aus der Liste ODER dem Wort STAY.
|
||||
Wähle STAY wenn die Nachricht thematisch zum Ursprungsraum passt ODER wenn du unsicher bist.
|
||||
Antworte NUR mit einem Wort, keine Erklärungen.
|
||||
|
||||
Ursprungsraum: {origin_room}
|
||||
|
||||
Verfügbare Räume (ID | Name | Keywords):
|
||||
{room_list}
|
||||
|
||||
Beispiele für STAY:
|
||||
- Eine Frage zum aktuellen Raumthema → STAY
|
||||
- Smalltalk, Begrüßung, Dank → STAY
|
||||
- Unklare oder mehrdeutige Nachricht → STAY
|
||||
|
||||
Beispiele für ROUTE (Raum-ID):
|
||||
- Ein klarer Arbeitsauftrag für ein anderes Raumthema → die passende Raum-ID
|
||||
- Eine Frage, die eindeutig in einen anderen Raum gehört → die passende Raum-ID
|
||||
|
||||
Nachricht: {text}
|
||||
Raum-ID:"""
|
||||
|
||||
# ── Betriebsstufen-Log ──────────────────────────────────────────────────────
|
||||
|
||||
ARCHIVAR_STUFE_LOG = (
|
||||
"Archivar Stufe 1: Embedding-Vorfilter + LLM-Raum-Router aktiv (5 Räume)"
|
||||
)
|
||||
|
||||
# ── Move-Request-Button-Template (Butler-Prinzip) ───────────────────────────
|
||||
# Vor dem Routing wird ein Button an Andreas gesendet:
|
||||
# "Soll ich nach [Raum-Name] kopieren?"
|
||||
# ✅Ja → Route + DeepSeek erhält "Antworte in [Raum-Name]"
|
||||
# 📍Hier → Kein Routing, Antwort im Ursprungsraum
|
||||
|
||||
MOVE_REQUEST_TEMPLATE: dict = {
|
||||
"text": "Soll ich diese Nachricht nach {target_name} kopieren?",
|
||||
"actions": [
|
||||
{"text": "✅Ja", "type": "confirm_move"},
|
||||
{"text": "📍Hier", "type": "stay_here"},
|
||||
],
|
||||
}
|
||||
|
||||
# ── 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")
|
||||
)
|
||||
|
||||
# ── Persistenz-Layer-Konfiguration ──────────────────────────────────────────
|
||||
|
||||
ARCHIVAR_STATE_PATH: str = os.path.expanduser(
|
||||
os.getenv("ARCHIVAR_STATE_PATH", "~/.hermes/hermes-agent/data/archivar_state.json")
|
||||
)
|
||||
|
||||
"""
|
||||
Pfad zur JSON-Datei, die den Zustand des Archivars pro Raum speichert.
|
||||
Enthält Entscheidungen wie "immer im Raum bleiben" oder "nie routen".
|
||||
"""
|
||||
|
||||
# ── FAISS Phase-1 Scoring-Schwellen ──────────────────────────────────────────
|
||||
# Drei-Schichten-Logik: FAISS → Keyword-Booster → LLM
|
||||
# Phase-1 (FAISS) routet direkt bei hohem Score — kein LLM-Aufruf nötig.
|
||||
# Bei mittlerem Score greift der Keyword-Booster zur Konfliktlösung.
|
||||
# Bei niedrigem Score fällt der Flow an den Embedding-Vorfilter + LLM durch.
|
||||
|
||||
FAISS_AUTO_ROUTE: float = 0.85
|
||||
"""FAISS-Score-Schwelle für automatisches Routing ohne LLM.
|
||||
Nachrichten mit FAISS-Score >= 0.85 (nach Keyword-Boost) werden direkt
|
||||
geroutet — kein LLM-Aufruf nötig. Spart ~2.4s Latenz pro Nachricht."""
|
||||
|
||||
FAISS_MIN_SCORE: float = 0.50
|
||||
"""Minimaler FAISS-Score für Treffer. Ergebnisse unter 0.50 werden
|
||||
verworfen und der Flow fällt an den Embedding-Vorfilter + LLM-Router durch.
|
||||
Verhindert False-Positives bei thematisch fremden Nachrichten."""
|
||||
|
||||
FAISS_TOP_K: int = 3
|
||||
"""Anzahl der Top-Treffer aus dem FAISS-Index. K=3 reicht für die
|
||||
Drei-Schichten-Logik (FAISS → Booster → LLM). Höhere Werte bringen
|
||||
keine bessere Konfliktlösung, nur mehr Rauschen."""
|
||||
|
||||
FAISS_CONFLICT_DIFF: float = 0.05
|
||||
"""Maximale Score-Differenz zwischen Top-1 und Top-2, unterhalb derer
|
||||
der Keyword-Booster zur Konfliktlösung eingesetzt wird. Bei Diff < 0.05
|
||||
entscheiden eindeutige Keywords, nicht der reine FAISS-Score."""
|
||||
|
||||
# ── 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,232 @@
|
||||
"""
|
||||
RoutingWiderspruchDetector — textbasierte Widerspruch-Erkennung für den Archivar.
|
||||
|
||||
Erkennt textuelle Widersprüche gegen Routing-Entscheidungen („Nein, das passt
|
||||
nicht in Raum X") und behandelt sie wie Button-Antworten. Wird NUR aktiv, wenn
|
||||
KEIN Button-Feedback (kein pending move-request) aktiv ist.
|
||||
|
||||
Button = geregelter Standard, Text = Fall ohne Button.
|
||||
|
||||
Usage::
|
||||
|
||||
detector = RoutingWiderspruchDetector()
|
||||
result = detector.detect("Nein, das passt nicht in #Dokumentation")
|
||||
if result and result.has_contradiction:
|
||||
# result.contradiction_type → 'routing_rejection' | 'reroute_request'
|
||||
# result.target_room → 'Dokumentation' (optional, für Umrouting)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, List
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ContradictionResult:
|
||||
"""Ergebnis der Widerspruch-Erkennung."""
|
||||
|
||||
has_contradiction: bool
|
||||
"""True wenn ein Widerspruch erkannt wurde."""
|
||||
|
||||
contradiction_type: str = ""
|
||||
"""Typ des Widerspruchs: 'routing_rejection' | 'reroute_request'."""
|
||||
|
||||
confidence: float = 0.0
|
||||
"""Konfidenz der Erkennung (0.0–1.0)."""
|
||||
|
||||
target_room: Optional[str] = None
|
||||
"""Zielraum-Name bei Umrouting-Wünschen, sonst None."""
|
||||
|
||||
matched_pattern: str = ""
|
||||
"""Name des Regex-Musters, das getroffen hat (für Debugging)."""
|
||||
|
||||
rejected_room: Optional[str] = None
|
||||
"""Raum-Name, der abgelehnt wurde (bei routing_rejection mit Raumnennung)."""
|
||||
|
||||
|
||||
class RoutingWiderspruchDetector:
|
||||
"""Erkennt textuelle Widersprüche gegen Routing-Entscheidungen via Regex.
|
||||
|
||||
Vier Regex-Gruppen, absteigend nach Spezifität:
|
||||
|
||||
a) **Hauptmuster** — „Nein, das passt nicht in X"
|
||||
Erkennt explizite Ablehnung mit Zielraum-Nennung.
|
||||
→ contradiction_type='routing_rejection', rejected_room=X
|
||||
|
||||
b) **Umrouting** — „Das sollte eigentlich in Y"
|
||||
Erkennt Umrouting-Wunsch mit alternativem Zielraum.
|
||||
→ contradiction_type='reroute_request', target_room=Y
|
||||
|
||||
c) **Verneinung** — „Bleib hier", „Nicht verschieben"
|
||||
Erkennt generelle Routing-Ablehnung ohne Raumnennung.
|
||||
→ contradiction_type='routing_rejection'
|
||||
|
||||
d) **Befehle** — „Falscher Raum", „Stop", „Nicht routen"
|
||||
Erkennt imperative Routing-Ablehnung.
|
||||
→ contradiction_type='routing_rejection'
|
||||
|
||||
Edge Cases:
|
||||
- „nicht in X, sondern in Y": X negativ gewichten, Y als Ziel setzen
|
||||
→ contradiction_type='reroute_request', target_room=Y, rejected_room=X
|
||||
- Mehrdeutig: None zurückgeben (stay_in_room Default)
|
||||
- Kein vorheriges Routing: stay_in_room (Default)
|
||||
"""
|
||||
|
||||
# ── Regex-Gruppen (kompiliert) ──────────────────────────────────────
|
||||
|
||||
# a) Hauptmuster: explizite Ablehnung mit Raumnennung
|
||||
# „Nein, das passt nicht in #Dokumentation"
|
||||
# „Stop, die Nachricht gehört nicht nach Support"
|
||||
# „Falsch, das soll nie in Projekt-X landen"
|
||||
HAUPTMUSTER: re.Pattern = re.compile(
|
||||
r"(?i)(nein|stop|nicht|falsch)(?:,|\s)(?:das|die)?.*?"
|
||||
r"(?:passt|gehört|gehoert|soll|landet).*?"
|
||||
r"(?:nicht|nie|keinesfalls|auf\s+keinen\s+fall).*?"
|
||||
r"(?:in|nach|zu)\s+(\w+)",
|
||||
)
|
||||
|
||||
# b) Umrouting: alternativer Zielraum gewünscht
|
||||
# „Das sollte eigentlich in #Support"
|
||||
# „Diese Nachricht sollte besser nach Projekt-Y"
|
||||
# „Das gehört eher in #Dokumentation"
|
||||
UMRUTING: re.Pattern = re.compile(
|
||||
r"(?i)(?:das|diese\s+nachricht|die|der\s+auftrag).*?"
|
||||
r"(?:sollte|besser|eigentlich|eher|richtigerweise|korrekterweise).*?"
|
||||
r"(?:in|nach|zu)\s+(\w+)",
|
||||
)
|
||||
|
||||
# b2) „nicht in X, sondern in Y" — Sonderfall: Ablehnung + Umrouting
|
||||
# Extrahiert BEIDE Räume: X = rejected, Y = target
|
||||
NICHT_IN_X_SONDERN_IN_Y: re.Pattern = re.compile(
|
||||
r"(?i)(?:nicht|nie|keinesfalls)\s+(?:in|nach|zu)\s+(\w+)"
|
||||
r".*?"
|
||||
r"(?:sondern|sondern\s+eher|sondern\s+besser)\s+(?:in|nach|zu)\s+(\w+)",
|
||||
)
|
||||
|
||||
# c) Verneinung: generelle Ablehnung ohne Raumnennung
|
||||
# „Bleib hier", „Bleibe da", „Nicht wechseln", „Nicht routen"
|
||||
# „Nicht verschieben", „Lass es hier"
|
||||
VERNEINUNG: re.Pattern = re.compile(
|
||||
r"(?i)(?:bleib|bleibe|lass\s+es|behalt|behalte)"
|
||||
r"\s+(?:hier|da|im\s+raum|in\s+diesem\s+raum)"
|
||||
r"|"
|
||||
r"(?:nicht|nie|keinesfalls)\s+"
|
||||
r"(?:wechseln|routen|verschieben|umleiten|bewegen|kopieren)",
|
||||
)
|
||||
|
||||
# d) Befehle: imperative Kurzformen
|
||||
# „Falscher Raum", „Stop", „Nicht routen", „Nicht verschieben"
|
||||
BEFEHLE: re.Pattern = re.compile(
|
||||
r"^\s*(?:falscher\s+raum|stop|halt|abbruch)\s*[.!]*\s*$"
|
||||
r"|"
|
||||
r"^\s*(?:nicht|nie)\s+(?:routen|verschieben|umleiten|bewegen)\s*[.!]*\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# ── Confidence-Werte pro Mustertyp ──────────────────────────────────
|
||||
|
||||
CONFIDENCE_MAP = {
|
||||
"hauptmuster": 0.90,
|
||||
"umruting": 0.88,
|
||||
"nicht_in_x_sondern_in_y": 0.92,
|
||||
"verneinung": 0.85,
|
||||
"befehle": 0.82,
|
||||
}
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
def detect(self, text: str) -> Optional[ContradictionResult]:
|
||||
"""Erkenne einen Routing-Widerspruch im Text.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext (kann Prefixe wie [WIDERSPRUCH] enthalten).
|
||||
|
||||
Returns:
|
||||
ContradictionResult wenn ein Widerspruch erkannt wurde, sonst None.
|
||||
"""
|
||||
if not text or not text.strip():
|
||||
return None
|
||||
|
||||
text = text.strip()
|
||||
|
||||
# ── b2) Sonderfall: „nicht in X, sondern in Y" ──────────────────
|
||||
# Dieser MUSS vor dem Hauptmuster geprüft werden, weil das Hauptmuster
|
||||
# nur „nicht in X" matchen würde und Y verloren ginge.
|
||||
m_sondern = self.NICHT_IN_X_SONDERN_IN_Y.search(text)
|
||||
if m_sondern:
|
||||
rejected = m_sondern.group(1)
|
||||
target = m_sondern.group(2)
|
||||
logger.debug(
|
||||
"Widerspruch (nicht_in_x_sondern_in_y): rejected=%s target=%s",
|
||||
rejected, target,
|
||||
)
|
||||
return ContradictionResult(
|
||||
has_contradiction=True,
|
||||
contradiction_type="reroute_request",
|
||||
confidence=self.CONFIDENCE_MAP["nicht_in_x_sondern_in_y"],
|
||||
target_room=target,
|
||||
rejected_room=rejected,
|
||||
matched_pattern="nicht_in_x_sondern_in_y",
|
||||
)
|
||||
|
||||
# ── a) Hauptmuster ──────────────────────────────────────────────
|
||||
m_haupt = self.HAUPTMUSTER.search(text)
|
||||
if m_haupt:
|
||||
negation_word = m_haupt.group(1).lower()
|
||||
room_name = m_haupt.group(2)
|
||||
logger.debug(
|
||||
"Widerspruch (hauptmuster): negation=%s room=%s",
|
||||
negation_word, room_name,
|
||||
)
|
||||
return ContradictionResult(
|
||||
has_contradiction=True,
|
||||
contradiction_type="routing_rejection",
|
||||
confidence=self.CONFIDENCE_MAP["hauptmuster"],
|
||||
rejected_room=room_name,
|
||||
matched_pattern="hauptmuster",
|
||||
)
|
||||
|
||||
# ── b) Umrouting ────────────────────────────────────────────────
|
||||
m_um = self.UMRUTING.search(text)
|
||||
if m_um:
|
||||
target_room = m_um.group(1)
|
||||
logger.debug(
|
||||
"Widerspruch (umruting): target=%s", target_room,
|
||||
)
|
||||
return ContradictionResult(
|
||||
has_contradiction=True,
|
||||
contradiction_type="reroute_request",
|
||||
confidence=self.CONFIDENCE_MAP["umruting"],
|
||||
target_room=target_room,
|
||||
matched_pattern="umruting",
|
||||
)
|
||||
|
||||
# ── c) Verneinung ───────────────────────────────────────────────
|
||||
m_verneinung = self.VERNEINUNG.search(text)
|
||||
if m_verneinung:
|
||||
logger.debug("Widerspruch (verneinung): matched")
|
||||
return ContradictionResult(
|
||||
has_contradiction=True,
|
||||
contradiction_type="routing_rejection",
|
||||
confidence=self.CONFIDENCE_MAP["verneinung"],
|
||||
matched_pattern="verneinung",
|
||||
)
|
||||
|
||||
# ── d) Befehle ──────────────────────────────────────────────────
|
||||
m_befehl = self.BEFEHLE.search(text)
|
||||
if m_befehl:
|
||||
logger.debug("Widerspruch (befehle): matched")
|
||||
return ContradictionResult(
|
||||
has_contradiction=True,
|
||||
contradiction_type="routing_rejection",
|
||||
confidence=self.CONFIDENCE_MAP["befehle"],
|
||||
matched_pattern="befehle",
|
||||
)
|
||||
|
||||
# Kein Widerspruch erkannt
|
||||
return None
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"$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. Version 2 splits keywords into keywords_100 (exact-match routing) and keywords_context (contextual routing).",
|
||||
"type": "object",
|
||||
"required": ["version", "rooms"],
|
||||
"properties": {
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"description": "Schema version for future migrations.",
|
||||
"minimum": 3
|
||||
},
|
||||
"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
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Detailed ~200-word description of the room's purpose, topics, artifacts, and typical tasks.",
|
||||
"minLength": 50
|
||||
},
|
||||
"keywords_100": {
|
||||
"type": "array",
|
||||
"description": "Keywords for exact-match routing (high-confidence, low false-positive).",
|
||||
"items": { "type": "string", "minLength": 1 },
|
||||
"default": []
|
||||
},
|
||||
"keywords_context": {
|
||||
"type": "array",
|
||||
"description": "Keywords for contextual / semantic routing (broader match, may need disambiguation).",
|
||||
"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). Optional.",
|
||||
"additionalProperties": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
"""
|
||||
FAISS-Index-Manager für Archivar v5.
|
||||
|
||||
Baut und verwaltet einen FAISS-Index über Raum-Embeddings für schnelle
|
||||
Ähnlichkeitssuche. Jeder Raum wird durch seinen Theme-Text und alle
|
||||
Keywords repräsentiert — der kombinierte Text wird via Ollama Embedding-API
|
||||
vektorisiert und in einem ``IndexFlatIP`` (Inner Product = Kosinus-Ähnlichkeit
|
||||
bei normalisierten Vektoren) abgelegt.
|
||||
|
||||
Der Index wird auf Disk persistiert (``room_index.faiss`` + ``room_index.meta``)
|
||||
und kann beim Start geladen werden, um teure Neuberechnungen zu vermeiden.
|
||||
|
||||
Usage::
|
||||
|
||||
from .room_map import RoomMap
|
||||
from .classifier import OllamaEmbeddingClient
|
||||
from .room_index import RoomIndexManager
|
||||
|
||||
room_map = RoomMap.load()
|
||||
emb_client = OllamaEmbeddingClient()
|
||||
index_mgr = RoomIndexManager(room_map, emb_client)
|
||||
|
||||
if not index_mgr.load():
|
||||
index_mgr.build_index()
|
||||
index_mgr.save()
|
||||
|
||||
query_vec = emb_client.get_embedding("Das Plugin hat einen Bug")
|
||||
hits = index_mgr.search(query_vec, k=3)
|
||||
# → [("room_id_abc", 0.87), ("room_id_def", 0.62), ...]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import faiss
|
||||
except ImportError:
|
||||
faiss = None # type: ignore[assignment]
|
||||
|
||||
from .config import OLLAMA_CONFIG
|
||||
from .classifier import EmbeddingClient
|
||||
from .room_map import RoomMap, RoomEntry
|
||||
from .seed_data import SEED_DATA
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Constants ─────────────────────────────────────────────────────────────
|
||||
|
||||
_DEFAULT_INDEX_DIR: str = os.path.expanduser(
|
||||
os.getenv("ARCHIVAR_INDEX_DIR", "~/.hermes/hermes-agent/data")
|
||||
)
|
||||
_INDEX_FILENAME: str = "room_index.faiss"
|
||||
_META_FILENAME: str = "room_index.meta"
|
||||
|
||||
# ── Exception ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RoomIndexError(Exception):
|
||||
"""Raised when FAISS operations fail (build, search, save, load)."""
|
||||
|
||||
|
||||
# ── RoomIndexManager ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RoomIndexManager:
|
||||
"""FAISS-Index-Manager für Raum-Embeddings.
|
||||
|
||||
Attributes:
|
||||
embedding_dim: Dimension der Embedding-Vektoren (default 768 für
|
||||
nomic-embed-text).
|
||||
index: Der FAISS-Index (``IndexFlatIP``). None vor ``build_index()``
|
||||
oder ``load()``.
|
||||
_room_ids: Parallele Liste — Index-Position → room_id.
|
||||
_room_map: Referenz auf die ``RoomMap`` (für Theme/Keyword-Zugriff).
|
||||
_emb_client: ``EmbeddingClient`` für Ollama-API-Calls.
|
||||
_index_dir: Verzeichnis für Persistenz-Dateien.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
room_map: RoomMap,
|
||||
embedding_client: EmbeddingClient,
|
||||
index_dir: Optional[str] = None,
|
||||
embedding_dim: Optional[int] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
room_map: Eine geladene und validierte ``RoomMap``-Instanz.
|
||||
embedding_client: Ein ``EmbeddingClient`` (z. B.
|
||||
``OllamaEmbeddingClient``) für die Vektorisierung.
|
||||
index_dir: Verzeichnis für Index-Persistenz. Default:
|
||||
``ARCHIVAR_INDEX_DIR`` oder ``~/.hermes/hermes-agent/data``.
|
||||
embedding_dim: Dimension der Vektoren. Default aus
|
||||
``OLLAMA_CONFIG["embedding_dim"]`` (768).
|
||||
"""
|
||||
if faiss is None:
|
||||
raise RoomIndexError(
|
||||
"faiss is not installed. Install with: pip install faiss-cpu"
|
||||
)
|
||||
|
||||
self._room_map = room_map
|
||||
self._emb_client = embedding_client
|
||||
self._index_dir = Path(index_dir or _DEFAULT_INDEX_DIR)
|
||||
self._embedding_dim = embedding_dim or OLLAMA_CONFIG["embedding_dim"]
|
||||
|
||||
# FAISS state
|
||||
self.index: Optional[faiss.IndexFlatIP] = None
|
||||
self._room_ids: List[str] = []
|
||||
self._built_at: float = 0.0
|
||||
self._version: int = 1
|
||||
|
||||
# ── Properties ─────────────────────────────────────────────────────
|
||||
|
||||
@property
|
||||
def is_built(self) -> bool:
|
||||
"""True wenn der Index gebaut oder geladen wurde."""
|
||||
return self.index is not None and len(self._room_ids) > 0
|
||||
|
||||
@property
|
||||
def size(self) -> int:
|
||||
"""Anzahl der Räume im Index."""
|
||||
return len(self._room_ids) if self._room_ids else 0
|
||||
|
||||
@property
|
||||
def room_ids(self) -> List[str]:
|
||||
"""Kopie der Raum-ID-Liste (Index-Position → room_id)."""
|
||||
return list(self._room_ids)
|
||||
|
||||
@property
|
||||
def index_path(self) -> Path:
|
||||
"""Pfad zur FAISS-Index-Datei."""
|
||||
return self._index_dir / _INDEX_FILENAME
|
||||
|
||||
@property
|
||||
def meta_path(self) -> Path:
|
||||
"""Pfad zur Metadaten-Datei (room_ids, version, timestamp)."""
|
||||
return self._index_dir / _META_FILENAME
|
||||
|
||||
# ── Build ──────────────────────────────────────────────────────────
|
||||
|
||||
def build_index(self) -> None:
|
||||
"""Baut den FAISS-Index aus allen Räumen der RoomMap.
|
||||
|
||||
Für jeden Raum (außer Catch-All) wird ein kombinierter Text aus
|
||||
Theme + allen Keywords gebildet, via Embedding-API vektorisiert
|
||||
und normalisiert in einen ``IndexFlatIP`` eingefügt.
|
||||
|
||||
Catch-All-Räume werden NICHT in den Index aufgenommen — sie
|
||||
dienen als Fallback und sollen nie via Similarity-Match getroffen
|
||||
werden.
|
||||
|
||||
Raises:
|
||||
RoomIndexError: Wenn keine Räume zum Indizieren vorhanden sind
|
||||
oder die Embedding-API für alle Räume fehlschlägt.
|
||||
"""
|
||||
rooms = [
|
||||
(rid, entry)
|
||||
for rid, entry in self._room_map.rooms.items()
|
||||
if not entry.catch_all
|
||||
]
|
||||
|
||||
if not rooms:
|
||||
raise RoomIndexError(
|
||||
"No indexable rooms in RoomMap (all are catch-all or empty). "
|
||||
"Add at least one non-catch-all room with theme/keywords."
|
||||
)
|
||||
|
||||
vectors: List[np.ndarray] = []
|
||||
room_ids: List[str] = []
|
||||
failed: int = 0
|
||||
|
||||
for room_id, entry in rooms:
|
||||
text = self._room_to_text(entry)
|
||||
if not text.strip():
|
||||
logger.warning(
|
||||
"Room '%s' has no theme or keywords — skipping index",
|
||||
entry.name,
|
||||
)
|
||||
continue
|
||||
|
||||
vec = self._embed_text(text)
|
||||
if vec is None:
|
||||
logger.warning(
|
||||
"Failed to embed room '%s' — skipping", entry.name
|
||||
)
|
||||
failed += 1
|
||||
continue
|
||||
|
||||
# Normalisieren für Kosinus-Ähnlichkeit via Inner Product
|
||||
vec = vec / np.linalg.norm(vec)
|
||||
vectors.append(vec)
|
||||
room_ids.append(room_id)
|
||||
|
||||
if not vectors:
|
||||
raise RoomIndexError(
|
||||
f"Failed to embed any room ({failed} failures). "
|
||||
"Check Ollama connectivity and model availability."
|
||||
)
|
||||
|
||||
# Baue IndexFlatIP (Inner Product = Kosinus-Ähnlichkeit bei normierten Vektoren)
|
||||
matrix = np.array(vectors, dtype=np.float32)
|
||||
index = faiss.IndexFlatIP(self._embedding_dim)
|
||||
index.add(matrix)
|
||||
|
||||
self.index = index
|
||||
self._room_ids = room_ids
|
||||
self._built_at = time.time()
|
||||
self._version = self._room_map.version
|
||||
|
||||
logger.info(
|
||||
"RoomIndex built: %d rooms, dim=%d, %d embedding failures",
|
||||
len(room_ids),
|
||||
self._embedding_dim,
|
||||
failed,
|
||||
)
|
||||
|
||||
# ── Search ─────────────────────────────────────────────────────────
|
||||
|
||||
def search(
|
||||
self,
|
||||
query_embedding: List[float],
|
||||
k: int = 5,
|
||||
min_score: float = 0.0,
|
||||
) -> List[Tuple[str, float]]:
|
||||
"""Sucht die *k* ähnlichsten Räume zu einem Query-Embedding.
|
||||
|
||||
Args:
|
||||
query_embedding: Der Embedding-Vektor der Nachricht (768 floats).
|
||||
k: Anzahl der zurückgegebenen Top-Treffer.
|
||||
min_score: Minimaler Score (0.0–1.0) für Treffer. Treffer
|
||||
darunter werden herausgefiltert.
|
||||
|
||||
Returns:
|
||||
Liste von ``(room_id, score)``-Tupeln, absteigend nach Score
|
||||
sortiert. Score ist Kosinus-Ähnlichkeit (0.0–1.0).
|
||||
|
||||
Raises:
|
||||
RoomIndexError: Wenn der Index noch nicht gebaut/geladen wurde.
|
||||
"""
|
||||
if not self.is_built:
|
||||
raise RoomIndexError(
|
||||
"Index not built or loaded. Call build_index() or load() first."
|
||||
)
|
||||
|
||||
# Normalisieren
|
||||
qvec = np.array(query_embedding, dtype=np.float32)
|
||||
qvec = qvec / np.linalg.norm(qvec)
|
||||
qvec = qvec.reshape(1, -1)
|
||||
|
||||
k_eff = min(k, self.size)
|
||||
scores, indices = self.index.search(qvec, k_eff) # type: ignore[union-attr]
|
||||
|
||||
results: List[Tuple[str, float]] = []
|
||||
for score, idx in zip(scores[0], indices[0]):
|
||||
if idx < 0 or idx >= len(self._room_ids):
|
||||
continue # FAISS kann -1 für "kein Treffer" liefern
|
||||
if score < min_score:
|
||||
continue
|
||||
results.append((self._room_ids[idx], float(score)))
|
||||
|
||||
return results
|
||||
|
||||
def search_text(
|
||||
self,
|
||||
text: str,
|
||||
k: int = 5,
|
||||
min_score: float = 0.0,
|
||||
) -> List[Tuple[str, float]]:
|
||||
"""Convenience: Embed *text* und suche die ähnlichsten Räume.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
k: Anzahl der Top-Treffer.
|
||||
min_score: Minimaler Kosinus-Score.
|
||||
|
||||
Returns:
|
||||
Liste von ``(room_id, score)``-Tupeln, oder leere Liste
|
||||
wenn die Embedding-API fehlschlägt.
|
||||
"""
|
||||
vec = self._embed_text(text)
|
||||
if vec is None:
|
||||
logger.warning("search_text: embedding failed for '%.80s...'", text)
|
||||
return []
|
||||
return self.search(vec, k=k, min_score=min_score)
|
||||
|
||||
# ── Incremental Updates ────────────────────────────────────────────
|
||||
|
||||
def add_room(self, room_id: str, entry: RoomEntry) -> bool:
|
||||
"""Fügt einen einzelnen Raum zum Index hinzu.
|
||||
|
||||
Hängt den normalisierten Embedding-Vektor an den bestehenden
|
||||
FAISS-Index an. Der Index MUSS bereits gebaut/geladen sein.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
entry: Der ``RoomEntry`` mit Theme und Keywords.
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich hinzugefügt, False wenn Embedding
|
||||
fehlschlug oder der Raum bereits im Index ist.
|
||||
|
||||
Raises:
|
||||
RoomIndexError: Wenn der Index noch nicht gebaut/geladen wurde.
|
||||
"""
|
||||
if not self.is_built:
|
||||
raise RoomIndexError(
|
||||
"Index not built or loaded. Call build_index() or load() first."
|
||||
)
|
||||
|
||||
if room_id in self._room_ids:
|
||||
logger.debug("Room '%s' already in index — skipping", room_id)
|
||||
return False
|
||||
|
||||
if entry.catch_all:
|
||||
logger.debug("Room '%s' is catch-all — skipping index", entry.name)
|
||||
return False
|
||||
|
||||
text = self._room_to_text(entry)
|
||||
if not text.strip():
|
||||
logger.warning("Room '%s' has no theme/keywords — skipping", entry.name)
|
||||
return False
|
||||
|
||||
vec = self._embed_text(text)
|
||||
if vec is None:
|
||||
logger.warning("Failed to embed room '%s'", entry.name)
|
||||
return False
|
||||
|
||||
vec = vec / np.linalg.norm(vec)
|
||||
vec = vec.reshape(1, -1).astype(np.float32)
|
||||
self.index.add(vec) # type: ignore[union-attr]
|
||||
self._room_ids.append(room_id)
|
||||
|
||||
logger.info("Added room '%s' (%s) to index", entry.name, room_id[:8])
|
||||
return True
|
||||
|
||||
def remove_room(self, room_id: str) -> bool:
|
||||
"""Entfernt einen Raum aus dem Index.
|
||||
|
||||
FAISS ``IndexFlatIP`` unterstützt kein ``remove_ids`` — daher
|
||||
wird der gesamte Index neu gebaut (``rebuild()``).
|
||||
|
||||
Args:
|
||||
room_id: Die zu entfernende Raum-ID.
|
||||
|
||||
Returns:
|
||||
True wenn der Raum entfernt wurde, False wenn er nicht
|
||||
im Index war.
|
||||
"""
|
||||
if room_id not in self._room_ids:
|
||||
return False
|
||||
|
||||
logger.info(
|
||||
"Removing room '%s' from index — triggering rebuild", room_id[:8]
|
||||
)
|
||||
self.rebuild()
|
||||
return True
|
||||
|
||||
def rebuild(self) -> None:
|
||||
"""Baut den Index komplett neu aus der aktuellen RoomMap.
|
||||
|
||||
Nützlich nach ``RoomMap.reload()`` oder mehreren add/remove-
|
||||
Operationen. Löscht den bestehenden Index und baut ihn frisch.
|
||||
"""
|
||||
self.index = None
|
||||
self._room_ids = []
|
||||
self.build_index()
|
||||
|
||||
# ── Persistence ─────────────────────────────────────────────────────
|
||||
|
||||
def save(self, index_dir: Optional[str] = None) -> str:
|
||||
"""Persistiert den FAISS-Index und Metadaten auf Disk.
|
||||
|
||||
Schreibt zwei Dateien:
|
||||
- ``room_index.faiss``: Der FAISS-Index (via ``faiss.write_index``).
|
||||
- ``room_index.meta``: JSON mit room_ids, version, timestamp, dim.
|
||||
|
||||
Verwendet ``fcntl.flock`` für sicheres Schreiben bei parallelen
|
||||
Prozessen.
|
||||
|
||||
Args:
|
||||
index_dir: Alternatives Verzeichnis. Default: ``self._index_dir``.
|
||||
|
||||
Returns:
|
||||
Pfad zur FAISS-Index-Datei.
|
||||
|
||||
Raises:
|
||||
RoomIndexError: Wenn der Index nicht gebaut ist.
|
||||
"""
|
||||
if not self.is_built:
|
||||
raise RoomIndexError(
|
||||
"Cannot save: index not built. Call build_index() first."
|
||||
)
|
||||
|
||||
directory = Path(index_dir) if index_dir else self._index_dir
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
faiss_path = directory / _INDEX_FILENAME
|
||||
meta_path = directory / _META_FILENAME
|
||||
|
||||
# ── FAISS-Index schreiben ──────────────────────────────────
|
||||
try:
|
||||
faiss.write_index(self.index, str(faiss_path)) # type: ignore[union-attr]
|
||||
except Exception as e:
|
||||
raise RoomIndexError(f"Failed to write FAISS index: {e}") from e
|
||||
|
||||
# ── Metadaten schreiben (mit File-Lock) ────────────────────
|
||||
meta = {
|
||||
"version": self._version,
|
||||
"embedding_dim": self._embedding_dim,
|
||||
"room_ids": self._room_ids,
|
||||
"built_at": self._built_at,
|
||||
"saved_at": time.time(),
|
||||
"room_count": len(self._room_ids),
|
||||
}
|
||||
|
||||
with open(meta_path, "w", encoding="utf-8") as f:
|
||||
try:
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
logger.warning(
|
||||
"RoomIndex.save: meta file locked, retrying with blocking lock"
|
||||
)
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
|
||||
try:
|
||||
json.dump(meta, f, indent=2, ensure_ascii=False)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
finally:
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
logger.info(
|
||||
"RoomIndex saved: %d rooms → %s",
|
||||
len(self._room_ids),
|
||||
faiss_path,
|
||||
)
|
||||
return str(faiss_path)
|
||||
|
||||
def load(self, index_dir: Optional[str] = None) -> bool:
|
||||
"""Lädt den FAISS-Index und Metadaten von Disk.
|
||||
|
||||
Args:
|
||||
index_dir: Alternatives Verzeichnis. Default: ``self._index_dir``.
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich geladen, False wenn die Dateien nicht
|
||||
existieren oder inkonsistent sind.
|
||||
"""
|
||||
directory = Path(index_dir) if index_dir else self._index_dir
|
||||
faiss_path = directory / _INDEX_FILENAME
|
||||
meta_path = directory / _META_FILENAME
|
||||
|
||||
if not faiss_path.exists():
|
||||
logger.info("No saved index at %s — needs build_index()", faiss_path)
|
||||
return False
|
||||
|
||||
if not meta_path.exists():
|
||||
logger.warning(
|
||||
"FAISS index exists but meta file missing at %s — needs rebuild",
|
||||
meta_path,
|
||||
)
|
||||
return False
|
||||
|
||||
# ── Metadaten laden ────────────────────────────────────────
|
||||
try:
|
||||
with open(meta_path, "r", encoding="utf-8") as f:
|
||||
meta = json.load(f)
|
||||
except (json.JSONDecodeError, OSError) as e:
|
||||
logger.error("Failed to read index meta: %s", e)
|
||||
return False
|
||||
|
||||
# Validierung
|
||||
stored_dim = meta.get("embedding_dim", 0)
|
||||
if stored_dim != self._embedding_dim:
|
||||
logger.warning(
|
||||
"Embedding dimension mismatch: stored=%d, current=%d — needs rebuild",
|
||||
stored_dim,
|
||||
self._embedding_dim,
|
||||
)
|
||||
return False
|
||||
|
||||
room_ids = meta.get("room_ids", [])
|
||||
if not room_ids:
|
||||
logger.warning("Meta file has empty room_ids — needs rebuild")
|
||||
return False
|
||||
|
||||
# ── FAISS-Index laden ──────────────────────────────────────
|
||||
try:
|
||||
index = faiss.read_index(str(faiss_path))
|
||||
except Exception as e:
|
||||
logger.error("Failed to read FAISS index: %s", e)
|
||||
return False
|
||||
|
||||
if not isinstance(index, faiss.IndexFlatIP):
|
||||
logger.error(
|
||||
"Loaded index is %s, expected IndexFlatIP — needs rebuild",
|
||||
type(index).__name__,
|
||||
)
|
||||
return False
|
||||
|
||||
if index.d != self._embedding_dim:
|
||||
logger.warning(
|
||||
"Loaded index dim=%d, expected %d — needs rebuild",
|
||||
index.d,
|
||||
self._embedding_dim,
|
||||
)
|
||||
return False
|
||||
|
||||
if index.ntotal != len(room_ids):
|
||||
logger.warning(
|
||||
"Index size mismatch: index=%d, meta=%d — needs rebuild",
|
||||
index.ntotal,
|
||||
len(room_ids),
|
||||
)
|
||||
return False
|
||||
|
||||
# ── Zustand übernehmen ─────────────────────────────────────
|
||||
self.index = index
|
||||
self._room_ids = room_ids
|
||||
self._built_at = meta.get("built_at", 0.0)
|
||||
self._version = meta.get("version", 1)
|
||||
|
||||
logger.info(
|
||||
"RoomIndex loaded: %d rooms, dim=%d, version=%d from %s",
|
||||
len(room_ids),
|
||||
self._embedding_dim,
|
||||
self._version,
|
||||
faiss_path,
|
||||
)
|
||||
return True
|
||||
|
||||
def is_stale(self, room_map_version: Optional[int] = None) -> bool:
|
||||
"""Prüft ob der Index veraltet ist (RoomMap-Version neuer).
|
||||
|
||||
Args:
|
||||
room_map_version: Aktuelle Version der RoomMap. Default:
|
||||
``self._room_map.version``.
|
||||
|
||||
Returns:
|
||||
True wenn der Index neu gebaut werden sollte.
|
||||
"""
|
||||
if not self.is_built:
|
||||
return True
|
||||
|
||||
current_version = (
|
||||
room_map_version if room_map_version is not None
|
||||
else self._room_map.version
|
||||
)
|
||||
return current_version > self._version
|
||||
|
||||
# ── Internal Helpers ────────────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _room_to_text(entry: RoomEntry) -> str:
|
||||
"""Bildet einen Embedding-Text aus Description + Seed-Messages + Keywords.
|
||||
|
||||
Der kombinierte Text wird von der Embedding-API vektorisiert.
|
||||
Wenn eine Description vorhanden ist, wird diese mit höherer Priorität verwendet.
|
||||
Seed-Data-Messages (kuratierte raum-spezifische Formulierungen) werden
|
||||
eingewoben, um die FAISS-Similarity zu schärfen.
|
||||
Keywords werden mit höherem Gewicht dupliziert, damit sie im
|
||||
Embedding-Raum stärker repräsentiert sind.
|
||||
"""
|
||||
parts: List[str] = []
|
||||
|
||||
# Verwende Description wenn vorhanden, sonst Theme
|
||||
if entry.description:
|
||||
parts.append(entry.description)
|
||||
elif entry.theme:
|
||||
parts.append(entry.theme)
|
||||
|
||||
# Seed-Data-Messages einweben (raum-spezifische Formulierungen)
|
||||
seed_entry = SEED_DATA.get(entry.room_id)
|
||||
if seed_entry is not None:
|
||||
for msg in seed_entry.get("messages", []):
|
||||
parts.append(msg["text"])
|
||||
|
||||
# Keywords doppelt für stärkere Gewichtung im Embedding
|
||||
for kw in entry.keywords_100:
|
||||
parts.extend([kw, kw])
|
||||
for kw in entry.keywords_context:
|
||||
parts.append(kw)
|
||||
|
||||
return " ".join(parts)
|
||||
|
||||
def _embed_text(self, text: str) -> Optional[np.ndarray]:
|
||||
"""Embed *text* via ``EmbeddingClient`` und gib numpy-Array zurück.
|
||||
|
||||
Returns:
|
||||
float32 numpy array der Länge ``embedding_dim``, oder None
|
||||
bei Fehler.
|
||||
"""
|
||||
raw = self._emb_client.get_embedding(text)
|
||||
if raw is None:
|
||||
return None
|
||||
if len(raw) != self._embedding_dim:
|
||||
logger.error(
|
||||
"Embedding dimension mismatch: got %d, expected %d",
|
||||
len(raw),
|
||||
self._embedding_dim,
|
||||
)
|
||||
return None
|
||||
return np.array(raw, dtype=np.float32)
|
||||
|
||||
# ── Stats / Debug ──────────────────────────────────────────────────
|
||||
|
||||
def stats(self) -> dict:
|
||||
"""Gibt Diagnose-Statistiken als Dict zurück."""
|
||||
return {
|
||||
"is_built": self.is_built,
|
||||
"room_count": self.size,
|
||||
"embedding_dim": self._embedding_dim,
|
||||
"version": self._version,
|
||||
"built_at": self._built_at,
|
||||
"built_at_iso": (
|
||||
time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(self._built_at))
|
||||
if self._built_at else None
|
||||
),
|
||||
"index_dir": str(self._index_dir),
|
||||
"index_path": str(self.index_path),
|
||||
"meta_path": str(self.meta_path),
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
"""
|
||||
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 fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Use absolute import instead of relative import
|
||||
try:
|
||||
from config import DEFAULT_MAP_PATH as CONFIG_DEFAULT_MAP_PATH
|
||||
DEFAULT_MAP_PATH = CONFIG_DEFAULT_MAP_PATH
|
||||
except ImportError:
|
||||
# Fallback for testing
|
||||
DEFAULT_MAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
|
||||
|
||||
# ── Constants ─────────────────────────────────────────────────────────────
|
||||
# DEFAULT_MAP_PATH is set above via config import or fallback
|
||||
|
||||
# ── 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)."""
|
||||
|
||||
description: str = ""
|
||||
"""Detaillierte Beschreibung des Raums (ca. 200 Wörter)."""
|
||||
|
||||
keywords_100: list[str] = field(default_factory=list)
|
||||
"""100% Evidenz Stichworte für Keyword-Matching."""
|
||||
|
||||
keywords_context: list[str] = field(default_factory=list)
|
||||
"""Kontextabhängige Stichworte für Keyword-Matching."""
|
||||
|
||||
catch_all: bool = False
|
||||
"""True wenn dieser Raum der EINE Catch-All-Raum ist."""
|
||||
|
||||
@property
|
||||
def keywords(self) -> list[str]:
|
||||
"""Legacy property for backward compatibility."""
|
||||
return self.keywords_context
|
||||
|
||||
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).
|
||||
"""
|
||||
# Prüfe beide Listen: keywords_100 und keywords_context
|
||||
text_lower = text.lower()
|
||||
score_100 = sum(1 for kw in self.keywords_100 if kw.lower() in text_lower)
|
||||
score_context = sum(1 for kw in self.keywords_context if kw.lower() in text_lower)
|
||||
return score_100 + score_context
|
||||
|
||||
|
||||
# ── 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, min_score: int = 2, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
|
||||
"""Find the room with the most keyword matches for *text*.
|
||||
|
||||
Args:
|
||||
text: The message text to classify.
|
||||
min_score: Minimum score required to return a room (default: 2).
|
||||
origin_room_id: Optional room ID of the message origin for priority matching.
|
||||
|
||||
Returns:
|
||||
The ``RoomEntry`` with the highest match score, or ``None``
|
||||
if no room has any matching keywords or if the best score
|
||||
is below the minimum threshold.
|
||||
"""
|
||||
text_lower = text.lower()
|
||||
|
||||
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
|
||||
# Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen
|
||||
best_100_room: Optional[RoomEntry] = None
|
||||
best_100_score: int = 0
|
||||
|
||||
for room in self._rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
|
||||
# Zähle 100%-Keyword-Treffer
|
||||
score_100 = sum(1 for kw in room.keywords_100 if kw.lower() in text_lower)
|
||||
if score_100 > best_100_score:
|
||||
best_100_score = score_100
|
||||
best_100_room = room
|
||||
|
||||
# Wenn mindestens ein 100%-Match existiert → sofort diesen Raum zurückgeben
|
||||
if best_100_room is not None and best_100_score > 0:
|
||||
return best_100_room
|
||||
|
||||
# Stufe 2: Origin-Priorität mit kontextabhängigen Keywords
|
||||
# Origin-Priorität gilt NUR für context-Keywords (100% schlagen immer durch)
|
||||
if origin_room_id is not None and origin_room_id in self._rooms:
|
||||
origin_room = self._rooms[origin_room_id]
|
||||
if not origin_room.catch_all:
|
||||
# Prüfe kontextabhängige Keywords im Ursprungsraum
|
||||
context_score = sum(1 for kw in origin_room.keywords_context if kw.lower() in text_lower)
|
||||
if context_score >= min_score:
|
||||
return origin_room
|
||||
|
||||
# Stufe 3: Globaler Scan mit kontextabhängigen 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
|
||||
|
||||
# Prüfe kontextabhängige Keywords
|
||||
context_score = sum(1 for kw in room.keywords_context if kw.lower() in text_lower)
|
||||
if context_score > best_score:
|
||||
best_score = context_score
|
||||
best_room = room
|
||||
|
||||
if best_room is not None and best_score >= min_score:
|
||||
return best_room
|
||||
return None
|
||||
|
||||
def calculate_weighted_score(self, text: str, room: RoomEntry) -> float:
|
||||
"""
|
||||
Berechnet einen gewichteten Score für ein Text-Raum-Paar.
|
||||
|
||||
Args:
|
||||
text: Der zu bewertende Text
|
||||
room: Der zu bewertende Raum
|
||||
|
||||
Returns:
|
||||
Gewichteter Score (0.0 - 1.0)
|
||||
"""
|
||||
# TODO: Diese Methode wird vom ArchivarState aufgerufen, wenn
|
||||
# das selbstlernende Keyword-Gewicht-System aktiv ist
|
||||
# Momentan verwenden wir eine einfache Keyword-Zählung
|
||||
text_lower = text.lower()
|
||||
matched_keywords = [kw for kw in room.keywords_context if kw.lower() in text_lower]
|
||||
if not matched_keywords:
|
||||
return 0.0
|
||||
|
||||
# Einfache Gewichtung: Anzahl der Treffer geteilt durch Anzahl der Keywords
|
||||
# In der vollständigen Implementierung würden wir hier die gelernten Gewichte verwenden
|
||||
return len(matched_keywords) / len(room.keywords_context) if room.keywords_context else 0.0
|
||||
|
||||
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
|
||||
|
||||
def get_room_by_id(self, room_id: str) -> Optional[RoomEntry]:
|
||||
"""Hole einen Raum anhand seiner ID.
|
||||
|
||||
Args:
|
||||
room_id: Die Rocket.Chat Raum-ID
|
||||
|
||||
Returns:
|
||||
RoomEntry wenn gefunden, sonst None
|
||||
"""
|
||||
return self._rooms.get(room_id)
|
||||
|
||||
# ── 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 = "", description: str = "", keywords_100: Optional[list] = None, keywords_context: 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)
|
||||
description: Detaillierte Beschreibung des Raums (ca. 200 Wörter)
|
||||
keywords_100: 100% Evidenz Stichworte für Keyword-Matching
|
||||
keywords_context: Kontextabhängige Stichworte für Keyword-Matching
|
||||
catch_all: True wenn dieser Raum der EINE Catch-All-Raum ist
|
||||
"""
|
||||
if keywords_100 is None:
|
||||
keywords_100 = []
|
||||
if keywords_context is None:
|
||||
keywords_context = []
|
||||
|
||||
# Erstelle oder aktualisiere den RoomEntry
|
||||
self._rooms[room_id] = RoomEntry(
|
||||
room_id=room_id,
|
||||
name=name,
|
||||
theme=theme,
|
||||
description=description,
|
||||
keywords_100=keywords_100,
|
||||
keywords_context=keywords_context,
|
||||
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 mit File-Lock.
|
||||
|
||||
Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele
|
||||
Schreibzugriffe zu verhindern. Blockiert maximal 5 Sekunden.
|
||||
|
||||
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,
|
||||
"description": room_entry.description,
|
||||
"keywords_100": room_entry.keywords_100,
|
||||
"keywords_context": room_entry.keywords_context,
|
||||
"catch_all": room_entry.catch_all
|
||||
}
|
||||
|
||||
# Schreibe die Datei mit exklusivem File-Lock
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
try:
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
logger.warning(
|
||||
"RoomMap.save: file locked, retrying with blocking lock (5s timeout)"
|
||||
)
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_EX) # blocking
|
||||
try:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
finally:
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
@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():
|
||||
# Abwärtskompatibilität: Wenn keywords_100 fehlt (alte room-map.json),
|
||||
# alte keywords-Liste als keywords_context interpretieren, keywords_100 bleibt leer
|
||||
if "keywords_100" in room_data:
|
||||
# Neue Struktur (Version 2+)
|
||||
keywords_100 = room_data.get("keywords_100", [])
|
||||
keywords_context = room_data.get("keywords_context", [])
|
||||
else:
|
||||
# Alte Struktur (Version 1) - Abwärtskompatibilität
|
||||
keywords_100 = []
|
||||
keywords_context = room_data.get("keywords", [])
|
||||
|
||||
rooms[room_id] = RoomEntry(
|
||||
room_id=room_id,
|
||||
name=room_data.get("name", room_id),
|
||||
theme=room_data.get("theme", ""),
|
||||
description=room_data.get("description", ""),
|
||||
keywords_100=keywords_100,
|
||||
keywords_context=keywords_context,
|
||||
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",
|
||||
"description": "Legacy catch-all room for all topics without their own 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",
|
||||
"description": "Legacy alarm room for critical alerts and urgent notifications.",
|
||||
"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",
|
||||
"description": "Legacy fakt room for documentation and factual information.",
|
||||
"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",
|
||||
"description": "Legacy question room for help requests and problem solving.",
|
||||
"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}",
|
||||
"description": f"Legacy project room for {proj_key} related discussions and tasks.",
|
||||
"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,871 @@
|
||||
"""
|
||||
Bidirektionales Routing für Archivar v3.
|
||||
|
||||
Ermittelt den Zielraum basierend auf Intent-Klassifikationsergebnis, Konfidenzschwelle
|
||||
und Fallback-Strategie. Unterstützt bidirektionales Routing mit Quellkanal-Benachrichtigung
|
||||
und Zusammenfassung nach Abschluss.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from .classifier import ClassificationResult, IntentClassifier
|
||||
from .config import (
|
||||
CONFIDENCE_THRESHOLDS,
|
||||
FALLBACK_KEYWORDS,
|
||||
OLLAMA_CONFIG,
|
||||
LLM_ROOM_PROMPT,
|
||||
ROOM_MAP_PATH,
|
||||
FAISS_AUTO_ROUTE,
|
||||
FAISS_MIN_SCORE,
|
||||
FAISS_TOP_K,
|
||||
FAISS_CONFLICT_DIFF,
|
||||
)
|
||||
from .room_map import RoomMap, RoomEntry
|
||||
from .room_index import RoomIndexManager
|
||||
from .booster import KeywordBooster
|
||||
from .archivar_state import ArchivarState
|
||||
|
||||
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),
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class RoutingDecision:
|
||||
"""Entscheidung, wohin eine Nachricht weitergeleitet wird."""
|
||||
|
||||
category: str
|
||||
"""Klassifikations-Kategorie: 'direct_question', 'smalltalk', 'work_order', 'ambiguous'."""
|
||||
|
||||
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 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."""
|
||||
|
||||
stay_in_room: bool = False
|
||||
"""True, wenn die Nachricht im Ursprungsraum bleiben soll."""
|
||||
|
||||
needs_clarification: bool = False
|
||||
"""True, wenn die Nachricht eine Klärung benötigt."""
|
||||
|
||||
move_request_sent: bool = False
|
||||
"""True, wenn ein Move-Request-Button gesendet wurde (Butler-Prinzip).
|
||||
Der Adapter muss auf die Button-Antwort warten, bevor geroutet wird."""
|
||||
|
||||
move_request_target_name: str = ""
|
||||
"""Name des vorgeschlagenen Zielraums für den Move-Request-Button."""
|
||||
|
||||
move_request_target_id: str = ""
|
||||
"""ID des vorgeschlagenen Zielraums (pending confirmation)."""
|
||||
|
||||
source_room_notification: Optional[str] = None
|
||||
"""Benachrichtigungstext für den Ursprungsraum bei bidirektionalem Routing."""
|
||||
|
||||
return_summary_to_source: Optional[str] = None
|
||||
"""Zusammenfassungstext, der nach Abschluss an den Ursprungsraum gesendet wird."""
|
||||
|
||||
matched_keywords: List[str] = field(default_factory=list)
|
||||
"""Liste der Keywords, die zum Routing-Vorschlag führten."""
|
||||
|
||||
# ── FAISS Phase-1 Felder ──────────────────────────────────────────
|
||||
|
||||
faiss_score: float = 0.0
|
||||
"""FAISS-Kosinus-Ähnlichkeitsscore (0.0–1.0) des besten Treffers.
|
||||
0.0 wenn Phase-1 nicht aktiv oder kein Treffer über FAISS_MIN_SCORE."""
|
||||
|
||||
faiss_room_id: str = ""
|
||||
"""Raum-ID des besten FAISS-Treffers. Leer wenn Phase-1 nicht aktiv
|
||||
oder kein Treffer über FAISS_MIN_SCORE."""
|
||||
|
||||
faiss_room_name: str = ""
|
||||
"""Raum-Name des besten FAISS-Treffers (für Logging/Debugging)."""
|
||||
|
||||
is_faiss_routed: bool = False
|
||||
"""True wenn Phase-1 (FAISS + Booster) direkt geroutet hat — kein
|
||||
LLM-Aufruf nötig. Spart ~2.4s Latenz pro Nachricht."""
|
||||
|
||||
booster_applied: bool = False
|
||||
"""True wenn der KeywordBooster auf die FAISS-Ergebnisse angewendet
|
||||
wurde (z.B. bei knappen Top-2 zur Konfliktlösung)."""
|
||||
|
||||
def should_route(self) -> bool:
|
||||
"""True wenn die Nachricht geroutet werden sollte.
|
||||
|
||||
Im neuen Flow (Embedding-Vorfilter + LLM-Raum-Router + Move-Request):
|
||||
Routing erfolgt nur, wenn ein Zielraum gesetzt ist und kein
|
||||
stay_in_room/meta/catch_all/unrouteable vorliegt.
|
||||
"""
|
||||
return (
|
||||
not self.stay_in_room and
|
||||
not self.is_meta and
|
||||
not self.is_catch_all and
|
||||
not self.is_unrouteable and
|
||||
bool(self.target_room)
|
||||
)
|
||||
|
||||
|
||||
class BidirectionalRouter:
|
||||
"""Bidirektionaler Router für Archivar v3.
|
||||
|
||||
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 = IntentClassifier()
|
||||
await classifier.initialize()
|
||||
state = ArchivarState()
|
||||
state.load()
|
||||
|
||||
router = BidirectionalRouter(room_map, classifier, state)
|
||||
router.set_subscribed_room_ids(["6a19...", "6a1f..."])
|
||||
decision = await router.route("Bitte dokumentiere das neue Feature", "6a1f...")
|
||||
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Dokumentation)
|
||||
# decision.source_room_notification → "📋 Bearbeite ich in #Dokumentation — [Link]"
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
room_map: RoomMap,
|
||||
classifier: IntentClassifier,
|
||||
state: ArchivarState,
|
||||
room_index: Optional[RoomIndexManager] = None,
|
||||
booster: Optional[KeywordBooster] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
room_map: A loaded and validated ``RoomMap`` instance.
|
||||
classifier: An (initialized) ``IntentClassifier``.
|
||||
state: An (loaded) ``ArchivarState`` instance.
|
||||
room_index: Optional ``RoomIndexManager`` für FAISS Phase-1.
|
||||
Wenn None, wird Phase-1 übersprungen (bestehendes Verhalten).
|
||||
booster: Optional ``KeywordBooster`` für FAISS-Score-Verfeinerung.
|
||||
Wenn None, wird Phase-1 übersprungen (bestehendes Verhalten).
|
||||
"""
|
||||
self._room_map = room_map
|
||||
self._classifier = classifier
|
||||
self._state = state
|
||||
self._room_index: Optional[RoomIndexManager] = room_index
|
||||
self._booster: Optional[KeywordBooster] = booster
|
||||
self._subscribed_room_ids: Optional[set] = None
|
||||
# Semaphore für Ollama-Concurrency: qwen2.5:7b kann nur 1 Request
|
||||
# parallel verarbeiten. Ohne diesen Schutz führen parallele Aufrufe
|
||||
# zu Timeout-Kaskaden.
|
||||
self._llm_semaphore: asyncio.Semaphore = asyncio.Semaphore(1)
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
|
||||
"""Klassifiziere und route eine Nachricht (v6 Flow mit Origin-First Guard).
|
||||
|
||||
Der neue Routing-Flow (v6):
|
||||
-0.5 ORIGIN-FIRST GUARD (VOR allen anderen Schritten):
|
||||
1. origin_room_id leer (echte DM) → normaler Flow
|
||||
2. origin_room ist Catch-All-Raum → stay_in_room
|
||||
3. origin_room ist excluded → ignore
|
||||
0. Excluded rooms check
|
||||
1. Raum-Zustand prüfen (persistenter Zustand)
|
||||
2. Meta-Fragen-Erkennung
|
||||
3. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig)
|
||||
3.5 FAISS Phase-1: Raum-Index + Keyword-Booster
|
||||
4. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag"
|
||||
5. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste → STAY oder room_id
|
||||
6. ORIGIN-FIRST GUARD (nach LLM):
|
||||
- LLM sagt STAY → stay_in_room
|
||||
- LLM == origin_room → stay_in_room
|
||||
- LLM == catch_all_room → stay_in_room (kein DM-Routing aus Projekträumen!)
|
||||
- LLM == anderer Raum → Move-Request (Butler-Prinzip)
|
||||
7. LLM-Fehler → stay_in_room
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
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="direct_question",
|
||||
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,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
text = text.strip()
|
||||
|
||||
try:
|
||||
# ── Schritt 0: DM-Guard (VOR allem anderen) ──────────────────
|
||||
# DMs haben origin_room_id=''. Der Origin-First Guard greift
|
||||
# nicht für DMs. LLM kann Projektraum vorschlagen → Guard 3 →
|
||||
# Move-Request im DM → Antwort landet in Projektraum statt DM.
|
||||
# DMs sollen nie vom Routing betroffen sein — sie bleiben IMMER
|
||||
# im DM. (Release-blockierend)
|
||||
if not origin_room_id:
|
||||
logger.debug("DM-Guard: origin_room_id leer → stay_in_room (DM)")
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 0: Excluded rooms check ──────────────────────────
|
||||
if origin_room_id and self._room_map.is_excluded(origin_room_id):
|
||||
logger.debug(
|
||||
"Message from excluded room %s — ignoring", origin_room_id[:8]
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
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,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 0.5: Check if origin room is catch-all ───────────
|
||||
origin_room = self._room_map.get_room_by_id(origin_room_id) if origin_room_id else None
|
||||
if origin_room and origin_room.catch_all:
|
||||
logger.debug(
|
||||
"Message from catch-all room %s — ignoring", origin_room_id[:8]
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room=origin_room_id,
|
||||
confidence=0.0,
|
||||
is_catch_all=True,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 1: Raum-Zustand prüfen ───────────────────────────
|
||||
room_state_decision = self._state.should_stay_in_room(origin_room_id)
|
||||
if room_state_decision is True:
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
elif room_state_decision is False:
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 2: Meta-Fragen-Erkennung ──────────────────────────
|
||||
if self._is_meta_question(text):
|
||||
logger.info("Meta-question detected: %.80s...", text)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
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] ",
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 3: Keyword-Match (aus RoomMap) ──────────────────
|
||||
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
||||
if matched_room is not None:
|
||||
# Self-Match-Schutz: Wenn Keyword-Match den Ursprungsraum
|
||||
# selbst trifft (z.B. 'RC' matched #RC und User ist bereits
|
||||
# in #RC), dann stay_in_room statt Routing.
|
||||
if matched_room.room_id == origin_room_id:
|
||||
logger.debug(
|
||||
"Keyword self-match: '%s' matched origin room %s → stay_in_room",
|
||||
text[:80], matched_room.name,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
"Keyword match: '%s' → %s", text[:80], matched_room.name
|
||||
)
|
||||
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
|
||||
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
|
||||
matched_keywords = self._extract_matched_keywords(text, matched_room)
|
||||
|
||||
return RoutingDecision(
|
||||
category="work_order",
|
||||
target_room=matched_room.room_id,
|
||||
confidence=0.95,
|
||||
matched_room_name=matched_room.name,
|
||||
source_room_notification=notification,
|
||||
matched_keywords=matched_keywords,
|
||||
)
|
||||
|
||||
# ── Schritt 3.5: FAISS Phase-1 (Raum-Index + Keyword-Booster) ─
|
||||
# Drei-Schichten-Logik: FAISS → Booster → LLM
|
||||
# Phase-1 routet direkt bei hohem FAISS-Score — kein LLM-Aufruf.
|
||||
# Übersprungen wenn _room_index oder _booster None sind.
|
||||
if self._room_index is not None and self._room_index.is_built:
|
||||
faiss_hits = self._room_index.search_text(
|
||||
text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE
|
||||
)
|
||||
if faiss_hits:
|
||||
# ── Keyword-Booster anwenden ──────────────────────
|
||||
boosted = faiss_hits
|
||||
booster_applied = False
|
||||
if self._booster is not None:
|
||||
# Boosten immer anwenden, nicht nur bei Konflikten
|
||||
boosted = self._booster.boost(text, faiss_hits)
|
||||
booster_applied = True
|
||||
logger.debug(
|
||||
"FAISS Booster applied: always active",
|
||||
)
|
||||
|
||||
top_room_id, top_score = boosted[0]
|
||||
|
||||
# ── Auto-Route bei hohem Score ────────────────────
|
||||
if top_score >= FAISS_AUTO_ROUTE:
|
||||
room = self._room_map.get_room_by_id(top_room_id)
|
||||
if room is not None:
|
||||
# Self-Match-Schutz: FAISS matched origin room
|
||||
if top_room_id == origin_room_id:
|
||||
logger.debug(
|
||||
"FAISS self-match: '%s' matched origin room %s → stay_in_room",
|
||||
text[:80], room.name,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
room_name = (
|
||||
room.name.replace("#", "")
|
||||
if room.name.startswith("#")
|
||||
else room.name
|
||||
)
|
||||
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
|
||||
matched_keywords = self._extract_matched_keywords(text, room)
|
||||
|
||||
logger.info(
|
||||
"FAISS Phase-1: auto-route '%s' → %s (score=%.3f, booster=%s)",
|
||||
text[:80],
|
||||
room.name,
|
||||
top_score,
|
||||
booster_applied,
|
||||
)
|
||||
|
||||
return RoutingDecision(
|
||||
category="work_order",
|
||||
target_room=top_room_id,
|
||||
confidence=top_score,
|
||||
matched_room_name=room.name,
|
||||
source_room_notification=notification,
|
||||
matched_keywords=matched_keywords,
|
||||
faiss_score=top_score,
|
||||
faiss_room_id=top_room_id,
|
||||
faiss_room_name=room.name,
|
||||
is_faiss_routed=True,
|
||||
booster_applied=booster_applied,
|
||||
)
|
||||
|
||||
# ── Score unter Schwelle → Fall-through zu Embedding + LLM
|
||||
logger.debug(
|
||||
"FAISS Phase-1: top score %.3f < %.3f — fall-through to LLM",
|
||||
top_score,
|
||||
FAISS_AUTO_ROUTE,
|
||||
)
|
||||
|
||||
# ── Schritt 4: Embedding-Vorfilter (binär) ────────────────────
|
||||
# Nur noch binär: "Smalltalk" vs. "potenzieller Auftrag"
|
||||
# Klarer Smalltalk → stay_in_room, alles andere → LLM-Router
|
||||
is_smalltalk = False
|
||||
result: Optional[ClassificationResult] = None
|
||||
if self._classifier.is_initialized:
|
||||
result = await self._classifier.classify(text)
|
||||
if result is not None:
|
||||
# Binärer Vorfilter: Nur Smalltalk mit hoher Konfidenz blocken
|
||||
if result.category == "smalltalk" and result.confidence >= 0.8:
|
||||
is_smalltalk = True
|
||||
logger.info(
|
||||
"Embedding-Vorfilter: Smalltalk erkannt (conf=%.3f) — stay_in_room",
|
||||
result.confidence,
|
||||
)
|
||||
|
||||
if is_smalltalk:
|
||||
return RoutingDecision(
|
||||
category="smalltalk",
|
||||
target_room="",
|
||||
confidence=result.confidence if result else 0.0,
|
||||
all_scores=result.all_scores if result else {},
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 4.5: Keyword-Matching vor LLM (FIX 2) ────────────
|
||||
# Wenn Embedding 'work_order' mit niedriger Konfidenz (< 0.9):
|
||||
# versuche Keyword-Match bevor wir das LLM aufrufen.
|
||||
# Verhindert unnötige LLM-Calls für Nachrichten mit klaren Keywords.
|
||||
if result is not None and result.category == "work_order" and result.confidence < 0.9:
|
||||
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
||||
if matched_room is not None:
|
||||
# Self-Match-Schutz (auch in Schritt 4.5)
|
||||
if matched_room.room_id == origin_room_id:
|
||||
logger.debug(
|
||||
"Keyword self-match (4.5): '%s' matched origin room %s → stay_in_room",
|
||||
text[:80], matched_room.name,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Keyword-Match vor LLM: '%s' → %s (embedding conf=%.3f)",
|
||||
text[:80], matched_room.name, result.confidence,
|
||||
)
|
||||
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
|
||||
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
|
||||
matched_keywords = self._extract_matched_keywords(text, matched_room)
|
||||
return RoutingDecision(
|
||||
category="work_order",
|
||||
target_room=matched_room.room_id,
|
||||
confidence=0.95,
|
||||
matched_room_name=matched_room.name,
|
||||
source_room_notification=notification,
|
||||
matched_keywords=matched_keywords,
|
||||
)
|
||||
|
||||
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
|
||||
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
|
||||
# liefert STAY oder room_id direkt (keine Kategorien, kein Name-Matching)
|
||||
llm_room, llm_stay, llm_failed = await self._llm_room_lookup(text, origin_room_id)
|
||||
|
||||
# ── Schritt 6: ORIGIN-FIRST GUARD (v6) ──────────────────────
|
||||
# Paradigmenwechsel: Ursprungsraum entscheidet WOHIN die Antwort geht.
|
||||
# Archivar schlägt nur VERLEGUNG vor (Move-Request).
|
||||
if llm_failed:
|
||||
# LLM-Aufruf fehlgeschlagen → stay_in_room
|
||||
logger.warning(
|
||||
"LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...' → stay_in_room (Ursprungsraum)",
|
||||
text,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
is_catch_all=False,
|
||||
)
|
||||
|
||||
if llm_stay or llm_room is None:
|
||||
# LLM sagt STAY oder unsicher → stay_in_room
|
||||
logger.info(
|
||||
"LLM-Raum-Router: STAY für '%.80s...' → stay_in_room", text[:80]
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# LLM hat einen Raum vorgeschlagen — Origin-First Guard prüfen
|
||||
catch_all = self._room_map.catch_all_room
|
||||
catch_all_id = catch_all.room_id if catch_all else ""
|
||||
|
||||
# Guard 1: LLM == origin_room → stay_in_room
|
||||
if origin_room_id and llm_room.room_id == origin_room_id:
|
||||
logger.info(
|
||||
"Origin-First Guard: LLM schlägt Ursprungsraum vor → stay_in_room"
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# Guard 2: LLM == catch_all_room → stay_in_room
|
||||
# (Kein DM-Routing aus Projekträumen!)
|
||||
if catch_all_id and llm_room.room_id == catch_all_id:
|
||||
logger.info(
|
||||
"Origin-First Guard: LLM schlägt Catch-All vor → stay_in_room"
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# Guard 2.5: LLM == excluded room → stay_in_room
|
||||
# Verhindert, dass der LLM einen excluded room vorschlägt und
|
||||
# ein Move-Request dorthin gesendet wird (Release-blockierend).
|
||||
if self._room_map.is_excluded(llm_room.room_id):
|
||||
logger.warning(
|
||||
"Origin-First Guard: LLM schlug excluded room '%s' (%s) vor → stay_in_room",
|
||||
llm_room.name, llm_room.room_id[:8],
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# Guard 3: LLM == anderer Raum → Move-Request (Butler-Prinzip)
|
||||
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
|
||||
logger.info(
|
||||
"LLM-Raum-Router: '%s' → %s (%s) — Move-Request pending",
|
||||
text[:80], llm_room.name, llm_room.room_id[:8],
|
||||
)
|
||||
|
||||
return RoutingDecision(
|
||||
category="work_order",
|
||||
target_room=llm_room.room_id,
|
||||
confidence=0.90,
|
||||
matched_room_name=llm_room.name,
|
||||
move_request_sent=True,
|
||||
move_request_target_name=llm_room.name,
|
||||
move_request_target_id=llm_room.room_id,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
# ── Catch-All-Schutz: unerwarteter Fehler → Fallback ──────
|
||||
logger.error(
|
||||
"route(): Unerwarteter Fehler für '%.80s...' — Fallback auf Catch-All: %s",
|
||||
text, e, exc_info=True,
|
||||
)
|
||||
catch_all = self._room_map.catch_all_room
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room=catch_all.room_id if catch_all else "",
|
||||
confidence=0.0,
|
||||
is_catch_all=True,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
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.
|
||||
work_order routes to the configured work_order room.
|
||||
"""
|
||||
# Für work_order: Nutze den konfigurierten Raum aus der RoomMap
|
||||
# Wir suchen nach einem Raum, der für work_order konfiguriert ist
|
||||
if category == "work_order":
|
||||
# In der neuen Architektur suchen wir nach spezifischen Räumen
|
||||
# vorerst verwenden wir den Catch-All-Raum als Fallback
|
||||
pass
|
||||
|
||||
# Fallback: catch_all_room
|
||||
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 ""
|
||||
|
||||
return catch_all.room_id
|
||||
|
||||
async def _llm_room_lookup(self, text: str, origin_room_id: str = "") -> Tuple[Optional[RoomEntry], bool, bool]:
|
||||
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
|
||||
|
||||
Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap
|
||||
und nutzt den LLM_ROOM_PROMPT für kontextbasiertes Routing.
|
||||
Das LLM liefert die Raum-ID direkt zurück (kein Name-Matching nötig).
|
||||
|
||||
Der LLM-Aufruf wird durch einen asyncio.Semaphore(1) geschützt, weil
|
||||
qwen2.5:7b nur einen parallelen Request verarbeiten kann. Ohne diesen
|
||||
Schutz führen parallele Aufrufe zu Timeout-Kaskaden.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums (für Kontext).
|
||||
|
||||
Returns:
|
||||
(RoomEntry, False, False) — LLM erfolgreich, Raum gefunden (ROUTE)
|
||||
(None, False, False) — LLM erfolgreich, STAY (kein Routing)
|
||||
(None, False, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout)
|
||||
"""
|
||||
# Build room list for LLM prompt: "ID | Name | Keywords"
|
||||
# Nur Nicht-Catch-All-Räume als Optionen (Catch-All ist nie ein Routing-Ziel)
|
||||
room_list_parts = []
|
||||
for room in self._room_map.rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
# Alle Keywords (100% + context) in die Liste
|
||||
all_keywords = list(room.keywords_100) + list(room.keywords_context)
|
||||
kw_str = ", ".join(all_keywords) if all_keywords else "(keine)"
|
||||
room_list_parts.append(
|
||||
f"{room.room_id} | {room.name} | {kw_str}"
|
||||
)
|
||||
|
||||
if not room_list_parts:
|
||||
# Keine Nicht-Catch-All-Räume → STAY
|
||||
return None, False, False
|
||||
|
||||
room_list = "\n".join(room_list_parts)
|
||||
|
||||
# Ursprungsraum-Name für Kontext
|
||||
origin_name = ""
|
||||
if origin_room_id:
|
||||
origin_room = self._room_map.get_room_by_id(origin_room_id)
|
||||
if origin_room:
|
||||
origin_name = origin_room.name
|
||||
|
||||
prompt = LLM_ROOM_PROMPT.format(
|
||||
room_list=room_list,
|
||||
text=text,
|
||||
origin_room=origin_name or "unbekannt",
|
||||
)
|
||||
|
||||
# Try LLM — expects room ID directly or "STAY"
|
||||
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
|
||||
async with self._llm_semaphore:
|
||||
llm_result = await self._classifier._llm_raw(prompt)
|
||||
if llm_result is None:
|
||||
return None, False, True # LLM-Aufruf fehlgeschlagen
|
||||
|
||||
# Parse LLM response — should be a room ID or "STAY"
|
||||
response = llm_result.strip()
|
||||
|
||||
# STAY = Nachricht bleibt im Ursprungsraum
|
||||
if response.upper() == "STAY":
|
||||
return None, False, False # LLM erfolgreich, STAY
|
||||
|
||||
# Direct lookup by room ID (LLM returns the ID directly)
|
||||
room = self._room_map.get_room_by_id(response)
|
||||
if room is not None:
|
||||
return room, False, False
|
||||
|
||||
# Fallback: try name matching (for LLMs that return names instead of IDs)
|
||||
response_lower = response.lower()
|
||||
for room in self._room_map.rooms.values():
|
||||
if response_lower == room.name.lower():
|
||||
return room, False, False
|
||||
if response_lower in room.name.lower():
|
||||
return room, False, False
|
||||
|
||||
logger.debug("LLM returned unknown room: %s", response)
|
||||
return None, False, False # Unbekannte Antwort → STAY
|
||||
|
||||
# ── 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 work_order keywords
|
||||
for kw in FALLBACK_KEYWORDS.get("work_order", []):
|
||||
if kw in text_lower:
|
||||
return "work_order", True
|
||||
|
||||
# Check direct_question keywords
|
||||
for kw in FALLBACK_KEYWORDS.get("direct_question", []):
|
||||
if kw in text_lower:
|
||||
return "direct_question", True
|
||||
|
||||
# Check smalltalk keywords
|
||||
for kw in FALLBACK_KEYWORDS.get("smalltalk", []):
|
||||
if kw in text_lower:
|
||||
return "smalltalk", True
|
||||
|
||||
# Default: direct_question
|
||||
return "direct_question", True
|
||||
|
||||
# ── Configuration ──────────────────────────────────────────────────
|
||||
|
||||
@property
|
||||
def confidence_threshold(self) -> float:
|
||||
"""Current confidence threshold."""
|
||||
return CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
|
||||
|
||||
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 ""
|
||||
|
||||
def _extract_matched_keywords(self, text: str, room: RoomEntry) -> List[str]:
|
||||
"""Extrahiere die Keywords, die zum Match führten.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext
|
||||
room: Der gematchte Raum
|
||||
|
||||
Returns:
|
||||
Liste der gematchten Keywords
|
||||
"""
|
||||
text_lower = text.lower()
|
||||
matched_keywords = []
|
||||
|
||||
# Prüfe 100% Evidenz Keywords
|
||||
for kw in room.keywords_100:
|
||||
if kw.lower() in text_lower and kw not in matched_keywords:
|
||||
matched_keywords.append(kw)
|
||||
|
||||
# Prüfe kontextabhängige Keywords
|
||||
for kw in room.keywords_context:
|
||||
if kw.lower() in text_lower and kw not in matched_keywords:
|
||||
matched_keywords.append(kw)
|
||||
|
||||
return matched_keywords
|
||||
|
||||
# ── Bidirektionales Routing ────────────────────────────────────────
|
||||
|
||||
async def move_message(self, source_room: str, target_room: str, message: str, message_id: str) -> bool:
|
||||
"""Verschiebe eine Nachricht bidirektional zwischen Räumen.
|
||||
|
||||
Args:
|
||||
source_room: ID des Ursprungsraums
|
||||
target_room: ID des Zielraums
|
||||
message: Die zu verschiebende Nachricht
|
||||
message_id: ID der Originalnachricht
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich, False bei Fehler
|
||||
"""
|
||||
# Diese Methode wird vom Adapter aufgerufen, wenn eine Routing-Entscheidung
|
||||
# ausgeführt wird. Sie implementiert den vollständigen bidirektionalen
|
||||
# Routing-Flow.
|
||||
|
||||
logger.info("Moving message from %s to %s", source_room[:8], target_room[:8])
|
||||
# Die tatsächliche Implementierung erfolgt im Adapter
|
||||
return True
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Archivar v5 — FAISS Phase-1 Seed-Daten.
|
||||
|
||||
Agent-kuratierte Trainingsbasis: Stichwortlisten + repräsentative Nachrichten
|
||||
pro Raum, nach SINN zugeordnet (nicht nach historischem Ort).
|
||||
|
||||
Jeder Eintrag: {"text": "...", "room": "room_id", "source": "agent_curated"}
|
||||
"""
|
||||
|
||||
SEED_DATA = {
|
||||
# ── #Rocketchat-Plugin ──────────────────────────────────────────────
|
||||
"6a19b0ff02aeecd36b1aa16c": {
|
||||
"stichworte": (
|
||||
"RC-Plugin-Entwicklung, Adapter, DDP, WebSocket, Buttons, "
|
||||
"Archivar, Routing, Gateway-Integration, Rocket.Chat-API, "
|
||||
"CLARIFY, Message-Handling, Raum-Management, install.sh, "
|
||||
"Deployment, Plugin, Hermes Gateway, Onboarding, "
|
||||
"Button-Garantie, Move-Request, Embedding, FAISS, "
|
||||
"Phase-1-Routing, Intent-Klassifikation, room-map.json"
|
||||
),
|
||||
"messages": [
|
||||
# Architektur-Strategie (heutiges Gespräch)
|
||||
{"text": "FAISS als Phase-1-Raum-Index für Archivar v5 — Drei-Schichten-Logik: FAISS + Keyword-Booster + LLM", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "Der Archivar und der Agent sind ein Team. Einer sagt wohin und der andere entscheidet, ob es eine Antwort braucht.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "Vier Bausteine: _CURRENT_ORIGIN_ROOM, _THEMATIC_TARGET_ROOM, _question_counter, Priority-0-Routing", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "Kontext-Reset fehlt als fünfter Baustein — _THEMATIC_TARGET_ROOM wird nicht zurückgesetzt nach DM", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
|
||||
# BUTTON_CLICK-Fix
|
||||
{"text": "BUTTON_CLICK-False-Positive: adapter.py:583 matched CLARIFY-Antworten mit :: als Button-Click", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "Fix: not text.startswith('CLARIFY:') in Zeile 583 — ein Wort, chirurgisch deployt", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
|
||||
# Button-Garantie
|
||||
{"text": "Button-Garantie: Move-Request von Textoptionen auf native Action-Buttons umgestellt — ✅Ja/📍Hier/📌Generell", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "Onboarding-Buttons: blaue Nummern statt Text-Labels, 12 auf 6 reduziert, skip_all/later global", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
|
||||
# Deployment
|
||||
{"text": "Deployment-Pipeline mit 3 Guards gehärtet: Syntax-Check, Vollständigkeits-Check, Pycache-Löschung", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "install.sh State-Cleanup vor Gateway-Restart in allen 3 Pfaden — gateway_state.json + reset-failed", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "Deployment-Pfad-Mismatch: Gateway lädt aus ~/.hermes/, nicht /usr/local/lib/. __pycache__ macht Fix unsichtbar.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
|
||||
# Archivar
|
||||
{"text": "Archivar v4: Embedding-Vorfilter (nomic-embed-text) → LLM_ROOM_PROMPT (qwen2.5:7b) → room_id → Move-Request → Route", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "LLM-Raum-Router: Median 2.4s, P95 2.6s, Cold-Start 7.9s. Timeout 10s, Fallback CATCH_ALL.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "Timeout-Fallback braucht Raumliste — ohne Kontext ist der Agent blind, mit Raumliste kann er selbst entscheiden", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "room-map.json v2: 100%-Keywords, ein Treffer = sofortiger Match, kein min_score=2 mehr", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
|
||||
# Gateway
|
||||
{"text": "Gateway-Crash-Recovery: rm gateway_state.json + gateway.lock → reset-failed → restart", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "systemctl stop während aktiver Session = Crash. Drain timeoutet 60s, StartLimitBurst exhausted.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
{"text": "gateway-preflight-briefing: Vor jedem Gateway-Start Briefing-Prompt mit Entwicklungsstand posten", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
|
||||
# Own-Message-Filter
|
||||
{"text": "Own-Message-Filter: StartObsidian und projekt sync via rocketchat_send werden verworfen — direkt ausführen", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
|
||||
# SOUL.md
|
||||
{"text": "SOUL.md: delegate_task vererbt Eltern-Modell an ALLE Subagenten — Team-Agenten NUR via terminal mit Profil", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
|
||||
],
|
||||
},
|
||||
|
||||
# ── #BAT-Team ───────────────────────────────────────────────────────
|
||||
"6a049d493a62ef8f1ead2320": {
|
||||
"stichworte": (
|
||||
"BAT Trading Platform, Docker, Next.js, Prisma, API, Web-UI, "
|
||||
"Krypto-Analyse, Wyckoff-Methodik, Boot-Window, install.sh, "
|
||||
"Container, Pre-Prod, .45, Build-VM, .101, docker-compose, "
|
||||
"pnpm, postgresql, pg_dump, API_KEY, Narrensicher-Test, "
|
||||
"Snapshot, Abweichungen, DATABASE_URL, Gateway, Tor, DB"
|
||||
),
|
||||
"messages": [
|
||||
# Narrensicher-Test
|
||||
{"text": "BAT Narrensicher-Test auf .45: 13 Abweichungen dokumentiert, install.sh --url http://192.168.180.45:3003", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "patch_compose() auf generisches Pattern umgestellt: bat_user:[^@]*@db matched JEDEN Platzhalter", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
|
||||
# Docker
|
||||
{"text": "docker compose down -v ist der Nuklear-Fix für P1000 — Docker cached Compose-Konfigurationen, --force-recreate reicht nicht", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "Docker-DNS fehlt auf frischem Debian: /etc/docker/daemon.json mit dns: [192.168.180.1, 8.8.8.8] nötig", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "Web-Container: prisma generate fehlte → Build scheiterte an Cannot find module .prisma/client/default", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "Gateway: Doppelter Protokoll-Fehler wss://https://... → getaddrinfo ENOTFOUND https", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
|
||||
# API_KEY
|
||||
{"text": "API_KEY wurde nie generiert — install.sh muss ALLE Secrets generieren, nicht nur DB-Passwort", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "Next.js NEXT_PUBLIC_* ist eine Falle: Server-seitige API_KEY-Env-Vars sind für Client unsichtbar", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
|
||||
# pg_dump
|
||||
{"text": "pg_dump: drei Teilprobleme — pg_dump not found, Unix-Socket statt TCP, Version-Mismatch v15↔v16", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "postgresql-client-16 via pgdg-Repo ins Dockerfile — Debian-Repos haben nur v15", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
|
||||
# SSH
|
||||
{"text": "SSH-Key-Mapping: bat_preprod_key für Build-VM→.45, gitea_hermes_key für .45→Gitea:222", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
|
||||
# Features
|
||||
{"text": "4 Features auf .45 deployt: KI-Provider, DB-Backup, Deutsche UI-Übersetzung, Freie Agenten-Konfiguration", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "AUTH_PUBLIC-Entscheidungsmatrix: Key-Test ja (keine Secrets), DB-Info nein (Passwort), Backup NIEMALS", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
|
||||
# Stash
|
||||
{"text": "2-Wochen-alter Stash im BAT-Repo: node:22-bookworm-libssl Dockerfile + Boot-Window-Registrierung", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
{"text": "Stash-Duplikat-Pattern: Vor git stash pop prüfen ob Feature bereits committed ist", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
|
||||
],
|
||||
},
|
||||
|
||||
# ── #LAN-Dokumentation ──────────────────────────────────────────────
|
||||
"6a1c56d4b73efec2bebec2db": {
|
||||
"stichworte": (
|
||||
"LAN Dokumentation, Homelab, Netzwerk, Proxmox, Subnetze, "
|
||||
"IP-Adressen, Router, Switch, Heimnetz, RZBLN, VLAN, "
|
||||
"Firewall, pfSense, Build-VM, .101, .45, .47, Server, "
|
||||
"Infrastruktur, Verkabelung, DHCP, DNS"
|
||||
),
|
||||
"messages": [
|
||||
{"text": "Build-VM .101: 23G/14C i9-13900H/244G, Pre-Prod .45 bat, Gitea/Doku .47", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
|
||||
{"text": "Susi: 62.238.14.195/Hetzner, SSH bernd, DGX-Spark qwen3-next-80b-fp8, vLLM :7999", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
|
||||
{"text": "Gitea-Repos USER Andreas, git@192.168.180.47:222, SSH-Key gitea_hermes_key", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
|
||||
{"text": "Docker-DNS: /etc/docker/daemon.json mit dns: [192.168.180.1, 8.8.8.8] für Container-Netzwerk", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
|
||||
{"text": "Samba-Vault-Zugriff: benutzerbasierte Authentifizierung valid users = bernd, kein nobody:nogroup", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
|
||||
{"text": "Host-Neustart: Gateway überlebt, Docker-Stack 5/5 UP, beide Plattformen connected", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
|
||||
],
|
||||
},
|
||||
|
||||
# ── #Protonbridge-Plugin ────────────────────────────────────────────
|
||||
"69f8beaef06dba03be82f9fc": {
|
||||
"stichworte": (
|
||||
"Proton Mail Bridge, Hermes Mailschnittstelle, Email-Integration, "
|
||||
"IMAP, SMTP, ProtonMail, Himalaya, Mail-Gateway, Bridge, "
|
||||
"PR #39288, Th0rgal, Proton-API, Passwort-Management"
|
||||
),
|
||||
"messages": [
|
||||
{"text": "Proton Mail Bridge: lokaler IMAP/SMTP-Proxy localhost:1143/localhost:1025 — funktioniert heute", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
|
||||
{"text": "PR #39288 (Th0rgal): Native Proton-Integration, 1.200 Zeilen, 5 Dateien, noch nicht gemerged", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
|
||||
{"text": "Gateway + Himalaya-Strategie: Gateway für IMAP-IDLE-Push, Himalaya CLI für SMTP-Antworten", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
|
||||
{"text": "Himalaya: Rust-CLI-Email-Client, TOML-Konfiguration, pipe cat << EOF | himalaya template send", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
|
||||
{"text": "Proton Mail REST-API existiert nicht — Bridge-Weg ist der einzig funktionierende Pfad heute", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
|
||||
],
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
"""
|
||||
Tests für das selbstlernende Keyword-Gewicht-System.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
# Add the parent directory to the path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from archivar_state import ArchivarState, KeywordWeightEntry, ManualOverride
|
||||
|
||||
|
||||
class TestArchivarStateKeywordWeights(unittest.TestCase):
|
||||
"""Tests für das selbstlernende Keyword-Gewicht-System."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
# Create a temporary file for the state
|
||||
self.temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json')
|
||||
self.temp_file.close()
|
||||
self.state_file_path = self.temp_file.name
|
||||
self.state = ArchivarState(self.state_file_path)
|
||||
|
||||
def tearDown(self):
|
||||
"""Clean up test fixtures."""
|
||||
# Remove the temporary file
|
||||
if os.path.exists(self.state_file_path):
|
||||
os.unlink(self.state_file_path)
|
||||
|
||||
def test_keyword_weight_entry_serialization(self):
|
||||
"""Test serialization of KeywordWeightEntry."""
|
||||
# Create a KeywordWeightEntry
|
||||
now = datetime.now().isoformat()
|
||||
entry = KeywordWeightEntry(
|
||||
weight=0.75,
|
||||
last_updated=now,
|
||||
confirmation_count=3,
|
||||
rejection_count=1,
|
||||
last_confirmation=now
|
||||
)
|
||||
|
||||
# Create an ArchivarState and add the entry
|
||||
self.state._keyword_weights = {
|
||||
"test_keyword": {
|
||||
"room1": entry
|
||||
}
|
||||
}
|
||||
|
||||
# Save and reload
|
||||
self.assertTrue(self.state.save())
|
||||
new_state = ArchivarState(self.state_file_path)
|
||||
self.assertTrue(new_state.load())
|
||||
|
||||
# Check that the entry was loaded correctly
|
||||
self.assertIn("test_keyword", new_state._keyword_weights)
|
||||
self.assertIn("room1", new_state._keyword_weights["test_keyword"])
|
||||
loaded_entry = new_state._keyword_weights["test_keyword"]["room1"]
|
||||
self.assertEqual(loaded_entry.weight, 0.75)
|
||||
self.assertEqual(loaded_entry.confirmation_count, 3)
|
||||
self.assertEqual(loaded_entry.rejection_count, 1)
|
||||
self.assertEqual(loaded_entry.last_updated, now)
|
||||
self.assertEqual(loaded_entry.last_confirmation, now)
|
||||
|
||||
def test_manual_override_serialization(self):
|
||||
"""Test serialization of ManualOverride."""
|
||||
# Create a ManualOverride
|
||||
now = datetime.now().isoformat()
|
||||
override = ManualOverride(
|
||||
override_weight=0.9,
|
||||
override_reason="Manual adjustment by admin",
|
||||
override_date=now,
|
||||
override_by="admin_user"
|
||||
)
|
||||
|
||||
# Create an ArchivarState and add the override
|
||||
self.state._manual_overrides = {
|
||||
"test_keyword": {
|
||||
"room1": override
|
||||
}
|
||||
}
|
||||
|
||||
# Save and reload
|
||||
self.assertTrue(self.state.save())
|
||||
new_state = ArchivarState(self.state_file_path)
|
||||
self.assertTrue(new_state.load())
|
||||
|
||||
# Check that the override was loaded correctly
|
||||
self.assertIn("test_keyword", new_state._manual_overrides)
|
||||
self.assertIn("room1", new_state._manual_overrides["test_keyword"])
|
||||
loaded_override = new_state._manual_overrides["test_keyword"]["room1"]
|
||||
self.assertEqual(loaded_override.override_weight, 0.9)
|
||||
self.assertEqual(loaded_override.override_reason, "Manual adjustment by admin")
|
||||
self.assertEqual(loaded_override.override_date, now)
|
||||
self.assertEqual(loaded_override.override_by, "admin_user")
|
||||
|
||||
def test_update_keyword_weight_confirm(self):
|
||||
"""Test updating keyword weight with confirm feedback."""
|
||||
# Initialize with a keyword weight
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.5,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=1,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
),
|
||||
"room2": KeywordWeightEntry(
|
||||
weight=0.3,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=0,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply confirm feedback
|
||||
result = self.state.update_keyword_weight("plugin", "room1", "confirm")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was updated correctly
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
# With learning rate 0.2: new_weight = 0.5 + (1 - 0.5) * 0.2 = 0.6
|
||||
self.assertAlmostEqual(entry.weight, 0.6, places=2)
|
||||
self.assertEqual(entry.confirmation_count, 2)
|
||||
|
||||
# Check that other room weights were reduced
|
||||
other_entry = self.state._keyword_weights["plugin"]["room2"]
|
||||
# With learning rate 0.2: reduced_weight = 0.3 - (0.3 * 0.2 / 1) = 0.24
|
||||
self.assertAlmostEqual(other_entry.weight, 0.24, places=2)
|
||||
|
||||
def test_update_keyword_weight_stay(self):
|
||||
"""Test updating keyword weight with stay feedback."""
|
||||
# Initialize with a keyword weight
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.5,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=1,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
),
|
||||
"room2": KeywordWeightEntry(
|
||||
weight=0.3,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=0,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply stay feedback
|
||||
result = self.state.update_keyword_weight("plugin", "room1", "stay")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was updated correctly
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
# With learning rate 0.2: new_weight = 0.5 - 0.5 * 0.2 * 0.5 = 0.45
|
||||
self.assertAlmostEqual(entry.weight, 0.45, places=2)
|
||||
self.assertEqual(entry.rejection_count, 1)
|
||||
|
||||
# Check that other room weights were increased
|
||||
other_entry = self.state._keyword_weights["plugin"]["room2"]
|
||||
# With learning rate 0.2: increased_weight = 0.3 + ((1 - 0.3) * 0.2 * 0.5 / 1) = 0.37
|
||||
self.assertAlmostEqual(other_entry.weight, 0.37, places=2)
|
||||
|
||||
def test_update_keyword_weight_never(self):
|
||||
"""Test updating keyword weight with never feedback."""
|
||||
# Initialize with a keyword weight
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.5,
|
||||
last_updated=datetime.now().isoformat(),
|
||||
confirmation_count=1,
|
||||
rejection_count=0,
|
||||
last_confirmation=None
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply never feedback
|
||||
result = self.state.update_keyword_weight("plugin", "room1", "never")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was set to 0.0
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
self.assertEqual(entry.weight, 0.0)
|
||||
self.assertEqual(entry.rejection_count, 2) # Counts as 2 negative confirmations
|
||||
|
||||
# Check that the keyword was added to sticky_keywords
|
||||
self.assertIn("plugin", self.state._sticky_keywords)
|
||||
self.assertIn("room1", self.state._sticky_keywords["plugin"])
|
||||
|
||||
def test_calculate_room_score_with_override(self):
|
||||
"""Test calculating room score with manual override."""
|
||||
# Set up a manual override
|
||||
now = datetime.now().isoformat()
|
||||
self.state._manual_overrides = {
|
||||
"plugin": {
|
||||
"room1": ManualOverride(
|
||||
override_weight=0.9,
|
||||
override_reason="Manual adjustment",
|
||||
override_date=now,
|
||||
override_by="admin"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Calculate score - should use override
|
||||
score = self.state.calculate_room_score("plugin", "room1")
|
||||
self.assertEqual(score, 0.9)
|
||||
|
||||
def test_calculate_room_score_with_sticky(self):
|
||||
"""Test calculating room score with sticky keyword."""
|
||||
# Set up a sticky keyword
|
||||
self.state._sticky_keywords = {
|
||||
"plugin": ["room1"]
|
||||
}
|
||||
|
||||
# Calculate score - should be 0.0
|
||||
score = self.state.calculate_room_score("plugin", "room1")
|
||||
self.assertEqual(score, 0.0)
|
||||
|
||||
def test_calculate_room_score_with_learned_weight(self):
|
||||
"""Test calculating room score with learned weight."""
|
||||
# Set up a learned weight
|
||||
now = datetime.now().isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.7,
|
||||
last_updated=now,
|
||||
confirmation_count=2,
|
||||
rejection_count=0,
|
||||
last_confirmation=now
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Calculate score - should use learned weight
|
||||
score = self.state.calculate_room_score("plugin", "room1")
|
||||
self.assertEqual(score, 0.7)
|
||||
|
||||
def test_check_promotion_eligibility(self):
|
||||
"""Test checking promotion eligibility."""
|
||||
# Set up a promotable keyword
|
||||
now = datetime.now().isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.9,
|
||||
last_updated=now,
|
||||
confirmation_count=3,
|
||||
rejection_count=0,
|
||||
last_confirmation=now
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Check promotion eligibility
|
||||
result = self.state.check_promotion_eligibility("plugin", "room1")
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that it was added to promotion candidates
|
||||
self.assertIn("plugin", self.state._promotion_candidates)
|
||||
self.assertIn("room1", self.state._promotion_candidates["plugin"])
|
||||
|
||||
def test_apply_decay(self):
|
||||
"""Test applying time-based decay."""
|
||||
# Set up a keyword weight with old last_updated date (45 days ago)
|
||||
old_date = (datetime.now() - timedelta(days=45)).isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.8,
|
||||
last_updated=old_date,
|
||||
confirmation_count=2,
|
||||
rejection_count=0,
|
||||
last_confirmation=old_date
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply decay
|
||||
result = self.state.apply_decay()
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was reduced (45 days is between 30 and 90 days,
|
||||
# so it should be reduced by 10%)
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
self.assertAlmostEqual(entry.weight, 0.8 * 0.9, places=2) # 0.72
|
||||
|
||||
# Test 90-day decay
|
||||
very_old_date = (datetime.now() - timedelta(days=95)).isoformat()
|
||||
self.state._keyword_weights = {
|
||||
"plugin": {
|
||||
"room1": KeywordWeightEntry(
|
||||
weight=0.8,
|
||||
last_updated=very_old_date,
|
||||
confirmation_count=2,
|
||||
rejection_count=0,
|
||||
last_confirmation=very_old_date
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
# Apply decay
|
||||
result = self.state.apply_decay()
|
||||
self.assertTrue(result)
|
||||
|
||||
# Check that the weight was reduced by 30% (90 days = 30% reduction)
|
||||
entry = self.state._keyword_weights["plugin"]["room1"]
|
||||
self.assertAlmostEqual(entry.weight, 0.8 * 0.7, places=2) # 0.56
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,299 @@
|
||||
"""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 (v2 Schema)
|
||||
self.test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"catchall_room_id": {
|
||||
"name": "#CatchAll",
|
||||
"theme": "Catch-all room for everything else",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"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)
|
||||
|
||||
# Patch ROOM_MAP_PATH und DEFAULT_MAP_PATH auf den temporären Pfad
|
||||
# (muss vor __init__ aktiv sein, weil _load_room_map() den Pfad sofort liest)
|
||||
# ROOM_MAP_PATH → für _load_room_map() in adapter_integration
|
||||
# DEFAULT_MAP_PATH → für reload()/save() ohne Pfad-Argument in room_map
|
||||
self._path_patcher = patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path))
|
||||
self._path_patcher.start()
|
||||
self._default_path_patcher = patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path))
|
||||
self._default_path_patcher.start()
|
||||
|
||||
def tearDown(self):
|
||||
"""Tear down test fixtures after each test method."""
|
||||
self._default_path_patcher.stop()
|
||||
self._path_patcher.stop()
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
def test_single_room_auto_catch_all(self):
|
||||
"""Testet die Single-Room-Regel: 1 relevanter Raum → automatisch catch_all."""
|
||||
# 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)
|
||||
|
||||
def test_multi_room_onboarding_triggered(self):
|
||||
"""Testet dass Onboarding bei mehreren fehlenden Räumen ausgelöst wird."""
|
||||
# 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")
|
||||
|
||||
def test_dm_rooms_ignored(self):
|
||||
"""Testet dass DM-Räume ignoriert werden (außer Operator-DM)."""
|
||||
# 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)
|
||||
|
||||
# Single-Room-Regel: der einzige Channel wird automatisch Catch-All
|
||||
# → keine fehlenden Räume. DMs wurden korrekt ignoriert.
|
||||
self.assertEqual(len(missing), 0)
|
||||
# Verifiziere: der Channel ist jetzt in der Map als Catch-All
|
||||
self.assertIn("channel_id", handler._room_map.rooms)
|
||||
self.assertTrue(handler._room_map.rooms["channel_id"].catch_all)
|
||||
|
||||
def test_map_already_complete_no_action(self):
|
||||
"""Testet dass nichts passiert wenn die Map bereits vollständig ist."""
|
||||
# Erstelle Testdaten mit bereits vorhandenen Räumen
|
||||
test_data_with_rooms = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"catchall_room_id": {
|
||||
"name": "#CatchAll",
|
||||
"theme": "Catch-all room for everything else",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True
|
||||
},
|
||||
"room1_id": {
|
||||
"name": "#Room1",
|
||||
"theme": "First test room",
|
||||
"keywords_100": ["test"],
|
||||
"keywords_context": [],
|
||||
"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)
|
||||
|
||||
|
||||
class TestAutoOnboardingV2(unittest.TestCase):
|
||||
"""v2-spezifische Tests: keywords_100/keywords_context Trennung, File-Lock."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
|
||||
|
||||
self.test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"catchall_room_id": {
|
||||
"name": "#CatchAll",
|
||||
"theme": "Catch-all room",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True
|
||||
}
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(self.temp_path.parent / "docs")
|
||||
}
|
||||
with open(self.temp_path, 'w') as f:
|
||||
json.dump(self.test_data, f)
|
||||
|
||||
def tearDown(self):
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
def test_v2_add_or_update_room_separate_keywords(self):
|
||||
"""Testet dass add_or_update_room keywords_100 und keywords_context trennt."""
|
||||
room_map = RoomMap._from_dict(self.test_data)
|
||||
|
||||
room_map.add_or_update_room(
|
||||
room_id="proj_room_id",
|
||||
name="#Projektraum",
|
||||
theme="Entwicklung des Plugins",
|
||||
keywords_100=["plugin", "gateway"],
|
||||
keywords_context=["architektur", "deployment"],
|
||||
catch_all=False,
|
||||
)
|
||||
|
||||
entry = room_map.rooms["proj_room_id"]
|
||||
self.assertEqual(entry.keywords_100, ["plugin", "gateway"])
|
||||
self.assertEqual(entry.keywords_context, ["architektur", "deployment"])
|
||||
self.assertNotEqual(entry.keywords_100, entry.keywords_context)
|
||||
|
||||
def test_v2_single_room_auto_catch_all_fields(self):
|
||||
"""Testet dass Single-Room-Regel v2-Felder korrekt setzt."""
|
||||
room_map = RoomMap._from_dict(self.test_data)
|
||||
|
||||
# Simuliere: nur 1 relevanter Raum, nicht in Map
|
||||
room_map.add_or_update_room(
|
||||
room_id="single_room_id",
|
||||
name="#SingleRoom",
|
||||
theme="Automatisch zugewiesener Catch-All-Raum",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
)
|
||||
|
||||
entry = room_map.rooms["single_room_id"]
|
||||
self.assertTrue(entry.catch_all)
|
||||
self.assertEqual(entry.keywords_100, [])
|
||||
self.assertEqual(entry.keywords_context, [])
|
||||
# Altes catch_all (catchall_room_id) sollte NICHT mehr catch_all sein
|
||||
self.assertFalse(room_map.rooms["catchall_room_id"].catch_all)
|
||||
|
||||
def test_v2_save_with_file_lock(self):
|
||||
"""Testet dass RoomMap.save() mit File-Lock funktioniert."""
|
||||
room_map = RoomMap._from_dict(self.test_data)
|
||||
room_map.add_or_update_room(
|
||||
room_id="test_room_id",
|
||||
name="#TestRaum",
|
||||
theme="Test-Thema",
|
||||
keywords_100=["test"],
|
||||
keywords_context=["versuch"],
|
||||
catch_all=False,
|
||||
)
|
||||
|
||||
# Save sollte ohne Exception durchlaufen
|
||||
RoomMap.save(room_map, self.temp_path)
|
||||
|
||||
# Reload und verifiziere
|
||||
reloaded = RoomMap.load(self.temp_path)
|
||||
entry = reloaded.rooms["test_room_id"]
|
||||
self.assertEqual(entry.name, "#TestRaum")
|
||||
self.assertEqual(entry.theme, "Test-Thema")
|
||||
self.assertEqual(entry.keywords_100, ["test"])
|
||||
self.assertEqual(entry.keywords_context, ["versuch"])
|
||||
self.assertFalse(entry.catch_all)
|
||||
|
||||
def test_v2_reload_updates_in_memory(self):
|
||||
"""Testet dass reload() die In-Memory-Daten aktualisiert."""
|
||||
room_map = RoomMap._from_dict(self.test_data)
|
||||
|
||||
# Schreibe eine geänderte Map auf Disk
|
||||
modified_data = dict(self.test_data)
|
||||
modified_data["rooms"]["new_room_id"] = {
|
||||
"name": "#NeuerRaum",
|
||||
"theme": "Neues Thema",
|
||||
"keywords_100": ["neu"],
|
||||
"keywords_context": ["frisch"],
|
||||
"catch_all": False,
|
||||
}
|
||||
with open(self.temp_path, 'w') as f:
|
||||
json.dump(modified_data, f)
|
||||
|
||||
# Vor reload: new_room_id nicht in Map
|
||||
self.assertNotIn("new_room_id", room_map.rooms)
|
||||
|
||||
# Reload
|
||||
room_map.reload(self.temp_path)
|
||||
|
||||
# Nach reload: new_room_id in Map
|
||||
self.assertIn("new_room_id", room_map.rooms)
|
||||
entry = room_map.rooms["new_room_id"]
|
||||
self.assertEqual(entry.keywords_100, ["neu"])
|
||||
self.assertEqual(entry.keywords_context, ["frisch"])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,511 @@
|
||||
"""
|
||||
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 []):
|
||||
room_data = {
|
||||
"name": room["name"],
|
||||
"theme": room.get("theme", ""),
|
||||
"catch_all": room.get("catch_all", False),
|
||||
}
|
||||
|
||||
# Handle both old and new room structures
|
||||
if "keywords_100" in room or "keywords_context" in room:
|
||||
# New structure (version 2)
|
||||
room_data["keywords_100"] = room.get("keywords_100", [])
|
||||
room_data["keywords_context"] = room.get("keywords_context", [])
|
||||
else:
|
||||
# Old structure (version 1)
|
||||
room_data["keywords"] = room.get("keywords", [])
|
||||
|
||||
data["rooms"][room["room_id"]] = room_data
|
||||
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"
|
||||
|
||||
|
||||
# ── Two-Stage Keyword Evidence System ──────────────────────────────────────
|
||||
|
||||
|
||||
class TestTwoStageKeywordEvidence:
|
||||
"""Tests for the two-stage keyword evidence system."""
|
||||
|
||||
@pytest.fixture
|
||||
def room_map_v2(self) -> RoomMap:
|
||||
"""Create a RoomMap with version 2 structure (keywords_100 + keywords_context)."""
|
||||
data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"r1": {
|
||||
"name": "#Plugin",
|
||||
"theme": "plugin dev",
|
||||
"keywords_100": ["rocketchat", "rc", "ddp", "websocket"],
|
||||
"keywords_context": ["plugin", "gateway", "deployment", "button", "sync", "hermes"]
|
||||
},
|
||||
"r2": {
|
||||
"name": "#BAT",
|
||||
"theme": "trading",
|
||||
"keywords_100": ["bat", "bat-team", "trading", "krypto"],
|
||||
"keywords_context": ["gateway"]
|
||||
},
|
||||
"r3": {
|
||||
"name": "DM Admin",
|
||||
"theme": "admin",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True
|
||||
}
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": "/tmp/test_docs"
|
||||
}
|
||||
json_str = json.dumps(data)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
return RoomMap.load(path)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_100_percent_keywords_immediate_match(self, room_map_v2):
|
||||
"""100% keywords should match immediately, even with low context score."""
|
||||
# "rocketchat" is a 100% keyword for #Plugin room
|
||||
result = room_map_v2.find_room_by_keywords("rocketchat plugin bug")
|
||||
assert result is not None
|
||||
assert result.name == "#Plugin"
|
||||
|
||||
def test_context_keywords_min_score(self, room_map_v2):
|
||||
"""Context keywords should require min_score=2."""
|
||||
# Only one context keyword match should not be enough
|
||||
result = room_map_v2.find_room_by_keywords("plugin")
|
||||
assert result is None
|
||||
|
||||
# Two context keyword matches should be enough
|
||||
result = room_map_v2.find_room_by_keywords("plugin gateway")
|
||||
assert result is not None
|
||||
assert result.name == "#Plugin"
|
||||
|
||||
def test_origin_priority_with_context_keywords(self, room_map_v2):
|
||||
"""Origin room should get priority with context keywords."""
|
||||
# Message from BAT room with context keywords for BAT
|
||||
# Use "gateway issue" which matches both rooms, but origin priority should win
|
||||
# We need at least min_score=2, so add another keyword
|
||||
result = room_map_v2.find_room_by_keywords("gateway bat", origin_room_id="r2")
|
||||
assert result is not None
|
||||
assert result.room_id == "r2" # Should go to origin room (bat is 100% keyword for BAT)
|
||||
|
||||
# Test with multiple context keywords
|
||||
result = room_map_v2.find_room_by_keywords("gateway trading", origin_room_id="r2")
|
||||
assert result is not None
|
||||
assert result.room_id == "r2" # Should go to origin room (gateway + trading = 2 context keywords)
|
||||
|
||||
def test_global_fallback_with_context_keywords(self, room_map_v2):
|
||||
"""Global fallback should work with context keywords."""
|
||||
# Context keywords for Plugin room
|
||||
result = room_map_v2.find_room_by_keywords("plugin deployment")
|
||||
assert result is not None
|
||||
assert result.name == "#Plugin"
|
||||
|
||||
def test_100_percent_overrides_origin_priority(self, room_map_v2):
|
||||
"""100% keywords should override origin priority."""
|
||||
# Message from BAT room but with 100% keyword for Plugin
|
||||
result = room_map_v2.find_room_by_keywords("rocketchat bug", origin_room_id="r2")
|
||||
assert result is not None
|
||||
assert result.name == "#Plugin" # Should go to Plugin room, not origin
|
||||
|
||||
def test_backward_compatibility_with_v1_structure(self):
|
||||
"""Old room-map.json (version 1) should still work."""
|
||||
# Simulate old structure with only "keywords" field
|
||||
data = {
|
||||
"version": 1,
|
||||
"rooms": {
|
||||
"r1": {
|
||||
"name": "#Plugin",
|
||||
"theme": "plugin dev",
|
||||
"keywords": ["plugin", "gateway", "deployment"]
|
||||
},
|
||||
"r2": {
|
||||
"name": "DM Admin",
|
||||
"theme": "admin",
|
||||
"keywords": [],
|
||||
"catch_all": True
|
||||
}
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": "/tmp/test_docs"
|
||||
}
|
||||
json_str = json.dumps(data)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
room_map = RoomMap.load(path)
|
||||
# Should work like before, treating all keywords as context keywords
|
||||
result = room_map.find_room_by_keywords("plugin gateway")
|
||||
assert result is not None
|
||||
assert result.name == "#Plugin"
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
# ── 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_100=["plugin", "gateway"],
|
||||
keywords_context=["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_100=[], keywords_context=[], 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_100=["Plugin"], keywords_context=["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,139 @@
|
||||
"""
|
||||
Tests für das gewichtete Scoring im RoomMap-Modul.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add the parent directory to the path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from room_map import RoomMap, RoomEntry
|
||||
|
||||
|
||||
class TestRoomMapWeightedScoring(unittest.TestCase):
|
||||
"""Tests für das gewichtete Scoring im RoomMap-Modul."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
# Create test rooms
|
||||
self.rooms = {
|
||||
"room1": RoomEntry(
|
||||
room_id="room1",
|
||||
name="#Plugin-Development",
|
||||
theme="Plugin development and bug fixes",
|
||||
keywords_100=["bug", "fix", "issue"],
|
||||
keywords_context=["plugin", "feature", "development"]
|
||||
),
|
||||
"room2": RoomEntry(
|
||||
room_id="room2",
|
||||
name="#Documentation",
|
||||
theme="Documentation and user guides",
|
||||
keywords_100=["doc", "document", "guide"],
|
||||
keywords_context=["documentation", "manual", "tutorial"]
|
||||
),
|
||||
"room3": RoomEntry(
|
||||
room_id="room3",
|
||||
name="#General",
|
||||
theme="General discussion",
|
||||
keywords_100=[],
|
||||
keywords_context=["general", "discussion", "chat"],
|
||||
catch_all=True
|
||||
)
|
||||
}
|
||||
|
||||
# Create a RoomMap instance
|
||||
self.room_map = RoomMap(
|
||||
rooms=self.rooms,
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_docs"),
|
||||
version=2
|
||||
)
|
||||
|
||||
def test_calculate_weighted_score(self):
|
||||
"""Test calculating weighted scores."""
|
||||
# Get a room entry
|
||||
room = self.rooms["room1"]
|
||||
|
||||
# Test with text that matches some keywords
|
||||
text = "I need help with plugin development"
|
||||
score = self.room_map.calculate_weighted_score(text, room)
|
||||
|
||||
# Should match "plugin" and "development" -> 2 out of 3 keywords = 0.6667
|
||||
self.assertAlmostEqual(score, 2/3, places=2)
|
||||
|
||||
def test_find_room_by_keywords_with_100_percent_match(self):
|
||||
"""Test finding room with 100% keyword match."""
|
||||
# Text with a 100% match keyword
|
||||
text = "There is a bug in the plugin"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text)
|
||||
|
||||
# Should find room1 because it has "bug" in keywords_100
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
def test_find_room_by_keywords_with_context_match(self):
|
||||
"""Test finding room with context keyword match."""
|
||||
# Text with context keyword match
|
||||
text = "I'm working on plugin development"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text)
|
||||
|
||||
# Should find room1 because it has "plugin" and "development" in keywords_context
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
def test_find_room_by_keywords_with_origin_priority(self):
|
||||
"""Test finding room with origin room priority."""
|
||||
# Text with context keyword match
|
||||
text = "I'm working on plugin development"
|
||||
|
||||
# When origin_room_id is set to room2, it should still find room1
|
||||
# because 100% keywords take precedence
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text, origin_room_id="room2")
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
# Text without 100% match but with context match
|
||||
text2 = "plugin development discussion"
|
||||
room = self.room_map.find_room_by_keywords(text2, origin_room_id="room2")
|
||||
|
||||
# Should find room1 because it has better context match
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
def test_find_room_by_keywords_no_match(self):
|
||||
"""Test finding room with no keyword matches."""
|
||||
# Text with no matching keywords
|
||||
text = "completely unrelated topic"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text)
|
||||
|
||||
# Should not find any room
|
||||
self.assertIsNone(room)
|
||||
|
||||
def test_find_room_by_keywords_min_score(self):
|
||||
"""Test finding room with minimum score requirement."""
|
||||
# Text with only one context keyword match
|
||||
text = "plugin unrelated stuff"
|
||||
room: Optional[RoomEntry] = self.room_map.find_room_by_keywords(text, min_score=2)
|
||||
|
||||
# Should not find any room because score is only 1 (below min_score of 2)
|
||||
self.assertIsNone(room)
|
||||
|
||||
# Same text with lower min_score
|
||||
room = self.room_map.find_room_by_keywords(text, min_score=1)
|
||||
|
||||
# Should find room1 because score is 1 (meets min_score of 1)
|
||||
self.assertIsNotNone(room)
|
||||
if room is not None:
|
||||
self.assertEqual(room.room_id, "room1")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
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 BidirectionalRouter
|
||||
from plugin.archivar.room_map import RoomMap
|
||||
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
||||
from plugin.archivar.archivar_state import ArchivarState
|
||||
|
||||
|
||||
# ── 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) -> BidirectionalRouter:
|
||||
# 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 = IntentClassifier(embedding_client=mock_client)
|
||||
state = ArchivarState()
|
||||
router = BidirectionalRouter(room_map, classifier, state)
|
||||
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
|
||||
label: Rocket.Chat
|
||||
kind: platform
|
||||
version: 1.0.0
|
||||
description: >
|
||||
Rocket.Chat gateway adapter for Hermes Agent.
|
||||
Connects to a self-hosted Rocket.Chat server via WebSocket/DDP for
|
||||
real-time message streaming and presence, and REST API for sending replies.
|
||||
Supports channels, private groups, and direct messages.
|
||||
author: Hermes Community
|
||||
requires_env:
|
||||
- ROCKETCHAT_BASE_URL
|
||||
- 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
|
||||
Connects via DDP (WebSocket) to a self-hosted Rocket.Chat server,
|
||||
monitors subscribed rooms, and routes messages through the Hermes
|
||||
agent. Includes the Archivar classification subsystem for automatic
|
||||
message routing (FAKT → doc_store, FRAGE → project room, ALARM → DM)
|
||||
plus Button-interaction support and file upload/download.
|
||||
author: Entwicklerteam
|
||||
|
||||
@@ -958,6 +958,84 @@ ROCKETCHAT_FILES_SCHEMA = {
|
||||
}
|
||||
|
||||
|
||||
# ── Proaktiver Raum-Broadcast (B6) ──────────────────────────────────────
|
||||
# Cooldown-Tracking: verhindert Spam bei vielen kleinen Aktionen.
|
||||
# Nur "Fertig"-Markierungen triggern einen Broadcast.
|
||||
_broadcast_cooldowns: Dict[str, float] = {} # room_id → timestamp
|
||||
_BROADCAST_COOLDOWN_SECONDS: float = 300.0 # 5 Minuten
|
||||
|
||||
|
||||
def _handle_rocketchat_broadcast(args: dict, **kw) -> str:
|
||||
"""Sende einen proaktiven Status-Broadcast in einen Projektraum.
|
||||
|
||||
Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.'
|
||||
|
||||
Cooldown: 5 Minuten pro Raum — verhindert Spam bei vielen kleinen Aktionen.
|
||||
Nur bei expliziten "Fertig"-Markierungen verwenden, nicht bei jeder kleinen Aktion.
|
||||
|
||||
Args:
|
||||
room_id: Zielraum-ID (aus room-map.json oder ROCKETCHAT.MAP.md)
|
||||
text: Der Broadcast-Text (menschenähnlich, kein Bot-Ton)
|
||||
"""
|
||||
global _broadcast_cooldowns
|
||||
client = _rc_client()
|
||||
if not client:
|
||||
return _rc_error()
|
||||
|
||||
room_id = str(args.get("room_id") or "").strip()
|
||||
text = str(args.get("text") or "").strip()
|
||||
|
||||
if not room_id:
|
||||
return tool_error("room_id is required for rocketchat_broadcast")
|
||||
if not text:
|
||||
return tool_error("text is required for rocketchat_broadcast")
|
||||
|
||||
# Cooldown-Check
|
||||
now = time.time()
|
||||
last = _broadcast_cooldowns.get(room_id, 0.0)
|
||||
if now - last < _BROADCAST_COOLDOWN_SECONDS:
|
||||
remaining = int(_BROADCAST_COOLDOWN_SECONDS - (now - last))
|
||||
return tool_result({
|
||||
"success": False,
|
||||
"cooldown": True,
|
||||
"message": f"Broadcast-Cooldown aktiv: noch {remaining}s für Raum {room_id[:8]}...",
|
||||
})
|
||||
|
||||
try:
|
||||
result = client.send_message(room_id, text)
|
||||
if result.get("success"):
|
||||
_broadcast_cooldowns[room_id] = now
|
||||
return tool_result({
|
||||
"success": True,
|
||||
"room_id": room_id,
|
||||
"text": text[:200],
|
||||
})
|
||||
else:
|
||||
return tool_error(f"Broadcast failed: {result.get('error', 'unknown error')}")
|
||||
except Exception as exc:
|
||||
return tool_error(f"rocketchat_broadcast failed: {type(exc).__name__}: {exc}")
|
||||
|
||||
|
||||
ROCKETCHAT_BROADCAST_SCHEMA = {
|
||||
"name": "rocketchat_broadcast",
|
||||
"description": (
|
||||
"Send a proactive status broadcast to a project room. "
|
||||
"Use this after completing a task to inform the team. "
|
||||
"Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.' "
|
||||
"Cooldown: 5 minutes per room to prevent spam. "
|
||||
"Only use for explicit 'done' markers, not for every small action."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"room_id": {"type": "string", "description": "Target project room ID (from room-map.json)"},
|
||||
"text": {"type": "string", "description": "Broadcast message (human-like, not bot-like)"},
|
||||
},
|
||||
"required": ["room_id", "text"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Registration helpers for the plugin register() function
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -970,6 +1048,7 @@ _TOOLS = (
|
||||
("rocketchat_upload", ROCKETCHAT_UPLOAD_SCHEMA, _handle_rocketchat_upload, "📎"),
|
||||
("rocketchat_download", ROCKETCHAT_DOWNLOAD_SCHEMA, _handle_rocketchat_download, "📥"),
|
||||
("rocketchat_files", ROCKETCHAT_FILES_SCHEMA, _handle_rocketchat_files, "📁"),
|
||||
("rocketchat_broadcast", ROCKETCHAT_BROADCAST_SCHEMA, _handle_rocketchat_broadcast, "📢"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
{
|
||||
"version": 3,
|
||||
"rooms": {
|
||||
"6a049d493a62ef8f1ead2320": {
|
||||
"name": "#BAT-Team",
|
||||
"theme": "Bot Agent Team, Trade, BAT, Projektarbeit an Bot Agent Team — Trading-Plattform, Multi-Agent-System, Krypto-Analysen, Wyckoff-Methodik, Boot-Window",
|
||||
"description": "Das BAT-Team (Bot Agent Team) konzentriert sich auf die Entwicklung und Wartung der Trading-Plattform. Hier werden komplexe Krypto-Analysen nach der Wyckoff-Methodik durchgeführt, um Handelsentscheidungen zu treffen. Die technische Infrastruktur basiert auf Docker-Containern mit einer Next.js-basierten Web-UI und einer Prisma-Datenbankschicht. Typische Arbeitsaufträge umfassen die Implementierung neuer Handelsstrategien, die Optimierung bestehender Algorithmen, das Debugging von Container-Problemen und die Integration neuer API-Endpunkte. Besondere Herausforderungen entstehen durch die Notwendigkeit, sowohl die Performance als auch die Sicherheit der Trading-Operationen zu gewährleisten. Der Raum behandelt auch die Konfiguration und Wartung der Entwicklungsumgebung, einschließlich der Docker-Compose-Setups, Datenbankmigrationen und der Verwaltung von API-Schlüsseln. Probleme mit pg_dump, SSH-Key-Mappings und der korrekten Konfiguration von Umgebungsvariablen sind häufige Themen. Die Diskussionen umfassen auch die Integration von KI-Providern und die deutsche Lokalisierung der Benutzeroberfläche.",
|
||||
"keywords_100": [
|
||||
"bat",
|
||||
"bat-team",
|
||||
"trading",
|
||||
"krypto",
|
||||
"wyckoff",
|
||||
"boot-window",
|
||||
"börse",
|
||||
"exchange",
|
||||
"analyst",
|
||||
"control-tower",
|
||||
"docker-image",
|
||||
"container-build",
|
||||
"trading-gateway"
|
||||
],
|
||||
"keywords_context": [
|
||||
"bot"
|
||||
],
|
||||
"catch_all": false
|
||||
},
|
||||
"6a19b0ff02aeecd36b1aa16c": {
|
||||
"name": "#Rocketchat-Plugin",
|
||||
"theme": "Rocketchat, Hermes Gateway, RC, Projektarbeit an Rocketchat Plugin — Hermes Plugin für Rocket.Chat, DDP/WebSocket, Archivar, Deployment",
|
||||
"description": "Der #Rocketchat-Plugin-Raum ist der zentrale Entwicklungsort für das Hermes Rocket.Chat-Plugin. Hier werden alle Aspekte der DDP/WebSocket-Adapter-Implementierung, des Archivars und des Gateway-Routings behandelt. Typische Arbeitsaufträge umfassen die Implementierung neuer Button-Interaktionen, das Debugging von False-Positives bei BUTTON_CLICK-Erkennung, die Optimierung der Deployment-Pipeline und die Verbesserung der Message-Handling-Mechanismen. Die technische Arbeit konzentriert sich auf die Integration mit dem Rocket.Chat-API, die Implementierung von Action-Buttons (✅Ja/📍Hier/📌Generell) und die Gewährleistung einer stabilen Gateway-Kommunikation. Besondere Aufmerksamkeit gilt der Fehlerbehebung bei Gateway-Crash-Recovery, der Optimierung von LLM-Raum-Routing-Zeiten und der Implementierung von Sicherheitsmechanismen. Die Diskussionen umfassen auch die Weiterentwicklung des Archivar v5 mit seinem FAISS-basierten Raum-Index und die Integration von Keyword-Booster-Mechanismen. Typische Fragestellungen betreffen die korrekte Konfiguration von install.sh-Skripten, die Behebung von Pycache-Problemen und die Implementierung von Preflight-Briefings.",
|
||||
"keywords_100": [
|
||||
"rocketchat",
|
||||
"rc",
|
||||
"websocket",
|
||||
"adapter",
|
||||
"install.sh",
|
||||
"gateway-crash",
|
||||
"core-dump",
|
||||
"message-handler",
|
||||
"hermes-gateway"
|
||||
],
|
||||
"keywords_context": [
|
||||
"plugin",
|
||||
"deployment",
|
||||
"button",
|
||||
"sync",
|
||||
"archivar",
|
||||
"hermes"
|
||||
],
|
||||
"catch_all": false
|
||||
},
|
||||
"6a1c56d4b73efec2bebec2db": {
|
||||
"name": "#LAN-Dokumentation",
|
||||
"theme": "LAN Dokumentation, Homelab, RZBLN, Doku — Dokumentation des Heimnetzwerks, Proxmox, Subnetze, IP-Adressen",
|
||||
"description": "Der #LAN-Dokumentation-Raum dient der Dokumentation und Wartung der gesamten Homelab-Infrastruktur. Hier werden alle Aspekte des Heimnetzwerks behandelt, einschließlich Proxmox-Server-Konfiguration, Subnetz-Management, IP-Adressvergabe und Router/Switch-Einstellungen. Typische Arbeitsaufträge umfassen die Dokumentation neuer Netzwerkgeräte, die Aktualisierung von Verkabelungsplänen, die Konfiguration von DHCP- und DNS-Einstellungen sowie die Fehlerbehebung bei Netzwerkproblemen. Besondere Herausforderungen entstehen durch die Komplexität der VLAN-Konfiguration, die Integration von pfSense-Firewall-Regeln und die Gewährleistung einer stabilen Docker-Netzwerkkommunikation. Der Raum behandelt auch die Dokumentation der Build-VM (.101) mit ihren 23GB/14C i9-13900H/244G Spezifikationen und deren Rolle im Pre-Production-Umfeld. Typische Fragestellungen betreffen die korrekte Konfiguration von Docker-DNS-Einstellungen, die Verwaltung von Samba-Vault-Zugriffen und die Dokumentation von Host-Neustart-Prozeduren. Die Diskussionen umfassen auch die Integration mit Hetzner-Services und die Dokumentation von SSH-Key-Mappings für verschiedene Systeme.",
|
||||
"keywords_100": [
|
||||
"lan",
|
||||
"dokumentation",
|
||||
"homelab",
|
||||
"netzwerk",
|
||||
"router",
|
||||
"switch",
|
||||
"subnetz",
|
||||
"proxmox",
|
||||
"heimnetz",
|
||||
"ip-adresse",
|
||||
"rzbln",
|
||||
"firewall",
|
||||
"ddp-client",
|
||||
"monitoring",
|
||||
"iptables",
|
||||
"dhcp",
|
||||
"dns"
|
||||
],
|
||||
"keywords_context": [
|
||||
"reverse-proxy",
|
||||
"traefik",
|
||||
"n8n"
|
||||
],
|
||||
"catch_all": false
|
||||
},
|
||||
"69f8beaef06dba03be82f9fc": {
|
||||
"name": "#Protonbridge-Plugin",
|
||||
"theme": "Proton Mail Bridge, Hermes Mailschnittstelle, PB, Projektarbeit an Proton Mail Bridge Plugin — Hermes Plugin für Proton Mail Bridge, SMTP/IMAP",
|
||||
"description": "Der #Protonbridge-Plugin-Raum behandelt die Entwicklung und Integration der Proton Mail Bridge in das Hermes-System. Hier werden alle Aspekte der IMAP/SMTP-Proxy-Implementierung, der Email-Integration und der Gateway-Kommunikation mit dem Proton-API behandelt. Typische Arbeitsaufträge umfassen die Implementierung neuer Email-Handling-Mechanismen, das Debugging von Bridge-Verbindungsproblemen, die Optimierung der Himalaya-CLI-Integration und die Verbesserung der Passwort-Management-Funktionen. Die technische Arbeit konzentriert sich auf die Implementierung eines lokalen IMAP/SMTP-Proxys (localhost:1143/localhost:1025) und die Integration mit dem Hermes Gateway für IMAP-IDLE-Push-Benachrichtigungen. Besondere Herausforderungen entstehen durch die Komplexität des Proton Mail REST-API-Zugriffs (der nicht existiert) und die Notwendigkeit, den Bridge-Weg als einzigen funktionierenden Ansatz zu verwenden. Der Raum behandelt auch die Weiterentwicklung des PR #39288 mit seinen 1.200 Zeilen Code in 5 Dateien. Typische Fragestellungen betreffen die korrekte Konfiguration von TOML-Konfigurationsdateien, die Implementierung von pipe-basierten Email-Versandmechanismen und die Fehlerbehebung bei Bridge-Verbindungsproblemen.",
|
||||
"keywords_100": [
|
||||
"protonbridge",
|
||||
"proton",
|
||||
"mail",
|
||||
"bridge",
|
||||
"email",
|
||||
"smtp",
|
||||
"imap",
|
||||
"pb",
|
||||
"mail-server",
|
||||
"imap-idle",
|
||||
"smtp-proxy"
|
||||
],
|
||||
"keywords_context": [
|
||||
"plugin"
|
||||
],
|
||||
"catch_all": false
|
||||
},
|
||||
"69f4e777f06dba03be82dce7": {
|
||||
"name": "DM mit Andreas",
|
||||
"theme": "Direktnachrichten — Strategie, Meta-Entscheidungen, Catch-All für alle Themen ohne eigenen Raum",
|
||||
"description": "Direktnachrichten mit Andreas für strategische und meta Entscheidungen. Dies ist der Catch-All-Raum für alle Themen, die keinen eigenen Raum haben.",
|
||||
"keywords_100": [
|
||||
"strategie",
|
||||
"entscheidung",
|
||||
"planung",
|
||||
"budget",
|
||||
"infrastruktur-strategie"
|
||||
],
|
||||
"keywords_context": [
|
||||
"meta",
|
||||
"roadmap",
|
||||
"priorisierung",
|
||||
"manifest"
|
||||
],
|
||||
"catch_all": true
|
||||
}
|
||||
},
|
||||
"excluded_rooms": [
|
||||
"6a0f4b2991db1dbf570a5442",
|
||||
"6a21495ede3de7118e84d82e"
|
||||
],
|
||||
"fact_store_path": "/data/Wissensdatenbank/0100 Inbox"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Rebuild Archivar v5 FAISS index from current room-map.json."""
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, "plugin")
|
||||
|
||||
from archivar.room_map import RoomMap
|
||||
from archivar.classifier import OllamaEmbeddingClient
|
||||
from archivar.room_index import RoomIndexManager
|
||||
|
||||
|
||||
def main() -> int:
|
||||
room_map = RoomMap.load()
|
||||
print(
|
||||
f"RoomMap geladen: {len(room_map.rooms)} rooms, Version {room_map.version}"
|
||||
)
|
||||
|
||||
emb = OllamaEmbeddingClient()
|
||||
idx = RoomIndexManager(room_map, emb)
|
||||
idx.build_index()
|
||||
print(f"Index gebaut: {idx.size} rooms, Version {idx._version}")
|
||||
|
||||
idx.save()
|
||||
print(f"Gespeichert: {idx.index_path} + {idx.meta_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,73 @@
|
||||
"""FAISS + Booster Smoke-Test: kombinierte Similarity + Keyword-Diskriminierung."""
|
||||
import sys
|
||||
sys.path.insert(0, "plugin")
|
||||
|
||||
from archivar.room_map import RoomMap
|
||||
from archivar.classifier import OllamaEmbeddingClient
|
||||
from archivar.room_index import RoomIndexManager
|
||||
from archivar.booster import KeywordBooster
|
||||
|
||||
|
||||
def main() -> int:
|
||||
room_map = RoomMap.load()
|
||||
emb = OllamaEmbeddingClient()
|
||||
idx = RoomIndexManager(room_map, emb)
|
||||
if not idx.load():
|
||||
print("FEHLER: Index nicht geladen")
|
||||
return 1
|
||||
|
||||
booster = KeywordBooster(room_map)
|
||||
|
||||
tests = [
|
||||
("Der Docker-Container startet nicht nach docker compose up", "BAT-Team"),
|
||||
("Die install.sh muss alle Secrets generieren", "Rocketchat-Plugin"),
|
||||
("Das Subnetz braucht eine Dokumentation", "LAN-Dokumentation"),
|
||||
("IMAP-IDLE funktioniert nicht mit der Proton Bridge", "Protonbridge-Plugin"),
|
||||
("Der Archivar routet falsch bei BUTTON_CLICK", "Rocketchat-Plugin"),
|
||||
("pg_dump scheitert an Version-Mismatch v15 vs v16", "BAT-Team"),
|
||||
("Proxmox Server hat hohe IO-Wait Zeiten", "LAN-Dokumentation"),
|
||||
("Himalaya CLI kann keine Emails via SMTP senden", "Protonbridge-Plugin"),
|
||||
]
|
||||
|
||||
print(f"FAISS+Booster Smoke-Test: {idx.size} Raeume, Version {idx._version}")
|
||||
print(f"Booster: {len(booster._keyword_to_rooms)} Keywords, immer aktiv, +0.10/unique")
|
||||
print()
|
||||
|
||||
ok = 0
|
||||
for text, expected in tests:
|
||||
# FAISS-Suche
|
||||
faiss_hits = idx.search_text(text, k=3, min_score=0.3)
|
||||
if not faiss_hits:
|
||||
print(f"❌ NO FAISS HIT | {text[:60]}")
|
||||
continue
|
||||
|
||||
# Booster anwenden (IMMER, wie im neuen router.py)
|
||||
boosted = booster.boost(text, faiss_hits)
|
||||
top_id, top_score = boosted[0]
|
||||
top_room = room_map.get_room_by_id(top_id)
|
||||
top_name = top_room.name if top_room else "?"
|
||||
|
||||
# Vergleich: FAISS-only vs FAISS+Booster
|
||||
faiss_top_id, faiss_top_score = faiss_hits[0]
|
||||
faiss_top_room = room_map.get_room_by_id(faiss_top_id)
|
||||
faiss_top_name = faiss_top_room.name if faiss_top_room else "?"
|
||||
|
||||
match = "✅" if expected in top_name else "❌"
|
||||
changed = "🔄" if faiss_top_name != top_name else " "
|
||||
others = ", ".join(
|
||||
f"{room_map.get_room_by_id(r).name}({s:.2f})"
|
||||
for r, s in boosted[1:]
|
||||
)
|
||||
|
||||
print(f"{match} {changed} {top_score:.3f} → {top_name:25s} | {text[:55]}")
|
||||
if match == "✅":
|
||||
ok += 1
|
||||
else:
|
||||
print(f" FAISS-only: {faiss_top_name}({faiss_top_score:.3f}), others: {others}")
|
||||
|
||||
print(f"\n{ok}/{len(tests)} korrekt (mit Booster)")
|
||||
return 0 if ok >= 6 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,57 @@
|
||||
"""FAISS Smoke-Test: granulare Similarity mit 200-Wort-Beschreibungen."""
|
||||
import sys
|
||||
sys.path.insert(0, "plugin")
|
||||
|
||||
from archivar.room_map import RoomMap
|
||||
from archivar.classifier import OllamaEmbeddingClient
|
||||
from archivar.room_index import RoomIndexManager
|
||||
|
||||
|
||||
def main() -> int:
|
||||
room_map = RoomMap.load()
|
||||
emb = OllamaEmbeddingClient()
|
||||
idx = RoomIndexManager(room_map, emb)
|
||||
if not idx.load():
|
||||
print("FEHLER: Index nicht geladen")
|
||||
return 1
|
||||
|
||||
tests = [
|
||||
("Der Docker-Container startet nicht nach docker compose up", "BAT-Team"),
|
||||
("Die install.sh muss alle Secrets generieren", "Rocketchat-Plugin"),
|
||||
("Das Subnetz braucht eine Dokumentation", "LAN-Dokumentation"),
|
||||
("IMAP-IDLE funktioniert nicht mit der Proton Bridge", "Protonbridge-Plugin"),
|
||||
("Der Archivar routet falsch bei BUTTON_CLICK", "Rocketchat-Plugin"),
|
||||
("pg_dump scheitert an Version-Mismatch v15 vs v16", "BAT-Team"),
|
||||
("Proxmox Server hat hohe IO-Wait Zeiten", "LAN-Dokumentation"),
|
||||
("Himalaya CLI kann keine Emails via SMTP senden", "Protonbridge-Plugin"),
|
||||
]
|
||||
|
||||
print(f"FAISS Smoke-Test: {idx.size} Räume, Version {idx._version}")
|
||||
print()
|
||||
|
||||
ok = 0
|
||||
for text, expected in tests:
|
||||
hits = idx.search_text(text, k=3, min_score=0.3)
|
||||
if hits:
|
||||
top_id, top_score = hits[0]
|
||||
top_room = room_map.get_room_by_id(top_id)
|
||||
top_name = top_room.name if top_room else "?"
|
||||
match = "✅" if expected in top_name else "❌"
|
||||
others = ", ".join(
|
||||
f"{room_map.get_room_by_id(r).name}({s:.2f})"
|
||||
for r, s in hits[1:]
|
||||
)
|
||||
print(f"{match} {top_score:.3f} → {top_name:25s} | {text[:60]}")
|
||||
if match == "✅":
|
||||
ok += 1
|
||||
else:
|
||||
print(f" expected: {expected}, others: {others}")
|
||||
else:
|
||||
print(f"❌ NO HIT (score < 0.3) | {text[:60]}")
|
||||
|
||||
print(f"\n{ok}/{len(tests)} korrekt")
|
||||
return 0 if ok >= len(tests) * 0.75 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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: PLACEHOLDER_MODEL
|
||||
provider: PLACEHOLDER_PROVIDER
|
||||
base_url: PLACEHOLDER_MODEL_BASE_URL
|
||||
|
||||
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
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"version": 1,
|
||||
"rooms": {},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": "PLACEHOLDER_VAULT_PATH"
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
"""
|
||||
F4-Tests für KeywordBooster — Boost und Konfliktlösung.
|
||||
|
||||
Zwei kritische Pfade (Rainer):
|
||||
F4.3 Boost: Eindeutiges Keyword → +0.05, mehrdeutiges → neutral
|
||||
F4.4 Konfliktlösung: Top-2 Diff < 0.03 → Raum mit mehr unique keywords gewinnt
|
||||
|
||||
Mock-FAISS-Index und Mock-EmbeddingClient sind NICHT nötig —
|
||||
KeywordBooster arbeitet rein auf RoomMap + Scores, ohne Embeddings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
# Ensure the archivar package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from plugin.archivar.booster import KeywordBooster
|
||||
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Helpers
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_booster_room_map() -> RoomMap:
|
||||
"""Erzeugt eine RoomMap mit kontrollierten Keyword-Überlappungen.
|
||||
|
||||
Raum-Struktur:
|
||||
room_a (#Plugin):
|
||||
keywords_100: ["rocketchat", "ddp"]
|
||||
keywords_context: ["plugin", "gateway", "deployment", "button"]
|
||||
→ "rocketchat", "ddp", "plugin", "deployment", "button" sind UNIQUE
|
||||
→ "gateway" ist SHARED mit room_b
|
||||
|
||||
room_b (#BAT):
|
||||
keywords_100: ["bat", "trading"]
|
||||
keywords_context: ["gateway", "docker", "prisma", "api"]
|
||||
→ "bat", "trading", "docker", "prisma", "api" sind UNIQUE
|
||||
→ "gateway" ist SHARED mit room_a
|
||||
|
||||
room_catchall (DM Admin):
|
||||
keywords_100: []
|
||||
keywords_context: []
|
||||
catch_all: True
|
||||
→ nimmt NICHT an Keyword-Boosts teil
|
||||
"""
|
||||
rooms: dict[str, RoomEntry] = {
|
||||
"room_a": RoomEntry(
|
||||
room_id="room_a",
|
||||
name="#Plugin",
|
||||
theme="Plugin-Entwicklung",
|
||||
keywords_100=["rocketchat", "ddp"],
|
||||
keywords_context=["plugin", "gateway", "deployment", "button"],
|
||||
catch_all=False,
|
||||
),
|
||||
"room_b": RoomEntry(
|
||||
room_id="room_b",
|
||||
name="#BAT",
|
||||
theme="Trading Platform",
|
||||
keywords_100=["bat", "trading"],
|
||||
keywords_context=["gateway", "docker", "prisma", "api"],
|
||||
catch_all=False,
|
||||
),
|
||||
"room_catchall": RoomEntry(
|
||||
room_id="room_catchall",
|
||||
name="DM Admin",
|
||||
theme="Catch-All",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
),
|
||||
}
|
||||
return RoomMap(
|
||||
rooms=rooms,
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_docs"),
|
||||
version=2,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# F4.3 — Boost: Eindeutiges Keyword → +0.05, mehrdeutiges → neutral
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestBoostUniqueKeyword:
|
||||
"""F4.3a: Eindeutiges Keyword (nur in einem Raum) → +0.05 Boost."""
|
||||
|
||||
@pytest.fixture
|
||||
def booster(self) -> KeywordBooster:
|
||||
return KeywordBooster(_make_booster_room_map())
|
||||
|
||||
def test_unique_keyword_plugin_boosts_room_a(self, booster: KeywordBooster) -> None:
|
||||
"""'plugin' ist nur in room_a → room_a bekommt +0.05."""
|
||||
# Arrange
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
text = "Das Plugin hat einen Bug"
|
||||
|
||||
# Act
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# Assert
|
||||
# room_a: 0.80 + 0.05 = 0.85
|
||||
# room_b: 0.75 (unverändert)
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.75)
|
||||
|
||||
def test_unique_keyword_bat_boosts_room_b(self, booster: KeywordBooster) -> None:
|
||||
"""'bat' ist nur in room_b → room_b bekommt +0.05.
|
||||
|
||||
'bat' + 'trading' + 'docker' sind alle unique für room_b
|
||||
→ +0.15 → room_b=0.90 schlägt room_a=0.80.
|
||||
"""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
text = "BAT Trading Platform Docker"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# room_b: 0.75 + 3×0.05 = 0.90
|
||||
# room_a: 0.80 (kein Keyword-Match)
|
||||
assert result[0][0] == "room_b"
|
||||
assert result[0][1] == pytest.approx(0.90)
|
||||
assert result[1][0] == "room_a"
|
||||
assert result[1][1] == pytest.approx(0.80)
|
||||
|
||||
def test_multiple_unique_keywords_cumulative_boost(self, booster: KeywordBooster) -> None:
|
||||
"""Mehrere eindeutige Keywords → kumulativer Boost (+0.05 pro Keyword)."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.70),
|
||||
("room_b", 0.80),
|
||||
]
|
||||
# "plugin" + "deployment" + "button" → 3 unique keywords für room_a
|
||||
text = "plugin deployment button gateway"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# room_a: 0.70 + 3×0.05 = 0.85
|
||||
# room_b: 0.80 (gateway ist shared → kein Boost)
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.80)
|
||||
|
||||
def test_keywords_100_also_trigger_boost(self, booster: KeywordBooster) -> None:
|
||||
"""keywords_100 sind auch im Mapping → eindeutig → Boost."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.70),
|
||||
("room_b", 0.80),
|
||||
]
|
||||
# "rocketchat" ist keywords_100 für room_a, unique
|
||||
text = "rocketchat websocket"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# room_a: 0.70 + 0.05 = 0.75
|
||||
assert result[0][0] == "room_b" # 0.80 > 0.75
|
||||
assert result[1][0] == "room_a"
|
||||
assert result[1][1] == pytest.approx(0.75)
|
||||
|
||||
|
||||
class TestBoostSharedKeyword:
|
||||
"""F4.3b: Mehrdeutiges Keyword (in mehreren Räumen) → neutral (kein Boost)."""
|
||||
|
||||
@pytest.fixture
|
||||
def booster(self) -> KeywordBooster:
|
||||
return KeywordBooster(_make_booster_room_map())
|
||||
|
||||
def test_shared_keyword_gateway_no_boost(self, booster: KeywordBooster) -> None:
|
||||
"""'gateway' ist in room_a UND room_b → kein Boost für beide."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
text = "gateway issue"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# Beide unverändert
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.80)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.75)
|
||||
|
||||
def test_mixed_unique_and_shared(self, booster: KeywordBooster) -> None:
|
||||
"""Mix: 'plugin' (unique room_a) + 'gateway' (shared) → nur room_a boost."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
text = "plugin gateway"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# room_a: 0.80 + 0.05 = 0.85
|
||||
# room_b: 0.75 (gateway shared → kein Boost)
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.75)
|
||||
|
||||
|
||||
class TestBoostEdgeCases:
|
||||
"""F4.3c: Edge Cases — leere Scores, keine Keywords, Case-Insensitivity."""
|
||||
|
||||
@pytest.fixture
|
||||
def booster(self) -> KeywordBooster:
|
||||
return KeywordBooster(_make_booster_room_map())
|
||||
|
||||
def test_empty_scores_returns_empty(self, booster: KeywordBooster) -> None:
|
||||
"""Leere Score-Liste → leere Liste zurück."""
|
||||
result = booster.boost("plugin bug", [])
|
||||
assert result == []
|
||||
|
||||
def test_no_keywords_matched_scores_unchanged(self, booster: KeywordBooster) -> None:
|
||||
"""Kein Keyword im Text → Scores unverändert, Reihenfolge erhalten."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
text = "Hallo wie gehts" # kein Keyword
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.80)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.75)
|
||||
|
||||
def test_case_insensitive_keyword_match(self, booster: KeywordBooster) -> None:
|
||||
"""Keywords sind case-insensitive."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
text = "PLUGIN BUG" # uppercase
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85)
|
||||
|
||||
def test_keyword_as_substring(self, booster: KeywordBooster) -> None:
|
||||
"""Keyword-Matching ist substring-basiert (nicht word-boundary)."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
# "plugin" ist substring von "pluginfix"
|
||||
text = "pluginfix"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85)
|
||||
|
||||
def test_catch_all_keywords_ignored(self, booster: KeywordBooster) -> None:
|
||||
"""Catch-All-Raum hat keine Keywords → nimmt nicht an Boosts teil."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_catchall", 0.60),
|
||||
]
|
||||
text = "plugin bug"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# room_a bekommt Boost, room_catchall nicht
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85)
|
||||
# room_catchall bleibt bei 0.60
|
||||
catchall_score = next(s for rid, s in result if rid == "room_catchall")
|
||||
assert catchall_score == pytest.approx(0.60)
|
||||
|
||||
def test_single_score_still_boosted(self, booster: KeywordBooster) -> None:
|
||||
"""Nur ein Raum in Scores → Boost wird trotzdem angewendet."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
]
|
||||
text = "plugin bug"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# F4.4 — Konfliktlösung: Top-2 Diff < 0.03
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestConflictResolution:
|
||||
"""F4.4: Top-2 Diff < 0.03 → Raum mit mehr unique keywords gewinnt (+0.02)."""
|
||||
|
||||
@pytest.fixture
|
||||
def booster(self) -> KeywordBooster:
|
||||
return KeywordBooster(_make_booster_room_map())
|
||||
|
||||
def test_conflict_room_a_wins_more_unique_keywords(self, booster: KeywordBooster) -> None:
|
||||
"""Top-2 Diff=0.02 < 0.03, room_a hat mehr unique keywords → +0.02."""
|
||||
# Arrange: knappe Top-2
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.87),
|
||||
("room_b", 0.85),
|
||||
]
|
||||
# "plugin" (unique room_a) + "gateway" (shared)
|
||||
# → room_a: 1 unique, room_b: 0 unique
|
||||
text = "plugin gateway"
|
||||
|
||||
# Act
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# Assert
|
||||
# Phase 1 Boost: room_a +0.05 (plugin unique) → 0.92
|
||||
# Phase 2 Konflikt: diff = 0.92 - 0.85 = 0.07 → KEIN Konflikt mehr!
|
||||
# Wait — der Konflikt-Check passiert NACH dem Boost.
|
||||
# Nach Boost: room_a=0.92, room_b=0.85, diff=0.07 ≥ 0.03 → kein Konflikt.
|
||||
#
|
||||
# Um Konflikt zu testen, brauchen wir Scores OHNE unique-Keyword-Boost,
|
||||
# also nur shared Keywords oder Scores die schon knapp sind.
|
||||
pass # Siehe nächster Test
|
||||
|
||||
def test_conflict_with_shared_keywords_only(self, booster: KeywordBooster) -> None:
|
||||
"""Konflikt bei shared Keywords: Diff < 0.03, unique counts entscheiden.
|
||||
|
||||
Strategy: Scores sind knapp, Text enthält NUR shared Keywords
|
||||
(kein unique Boost in Phase 1) → Diff bleibt < 0.03 →
|
||||
Konfliktlösung greift.
|
||||
"""
|
||||
# Arrange: knappe Scores, nur shared Keyword "gateway"
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.87),
|
||||
("room_b", 0.85),
|
||||
]
|
||||
text = "gateway issue" # "gateway" shared → kein Phase-1 Boost
|
||||
|
||||
# Act
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# Assert
|
||||
# Phase 1: kein Boost (gateway shared)
|
||||
# Phase 2: diff = 0.87 - 0.85 = 0.02 < 0.03 → Konflikt!
|
||||
# unique_count_1 = 0 (gateway shared, keine unique keywords im Text)
|
||||
# unique_count_2 = 0 → Gleichstand → kein +0.02
|
||||
# → Reihenfolge unverändert
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.87)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.85)
|
||||
|
||||
def test_conflict_room_a_wins_by_unique_count(self, booster: KeywordBooster) -> None:
|
||||
"""Konflikt: room_a hat 1 unique keyword, room_b 0 → room_a +0.02.
|
||||
|
||||
Strategy: Scores knapp, Text hat 1 unique keyword für room_a
|
||||
ABER der unique Boost (+0.05) macht Diff ≥ 0.03 → Konflikt verschwindet.
|
||||
Wir brauchen Scores die NACH dem unique Boost noch knapp sind.
|
||||
"""
|
||||
# Arrange: room_b startet höher, room_a hat unique keyword
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_b", 0.87),
|
||||
("room_a", 0.82),
|
||||
]
|
||||
# "plugin" unique für room_a → +0.05 → room_a=0.87
|
||||
# Nach Boost: room_b=0.87, room_a=0.87, diff=0.00 < 0.03
|
||||
# Konflikt: room_a hat 1 unique ("plugin"), room_b hat 0 → room_a +0.02
|
||||
text = "plugin gateway"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# room_a: 0.82 + 0.05 (unique boost) + 0.02 (conflict) = 0.89
|
||||
# room_b: 0.87 (gateway shared → kein Boost, 0 unique → kein conflict boost)
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.89)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.87)
|
||||
|
||||
def test_conflict_room_b_wins_by_unique_count(self, booster: KeywordBooster) -> None:
|
||||
"""Konflikt: room_b hat mehr unique keywords → room_b +0.02."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.87),
|
||||
("room_b", 0.82),
|
||||
]
|
||||
# "docker" unique für room_b → +0.05 → room_b=0.87
|
||||
# Nach Boost: room_a=0.87, room_b=0.87, diff=0.00 < 0.03
|
||||
# Konflikt: room_b hat 1 unique ("docker"), room_a hat 0 → room_b +0.02
|
||||
text = "docker gateway"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
assert result[0][0] == "room_b"
|
||||
assert result[0][1] == pytest.approx(0.89)
|
||||
assert result[1][0] == "room_a"
|
||||
assert result[1][1] == pytest.approx(0.87)
|
||||
|
||||
def test_conflict_tie_no_extra_boost(self, booster: KeywordBooster) -> None:
|
||||
"""Gleichstand bei unique counts → kein zusätzlicher Boost."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.87),
|
||||
("room_b", 0.85),
|
||||
]
|
||||
# Nur shared keyword → kein unique Boost, kein unique count
|
||||
text = "gateway"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# diff = 0.02 < 0.03 → Konflikt-Check
|
||||
# unique_count_1 = 0, unique_count_2 = 0 → Gleichstand → kein +0.02
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.87)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.85)
|
||||
|
||||
def test_no_conflict_when_diff_above_threshold(self, booster: KeywordBooster) -> None:
|
||||
"""Diff ≥ 0.03 → keine Konfliktlösung."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.90),
|
||||
("room_b", 0.87), # diff = 0.03 → genau an der Grenze
|
||||
]
|
||||
text = "gateway"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# diff = 0.03 → NICHT < 0.03 → kein Konflikt
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.90)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.87)
|
||||
|
||||
def test_conflict_with_multiple_unique_both_sides(self, booster: KeywordBooster) -> None:
|
||||
"""Beide Räume haben unique keywords → der mit MEHR unique gewinnt."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.82),
|
||||
("room_b", 0.80),
|
||||
]
|
||||
# "plugin" + "deployment" → 2 unique für room_a → +0.10 → room_a=0.92
|
||||
# "docker" → 1 unique für room_b → +0.05 → room_b=0.85
|
||||
# Nach Boost: diff = 0.07 ≥ 0.03 → kein Konflikt mehr.
|
||||
#
|
||||
# Um Konflikt zu testen: starte mit room_b höher
|
||||
scores2: list[tuple[str, float]] = [
|
||||
("room_b", 0.87),
|
||||
("room_a", 0.77),
|
||||
]
|
||||
# "plugin" + "deployment" → 2 unique für room_a → +0.10 → room_a=0.87
|
||||
# "docker" → 1 unique für room_b → +0.05 → room_b=0.92
|
||||
# Nach Boost: room_b=0.92, room_a=0.87, diff=0.05 ≥ 0.03 → kein Konflikt
|
||||
#
|
||||
# Dritter Versuch: Scores so dass nach Boost diff < 0.03
|
||||
scores3: list[tuple[str, float]] = [
|
||||
("room_b", 0.87),
|
||||
("room_a", 0.82),
|
||||
]
|
||||
# "plugin" + "deployment" → 2 unique für room_a → +0.10 → room_a=0.92
|
||||
# "docker" → 1 unique für room_b → +0.05 → room_b=0.92
|
||||
# Nach Boost: diff=0.00 < 0.03 → Konflikt!
|
||||
# unique_count_1 (room_b) = 1 ("docker")
|
||||
# unique_count_2 (room_a) = 2 ("plugin", "deployment")
|
||||
# → room_a gewinnt → +0.02 → room_a=0.94
|
||||
text = "plugin deployment docker gateway"
|
||||
|
||||
result = booster.boost(text, scores3)
|
||||
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.94)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.92)
|
||||
|
||||
|
||||
class TestConflictEdgeCases:
|
||||
"""F4.4b: Konfliktlösung Edge Cases."""
|
||||
|
||||
@pytest.fixture
|
||||
def booster(self) -> KeywordBooster:
|
||||
return KeywordBooster(_make_booster_room_map())
|
||||
|
||||
def test_single_score_no_conflict_check(self, booster: KeywordBooster) -> None:
|
||||
"""Nur ein Score → kein Konflikt-Check (braucht ≥2)."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
]
|
||||
text = "plugin gateway"
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
assert len(result) == 1
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.85) # nur unique Boost
|
||||
|
||||
def test_three_scores_conflict_only_top2(self, booster: KeywordBooster) -> None:
|
||||
"""Bei 3 Scores: Konfliktlösung betrachtet NUR Top-1 und Top-2."""
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.87),
|
||||
("room_b", 0.85),
|
||||
("room_catchall", 0.60),
|
||||
]
|
||||
text = "gateway" # shared → kein unique Boost
|
||||
|
||||
result = booster.boost(text, scores)
|
||||
|
||||
# diff = 0.02 < 0.03 → Konflikt, aber unique_count beide 0 → kein +0.02
|
||||
assert result[0][0] == "room_a"
|
||||
assert result[0][1] == pytest.approx(0.87)
|
||||
assert result[1][0] == "room_b"
|
||||
assert result[1][1] == pytest.approx(0.85)
|
||||
assert result[2][0] == "room_catchall"
|
||||
assert result[2][1] == pytest.approx(0.60)
|
||||
|
||||
def test_reload_rebuilds_mapping(self, booster: KeywordBooster) -> None:
|
||||
"""reload() baut Keyword-Mapping neu (nach RoomMap-Änderung)."""
|
||||
# Merke initiales Verhalten
|
||||
scores: list[tuple[str, float]] = [
|
||||
("room_a", 0.80),
|
||||
("room_b", 0.75),
|
||||
]
|
||||
result_before = booster.boost("plugin bug", scores)
|
||||
assert result_before[0][1] == pytest.approx(0.85)
|
||||
|
||||
# Ändere RoomMap: füge "plugin" auch zu room_b hinzu
|
||||
room_map = booster._room_map
|
||||
room_b_entry = room_map._rooms["room_b"]
|
||||
room_b_entry.keywords_context.append("plugin")
|
||||
|
||||
# Reload
|
||||
booster.reload()
|
||||
|
||||
# Jetzt ist "plugin" shared → kein Boost mehr
|
||||
result_after = booster.boost("plugin bug", scores)
|
||||
assert result_after[0][0] == "room_a"
|
||||
assert result_after[0][1] == pytest.approx(0.80) # unverändert
|
||||
@@ -0,0 +1,510 @@
|
||||
"""
|
||||
F4-Tests für RoomIndexManager — Cold-Start und Rebuild.
|
||||
|
||||
Zwei kritische Pfade (Rainer):
|
||||
F4.1 Cold-Start: Leerer/nicht gebauter FAISS-Index → search() scheitert
|
||||
→ Phase-1 übersprungen → LLM-Fallback
|
||||
F4.2 Rebuild: seed_data laden → Embeddings holen → Index bauen
|
||||
→ search() findet korrekten Raum
|
||||
|
||||
Mock-FAISS-Index (faiss-cpu muss NICHT installiert sein).
|
||||
Mock-EmbeddingClient (gibt feste Vektoren zurück, keine echten Ollama-Calls).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
# Ensure the archivar package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from plugin.archivar.room_index import RoomIndexManager, RoomIndexError
|
||||
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||
from plugin.archivar.classifier import EmbeddingClient
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Mock FAISS
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class MockIndexFlatIP:
|
||||
"""Mock FAISS IndexFlatIP — Kosinus-Ähnlichkeit via Inner Product.
|
||||
|
||||
Speichert Vektoren in einer Liste und berechnet dot-product
|
||||
für search(). Kein echtes FAISS nötig.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int) -> None:
|
||||
self.d = dim
|
||||
self._vectors: list[np.ndarray] = []
|
||||
self.ntotal: int = 0
|
||||
|
||||
def add(self, matrix: np.ndarray) -> None:
|
||||
"""Füge Vektoren hinzu (wie faiss.IndexFlatIP.add)."""
|
||||
if matrix.ndim == 1:
|
||||
matrix = matrix.reshape(1, -1)
|
||||
for vec in matrix:
|
||||
self._vectors.append(vec.copy())
|
||||
self.ntotal = len(self._vectors)
|
||||
|
||||
def search(
|
||||
self, query_vec: np.ndarray, k: int
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Suche k nächste Nachbarn (wie faiss.IndexFlatIP.search).
|
||||
|
||||
Returns:
|
||||
(scores, indices) — jeweils shape (1, k_eff).
|
||||
"""
|
||||
k_eff = min(k, self.ntotal)
|
||||
if self.ntotal == 0 or k_eff == 0:
|
||||
return (
|
||||
np.array([[-1.0]], dtype=np.float32),
|
||||
np.array([[-1]], dtype=np.int64),
|
||||
)
|
||||
|
||||
query_flat = query_vec.reshape(-1)
|
||||
sims = np.array([np.dot(v, query_flat) for v in self._vectors])
|
||||
top_k = np.argsort(sims)[::-1][:k_eff]
|
||||
return (
|
||||
np.array([sims[top_k]], dtype=np.float32),
|
||||
np.array([top_k], dtype=np.int64),
|
||||
)
|
||||
|
||||
|
||||
class MockFAISSModule:
|
||||
"""Mock faiss module — ersetzt `import faiss` in room_index.py."""
|
||||
|
||||
IndexFlatIP = MockIndexFlatIP
|
||||
|
||||
@staticmethod
|
||||
def write_index(index: MockIndexFlatIP, path: str) -> None:
|
||||
"""No-op: Tests persistieren nicht auf Disk."""
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def read_index(path: str) -> MockIndexFlatIP:
|
||||
"""Simuliert 'kein gespeicherter Index'."""
|
||||
raise FileNotFoundError(f"Mock: no saved index at {path}")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Mock EmbeddingClient
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class MockEmbeddingClient(EmbeddingClient):
|
||||
"""Gibt deterministische, feste Vektoren basierend auf Text-Inhalt zurück.
|
||||
|
||||
Kodiert Raum-Identität in den ersten 4 Dimensionen:
|
||||
dim 0 → #Rocketchat-Plugin (keywords: plugin, rocketchat, adapter, …)
|
||||
dim 1 → #BAT-Team (keywords: bat, trading, docker, …)
|
||||
dim 2 → #LAN-Dokumentation (keywords: lan, netzwerk, proxmox, …)
|
||||
dim 3 → #Protonbridge (keywords: proton, mail, bridge, …)
|
||||
|
||||
Zählt Keyword-Matches pro Dimension — die Dimension mit den meisten
|
||||
Treffern bekommt das stärkste Signal. So gewinnt die dominante
|
||||
Raum-Identität auch wenn Seed-Messages Cross-Contamination erzeugen.
|
||||
|
||||
Query-Vektor und Raum-Vektor sind nah beieinander wenn sie
|
||||
dieselbe dominante Dimension aktivieren → Kosinus-Ähnlichkeit ≈ 1.0.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int = 768) -> None:
|
||||
self._dim = dim
|
||||
|
||||
def get_embedding(self, text: str) -> list[float]:
|
||||
text_lower = text.lower()
|
||||
vec = np.zeros(self._dim, dtype=np.float32)
|
||||
|
||||
# ── Dimension 0: Rocketchat-Plugin ─────────────────────────
|
||||
vec[0] = float(sum(
|
||||
1 for kw in [
|
||||
"plugin", "rocketchat", "rc-plugin", "adapter", "ddp",
|
||||
"websocket", "archivar", "routing", "gateway-integration",
|
||||
"button", "onboarding", "move-request", "embedding",
|
||||
"faiss", "phase-1", "intent-klassifikation",
|
||||
"room-map.json", "deployment", "soul.md",
|
||||
] if kw in text_lower
|
||||
))
|
||||
|
||||
# ── Dimension 1: BAT-Team ─────────────────────────────────
|
||||
vec[1] = float(sum(
|
||||
1 for kw in [
|
||||
"bat", "trading", "docker", "next.js", "prisma", "api",
|
||||
"krypto", "wyckoff", "container", "pre-prod", ".45",
|
||||
"build-vm", ".101", "pnpm", "postgresql", "pg_dump",
|
||||
"api_key", "narrensicher", "snapshot", "database_url",
|
||||
"tor", "ssh-key",
|
||||
] if kw in text_lower
|
||||
))
|
||||
|
||||
# ── Dimension 2: LAN-Dokumentation ────────────────────────
|
||||
vec[2] = float(sum(
|
||||
1 for kw in [
|
||||
"lan", "dokumentation", "homelab", "netzwerk", "proxmox",
|
||||
"subnetze", "ip-adressen", "router", "switch", "heimnetz",
|
||||
"rzbln", "vlan", "firewall", "pfsense", "server",
|
||||
"infrastruktur", "verkabelung", "dhcp", "dns", "samba",
|
||||
] if kw in text_lower
|
||||
))
|
||||
|
||||
# ── Dimension 3: Protonbridge-Plugin ──────────────────────
|
||||
vec[3] = float(sum(
|
||||
1 for kw in [
|
||||
"proton", "bridge", "mail", "email", "imap", "smtp",
|
||||
"protonmail", "himalaya", "pr #39288", "th0rgal",
|
||||
"proton-api", "passwort",
|
||||
] if kw in text_lower
|
||||
))
|
||||
|
||||
# ── Normalisieren (für Kosinus-Ähnlichkeit via IP) ────────
|
||||
norm = float(np.linalg.norm(vec))
|
||||
if norm > 0.0:
|
||||
vec = vec / norm
|
||||
else:
|
||||
# Fallback: schwaches Signal in Dimension 4 (matched keinen Raum)
|
||||
vec[4] = 1.0
|
||||
vec = vec / np.linalg.norm(vec)
|
||||
|
||||
return vec.tolist()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Helpers
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_room_map_with_seed_rooms() -> RoomMap:
|
||||
"""Erzeugt eine RoomMap mit Räumen, die den seed_data-Einträgen entsprechen.
|
||||
|
||||
Returns:
|
||||
RoomMap mit 4 thematischen Räumen + 1 Catch-All.
|
||||
"""
|
||||
rooms: dict[str, RoomEntry] = {
|
||||
"6a19b0ff02aeecd36b1aa16c": RoomEntry(
|
||||
room_id="6a19b0ff02aeecd36b1aa16c",
|
||||
name="#Rocketchat-Plugin",
|
||||
theme=(
|
||||
"RC-Plugin-Entwicklung, Adapter, DDP, WebSocket, Buttons, "
|
||||
"Archivar, Routing, Gateway-Integration, Rocket.Chat-API"
|
||||
),
|
||||
keywords_100=["rocketchat", "rc", "ddp", "websocket"],
|
||||
keywords_context=[
|
||||
"plugin", "adapter", "gateway", "archivar", "routing",
|
||||
"button", "deployment", "onboarding", "embedding", "faiss",
|
||||
],
|
||||
catch_all=False,
|
||||
),
|
||||
"6a049d493a62ef8f1ead2320": RoomEntry(
|
||||
room_id="6a049d493a62ef8f1ead2320",
|
||||
name="#BAT-Team",
|
||||
theme=(
|
||||
"BAT Trading Platform, Docker, Next.js, Prisma, API, "
|
||||
"Web-UI, Krypto-Analyse, Wyckoff-Methodik"
|
||||
),
|
||||
keywords_100=["bat", "bat-team", "trading", "krypto"],
|
||||
keywords_context=[
|
||||
"docker", "next.js", "prisma", "api", "container",
|
||||
"pre-prod", "postgresql", "pg_dump",
|
||||
],
|
||||
catch_all=False,
|
||||
),
|
||||
"6a1c56d4b73efec2bebec2db": RoomEntry(
|
||||
room_id="6a1c56d4b73efec2bebec2db",
|
||||
name="#LAN-Dokumentation",
|
||||
theme=(
|
||||
"LAN Dokumentation, Homelab, Netzwerk, Proxmox, Subnetze, "
|
||||
"IP-Adressen, Router, Switch, Heimnetz"
|
||||
),
|
||||
keywords_100=["lan", "dokumentation", "homelab"],
|
||||
keywords_context=[
|
||||
"netzwerk", "proxmox", "subnetze", "router", "switch",
|
||||
"firewall", "pfsense", "server", "infrastruktur",
|
||||
],
|
||||
catch_all=False,
|
||||
),
|
||||
"69f8beaef06dba03be82f9fc": RoomEntry(
|
||||
room_id="69f8beaef06dba03be82f9fc",
|
||||
name="#Protonbridge-Plugin",
|
||||
theme=(
|
||||
"Proton Mail Bridge, Hermes Mailschnittstelle, "
|
||||
"Email-Integration, IMAP, SMTP, ProtonMail"
|
||||
),
|
||||
keywords_100=["proton", "bridge", "mail"],
|
||||
keywords_context=[
|
||||
"email", "imap", "smtp", "protonmail", "himalaya", "passwort",
|
||||
],
|
||||
catch_all=False,
|
||||
),
|
||||
"catch_all_room": RoomEntry(
|
||||
room_id="catch_all_room",
|
||||
name="DM Admin",
|
||||
theme="Catch-All für nicht zuordenbare Nachrichten",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
),
|
||||
}
|
||||
return RoomMap(
|
||||
rooms=rooms,
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_docs"),
|
||||
version=2,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# F4.1 — Cold-Start
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestColdStart:
|
||||
"""F4.1: Leerer/nicht gebauter FAISS-Index → Phase-1 übersprungen.
|
||||
|
||||
Der Router fängt RoomIndexError und fällt an LLM-Fallback durch.
|
||||
"""
|
||||
|
||||
def test_search_raises_when_index_not_built(self) -> None:
|
||||
"""Cold-Start: Index nicht gebaut → search() raises RoomIndexError.
|
||||
|
||||
Arrange: RoomIndexManager ohne build_index()/load()
|
||||
Act: search() aufrufen
|
||||
Assert: RoomIndexError mit 'not built or loaded'
|
||||
"""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
|
||||
# Index ist NICHT gebaut — Cold-Start
|
||||
assert not mgr.is_built
|
||||
assert mgr.size == 0
|
||||
|
||||
query_vec = emb_client.get_embedding("Das Plugin hat einen Bug")
|
||||
|
||||
with pytest.raises(RoomIndexError, match="not built or loaded"):
|
||||
mgr.search(query_vec, k=3)
|
||||
|
||||
def test_is_built_false_on_fresh_instance(self) -> None:
|
||||
"""Cold-Start: Frische Instanz → is_built=False, size=0."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
|
||||
assert not mgr.is_built
|
||||
assert mgr.size == 0
|
||||
assert mgr.room_ids == []
|
||||
|
||||
def test_load_returns_false_when_no_saved_index(self) -> None:
|
||||
"""Cold-Start: load() gibt False zurück wenn kein Index auf Disk."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
|
||||
# MockFAISSModule.read_index wirft FileNotFoundError
|
||||
result = mgr.load()
|
||||
assert result is False
|
||||
assert not mgr.is_built
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# F4.2 — Rebuild
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestRebuild:
|
||||
"""F4.2: seed_data laden → Embeddings holen → Index bauen → search() findet korrekten Raum."""
|
||||
|
||||
def test_build_index_from_seed_rooms(self) -> None:
|
||||
"""Rebuild: Index aus seed_data-Räumen bauen — 4 Räume, kein Catch-All."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
|
||||
# Act
|
||||
mgr.build_index()
|
||||
|
||||
# Assert
|
||||
assert mgr.is_built
|
||||
assert mgr.size == 4 # 4 nicht-catch-all Räume
|
||||
assert "catch_all_room" not in mgr.room_ids
|
||||
# Alle seed_data Raum-IDs müssen im Index sein
|
||||
assert "6a19b0ff02aeecd36b1aa16c" in mgr.room_ids
|
||||
assert "6a049d493a62ef8f1ead2320" in mgr.room_ids
|
||||
assert "6a1c56d4b73efec2bebec2db" in mgr.room_ids
|
||||
assert "69f8beaef06dba03be82f9fc" in mgr.room_ids
|
||||
|
||||
def test_search_finds_plugin_room(self) -> None:
|
||||
"""Rebuild: Plugin-Query → #Rocketchat-Plugin als Top-1."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
# Act: Query mit Plugin-Keywords
|
||||
query_vec = emb_client.get_embedding(
|
||||
"Das Plugin hat einen Bug im Adapter"
|
||||
)
|
||||
results = mgr.search(query_vec, k=3)
|
||||
|
||||
# Assert
|
||||
assert len(results) >= 1
|
||||
top_room_id, top_score = results[0]
|
||||
assert top_room_id == "6a19b0ff02aeecd36b1aa16c"
|
||||
assert top_score > 0.5 # hohe Kosinus-Ähnlichkeit
|
||||
|
||||
def test_search_finds_bat_room(self) -> None:
|
||||
"""Rebuild: BAT-Query → #BAT-Team als Top-1."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
query_vec = emb_client.get_embedding(
|
||||
"Docker Container für Trading Platform"
|
||||
)
|
||||
results = mgr.search(query_vec, k=3)
|
||||
|
||||
assert len(results) >= 1
|
||||
top_room_id, top_score = results[0]
|
||||
assert top_room_id == "6a049d493a62ef8f1ead2320"
|
||||
assert top_score > 0.5
|
||||
|
||||
def test_search_finds_lan_room(self) -> None:
|
||||
"""Rebuild: LAN-Query → #LAN-Dokumentation als Top-1."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
query_vec = emb_client.get_embedding(
|
||||
"Netzwerk Dokumentation für Proxmox Server"
|
||||
)
|
||||
results = mgr.search(query_vec, k=3)
|
||||
|
||||
assert len(results) >= 1
|
||||
top_room_id, top_score = results[0]
|
||||
assert top_room_id == "6a1c56d4b73efec2bebec2db"
|
||||
assert top_score > 0.5
|
||||
|
||||
def test_search_finds_proton_room(self) -> None:
|
||||
"""Rebuild: Proton-Query → #Protonbridge-Plugin als Top-1."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
query_vec = emb_client.get_embedding(
|
||||
"Proton Mail Bridge IMAP SMTP"
|
||||
)
|
||||
results = mgr.search(query_vec, k=3)
|
||||
|
||||
assert len(results) >= 1
|
||||
top_room_id, top_score = results[0]
|
||||
assert top_room_id == "69f8beaef06dba03be82f9fc"
|
||||
assert top_score > 0.5
|
||||
|
||||
def test_search_text_convenience(self) -> None:
|
||||
"""Rebuild: search_text() Convenience-Methode funktioniert."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
results = mgr.search_text(
|
||||
"FAISS Phase-1 Routing für Archivar", k=3
|
||||
)
|
||||
|
||||
assert len(results) >= 1
|
||||
top_room_id, _ = results[0]
|
||||
assert top_room_id == "6a19b0ff02aeecd36b1aa16c"
|
||||
|
||||
def test_rebuild_after_room_removed(self) -> None:
|
||||
"""Rebuild: rebuild() nach Raum-Entfernung produziert korrekten Index."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
assert mgr.size == 4
|
||||
|
||||
# Simuliere: Proton-Raum aus RoomMap entfernt
|
||||
del room_map._rooms["69f8beaef06dba03be82f9fc"]
|
||||
mgr.rebuild()
|
||||
|
||||
assert mgr.size == 3
|
||||
assert "69f8beaef06dba03be82f9fc" not in mgr.room_ids
|
||||
# Andere Räume noch da
|
||||
assert "6a19b0ff02aeecd36b1aa16c" in mgr.room_ids
|
||||
|
||||
def test_min_score_filters_weak_matches(self) -> None:
|
||||
"""Rebuild: min_score filtert schwache Treffer aus.
|
||||
|
||||
Query ohne Keyword-Match → Vektor in Dimension 4 →
|
||||
dot-product ≈ 0 mit allen Räumen → alle unter min_score=0.5.
|
||||
"""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
# "völlig fremdes Thema" matched keine Keywords
|
||||
# → MockEmbeddingClient gibt Vektor mit Signal nur in dim 4
|
||||
query_vec = emb_client.get_embedding("völlig fremdes Thema")
|
||||
results = mgr.search(query_vec, k=3, min_score=0.5)
|
||||
|
||||
# Alle Scores ≈ 0.0 → unter min_score → leere Liste
|
||||
assert len(results) == 0
|
||||
|
||||
def test_search_respects_k_limit(self) -> None:
|
||||
"""Rebuild: search() respektiert k-Limit."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
# Query die mehrere Räume matched (dim 0 + dim 1)
|
||||
query_vec = emb_client.get_embedding("plugin gateway docker")
|
||||
results = mgr.search(query_vec, k=2)
|
||||
|
||||
assert len(results) <= 2
|
||||
|
||||
def test_stats_after_build(self) -> None:
|
||||
"""Rebuild: stats() liefert korrekte Diagnosedaten nach build_index()."""
|
||||
room_map = _make_room_map_with_seed_rooms()
|
||||
emb_client = MockEmbeddingClient(dim=768)
|
||||
|
||||
with patch("plugin.archivar.room_index.faiss", MockFAISSModule):
|
||||
mgr = RoomIndexManager(room_map, emb_client, embedding_dim=768)
|
||||
mgr.build_index()
|
||||
|
||||
stats = mgr.stats()
|
||||
assert stats["is_built"] is True
|
||||
assert stats["room_count"] == 4
|
||||
assert stats["embedding_dim"] == 768
|
||||
assert stats["version"] == 2
|
||||
assert stats["built_at"] > 0.0
|
||||
assert stats["built_at_iso"] is not None
|
||||
Reference in New Issue
Block a user