65a3baa3e5
3 Architekturentscheidungen getroffen: - L1: room-map.json als Single Source of Truth (JSON, ~/.hermes/hermes-agent/data/) - L2: FATAL-Validierung bei Gateway-Start (0/>1 Catch-All) - L3: Onboarding als separates Plugin-Tool (nicht im Archivar-Modul) Enthält: Datenmodell (RoomMap, RoomEntry, RoomRouter), Migrationspfad in 4 Phasen, Datenfluss-Diagramm, Checkliste für Andreas' Review.
341 lines
12 KiB
Markdown
341 lines
12 KiB
Markdown
# 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. Checkliste für Andreas' Review
|
|
|
|
- [ ] **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?
|