174 Commits

Author SHA1 Message Date
Bernd (Hermes) bc815e67c8 fix: P0-BUGFIX Meta-Pattern restriktiver + target_room origin_room_id
- router.py: Meta-Pattern 3 war "archivar" allein → spezifische Verb-Patterns
- router.py Z.515: target_room=catch_all_id → origin_room_id bei stay_in_room
- adapter.py Z.1448: _THEMATIC_TARGET_ROOM.set() nur wenn not stay_in_room
- 16 neue Tests: 13 Meta-Pattern + 3 target_room
- 192/193 passed (1 pre-existing: test_no_env_vars)
2026-07-13 20:39:15 +02:00
Bernd (Hermes) 344043b081 P0-BUGFIX: Meta-Check zu aggressiv + Router-Raum-Confusion
Bug 1: _META_PATTERNS Pattern 3 matchte JEDES Vorkommen von 'Archivar',
auch in Sachfragen wie 'Was hat der Archivar empfohlen?' → is_meta=True
→ 100%-Keyword-Match wurde nie geprüft.

Fix: Pattern 3 aufgeteilt in zwei bidirektionale Patterns:
- 'archivar' + System-Operationsverb (klassifiziert, routet, leitet weiter,
  arbeitet, funktioniert, macht) — in beiden Richtungen
- System-Begriffe ohne 'archivar' (klassifikation, routing, weiterleitung)
  bleiben eigenständige Meta-Signale

Bug 2: Bei stay_in_room=True wurde target_room=catch_all_id (DM) gesetzt
statt target_room=origin_room_id. Das leakt in _THEMATIC_TARGET_ROOM →
Agent-Prompt bekommt falschen Raum → Agent denkt er sei im DM.

Fix:
- router.py: Meta-Frage target_room=origin_room_id statt catch_all_id
- adapter.py: _THEMATIC_TARGET_ROOM nur setzen wenn NICHT stay_in_room

Tests: 16 neue Tests (TestMetaPatternsP0 + TestTargetRoomStayInRoomP0)
- 26/26 test_router.py PASS
- 32/32 test_v7_4_recursive.py PASS
- 192/193 full suite PASS (1 pre-existing env-var failure)
2026-07-13 20:34:43 +02:00
Bernd (Hermes) 1f2c687ccd feat: V7-5 + Fix C v7 — Pausen-Definition finalisiert + Butler-Mode Onboarding
V7-5:
- W2: topic_hint-Update in extend_never_route (Inkonsistenz fix)
- W3: LLM-Bypass wenn keine never_route Einträge für Raum (Performance)
- W1: get_never_route_entry() Public-Methode (Encapsulation)

Fix C v7:
- room_map.py: butler_mode (cognitive/strict/off) in Schema, Default cognitive, abwärtskompatibel
- router.py: _resolve_move_request wendet Butler-Mode an (off = Hard-Kill)
- adapter.py: Onboarding-Frage nach Catch-All (🤖📋🔇 Buttons), Speicherung in room-map.json
- 13 neue Tests: 9 RoomMap + 4 Router

Archivar v7 vollständig: V7-1 bis V7-5 + Fix C v7
2026-07-13 16:25:08 +02:00
Bernd (Hermes) 0de95008c9 feat: V7-4 Rekursive Einleitungen erkennen + Wiederherstellung
- RECURSIVE_MARKERS: 10 Marker (nochmal, zurückkommen, eingefallen, etc.)
- _detect_recursive_reference: Heuristisch (Marker) → LLM (REKURSIV/NEU mit Historie)
- Wiederherstellung: VERBLASST → AKTIV via restore_never_route, Butler blockiert
- route() Reihenfolge: V7-4 nach V7-3, vor Meta-Fragen
- LLM-Prompt mit Konversationshistorie, Timeout 5s, Fallback NEU
- 32 neue Tests + 5 TopicChange-Tests (V7-3 Lücke geschlossen)
2026-07-13 16:12:16 +02:00
Bernd (Hermes) d20c06f02c feat: V7-3 "Jetzt" verblasst + Wiederherstellung — Drei-Zustands-Logik
- archivar_state.py: expire_stale_entries() mit 24h hard limit + adaptive Pause (Median×3)
- archivar_state.py: is_never_route prüft nur AKTIV — VERBLASST erlaubt Butler
- archivar_state.py: extend_never_route() + restore_never_route() (Stub für V7-4)
- router.py: Themenwechsel-Erkennung via Konversationshistorie (topic_hint Vergleich)
- router.py: expire_stale_entries VOR _check_never_route_topic in route()
- 24 neue Tests: 24h Verfall, adaptive Pause, AKTIV/VERBLASST, Verlängerung, Wiederherstellung
2026-07-13 16:00:05 +02:00
Bernd (Hermes) dff524d3e7 feat: V7-2 Sticky thematisch — never_route[room_id][topic]
- Button 2 (Generell hier bleiben): set_never_route mit Thema, state=AKTIV
- Button 3 (Nur diesmal): stay_tracker + Auto-Promotion nach 3x mit Thema
- Router: _check_never_route_topic fragt "Ist matchendes Thema sticky?" → Stay
- Reihenfolge: Self-Match → never_route topic → 100%-Check → Kontext → FAISS → LLM
- never_route für lan-doku blockt NICHT protonbridge im selben Raum
- 8 neue Tests: thematischer Sticky, Multi-Topic, Raum-Isolation, Konversion
2026-07-13 15:50:26 +02:00
Bernd (Hermes) d36ac73212 V7-2: Thematisches never_route — _sticky_rooms spatial bypass entfernt
Button 2 (Generell hier bleiben): set_never_route(room_id, topic) mit
Thema aus room_name_to_topic() — bereits korrekt in P0-B implementiert.

Button 3 (Nur diesmal): stay_tracker-Inkrement + Auto-Promotion nach 3x
mit set_never_route(room_id, topic) — bereits korrekt in P0-B.

Router: _check_never_route_topic prüft matched_room.name → topic gegen
never_route[room_id][topic] — bereits korrekt in P0-B.

DER BUG: _sticky_rooms war ein räumlicher Bypass, der ALLE Nachrichten
in einem Raum blockierte, unabhängig vom Thema. Entfernt:
- __init__: _sticky_rooms-Dict entfernt
- Button 2: _sticky_rooms[room_id] = time.time() entfernt
- Button 3 Auto-Promotion: _sticky_rooms[room_id] = time.time() entfernt
- Archivar-Bypass: elif room_id in self._sticky_rooms entfernt

Jetzt läuft jede Nachricht durch den Router, der thematisch prüft:
never_route für 'lan-dokumentation' blockt NICHT 'protonbridge'.

Tests: 8 neue Tests in TestNeverRouteThematic (alle grün, 107/108 passed,
1 pre-existing env-var failure unrelated).
2026-07-13 15:44:08 +02:00
Bernd (Hermes) f687c49295 P0 Nachbesserungen + V7-1: Butler antwortet im Zielraum
Auflage 1: Unit-Tests für ConversationHistory (34 Tests)
- test_conversation_history.py: add/get, Ring-Buffer, topic_hint,
  cleanup_orphaned_rooms (sync+async), Thread-safety, Edge cases

Auflage 2: Schritt-4.5 Stick-Check im Router
- router.py Zeile ~556: _check_never_route_topic VOR is_100_percent_match
  in Schritt 4.5 (Keyword-Match vor LLM) eingefügt

Auflage 3: Topic-Extraktion zentralisieren
- router.py: room_name_to_topic als Module-Level-Alias exportiert
- adapter.py: importiert room_name_to_topic, ersetzt 2× inline
  .lstrip('#').lower().replace(' ', '-') durch zentralen Aufruf

V7-1: Butler antwortet im Zielraum + Breadcrumb
- adapter.py _process_incoming: move_request_sent=True → return (kein Agent-Dispatch)
- adapter.py Move-Request-Handler: bei ✅Ja → Breadcrumb im Ursprungsraum,
  _CURRENT_ORIGIN_ROOM + _THEMATIC_TARGET_ROOM auf Zielraum gesetzt,
  _dispatch_agent() im Zielraum-Kontext
- adapter.py _dispatch_agent(): extrahierte Dispatch-Methode für V7-1-Pfad

Syntax-Check: alle .py bestehen py_compile
Tests: 99/100 passed (1 pre-existing env-var failure)
2026-07-13 15:33:54 +02:00
Bernd (Hermes) 2f2690a034 P0-B: Schema-Migration never_route[room_id] → never_route[room_id][topic] (v7)
- archivar_state.py: _never_route von Set zu Dict[room_id][topic] migriert
  - Neue Methoden: set_never_route, is_never_route, remove_never_route,
    get_never_route_topics, expire_stale_entries (Stub)
  - Migrations-Logik: Altes Listen-Format → leeren + loggen
  - GC: cleanup_orphaned_rooms bereinigt jetzt auch _never_route
  - Persistenz: _to_dict/save/load für neues JSON-Format

- router.py: Raum-Level never_route-Bypass entfernt
  - _room_name_to_topic: Raum-Name → Topic-Slug
  - _check_never_route_topic: Prüft Thema in allen 3 Match-Pfaden
    (Keyword, FAISS, LLM)
  - Kein Thema erkennbar → Fallback: Butler darf fragen

- adapter.py: 'Generell hier bleiben' + Auto-Promotion thematisch
  - set_never_route(room_id, topic) statt set_room_state(never_route)
  - Topic aus move_req['target_name'] extrahiert
  - should_stay_in_room nur noch für 'always' als Bypass

Tests: 18/18 archivar_state + 2/2 router — alle grün
Syntax: python3 -m py_compile auf allen 3 Dateien — OK
2026-07-13 15:19:07 +02:00
Bernd (Hermes) 45f3259350 fix: Onboarding Frage 4/4 — Catch-All in der Frage erklärt
- Alt: "Soll dieser Raum der Catch-All sein? (Ja/Nein)"
- Neu: "Soll dieser Raum der Auffang-Raum (Catch-All) sein — also der Raum für Themen, die in keinen anderen passen? (Ja/Nein)"
2026-07-13 10:32:42 +02:00
Bernd (Hermes) cb0f869595 fix: Onboarding Catch-All-Erklärung ergänzt — Auffang-Raum statt Fachjargon
- Alt: "Möchtest du den Catch-All-Raum ändern?"
- Neu: "Gibt es ein Thema, das in keines der eingerichteten Räume passt — wo sollen wir dann darüber sprechen? Das ist der Auffang-Raum (Catch-All)."
2026-07-13 10:04:48 +02:00
Bernd (Hermes) 280be0fbdb NACHBESSERUNG: Fix E + DM-Onboarding (3 Punkte)
A: Skill rocketchat-room-context gelöscht (Repo + Profil)
B: _reconnect_ddp() baut _room_map_summary nach M13 GC neu
C: DM wird thematisch beim Onboarding abgefragt (Thema, Keywords, Catch-All)

- _reconnect_ddp() hat jetzt 4 refresh-Punkte: M13 GC, _room_map_summary,
  Raum-Subscriptions, Archivar subscribed_room_ids
- DM als letzter Raum im Onboarding mit 3 spezifischen Fragen (1/3, 2/3, 3/3)
- DM catch_all immer true, Frage 4/4 wird übersprungen
- Connect-Flow ruft _start_onboarding([]) auch bei nur-DM-Szenarien
2026-07-12 19:10:48 +02:00
Bernd (Hermes) 2d4359071b feat: Raum-Kontext-Injection + Butler-Trigger-Logik + Room-Context Skill
- Fix A: Raum-Name/Typ als Text-Prefix in User-Nachricht injiziert
- Fix B: Skill rocketchat-room-context im Plugin-Repo + deploy via install.sh
- Fix C: 100% Keywords → auto-route (kein Butler), Kontext → Butler fragt
- Fix D: FAISS-Auto-Route move_request_sent=False (konsistent mit Fix C)

Rainer-Review: 4/4 freigegeben (2 Iterationen, Fix A Kommentar + Fix B Skill-Ort korrigiert)
2026-07-12 18:11:54 +02:00
Bernd (Hermes) c99cbfd76b P0 Fixes (Rainer 2. Analyse): RC-1 never_route/always Unterscheidung, RC-2 _version in add_or_update_room, RC-3 stay_here Action-Token
RC-1: archivar_state.py:264-287 + router.py:307-323
  should_stay_in_room() gab 'origin_first'/'sticky' zurück, aber beide
  wurden identisch behandelt (stay_in_room=True). never_route sollte
  bedeuten: NIE wieder routen, KEIN Move-Request. always: immer hier
  bleiben. Jetzt klare Unterscheidung: 'always' vs 'never_route'.

RC-2: room_map.py:356-393
  add_or_update_room() erhöhte self._version NICHT nach Änderungen.
  is_stale() im FAISS-Index vergleicht Versionen → dachte Index aktuell
  → lud veralteten Index von Disk. Fix: self._version += 1 nach jeder
  Änderung.

RC-3: adapter.py:1241
  stay_here Action-Token aus MOVE_REQUEST_TEMPLATE (v4 Button 'Hier')
  war nicht im Handler-Mapping. Fiel in else-Zweig (one-time stay)
  statt never_route (permanent). Fix: 'stay_here' zu Option-2-Mapping
  hinzugefügt.
2026-07-12 17:22:32 +02:00
Bernd (Hermes) ec7c6144d8 P0+P1 Fixes: ARCHIVAR_ENABLE_LLM, Dead-Code, should_stay_in_room Diff, Reconnect-Onboarding, FAISS-Rebuild, stay_tracker+onboarding Persistenz
P0-1: install.sh schreibt ARCHIVAR_ENABLE_LLM=true in rocketchat.env bei MULTIROOM=true
P0-2: Dead-Code adapter.py:1359-1435 entfernt (Silent-Copy-Pfad im v6-Flow unerreichbar)
P0-3: should_stay_in_room() gibt jetzt 'origin_first'/'sticky'/None statt True/False/None
P1-1: Reconnect-Onboarding prüft jetzt auf neue Räume statt immer zu skippen
P1-2: _set_catch_all() baut FAISS-Index nach Catch-All-Wechsel neu
P1-3: stay_tracker in ArchivarState persistiert (archivar_state.json)
P1-4: onboarding_state in ArchivarState persistiert (archivar_state.json)
2026-07-12 17:13:42 +02:00
Bernd (Hermes) 1e81c2abc4 fix: Bug 8 — excluded_rooms bei DDP-Subscription berücksichtigen
- _excluded_room_ids Attribut in init
- _sync_room_map_with_membership() lädt excluded_room_ids aus RoomMap
- Beide subscribe-Loops (connect + _reconnect_ddp) filtern excluded_rooms
- Defense in depth: Router-Filter bleibt als 2. Verteidigungslinie

Rainer-Quality-Loop: freigegeben (1 Iteration)
2026-07-12 16:55:34 +02:00
Bernd (Hermes) 7fd7c871ab feat: M13 Room-Map Garbage Collection + Bug 7 Reconnect-GC
- M13: _sync_room_map_with_membership() — room-map.json gegen REST Mitgliedschaft syncen
- FAISS-Index rebuild nach GC (nur gültige Räume)
- KeywordBooster.cleanup_orphaned_rooms() — Mapping neu bauen
- ArchivarState.cleanup_orphaned_rooms() — sticky/weights/overlays bereinigen
- Onboarding _stay_tracker bereinigen
- P1: M13→B9 Reihenfolge dokumentiert (M13 vor B9, keine Race)
- P2: _subscribed_rooms + _room_info in GC aufräumen (keine Geister-Subs)
- P3: DDPClient.unsubscribe() neu + in GC aufgerufen
- Bug 7: _reconnect_ddp() ersetzt reconnect_and_restore — macht get_rooms() + M13 GC + subscribe nur Mitglieder
- N1: RECONNECT_BACKOFFS toter Code entfernt
- 35 M13-Tests PASS

Rainer-Quality-Loop: freigegeben (2 Iterationen, 4 Punkte behoben)
2026-07-12 16:00:15 +02:00
Bernd (Hermes) df07e7c5e0 M13 Rainer-Review + Bug 7 (Reconnect): P1-P3 fixes + reconnect GC
P1: Document M13→B9 ordering guarantee in _sync_room_map_with_membership docstring
P2: Clean up self._subscribed_rooms and self._room_info for removed rooms in M13 GC
P3: Add DDPClient.unsubscribe() and call it for each removed room in M13 GC
Bug 7: Replace reconnect_and_restore() calls with _reconnect_ddp() that runs
       REST get_rooms() + M13 GC before subscribing, preventing ghost re-subscriptions
       after kick. reconnect_and_restore() kept as deprecated wrapper.
2026-07-12 15:56:57 +02:00
Bernd (Hermes) 3179ce8b7b M13: Vollständige Garbage Collection — FAISS-Rebuild + KeywordBooster-Reset + ArchivarState-Bereinigung + Onboarding-StayTracker-Cleanup
Erweitert _sync_room_map_with_membership() um die von Andreas geforderten
Bereinigungsschritte nach room-map.json-GC:

1. FAISS-Index: rebuild + save (war bereits in M13, jetzt robuster)
2. KeywordBooster: cleanup_orphaned_rooms() — baut _keyword_to_rooms
   Mapping aus bereinigter RoomMap neu
3. ArchivarState: cleanup_orphaned_rooms() — entfernt stay_decision,
   keyword_weights, sticky_keywords, manual_overrides, promotion_candidates
   für gelöschte Räume
4. Onboarding _stay_tracker: entfernt Einträge für gelöschte Räume

Reihenfolge im Gateway-Start (adapter.py connect()):
  DDP connect → _sync_room_map_with_membership() → DDP subscribe →
  Archivar init → Auto-Onboarding

Alle neuen Methoden sind idempotent und mit Tests abgedeckt:
- test_archivar_state.py: +8 Tests (cleanup_orphaned_rooms)
- test_booster.py: +4 Tests (cleanup_orphaned_rooms)
2026-07-12 15:49:17 +02:00
Bernd (Hermes) 63ca3bed96 fix: R8 Origin-First Guard — 3 Auto-Route-Pfade entfernt
- Keyword Schritt 3: Cross-Room → move_request_sent=True + STAY
- FAISS Schritt 3.5: Cross-Room → move_request_sent=True + STAY
- Hybrid Schritt 4.5: Cross-Room → move_request_sent=True + STAY
- should_route(): not move_request_sent als Bedingung
- Same-Room-Match wird noch geroutet (korrekt)
- move_request_target_{name,id} für Butler-Button gesetzt

Rainer-Quality-Loop: freigegeben (1 Iteration, alle 4 Stellen korrekt)
2026-07-12 15:13:27 +02:00
Bernd (Hermes) 3f1d688983 Bug 6: Konsistenz _finish_onboarding / _get_onboarding_room_list
- Gleiche Sortierreihenfolge in beiden Funktionen: (not is_catch, name)
- _get_onboarding_room_list liefert jetzt 3-Tupel (rid, name, is_current)
  statt 2-Tupel — '(aktuell)'-Marker kann nun auch in der Auswahlliste
  angezeigt werden (is_current=True für den Operator-DM)
- Tote insert(0,...)-Aufrufe in beiden Funktionen durch append + Kommentar
  'wird nachfolgend einsortiert' ersetzt
- Caller (catch_all_change-Phase) auf 3-Tupel-Unpacking angepasst
2026-07-12 15:04:31 +02:00
Bernd (Hermes) 13575aaf40 Bug 6: Onboarding Catch-All-Auswahl zeigt jetzt DM als Option an
_finish_onboarding: DM-Raum aus _room_info wird immer in die
Catch-All-Auswahlliste aufgenommen (auch wenn nicht in room_map).
DM bekommt '(aktuell)'-Marker statt '(Catch-All)'.

_get_onboarding_room_list: Gleiche Logik — DM immer inkludiert,
mit echtem Namen statt 'Catch-All (legacy)'.

catch_all_change-Phase: DM-Auswahl ist no-op (bleibt Catch-All),
andere Raum-Auswahl setzt _set_catch_all() wie bisher.
2026-07-12 14:58:57 +02:00
Bernd (Hermes) d478d8079a fix(install): M11 numpy/faiss via uv pip, M12 bootstrap.sh + broken clone recovery
M11: _venv_install() helper nutzt uv pip (Hermes v0.18.0+) mit Fallback-Kette:
  uv pip > pip > python -m pip, für venv/ und .venv/.
  Ersetzt alle 3 numpy/faiss-Installationsblöcke (perform_update,
  perform_update_only, main install path).

M12: bootstrap.sh als One-Command-Entrypoint:
  ssh-keyscan → git clone (SSH→HTTP fallback) → exec install.sh.
  _bootstrap_repo() erkennt jetzt broken clones (.git ja, plugin/ nein)
  und löscht + cloned neu statt fatal abzubrechen.
2026-07-12 14:34:20 +02:00
Bernd (Hermes) 17e6670358 fix: Rainer-Review Bug 3+4+5+B9 — 4 kritische Mängel behoben
Bug 5 (Datenverlust): python3-Check in install.sh unsicher
- 3 Stellen: python3-Verfügbarkeit VOR room-map.json-Check prüfen
- Falls python3 fehlt: Warnung + Skip (nicht überschreiben)
- install.sh: Zeilen ~487, ~711, ~1103

Bug 4 (Schleife): should_stay_in_room() nicht im Bypass gelesen
- Bypass-Logik prüft jetzt ArchivarState-Persistenz
- Nach Gateway-Neustart: persistierte never_route/always-Entscheidungen
  werden gelesen → Sticky-Schleife kommt nicht zurück
- adapter.py: Zeile ~952

B9 (Endlosschleife): Kein Idempotenz-Guard bei Reconnects
- (a) onboarding_active-Check VOR B9-Block
- (b) is_reconnect + rooms initialisiert → skip
- (c) FAISS-Rebuild: RoomIndexError → _room_index=None + warnen
- adapter.py: Zeilen ~622, ~1713

Bug 3 (Asymmetrie): send()-Handler ohne Fallback + _is_user_operator tot
- (a) send(): Text-Fallback wenn button_template nicht gerendert werden kann
  (z.B. 'Antworte mit 1, 2 oder 3')
- (b) _is_user_operator entfernt (toter Code, nie aufgerufen, first-touch-Bug)
- adapter.py: Zeilen ~1942, ~1801
2026-07-12 12:22:07 +02:00
Bernd (Hermes) c3a66239fd fix: Bug 3 (Onboarding-Buttons), Bug 4 (Move-Request-Sticky), Bug 5 (room-map.json), B9 (Auto-Onboarding)
Bug 3 — Onboarding-Buttons als Text statt interactive:
- adapter.py: Neue Methode _get_build_custom_buttons() mit lokalem Fallback
  der korrekte Rocket.Chat Button-Dicts baut, wenn das rocketchat-Modul
  nicht in sys.modules ist (Race-Condition beim Import)
- _start_onboarding() nutzt jetzt _get_build_custom_buttons() statt
  des Modul-Level-Fallbacks _build_custom_buttons (der [] liefern kann)
- _onboarding_next_room() ebenfalls auf _get_build_custom_buttons() umgestellt
- Operator-DM-Erkennung nicht mehr hardcoded auf 'andreas' — nimmt ersten DM
- Selbsterklärende Onboarding-Nachricht mit Emoji und Kontext

Bug 4 — Move-Request-Schleife, Sticky greift nicht:
- Option 2 (Generell hier): Persistiert jetzt in ArchivarState
  (set_room_state(room_id, 'never_route', username)) — überlebt Neustarts
- Option 3 (Hier bleiben): Stay-Counter — nach 3x Stay in 10 Min
  wird der Raum automatisch auf never_route promoted
- _sticky_rooms (in-memory) bleibt als schneller Cache erhalten

Bug 5 — Falsche room-map.json wird geladen:
- install.sh: Alle 3 room-map.json-Deploy-Stellen prüfen jetzt, ob die
  existierende Datei 0 Räume enthält (leeres Template) → dann neu deployen
- Verhindert dass das leere Template nach Erstinstallation für immer bleibt

B9 — Auto-Onboarding ohne Vorkenntnisse:
- connect(): Trigger prüft jetzt: MULTIROOM_AGENT=true + Räume ohne Map-Eintrag
  + Ausnahme: Nur DM → kein Onboarding
- Zusätzlich: Wenn room-map.json 0 Räume hat → Onboarding für ALLE non-DM-Räume
- _finish_onboarding(): FAISS-Index wird nach Onboarding neu gebaut + gespeichert
- _is_user_operator(): Nicht mehr hardcoded — erster DM-User wird Operator

Syntax-Check: Alle .py (20 Dateien) + install.sh → OK
2026-07-12 12:11:26 +02:00
Bernd (Hermes) c850ca1ba7 fix(install.sh): Multi-Room Fixes M5-M9
- M5: RC_MULTIROOM env var korrekt übernommen (war immer false)
- M6: MULTIROOM_AGENT in systemd drop-in synchron mit RC_MULTIROOM
- M7: PYTHONPATH in drop-in gesetzt (Plugin-Module gefunden)
- M8: ARCHIVAR_CATCHALL_ROOM=RC_HOME_CHANNEL (DM-Catch-All)
- M9: numpy immer installiert, faiss-cpu best-effort

Rainer-Quality-Loop: freigegeben (1 Iteration, 1 optionale Empfehlung)
2026-07-12 11:37:40 +02:00
Bernd (Hermes) 1157c73d65 fix(install.sh): ssh-keyscan + SSH→HTTP Fallback + Endlosschleife-Guard
- U1: ssh-keyscan -p 222 192.168.180.47 vor git clone (frische VM)
- U2: git clone SSH→HTTP Fallback (kein SSH-Key auf frischer VM)
- Rainer-Bug: Endlosschleife bei .git ohne plugin/ → fatal Guard
- chmod 700 ~/.ssh nach mkdir (SSH strict-mode)
- ssh-keyscan Argumentreihenfolge: -p PORT HOST

Rainer-Quality-Loop: freigegeben (2 Iterationen)
2026-07-12 11:23:58 +02:00
Bernd (Hermes) 5a9cf5f160 fix: Rainer-Quality-Loop — 4 Fixes (2 release-blockierend, 2 dringend)
D1 (RELEASE-BLOCKIEREND): Guard 2.5 — LLM schlägt excluded room vor
  router.py: Nach Guard 2 (Catch-All) prüft Guard 2.5 ob LLM-Raum
  excluded ist → stay_in_room. Verhindert Move-Request in excluded room.

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

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

D4 (DRINGEND): install.sh base_url-Löschung zu aggressiv
  install.sh: base_url mit openrouter nur löschen wenn
  _RC_PROVIDER == ollama-cloud. Bei explizitem openrouter bleibt sie.
2026-07-09 17:41:01 +02:00
Bernd (Hermes) 8b67e03f7e feat(v6): Phase 1 — Origin-First Guard + LLM Fix + Proaktiver Broadcast
P3: LLM_CONFIG base_url jetzt aus OLLAMA_BASE_URL Env-Var (config.py:150)
I1: LLM_ROOM_PROMPT umgeschrieben — STAY/ROUTE statt CATCH_ALL,
    Ursprungsraum-Kontext, Few-Shot-Beispiele, Catch-All nicht als Option
    (config.py:175-195, router.py:_llm_room_lookup)
P2: Origin-First Guard (Schritt -0.5) in router.py:route():
    - origin_room_id leer (echte DM) → normaler Flow
    - origin_room ist Catch-All → stay_in_room
    - origin_room ist excluded → ignore
    - LLM sagt STAY → stay_in_room
    - LLM == origin_room → stay_in_room
    - LLM == catch_all_room → stay_in_room (kein DM-Routing!)
    - LLM == anderer Raum → Move-Request (Butler-Prinzip)
Catch-All-Schutz: DM-Nachrichten skippen Routing-Flow (router.py:270-282)
Move-Request-Routing-Fix (adapter.py):
    - 1️⃣ Rüberkopieren → _CURRENT_ORIGIN_ROOM = Zielraum
    - 2️⃣ Generell hier bleiben → Sticky-Eintrag
    - 3️⃣ Hier bleiben → nur diesmal, kein Sticky
    - Button-Labels aktualisiert: 1️⃣ Rüber / 2️⃣ Generell / 3️⃣ Hier
B6: Proaktiver Raum-Broadcast (tools.py):
    - Neues Tool rocketchat_broadcast mit 5-Min-Cooldown
    - Format: menschenähnlich, kein Bot-Ton
    - Registriert in _TOOLS mit 📢 Emoji
2026-07-09 17:33:14 +02:00
Bernd (Hermes) 1ade5549b3 fix(templates): Platzhalter statt harter Konfigurationsdaten — keine .101-Leaks 2026-06-23 10:22:57 +02:00
Bernd (Hermes) 9488f44d88 fix(install.sh): MULTIROOM_AGENT in Drop-in für true UND false — überlebt gateway install 2026-06-23 08:31:27 +02:00
Bernd (Hermes) 85713a7e29 fix(install.sh): MULTIROOM_AGENT in Drop-in statt Haupt-Unit — überlebt gateway install 2026-06-23 08:30:29 +02:00
Bernd (Hermes) 4f9054fea1 fix(install.sh): MULTIROOM_AGENT conditional — numpy/faiss, room-map.json, systemd-Unit Environment=, OLLAMA_API_KEY 2026-06-23 07:01:15 +02:00
Bernd (Hermes) 8760d29036 fix(adapter): Antwort-Routing — _CURRENT_ORIGIN_ROOM hat Vorrang vor Archivar-Target 2026-06-23 06:16:43 +02:00
Bernd (Hermes) 9be9e616d1 fix(install.sh): deploy to plugins/rocketchat/ not plugins/platforms/rocketchat/ 2026-06-22 17:40:25 +02:00
Bernd (Hermes) bc7b05d768 fix(adapter): _MULTIROOM from module-level constant to runtime function 2026-06-22 13:26:38 +02:00
Bernd (Hermes) 6f47885b1c fix(install.sh): numpy, circular import, room-map.json, archivar symlink in hermes root
FIX 1: numpy/faiss-cpu pip install in venv nach Plugin-Deployment
       in allen drei Pfaden (perform_update, perform_update_only,
       main interactive). Archivar braucht diese Packages für
       FAISS Phase-1 RoomIndex — ohne sie crasht der Import.

FIX 2: Zirkelimport adapter.py ↔ archivar/adapter_integration.py
       gebrochen. _room_context/_room_context_lock werden jetzt
       lazy innerhalb handle_feedback_response() importiert.

FIX 3: Minimale room-map.json (version=1, rooms={}) wird als
       Template bereitgestellt und bei Clean-Install ins
       Datenverzeichnis kopiert. RC-Skill-Onboarding erstellt
       die vollständige, maschinen-spezifische Version.

FIX 4: Archivar-Symlink liegt bereits korrekt im HERMES_DIR
       (Commit 5c8026c). Keine Änderung nötig.
2026-06-22 12:47:50 +02:00
Bernd (Hermes) 572bc89205 fix(adapter): move same-room check before _THEMATIC_TARGET_ROOM.set() 2026-06-22 12:05:20 +02:00
Bernd (Hermes) 54de0d1b69 fix(adapter): prevent move-request when target room equals origin room 2026-06-22 11:59:11 +02:00
Bernd (Hermes) 868ee153ac docs(install.sh): add resource warning before multi-room prompt 2026-06-22 11:46:55 +02:00
Bernd (Hermes) 40563864ac fix(install.sh): correct systemd unit + MULTIROOM_AGENT interactive prompt (default N) 2026-06-22 11:45:04 +02:00
Bernd (Hermes) 5c8026c0f0 fix(install.sh): create archivar symlink for core plugin loader 2026-06-22 11:21:23 +02:00
Bernd (Hermes) 52dd470e00 debug: add Archivar trace logging to identify classify_and_route blocker 2026-06-22 10:32:12 +02:00
Bernd (Hermes) a442e42b4e feat: MULTIROOM_AGENT env switch for single-room mode 2026-06-22 10:12:07 +02:00
Bernd (Hermes) 4d6fae6bf7 fix(archivar): is_stale()-Check in initialize() — FAISS-Index erkennt Keyword-Updates in room-map.json
P45-Fix: Nach load() wird is_stale() geprüft. Wenn die RoomMap-Version
neuer ist als der gespeicherte Index, wird automatisch rebuild + save
ausgeführt. Verhindert, dass Keyword-Änderungen in room-map.json erst
nach manuellem Löschen der .faiss/.meta-Dateien wirken.
2026-06-21 08:06:17 +02:00
Bernd (Hermes) cd7fae1ad0 chore: move test scripts to scripts/ directory (rebuild_index, smoke_test_booster, smoke_test_faiss) 2026-06-20 17:00:10 +02:00
Bernd (Hermes) ba2ba33616 fix(adapter): _room_context + _room_context_lock vor Archivar-Import definieren
Zirkulärer Import: adapter.py → adapter_integration.py → adapter.py.
_room_context und _room_context_lock fehlten komplett in adapter.py,
adapter_integration.py versuchte sie zu importieren → ImportError.

Fix: _room_context (Dict) + _room_context_lock (threading.Lock) VOR
dem ArchivarMessageHandler-Import definieren. Behebt P17-Altlast
(ContextVar→global dict war nie ins Repo zurückportiert).

Deployment-Pfad braucht zusätzlich relative Imports (.archivar.),
weil Gateway Plugins als flache Module lädt (Pattern D4).
2026-06-20 16:39:36 +02:00
Bernd (Hermes) 5abab32d0f fix(install.sh): systemctl --user enable hermes-gateway in allen drei Start-Pfaden
Gateway startete nach Reboot nicht automatisch, weil install.sh nur
stop+start ausführte, aber den Service nie enabled hat.

Fix: systemctl --user enable hermes-gateway in perform_update(),
perform_update_only() und main script — jeweils nach reset-failed,
vor stop. enable ist idempotent, daher bei jedem Durchlauf sicher.

Root Cause: hermes gateway install installiert die Unit, aber ob es
sie enabled ist unklar. Explizites enable stellt Autostart sicher.

Review: Rainer (Session 20260620_155910_6559a0)
Patch: Don (Session 20260620_155930_3dce08)
2026-06-20 16:00:10 +02:00
Bernd (Hermes) 8e7dfa5ccb curate(keywords): T7-Fix — reverse-proxy/traefik/n8n von keywords_100 → keywords_context (Smoke-Test R11-R19 Erkenntnis) 2026-06-20 14:50:29 +02:00
Bernd (Hermes) 658f1ba8a0 fix(adapter): exponential backoff retry for 429 rate-limit on chat.postMessage 2026-06-19 23:12:48 +02:00
Bernd (Hermes) 1ad9155a24 fix(config): use ARCHIVAR_EMBEDDING_BASE_URL for embeddings — separate from OLLAMA_BASE_URL (chat) 2026-06-19 21:08:36 +02:00
Bernd (Hermes) 4596ffba2a perf(config): increase LLM timeout 10s→30s — iterative binary search optimization 2026-06-19 21:06:11 +02:00
Bernd (Hermes) 2599a574e1 fix(classifier): wrap sync generate() in asyncio.to_thread() — remove broken await on non-coroutine 2026-06-19 19:53:59 +02:00
Bernd (Hermes) ac1751e9ce debug(adapter): enable DEBUG logging + DDP health check for 24h stability test 2026-06-19 19:31:00 +02:00
Bernd (Hermes) 34087299e8 fix(adapter): remove last 2 relative imports — use top-level sys.modules access 2026-06-19 17:44:04 +02:00
Bernd (Hermes) 0e13e4b30d fix(archivar): ContextVar→global dict, asyncio.to_thread, EMBEDDING_BASE_URL, FAISS_AUTO_ROUTE=0.55
- adapter.py: ContextVars durch globales _room_context dict + threading.Lock ersetzt
  (Agent-Task sieht jetzt Archivar-Zielraum — kein error-not-allowed mehr)
- adapter_integration.py: Stay-Feedback-Handler leert thematic_target
  (verhindert dass nächster Send auf alten Archivar-Vorschlag fällt)
- classifier.py: _llm_raw() nutzt asyncio.to_thread() statt direktem await
  (LLMClient.generate() ist synchron — vorher TypeError)
- config.py: ARCHIVAR_EMBEDDING_BASE_URL trennt Embeddings von Chat-URL
  (OLLAMA_BASE_URL-Kollision behoben). FAISS_AUTO_ROUTE 0.70→0.55
  (mehr Nachrichten durch Booster statt direktem FAISS-Routing)
2026-06-19 09:09:17 +02:00
Bernd (Hermes) d005eb769d feat(archivar): Booster-Gewichtung verstärkt — FAISS + Keywords
Booster-Strategie: IMMER aktiv (nicht nur bei Konflikten)
- router.py: Konfliktbedingung entfernt, Booster auf alle FAISS-Treffer
- booster.py: Boost +0.05→+0.10, zusätzlich +0.05 pro weiterem unique Keyword
- config.py: FAISS_AUTO_ROUTE 0.85→0.70

Kombiniert semantische Breite (FAISS) mit präziser Keyword-Diskriminierung.
Ziel: granulare Raum-Entscheidungen bei überlappenden Themen.
2026-06-18 07:55:14 +02:00
Bernd (Hermes) 97d59f5272 feat(room_index): weave seed_data messages into FAISS embedding text
Strategie B: _room_to_text() webt kuratierte seed_data-Messages
in den Embedding-Text ein, um FAISS-Similarity zu schärfen.

Änderungen:
- room_index.py: import SEED_DATA, _room_to_text() erweitert
  um Seed-Message-Einwebung (nur für Räume mit SEED_DATA-Eintrag)
- test_room_index.py: MockEmbeddingClient auf Keyword-Zählung
  umgestellt (statt binär any()) — verhindert Cross-Contamination
  durch längere Embedding-Texte mit Seed-Messages

Tests: 35/35 passed (22 booster + 13 room_index)
2026-06-18 07:27:34 +02:00
Bernd (Hermes) 60665c5fd4 feat(archivar): 200-Wort-Raumbeschreibungen für FAISS Phase-1
room-map.json v3:
- Neues 'description'-Feld (~200 Wörter) für alle 4 Nicht-Catch-All-Räume
- BAT-Team: Trading-Plattform, Docker, Next.js, Prisma, Wyckoff
- Rocketchat-Plugin: DDP/WebSocket, Archivar, Gateway, Buttons
- LAN-Dokumentation: Homelab, Proxmox, Subnetze, VLAN, pfSense
- Protonbridge-Plugin: IMAP/SMTP-Proxy, Himalaya, Bridge

room_map.py:
- RoomEntry.description als optionales Feld (default '')
- _from_dict, save, add_or_update_room, Legacy-Migration aktualisiert

room_index.py:
- _room_to_text(): description prioritär, theme als Fallback
- Keywords weiterhin doppelt gewichtet im Embedding-Text

room-map.schema.json:
- description als optional string (minLength 50)
- version minimum auf 3

FAISS-Neubau via is_stale() nach Version-Bump automatisch
2026-06-18 06:31:11 +02:00
Bernd (Hermes) 8d6deb7f2d feat(archivar): RoutingWiderspruchDetector — textbasierte Widerspruch-Erkennung
NEUES MODUL: plugin/archivar/feedback_detector.py
- RoutingWiderspruchDetector mit 4 Regex-Gruppen (Hauptmuster, Umrouting,
  Verneinung, Befehle)
- ContradictionResult dataclass: has_contradiction, contradiction_type,
  confidence, target_room, rejected_room, matched_pattern
- Edge Cases: 'nicht in X, sondern in Y' → X negativ, Y als Ziel
- Kein LLM-Fallback (nur Regex in v1)

EINHAENGUNG adapter_integration.py:
- ArchivarMessageHandler.__init__(): self._feedback_detector
- detect_routing_contradiction(text, origin_room_id) → ContradictionResult|None
- Bei Treffer: update_keyword_weight(feedback_type='never')
- _resolve_room_name_to_id() für Raum-Name → room_id Auflösung

EINHAENGUNG adapter.py:
- _process_incoming(): VOR classify_and_route() → contradiction-Check
- Bei Treffer: Decision überschreiben (stay_in_room=True)
- [WIDERSPRUCH]-Präfix — Nachricht NICHT schlucken, normal an Agent
- NUR wenn KEIN Button-Feedback aktiv (kein pending move-request)

Tests: 57/58 passed (1 pre-existing env-var failure unverändert)
2026-06-18 06:21:24 +02:00
Bernd (Hermes) 3fe2dd832e fix(archivar): correct Coroutine-Bug root cause — _llm_raw_sync→async _llm_raw, direct await
OllamaLLMClient.generate() is async def — run_in_executor cannot
correctly execute async functions. The coroutine was never awaited.

Also fix Move-Request parser: native button '1️⃣ Rüber' was not
matched against '1️⃣' — fell through to 'stay' instead of 'move'.

- classifier.py: _llm_raw_sync → async _llm_raw, await generate()
- router.py: remove run_in_executor, direct await _llm_raw()
- adapter.py: normalize MOVE_REQ choice (extract leading digit/emoji)
2026-06-17 22:01:45 +02:00
Bernd (Hermes) 27b117e151 fix(adapter): BUTTON_CLICK lost-context fallback — retry as TEXT after gateway restart 2026-06-17 21:38:22 +02:00
Bernd (Hermes) c590b8a53a fix(archivar): replace asyncio.to_thread with run_in_executor in _llm_room_lookup 2026-06-17 20:21:29 +02:00
Bernd (Hermes) ea96ebbde7 fix(archivar): Multi-Request-Resilienz — threading.Lock, asyncio.Semaphore, Catch-All-Schutz + try/except 2026-06-17 07:54:12 +02:00
Bernd (Hermes) a3875f5fbf fix: Silent Copy setzt _CURRENT_ORIGIN_ROOM auf Zielraum statt Ursprungsraum
Bei Auto-Route Silent Copy (Typ 1, kein Move-Request) wurde die
Notiz im Ursprungsraum gesendet, aber _CURRENT_ORIGIN_ROOM blieb auf
dem Ursprungsraum — der Agent antwortete dann fälschlich dort.

Fix: Nach der Silent Copy _CURRENT_ORIGIN_ROOM auf decision.target_room
setzen und forwarded=True, damit der Fallback in Zeile 927-928
übersprungen wird. Der Agent antwortet jetzt im Zielraum.
2026-06-16 21:28:07 +02:00
Bernd (Hermes) 7776e26fb2 FAISS index persistence: load() before build_index(), save() after build
- initialize() now tries load() from disk first
- If load succeeds: log 'Index von Disk geladen' + wire router
- If load fails: build_index() + save() + log 'Index gebaut + gespeichert' + wire router
- Eliminates unnecessary index rebuild on every gateway restart
- All 58 tests pass
2026-06-16 21:07:37 +02:00
Bernd (Hermes) d54c9a8896 fix(archivar): add StreamHandler to adapter_integration logger
setLevel(INFO) alone was not enough — without a handler and with
propagate=True (default), logs were accepted by the root logger
(level WARNING) but silently discarded since root has no handlers.

Now matches adapter.py pattern: StreamHandler + propagate=False,
so all submodule logs (classifier, router, room_index, booster)
are visible via the shared parent logger.
2026-06-16 20:42:01 +02:00
Bernd (Hermes) 0b4ff2169e fix(archivar): set logger level to INFO in adapter_integration.py
Root logger defaults to WARNING (level 30) when no basicConfig is set.
adapter_integration.py only called getLogger(__name__) without setLevel,
so all INFO logs were silently filtered. adapter.py already had its own
setLevel(INFO) + handler, which is why its logs appeared.

Fix: add logger.setLevel(logging.INFO) after getLogger(__name__) at line 94.
This restores all suppressed INFO logs:
- Initializing ArchivarMessageHandler...
- FAISS Phase-1: RoomIndexManager + KeywordBooster ready
- FAISS Phase-1: Index built
- FAISS Phase-1: Router wired
- ArchivarMessageHandler ready
2026-06-16 20:38:50 +02:00
Bernd (Hermes) 03d3bb44df BUGFIX: FAISS Phase-1 TypeError float+str in adapter_integration.py:292
Root cause: RoomIndexManager.stats() returns a dict with mixed types
(bool, int, float, str). sum() iterated over all values and crashed
when hitting built_at_iso (str) after built_at (float).

Fix: Replace stats() call with direct .size and .room_ids properties.
Also commit FAISS Phase-1 files (booster.py, room_index.py, seed_data.py)
that were deployed to Gateway but not yet in repo.

Tests: 58 passed (0 failures)
2026-06-16 20:31:57 +02:00
Bernd (Hermes) 43d14b2d58 fix(archivar): FAISS Phase-1 Integration — RoomIndexManager + KeywordBooster in ArchivarMessageHandler verdrahtet
- __init__: RoomIndexManager(room_map, embedding_client) + KeywordBooster(room_map)
- initialize(): build_index() aus Seed-Daten, Router mit FAISS-Objekten neu erstellen
- Fallback: bei Fehler → None → bestehendes LLM-Verhalten
2026-06-16 19:58:15 +02:00
Bernd (Hermes) 4fff5980c7 F4-Tests: Archivar v5 Quality Gate — Cold-Start, Rebuild, Boost, Konfliktlösung
4 kritische Pfade (Rainer):
  F4.1 Cold-Start: Leerer FAISS-Index → search() raises RoomIndexError
  F4.2 Rebuild: seed_data-Räume → build_index() → search() findet korrekten Raum
  F4.3 Boost: Eindeutiges Keyword +0.05, mehrdeutiges neutral
  F4.4 Konfliktlösung: Top-2 Diff < 0.03 → mehr unique keywords gewinnt +0.02

Mock-FAISS-Index (MockIndexFlatIP) — faiss-cpu muss NICHT installiert sein.
Mock-EmbeddingClient — deterministische Vektoren, keine echten Ollama-Calls.
35 Tests, alle grün (0.23s).
2026-06-16 19:31:24 +02:00
Bernd (Hermes) 134c21a218 feat(archivar): FAISS Phase-1 Router-Integration
config.py:
- FAISS_AUTO_ROUTE (0.85): Direkt-Routing-Schwelle ohne LLM
- FAISS_MIN_SCORE (0.50): Minimaler Treffer-Score
- FAISS_TOP_K (3): Top-Treffer aus dem Index
- FAISS_CONFLICT_DIFF (0.05): Booster-Aktivierungsschwelle

router.py:
- RoutingDecision: 5 neue FAISS-Felder (faiss_score, faiss_room_id,
  faiss_room_name, is_faiss_routed, booster_applied)
- BidirectionalRouter.__init__: optionale room_index + booster Parameter
  (None = Phase-1 übersprungen, bestehendes Verhalten)
- route(): Schritt 3.5 FAISS Phase-1 zwischen Keyword-Match und
  Embedding-Vorfilter eingefügt
  - search_text() → Booster bei knappen Top-2 → Auto-Route bei >= 0.85
  - Score < 0.85 → Fall-through zu Embedding + LLM (unverändert)
- Drei-Schichten-Logik: FAISS → Keyword-Booster → LLM
- Bestehender LLM/Embedding-Code unverändert
2026-06-16 19:18:36 +02:00
Bernd (Hermes) 1f7054eab8 fix(adapter): CLARIFY-Exklusion in Button-Detection — False-Positive BUTTON_CLICK bei CLARIFY-Antworten 2026-06-16 05:18:49 +02:00
Bernd (Hermes) a1fc4cc9b5 fix(onboarding): globale Button-Actions skip_all/later erkennen 2026-06-15 20:32:18 +02:00
Bernd (Hermes) aa50857193 fix(ux): Onboarding-Buttons — blaue Nummern statt Text-Labels (12→6 Buttons)
Pro Raum: EIN blauer Nummern-Button (1️⃣, 2️⃣, …) via style='primary'
Globale Buttons: ⏭️ Alle überspringen, ⏰ Später
Payload: ONBOARD:<rid>::select, ONBOARD::skip_all, ONBOARD::later

UX-Fix: Rocket.Chat UI hat feste Button-Breite — 12 Buttons
(4 Räume × 3 Aktionen) wurden auf 1 Buchstabe gekürzt.
6 Buttons (4 Nummern + 2 global) passen ohne Truncation.
2026-06-15 20:24:23 +02:00
Bernd (Hermes) 00d6ca4e75 fix(archivar): Hardcodierte Pfade durch ROOM_MAP_PATH/DEFAULT_MAP_PATH ersetzt
check_room_map_completeness() und _load_room_map() verwendeten
hardcodierte Pfade (~/.hermes/hermes-agent/data/room-map.json)
statt der Konstanten ROOM_MAP_PATH/DEFAULT_MAP_PATH.

Das führte dazu, dass Unit-Tests die produktive room-map.json
überschrieben — der Mock-Patch auf ROOM_MAP_PATH griff nicht,
weil save() und reload() den hardcodierten Pfad verwendeten.

Fix:
- adapter_integration.py: 2 hardcodierte Pfade → ROOM_MAP_PATH
- room_map.py: Doppelte DEFAULT_MAP_PATH-Zuweisung entfernt
2026-06-15 20:07:05 +02:00
Bernd (Hermes) 92697b5fff fix(test): ROOM_MAP_PATH-Patch in setUp/tearDown statt Decorator 2026-06-15 20:06:06 +02:00
Bernd (Hermes) 948666fcdd fix(archivar): Timeout-Fallback auf Ursprungsraum + Keyword-Matching vor LLM
Drei Routing-Bug-Fixes basierend auf Analyse des Timeout-Falls vom 15.06.2026:

FIX 1 (KRITISCH): Timeout-Fallback auf Ursprungsraum statt Catch-All
- _llm_room_lookup() gibt jetzt (RoomEntry|None, bool) zurück
- bool=True signalisiert LLM-Aufruf-Fehler (Exception/Timeout)
- Bei LLM-Fehler: stay_in_room=True, is_catch_all=False
- Nur bei explizitem CATCH_ALL vom LLM: catch_all-Raum als Ziel

FIX 2: Keyword-Matching vor LLM-Aufruf (Embedding+Keyword-Fallback)
- Nach Embedding-Vorfilter: wenn work_order mit conf < 0.9
- find_room_by_keywords() aufrufen, bei Match direkt zurückgeben
- Verhindert unnötige LLM-Calls für klare Keyword-Matches

FIX 3: find_room_by_keywords() verbessert
- keywords_100-Matches: nicht erster Treffer, sondern Raum mit
  den MEISTEN 100%-Matches gewinnt (best_100_score)
- keywords_context bleibt Fallback wenn kein 100%-Match existiert

Tests: 57/58 passed (1 pre-existing env-var failure)
2026-06-15 19:43:43 +02:00
Bernd (Hermes) 2eb723fb63 feat(archivar): Auto-Onboarding v2 — strukturiertes 4-Fragen-Interview pro Raum
Ersetzt den v1-Text-Flow ('Name = Thema') durch ein strukturiertes
Interview mit 4 Fragen pro fehlendem Raum:

1. theme — 'Worum geht es in diesem Raum? (1–2 Sätze)'
2. keywords_100 — 'Welche Begriffe treffen SICHER zu? (Sofort-Match)'
3. keywords_context — 'Welche Begriffe deuten auf das Thema hin? (Kontext-Match)'
4. catch_all — 'Soll dieser Raum der Catch-All sein? (Ja/Nein)'

Änderungen:
- adapter.py: _start_onboarding() sendet Buttons pro Raum
  [Projektraum einrichten] [Überspringen] [Später]
- adapter.py: _onboarding_state dict steuert Interview-Phasen
- adapter.py: _process_onboarding_response() verarbeitet Button-Klicks
  (ONBOARD:<room_id>::<action>) und Text-Antworten auf die 4 Fragen
- adapter.py: _ask_onboarding_question(), _onboarding_next_room(),
  _finish_onboarding() für den strukturierten Ablauf
- adapter.py: _process_incoming() erkennt ONBOARD:-Prefix und
  prüft Operator-Raum-Zugehörigkeit
- room_map.py: RoomMap.save() mit fcntl.flock File-Lock gegen
  parallele Schreibzugriffe
- room_map.py: add_or_update_room() akzeptiert keywords_100 und
  keywords_context getrennt (v2-Schema)
- room-map.schema.json: version minimum=2, keywords→keywords_100
  + keywords_context
- room-map.json: generische Platzhalter (öffentliches Repo)
- Tests: 4 neue v2-Tests (keyword-Trennung, File-Lock, reload,
  Single-Room v2-Felder), bestehende Tests auf v2-Schema migriert

Invarianten erhalten: Single-Room-Regel, DM-Ignorierung,
onboarding_active-Flag, kein Dauer-Check.
2026-06-15 19:39:04 +02:00
Bernd (Hermes) 6e02a12431 fix(archivar): Kontext-Reset — _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen
Bug: DM ohne Routing nach einem Projektraum-Turn → alte
_THEMATIC_TARGET_ROOM klebt → Antwort im falschen Raum.

Fix: _THEMATIC_TARGET_ROOM.set('') zu Beginn jeder neuen Nachricht
in _process_incoming(). Der Archivar setzt sie dann neu — oder sie
bleibt leer (DM, Smalltalk, Catch-All).

Erkannt 20:21 durch Andreas: Tagesabschluss-Anfrage im DM,
Antwort landete in #Rocketchat-Plugin (vorheriger Turn).
2026-06-14 20:30:31 +02:00
Bernd (Hermes) b05b1ab1ec feat(archivar): Vierter Baustein — Agent-Antwortziel via Archivar-Kontext
Option C (Adapter routet Antwort automatisch um):
Priority 0 im Virtual→Real Room Translation: Wenn _THEMATIC_TARGET_ROOM
gesetzt ist und vom Ursprungsraum abweicht, geht die Antwort dorthin.

Null Core-Impact, +8 Zeilen in adapter.py, kein Prompt-Cache-Break.
Der Agent antwortet wie bisher — der Adapter lenkt um.

Flow: Agent sendet Antwort → Adapter prüft _THEMATIC_TARGET_ROOM →
gesetzt? → Zielraum. Sonst → _CURRENT_ORIGIN_ROOM (wie bisher).
2026-06-14 19:41:19 +02:00
Bernd (Hermes) 48fb292fe0 fix(install.sh): Deployment-Pipeline mit 3 Guards gehärtet
Guard 1 — Syntax-Check VOR Deployment:
  python3 -m py_compile für alle .py-Dateien im plugin/-Ordner.
  Bei SyntaxError → Abbruch mit Meldung.

Guard 2 — Vollständigkeits-Check NACH Deployment:
  diff zwischen plugin/-Ordner und Zielpfad.
  Fehlende Dateien → Abbruch mit Liste.

Guard 3 — Pycache-Löschung NACH Deployment:
  find -name '__pycache__' -delete + find -name '*.pyc' -delete.
  Verhindert Stale-Bytecode-Falle.

Alle 3 Guards in deploy_plugin_files() integriert.
2026-06-14 19:40:17 +02:00
Bernd (Hermes) 1f7d09a7fd fix(archivar): Timeout-Fallback zeigt Raumliste für Agent-Autonomie
Wenn der Archivar-LLM-Call timed out, erhält der Agent jetzt die
Liste aller subscribed Projekt-Räume im Prompt:
  [Frage N, Timeout — Räume: #BAT-Team, #Rocketchat-Plugin, ...]

Damit kann der Agent selbstständig entscheiden, in welchen Raum
eine Frage gehört — auch ohne Archivar-Ergebnis. Erfüllt die
Auftraggeber-Vision: 'Antwortet der Archivar nach dem Timeout
nicht, entscheidet der Agent selbst, auch wenn es Token kostet.'
2026-06-14 19:26:58 +02:00
Bernd (Hermes) c6b82cc33c fix: remove duplicate global _question_counter in TimeoutError handler 2026-06-14 18:35:56 +02:00
Bernd (Hermes) 80842a365e fix(archivar): Move-Request-Zielraum an _CURRENT_ORIGIN_ROOM übergeben
ZWEI-PUNKT-FIX (Miguel):

1. adapter_integration.py (Zeile 458-466):
   _send_move_request() übergibt jetzt _move_request-Payload an
   den Button-Send-Callback — mit target_room, target_name, text.

2. adapter.py _send_archivar_buttons (Zeile 978-1004):
   Erkennt den _move_request-Payload, befüllt _pending_move_requests,
   verwendet MOVE_REQ:: Separator für korrektes Button-Parsing.

3. adapter.py Move-Request-Handler (Zeile 739):
   Akzeptiert 'confirm_move' und '✅ja' als Routing-Trigger.

Flow: Archivar v4 → _send_move_request → _send_archivar_buttons
→ _pending_move_requests gesetzt → ✅Ja-Button → Response-Handler
findet pending request → _CURRENT_ORIGIN_ROOM auf Zielraum gesetzt ✓
2026-06-14 16:14:48 +02:00
Bernd (Hermes) 186308c983 fix(archivar): Timeouts auf 10s erhöht — empirisch ermittelt (Ø 2.4s, Cold-Start 7.8s) 2026-06-14 15:47:28 +02:00
Bernd (Hermes) 44121da702 docs: Archivar v4 — README + Community Post aktualisiert
- Archivar v3 → v4: LLM-basierter Raum-Router statt IntentClassifier
- 2-stage pipeline: Embedding pre-filter + LLM room router
- Keywords as anchors, zero DeepSeek tokens for routing
- 10s timeout, CATCH_ALL fallback, Butler principle
- Operating stage log dokumentiert
2026-06-14 13:59:22 +02:00
Bernd (Hermes) 170f7e6096 feat(archivar): LLM-basierter Raum-Router ersetzt IntentClassifier — Embedding-Vorfilter + LLM_ROOM_PROMPT + Move-Request-Buttons
Korrigierter Archivar-Routing-Flow gemäß Architekturskizze:

1. Embedding-Vorfilter (nomic-embed-text): binär Smalltalk vs. potenzieller Auftrag
   - Klarer Smalltalk → stay_in_room
   - Unsicher → LLM-Raum-Router

2. LLM-Raum-Router (qwen2.5:7b): LLM_ROOM_PROMPT als zentraler Prompt
   - Erhält Nachrichtentext + Raumliste mit IDs und ALLEN Keywords
   - Liefert room_id direkt (keine Kategorien, kein Name-Matching)

3. Move-Request-Buttons (Butler-Prinzip): ✅Ja/📍Hier VOR Routing
   - Kein automatisches Routing ohne User-Bestätigung

4. Betriebsstufen-Log: 'Archivar Stufe 1: Embedding-Vorfilter + LLM-Raum-Router aktiv (5 Räume)'

Änderungen:
- config.py: LLM_ROOM_PROMPT auf Raum-ID-Ausgabe umgestellt, Keywords pro Raum,
  ARCHIVAR_STUFE_LOG, MOVE_REQUEST_TEMPLATE, max_tokens=30
- classifier.py: LLMClient.generate() als neue ABC-Methode + OllamaLLMClient-Impl,
  _llm_raw_sync nutzt generate() statt classify()
- router.py: RoutingDecision um move_request_sent/target_name/target_id erweitert,
  route() komplett neu: Embedding→LLM→Move-Request, _llm_room_lookup() mit IDs+Keywords
- adapter_integration.py: _send_move_request() + handle_move_request_response(),
  classify_and_route() behandelt move_request_sent, handle_and_forward() wartet auf Bestätigung

IntentClassifier.classify() wird NICHT gelöscht — nur als binärer Vorfilter verwendet.
Bestehende Tests: 53/54 grün (1 pre-existing env-var issue).
2026-06-14 10:25:33 +02:00
Hermes Agent 0a7702475f docs: Archivar-Lernsystem Nutzer-Anleitung — Move-Request + Clarify verständlich erklärt 2026-06-13 10:05:19 +02:00
Hermes Agent 4bb1ccbc82 feat(archivar): Lernsystem-Verdrahtung — Move-Request + Clarify lernen Keyword-Gewichte
- RoutingDecision um matched_keywords-Feld erweitert (router.py)
- _extract_routing_keywords-Stub entfernt, Keywords aus Decision durchreichen (adapter_integration.py)
- _routed_messages nach classify_and_route() befüllen (adapter.py)
- move_req-Dict um message_id erweitert (adapter.py)
- Move-Request-Handler: handle_feedback_response mit confirm/stay/never aufrufen (adapter.py)
- handle_clarification_response: update_keyword_weight für ambige Keywords lernen (adapter_integration.py)
- Clarify-Frage-Text: "Ich möchte mir das für die Zukunft richtig merken..." (config.py)

Feedback-Mapping: 1️⃣ Rüber=confirm, 2️⃣ Hier=stay, 3️⃣ Nein=never, 📝/💬=stay, 📋=confirm
2026-06-13 09:50:54 +02:00
Hermes Agent f27de836dc chore(archivar): Test an Single-Room-Regel angepasst, room-map.json auf v2 aktualisiert, Model-Check-Architecture-Skizze 2026-06-13 05:55:33 +02:00
Hermes Agent 2b53537638 fix(adapter): stay_in_room vom Router respektieren
Bug: Der Router setzte stay_in_room=True (excluded_rooms, Meta-Fragen,
Keyword-Match auf Ursprungsraum), aber der Adapter ignorierte das Flag.
Er prüfte nur target_room != room_id → routete trotzdem.

Symptom: 'Die RC Beschreibung klingt toll' aus #Rocketchat-Plugin
löste Move-Request aus, obwohl:
- excluded_rooms → stay_in_room=True
- 'RC' matcht keywords_100 'rc' → Ziel = Ursprungsraum

Fix: Eine Zeile in der Routing-Bedingung:
  and not getattr(decision, 'stay_in_room', False)

Jetzt respektiert der Adapter, wenn der Router sagt 'bleib hier'.
2026-06-12 20:43:45 +02:00
Hermes Agent 6b97ccfad9 feat(archivar): Selbstlernendes Keyword-Gewicht-System (Teil 2)
- KeywordWeightEntry + ManualOverride Dataclasses in archivar_state.py
- Lernalgorithmus: confirm (+0.1), stay (-0.05), never (0.0+sticky)
- Promotion: 3 confirmations + weight ≥0.85 → keywords_100
- Degradation + zeitbasierte Abwertung (Decay: 30d -10%, 90d -30%)
- Cold-Start: Bootstrap Tag 1-7 (LR=0.2), Tag 8+ (LR=0.1)
- Gewichtetes Scoring in find_room_by_keywords()
- Feedback-Schleife in adapter_integration.py nach Move-Request-Auflösung
- 54 Tests grün (inkl. 8 neue für gewichtetes Scoring)
2026-06-12 19:57:46 +02:00
Hermes Agent 9177c99088 docs(archivar): Vertiefte Architekturskizze — selbstlernendes Keyword-Gewicht-System (Teil 2)
- Präziser Lernalgorithmus mit gedämpfter Lernrate (0.1)
- Drei Feedback-Typen: ✅Ja (+0.1), 📍Hier (-0.05), 📌Generell (0.0+Sticky)
- Promotion-Schwelle: 3 Bestätigungen + Gewicht ≥0.85
- Degradation + zeitbasierte Abwertung (Decay)
- JSON-Schema für keyword_weights in archivar_state.json
- Cold-Start: Bootstrap-Strategie (Tag 1-7: 0.2, danach 0.1)
- Manuelle Overrides mit Vorrang
2026-06-12 19:31:46 +02:00
Hermes Agent 017dc2b69c feat(archivar): Zweistufiges Keyword-Evidenz-System — 100% + context 2026-06-12 19:30:27 +02:00
Hermes Agent 53dd436a86 feat(archivar): Origin-Priorität im Keyword-Matcher + Architekturskizzen
- room_map.py: find_room_by_keywords() prüft zuerst Ursprungsraum (Origin-First)
- router.py: reicht origin_room_id an Keyword-Matcher durch
- docs/keyword-matcher-origin-priority.md: Architekturskizze (Rainer)
- docs/move-request-button-ux.md: Architekturskizze Button-UX (Rainer)
- docs/keyword-evidence-system.md: Architekturskizze Evidenz-System (Rainer)
2026-06-12 19:25:36 +02:00
Hermes Agent 281c2af9dd fix(room-map): RC-Plugin-Keywords von 5 auf 13 erweitert
Problem: Keyword-Matcher (min_score=2) fand keine Matches für
Nachrichten wie 'Projekt-Sync RC-Plugin' oder 'Gateway-Ausfall'.
Nur 'rc' matchte → Score 1 < Threshold 2 → Catch-All.

Neue Keywords: plugin, gateway, adapter, deployment, install.sh,
button, sync, hermes — decken jetzt alle typischen Plugin-Themen ab.

Score-Beispiele nach Fix:
- 'Projekt-Sync RC-Plugin abgeschlossen' → rc(1) + sync(1) + plugin(1) = 3 ✅
- 'Gateway-Ausfall Analyse' → gateway(1) + rc(0) = 1 ⚠️ (braucht 'plugin' im Text)
- 'install.sh Deployment-Pfad' → install.sh(1) + deployment(1) = 2 ✅
2026-06-12 18:11:43 +02:00
Hermes Agent 7e6e9fb15d fix(adapter): Move-Request Button-UX — erklärender Text vor Buttons 2026-06-12 17:52:37 +02:00
Hermes Agent 53ffcf9b4d fix(install.sh): Verifikation prüft gateway_state.json statt Journal-Grep
Problem: Journal-Grep suchte nur nach 'rocketchat.*connected' —
wenn Telegram die einzige Plattform war (Discovery-Bug), galt
die Verifikation trotzdem als erfolgreich.

Fix: python3 liest gateway_state.json und prüft BEIDE Plattformen:
rocketchat=connected UND telegram=connected. Erst dann gilt
der Gateway-Start als erfolgreich.

Robuster als Journal-Grep: state.json ist die Ground Truth,
nicht Log-Zeilen die fehlen können.
2026-06-12 17:30:23 +02:00
Hermes Agent 213831757a fix(install.sh): State-Cleanup vor Gateway-Restart in allen drei Pfaden
Problem: systemctl restart hing in 'deactivating' (Gateway-Drain bis 60s).
Der neue Prozess startete nie — deployter Code war nicht aktiv.

Fix in allen drei Restart-Pfaden (--update-only, --update, Erstinstallation):
1. State-Cleanup: gateway_state.json + .lock + .tmp löschen
   → verhindert Discovery-Bug (Platform-Verlust nach SIGTERM)
   → verhindert Auto-Resume-Crash-Loop
2. reset-failed: systemd-Failure-Counter zurücksetzen
3. stop + wait (bis 60s): Gateway sauber stoppen vor Neustart
4. start: Gateway frisch starten (statt restart)

Verify-Timeout von 15s auf 60s erhöht (Gateway braucht länger nach Cleanup).
Verify-Pattern erweitert: 'rocketchat.*connected' + '✓ rocketchat connected'
2026-06-12 08:33:21 +02:00
Hermes Agent 6eda62b94c docs: README + Community-Post komplett überarbeitet
README.md (13026 bytes):
- Archivar v3 dokumentiert (3-stage classifier, User-Flow C, Button-Garantie)
- Move-Request mit nativen Buttons (✅Ja/📍Hier/📌Generell)
- Auto-Onboarding, FAKT→Obsidian, Sticky Rooms
- Deployment-Pfad-Klärung (~/.hermes/... vs /usr/local/lib/...)
- Troubleshooting um 5 neue Einträge erweitert (Discovery Bug, __pycache__,
  install.sh path mismatch, Button-Text-Fallback, ENOTFOUND https)
- Button-Garantie als eigenes Feature hervorgehoben

COMMUNITY_POST.md (6857 bytes) — NEU:
- Use-Case-getriebener Community-Beitrag (DevOps, Personal Assistant, PM)
- Button-Garantie als Alleinstellungsmerkmal
- FAQ-Sektion (SaaS, Multi-User, Permissions, Gateway-Restarts)
- Quick-Start mit install.sh
2026-06-12 08:30:32 +02:00
Hermes Agent 6348578678 fix(adapter): Move-Request auf native Action-Buttons umgestellt
- Move-Request sendet jetzt native RC Buttons (✅Ja, 📍Hier, 📌Generell)
  statt nummerierter Textoptionen — Button-Garantie eingehalten
- Response-Handler erkennt MOVE_REQ:room_id::choice Payloads
- Fallback auf Textoptionen bei Button-Send-Fehler
- Altes numerisches Format (1/2/3) weiterhin unterstützt
2026-06-12 07:29:26 +02:00
Hermes Agent a261c771fc fix(archivar): wire button_send_callback — Archivar now sends native RC buttons
ArchivarMessageHandler was initialized without button_send_callback,
so every clarification request fell back to text-only ('Antworte mit
einer Zahl: 1 = Ja...'). Added _send_archivar_buttons() method that
translates Archivar button format into native Rocket.Chat Action-Buttons
with msg_in_chat_window=True. Also marks room in _rooms_with_pending_questions
so the response stays in the same room.
2026-06-12 07:24:57 +02:00
Hermes Agent c23127c9c5 fix(archivar): sync __init__.py barrel imports + test_router.py to v3 class names
- __init__.py: MessageClassifier→IntentClassifier, MessageRouter→BidirectionalRouter, CONFIDENCE_THRESHOLD→CONFIDENCE_THRESHOLDS, added ROOM_MAP_PATH, ARCHIVAR_STATE_PATH, ArchivarState
- config.py: added missing ROOM_MAP_PATH constant (imported by router.py)
- test_router.py: updated imports + BidirectionalRouter(state=ArchivarState()) constructor

Root cause: Miguel's v3 refactoring renamed classes but didn't update the barrel file. Gateway failed with 'No adapter available for rocketchat' because archivar/__init__.py imported non-existent names.
2026-06-11 22:25:35 +02:00
Hermes Agent 58749914fc feat(archivar): Add Q-Gate Code-Review for Archivar v3 implementation 2026-06-11 21:49:35 +02:00
Hermes Agent dba856ffab feat(archivar): Implement Button-Garantie und ArchivarState-Integration für Archivar v3 2026-06-11 21:44:38 +02:00
Hermes Agent b11c2c9fe7 feat(archivar): Implement bidirektionales Routing für Archivar v3 2026-06-11 21:42:26 +02:00
Hermes Agent 87f95b818f feat(archivar): Implement Persistenz-Layer (archivar_state.py) für Archivar v3 2026-06-11 21:40:44 +02:00
Hermes Agent 5e8e9c9a9c feat(archivar): Implement Intent-Erkenner und Confidence-Framework für Archivar v3 2026-06-11 21:40:21 +02:00
Hermes Agent 92bdb396a9 feat(archivar): Update config.py für Archivar v3 - Neue CATEGORY_TEXTS, Intent-Typen und Konfiguration 2026-06-11 21:39:21 +02:00
Hermes Agent 50e7639aec Add Archivar v3 architecture sketch - Complete architecture reset with new intent-based classification, bidirectional routing, confidence framework, persistence layer, and button guarantee 2026-06-11 21:37:16 +02:00
Hermes Agent 43ef3e6a91 fix(adapter): Button-Detection False-Positive — :: in Text matched Normalsprache
'::' in text (Zeile 571) klassifizierte JEDE Nachricht mit :: als
BUTTON_CLICK — z.B. Andreas' ':: Ich brauche den Wetterbericht'.
Der Agent sah die Nachricht nie → keine Antwort trotz grünem Status.

Fix: text.split('::', 1)[0].strip() != '' — erkennt nur echte
Button-Payloads (wo vor :: tatsächlich Inhalt steht wie CLARIFY:id).
':: Nachricht' → split[0] ist leer → kein Button → MessageType.TEXT.

Root Cause: Ein 3-Zeilen-ODER-Detector, der drei Payload-Formate
in einer Variable vermischt. Fragil weil Substring-Match.
2026-06-09 21:56:46 +02:00
Hermes Agent e7e6b66ba2 fix(adapter): CLARIFY-Trennzeichen-Bug — :: vs : zwischen clarify_id und choice
_build_custom_buttons() sendet Payloads mit :: (Doppel-Doppelpunkt),
aber _process_incoming() splittete mit text.split(':', 2) → choice=':1'
→ ':1'.isdigit()=False → Clarify nie resolved → Gateway Timeout.

Fix: Zweistufiger Split — erst '::' prüfen (neues Format),
dann ':' als Fallback (Other-Button). Beide Formate werden erkannt:
- CLARIFY:id::1 (numerischer Button)
- CLARIFY:id:other (Other-Button)

Architektur: Rainer | Implementierung: Miguel | QG: Rainer F1-F5 bestanden
2026-06-09 21:32:07 +02:00
Hermes Agent b21a8bec19 feat(archivar): zweistufige Keyword-Optimierung mit min_score=2
- find_room_by_keywords() mit min_score Parameter (default=2)
  Nur wenn best_score >= min_score → Raum returned, sonst None
  → Router fällt zu Embedding/LLM-Klassifikator durch
- verhindert Fehlrouting bei einzelnen Keyword-Treffern (plugin, etc.)

Architektur: Rainer | Implementierung: Miguel | QG: Rainer F1-F5 bestanden
2026-06-09 21:13:27 +02:00
Hermes Agent 2fe574cf71 feat(rc-adapter): native clarify buttons via REST attachments
Render clarify prompts with Rocket.Chat action buttons instead of
fallback text lists ('Reply with the number'). Full flow:

send_clarify():
- choices non-empty: builds RC buttons via _build_custom_buttons(),
  one per choice + '✏️ Other' button
- clarify_id encoded as CLARIFY:{id}:{idx} or CLARIFY:{id}:other
- stores clarify_id→session_key in _clarify_state
- fallback to super().send_clarify() on empty choices or REST failure

_process_incoming():
- intercepts DDP messages starting with 'CLARIFY:'
- 'other' token → mark_awaiting_text() for text capture
- numeric token → resolve_gateway_clarify() with choice text
- returns immediately (no agent routing) for button clicks

__init__:
- adds self._clarify_state dict for session key mapping
2026-06-09 20:55:18 +02:00
Hermes Agent 09c327b5a1 fix(archivar): integrate '::' into bypass branch, not Archivar call
The uncommitted diff from 06.06. had a bug: '::' (button response
marker) was placed in the wrong elif branch, routing it through the
Archivar instead of bypassing it.

Fixed: '::' detection moved into the top-level bypass condition alongside
is_button_response and _rooms_with_pending_questions. The dead
'elif room_type == d and is_auftrag' guard removed (redundant — DM
orders never reach this branch). Last elif promoted to else.
2026-06-09 16:13:14 +02:00
Hermes Agent 0f8dc06f15 fix(archivar): echte Rocket.Chat Action-Buttons statt numerischer Optionen
Der Adapter kann schon lange Buttons (send() parst [[BUTTONS:custom]] seit
Monaten). Move-Requests nutzten trotzdem nur numerische Text-Optionen.

Jetzt: _build_custom_buttons() direkt im Move-Request-Flow. Rocket.Chat
Action-Buttons [Ja, rüberkopieren] [Hier bleiben] [Generell hier bleiben]
— klickbar, keine Zahlen, kein Kontext-Verlust.
2026-06-08 19:06:35 +02:00
Hermes Agent ffb7cafff6 fix(archivar): Move-Request NICHT returnen — Originaltext an Agent durchreichen
Kritischer Bug: Nach 'Hier bleiben'/'Generell hier bleiben' wurde return
aufgerufen → der Original-Auftragstext ging verloren, nur '3' erreichte
den Agenten → Agent antwortete verwirrt.

Jetzt: Originaltext aus move_req['text'] wiederherstellen, skip_archivar=True
setzen, als normale Nachricht durchreichen. Der Agent verarbeitet den Auftrag
normal weiter — der User hat nur das Routing entschieden.
2026-06-08 16:05:55 +02:00
Hermes Agent 62c996c4da fix(archivar): Move-Request vor Archivar, room-basiert, numerische Antworten
Drei kritische Bugs behoben:
1. Move-Request-Prüfung VOR Archivar-Klassifikation — '3' wurde vorher als
   thematische Frage ins Catch-All kopiert, jetzt wird die Antwort erkannt
2. _pending_move_requests von msg_id auf room_id umgestellt — jede Antwort
   mit neuer msg_id schlug vorher fehl
3. Numerische Antworten (1/2/3) werden jetzt direkt erkannt, nicht nur
   Text-Matches ('rüberkopieren'/'hier bleiben'/'generell')
2026-06-08 15:53:51 +02:00
Hermes Agent f47ffc93f4 fix(archivar): Raum-Name-Fallback + nummerierte Optionen statt Buttons
- Bug 1: 'Zielraum' als Platzhalter → jetzt 3-Stufen-Fallback (matched_room_name → room_info → room_map → ID-Fragment)
- Bug 2: Native Buttons existieren nicht im Adapter → nummerierte Text-Optionen (1/2/3)
2026-06-08 14:32:31 +02:00
Hermes Agent e7ed81c189 fix: send() method structure — restore button-parsing + REST-post code that fell out of method body
The send() method in adapter.py had a structural defect where the
button-parsing, template-handling, and rest.post_message code (98 lines)
was at module level instead of inside the send() method body.

send() ended after room-resolution without a return statement, causing
it to return None. _send_with_retry() in base.py then crashed with
AttributeError: 'NoneType' object has no attribute 'success'.

This made every Rocket.Chat response silently fail — the agent
processed messages but could never deliver replies.

Fix: moved the orphaned code block back into the send() method body
where it belongs, after the room-resolution logic and before
_find_fallback_room_for_user.
2026-06-08 11:33:59 +02:00
Hermes Agent 83a5d262c7 fix: User-Map-Fallback + LLM-Prompt-Fix
- User-Map: Fallback aus DM-Namen-Parsing + REST-API-Abfrage wenn usernames-Feld fehlt (Rainer)
- LLM: max_tokens 10→5, Prompt verschärft auf Ein-Wort-Antwort (Raum-Name oder CATCH_ALL)
- Keine Erklärungen, keine Sätze — der Validator akzeptiert jetzt alle Antworten
- Vault-Doku: Rocket.Chat Plugin.md aktualisiert (User-Flow C, Bugfixes)
2026-06-08 07:40:04 +02:00
Hermes Agent af56280ebc fix(archivar): User-Flow C — Antwort bleibt im Ursprungsraum, Nachricht wird kopiert
DM-Aufträge werden nie geroutet. Bei thematischen Fragen: Silent Copy.
Bei Aufträgen: Buttons [Ja, rüberkopieren] [Hier bleiben] [Generell hier bleiben].

Architektur-Skizze: docs/archivar-user-flow-c.md
2026-06-08 06:44:40 +02:00
Hermes Agent 5e9c4ece77 fix(adapter): button clicks bypass Archivar routing
Button responses (`is_button_response`) are ALWAYS direct replies to an agent
question and carry a `question_id::choice` payload. Routing them through the
Archivar risked landing a one-character "A" in the catch-all room where the
agent would see it without the original question context.

Now button clicks skip `classify_and_route()` entirely and stay in whatever
room they originated from.
2026-06-06 20:43:36 +02:00
Hermes Agent ad852c1642 fix(archivar): doc_store writes to fact_store_path from room_map
DocumentationStore() now uses RoomMap.fact_store_path instead of the
hardcoded ~/.hermes/.../archivar_docs default. One-line change — the
doc_store is initialized after _load_room_map() so room_map is available.

This allows per-deployment configuration: in production, fact_store_path
points to /data/Wissensdatenbank/0100 Inbox so FAKT messages land in the
Obsidian vault's inbox for StartObsidian integration.
2026-06-06 20:32:13 +02:00
Hermes Agent 7140da3154 feat(onboarding): catch-all change via numeric answer, generic example
- Trigger now catches 'Name = Thema', '#Name', 'Raum:', digits, skip words
- After onboarding: numbered room list with Catch-All marker
- User can change Catch-All by replying with room number
- 'überspringen'/'skip' keeps current Catch-All
- Example text is generic (not project-specific): 'Projektraum = Entwicklung, ...'
2026-06-06 20:03:04 +02:00
Hermes Agent 72e8c8cb90 fix(onboarding): generic example, numbered rooms, catch-all change prompt
- Example text: 'Projektraum = Entwicklung, Code-Reviews, ...' (not project-specific)
- Onboarding prompt: numbered list (1. Raum, 2. Raum, ...)
- After completion: shows all rooms with Catch-All marker, asks if change wanted
2026-06-06 20:01:02 +02:00
Hermes Agent ddc69167c1 fix(onboarding): remove # from display to prevent RC link rendering
- Onboarding message shows room names WITHOUT # (RC auto-links them)
- Parser accepts both 'Name' and '#Name' (case-insensitive match)
- Pattern: #? makes hash optional, matching against lstrip(#)
2026-06-06 19:58:31 +02:00
Hermes Agent 7d454f62b6 fix(onboarding): parse #Name = Thema format, auto-derive keywords, fix newlines
- Parser accepts '#Name = Thema' (no 'Raum:' prefix needed)
- _derive_keywords() extracts keywords from room name + theme
- Onboarding message uses real newlines (join list, not \n literals)
- Shows actual missing room names with '=' prompt, plus example
2026-06-06 19:51:34 +02:00
Hermes Agent 8591933d8d feat(archivar): auto-onboarding — room-map completeness check after gateway start
Implements the RC-Skill's promised room-map completeness check after
Adapter.connect(). Previously the adapter subscribed to rooms but never
verified they were all present in room-map.json. New rooms were
subscribed but invisible to the Archivar router.

Scope (~450 lines, 4 files):

- adapter_integration.py: check_room_map_completeness() compares
  subscribed rooms (filtered to c/p types) against RoomMap.
  Single-Room-Regel: 1 relevant room → auto catch_all, no interview.
  onboarding_active flag in _stats prevents re-triggering.

- room_map.py: add_or_update_room() for safe in-memory mutations,
  reload() for disk-to-memory sync without gateway restart,
  static save() for atomic file writes.

- adapter.py: connect() calls check after Archivar init, triggers
  _start_onboarding() if rooms missing. _process_incoming() intercepts
  'Raum: #Name = Thema' responses during active onboarding.

- test_auto_onboarding.py: 4 unit tests covering single-room
  auto-assign, multi-room detection, DM filtering, and already-
  complete map (no action).

Deployed to production: adapter.py + archivar/*.py copied to
Auslieferungspfad. Gateway restarted — no onboarding triggered
(map already complete).
2026-06-06 19:31:46 +02:00
Hermes Agent 63e0616d7a docs(architektur): auto-onboarding skizze — single-room regel ergänzt 2026-06-06 19:18:58 +02:00
Hermes Agent 3f480d5423 chore: add __pycache__/ to gitignore 2026-06-06 19:15:39 +02:00
Hermes Agent 4d35669174 fix: prevent room-map.json overwrite + is_unrouteable handler
ROOT CAUSE: install.sh --update-only blindly deployed room-map.json
from the repo (containing 'GENERAL' as catch_all) to the production
/home/bernd/.hermes/data/ directory, overwriting the machine-specific map.

FIXES (3 changes):

1. REMOVED room-map.json from repo + added to .gitignore
   This file is machine-specific data, not source code.

2. REMOVED room-map.json deploy from install.sh (both paths):
   - Normal install block (section 3.5)
   - --update-only emergency deploy (section 3.5)
   Replaced with comment: 'MACHINE-SPECIFIC — created by RC-Skill onboarding'

3. FIX adapter.py: is_unrouteable guard on ContextVar routing
   Before: ContextVar set to target_room even when unrouteable
   Result: 'Ich antworte im Zielraum.' note appeared, but Hermes
   couldn't deliver to unsubscribed room — answer lost silently.
   After: Forward block checks not getattr(decision, 'is_unrouteable', False)
   If unrouteable → stays in origin room, answers there normally.

PRODUCTION: Correct room-map.json deployed with 4 project rooms
+ DM catch_all on .101. Excluded rooms: multi-agent DM, testbot DM.
2026-06-06 18:53:11 +02:00
Hermes Agent 024a173c8d Fix Archivar forward note bug: Use rest.post_message() instead of self.send() to ensure note appears in origin room 2026-06-06 09:11:41 +02:00
Hermes Agent e3f9ee31f4 feat(archivar): Route-Antwort in Zielraum + Notiz im Ursprungsraum 2026-06-06 08:42:11 +02:00
Hermes Agent 1fca310228 feat(archivar): use handle_and_forward() in _process_incoming
Ersetzt classify_and_route() durch handle_and_forward().
Nachrichten werden jetzt klassifiziert UND automatisch in den
Zielraum kopiert, wenn target_room != origin_room.

send_callback ist bereits im ArchivarMessageHandler-Konstruktor
gesetzt (adapter.py:416).
2026-06-06 06:33:26 +02:00
Hermes Agent c98228ef6f fix(archivar): pass origin_room_id to classify_and_route()
Ohne diesen Parameter kann der Router:
- Multi-Agent-Raum nicht ausschließen (Schritt 0)
- Herkunft nicht in LLM-Room-Lookup einbeziehen
- Keine korrekte Catch-All-Validierung durchführen

Adapter hat room_id in _process_incoming() bereits verfügbar.
2026-06-06 06:30:20 +02:00
Hermes Agent 1afa822e6f Task 5: Neuen test_router.py mit 2 Integrationstests erstellt 2026-06-06 06:14:58 +02:00
Hermes Agent 06567d3988 Task 4: test_room_map.py um 2 LLM-Lookup-Tests erweitert 2026-06-06 06:14:56 +02:00
Hermes Agent 54a19a039d Task 3: Deprecated marker für LLM_CLASSIFY_PROMPT in config.py hinzugefügt 2026-06-06 06:14:52 +02:00
Hermes Agent 527d664a07 Task 2: Logtext in adapter.py auf "Thematischer Raum-Router aktiv (room-map.json)" geändert 2026-06-06 06:14:49 +02:00
Hermes Agent 9bc06ef858 Task 1: LLM_CONFIDENCE_THRESHOLD-Zweig entfernt und durch einfaches Return des Embedding-Ergebnisses ersetzt 2026-06-06 06:14:45 +02:00
Hermes Agent 58f00c0c23 feat(archivar): Phase 1-3 — RoomMap + thematischer Router
Phase 1 (Datenmodell):
- plugin/archivar/room_map.py: RoomMap, RoomEntry, RoomMapValidationError
- room-map.schema.json: JSON-Schema für room-map.json
- room-map.json: Echte Raum-IDs (RC, BAT, LAN-Doku, DM Andreas)
- config.py: LLM_ROOM_PROMPT, ROOM_MAP_PATH, deprecated-Marker

Phase 2 (Router-Umbau):
- router.py: MessageRouter nutzt RoomMap statt ROOM_MAPPING Env-Vars
  - Neue Methode _llm_room_lookup() fragt LLM: 'In welchen Raum?'
  - Keyword-Match aus RoomEntry.keywords (vor Embedding)
  - Excluded rooms check via RoomMap.is_excluded()
  - origin_room_id Parameter für Multi-Agent-Raum-Ausschluss

Phase 3 (Integration):
- adapter_integration.py: _load_room_map() mit Env-Var-Fallback
  - validate() beim Gateway-Start
  - classify_and_route() reicht origin_room_id durch
- classifier.py: _llm_raw_sync() für Room-Prompts (nicht Kategorien)

12/12 Unit-Tests bestanden ✅
2026-06-05 22:06:32 +02:00
Hermes Agent 1bb3f52fad docs: Menschlicher Override ergänzt (Archivar-Architektur §6)
!r <raum> Reply-Mechanismus für Admin-Korrektur:
- Erkennt fehlgeleitete Nachrichten, löscht Original, verschiebt
- Lernt aus Overrides: keyword_overrides in room-map.json
- 3× gleiches Keyword-Muster → permanenter Override
- Höchste Keyword-Priorität im Datenfluss
- 5 Sicherheitsregeln (Admin-only, keine Selbst-Overrides, etc.)

Checkliste um 5 Override-Review-Punkte erweitert.
2026-06-05 21:36:02 +02:00
Hermes Agent 65a3baa3e5 docs: Architekturskizze Archivar-Umbau (Kategorien-Klassifikator → thematischer Router)
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.
2026-06-05 20:53:09 +02:00
Hermes Agent a3f67775ab docs: Archivar-Konzept — FAKT-Ablage + Gap-Analyse (3 Lücken für Rainer)
Ergänzt:
- FAKT-Ablage als Dateisystem-Pfad (kein Chat-Raum)
- Community-konfigurierbarer Ablagepfad
- Gap-Analyse um 3 konkrete Entscheidungspunkte erweitert:
  L1: Raum-Map-Format (JSON unter data/room-map.json)
  L2: Catch-All-Validierung (genau 1 Raum, Gateway-Start-Gate)
  L3: Onboarding als Gateway-Hook

Story ist jetzt gut genug für Rainer als Architekturauftrag.
2026-06-05 20:18:47 +02:00
Hermes Agent fa2a24f747 docs: Archivar-Konzept — Story, Gap-Analyse und Architekturziel
Dokumentiert das WARUM des Archivars als thematischen Router,
nicht als Kategorie-Klassifikator. Enthält:

- Multi-Room-Agent-Kommunikationsverhalten
- Raum-Map mit Catch-All als Raum-Attribut
- Multi-Agent-Raum-Ausschluss-Regel
- Onboarding-Interview für neue Räume
- Gap-Analyse: Konzept vs. aktuelle Implementierung (5 Gaps)
- LLM als Kontext-Interpreter, nicht als Kategorie-Klassifikator

Commit spiegelt die konzeptionelle Arbeit vom 05.06.2026 mit Andreas.
2026-06-05 20:03:06 +02:00
Hermes Agent be917afcbd feat(install): add --update-only emergency deploy mode
Adds '--update-only' flag for crisis deployment — no questions,
no Ollama, no config provisioning. Just find hermes dir, deploy
all plugin files, clear __pycache__, restart gateway, verify.

Flow:
  1. find_hermes_dir() → resolve correct path (6-priority cascade)
  2. create_backup() → tar.gz safety net
  3. cp plugin/ → $HERMES_DIR/plugins/platforms/rocketchat/
  4. rm -rf __pycache__
  5. systemctl restart hermes-gateway
  6. journalctl grep verification (15s timeout)

Use case: Gateway loses plugin discovery after clean shutdown.
Instead of manual cp + restart, one command: ./install.sh --update-only

Language strings added for DE + EN. Help text updated.
2026-06-05 18:00:36 +02:00
Hermes Agent a078620827 feat(plugin): plugin.yaml für Gateway-Platform-Discovery
Platform._scan_bundled_plugin_platforms() erwartet plugin.yaml im
Plattform-Verzeichnis, sonst wird Rocket.Chat nicht discovered.
Ohne dieses Manifest überlebt RC keinen kalten Gateway-Neustart.

Root cause: gateway/config.py:176-194 scannt plugins/platforms/
und filtert Verzeichnisse ohne plugin.yaml aus. War vorher kein
Problem, weil die platform_registry in-process überlebte.
2026-06-05 08:15:46 +02:00
Hermes Agent b5a43223ac fix: make install.sh executable (chmod +x) 2026-06-05 05:40:39 +02:00
Hermes Agent e5a32abf5c feat(archivar): dreistufiger Klassifikator — Keyword + Embedding + LLM (qwen2.5:7b)
Phase 3 (Miguel): 236 Zeilen in config.py, classifier.py, adapter_integration.py.
Phase 4 (Rainer): Quality Gate F1–F5 bestanden.

- Stufe 0: Keyword-Vorfilter mit erweiterten ALARM/FRAGE-Listen
- Stufe 1: Embedding (nomic-embed-text, Schwelle 0.70)
- Stufe 2: LLM-Klassifikation (qwen2.5:7b) für Grenzfälle
- Feature-Flag ARCHIVAR_ENABLE_LLM über Env-Variable
- LLMClient-Interface für Testbarkeit
- router.py unverändert (Blackbox-Integration)
2026-06-04 21:49:17 +02:00
Hermes Agent 4b2e933529 docs: Architektur-Skizze — zweistufiger Archivar-Klassifikator (Strategiegespräch 04.06.) 2026-06-04 20:11:12 +02:00
Hermes Agent f509710193 Fix find_hermes_dir(): trailing-space in Prio 2 sed, multi-PID in Prio 3 pgrep 2026-06-04 08:51:20 +02:00
Hermes Agent c2ded4ab9a Fix find_hermes_dir(): set +e vor jedem Subshell-Block um set -euo pipefail zu überleben 2026-06-04 08:48:51 +02:00
Hermes Agent 4af89ce13e Fix find_hermes_dir() Prio 5: check hermes-agent subdir when using get_hermes_home() 2026-06-04 08:44:49 +02:00
Hermes Agent 7364ae3333 Fix function order: move find_hermes_dir() before perform_update() to ensure proper definition before use 2026-06-04 08:42:10 +02:00
Hermes Agent 4ef07a14b9 fix: zielsichere HERMES_DIR-Ermittlung mit Prioritätenkaskade (Rainer/P1-P6) 2026-06-04 08:38:10 +02:00
Hermes Agent 7eac6b7dba Fix: replace find|while pipe with process substitution in perform_update() and main script
This fixes the issue where cp and mkdir in the while loop were running in a subshell
due to pipe usage, preventing proper error propagation with 'set -euo pipefail'.
Using process substitution ensures the while loop runs in the main process.
2026-06-04 08:04:03 +02:00
Hermes Agent c4775ca99e Fix update flow: git pull statt checkout, Plugin-Dateien direkt kopieren, kein ./install.sh Selbstaufruf 2026-06-04 06:25:30 +02:00
Hermes Agent d7ce3afcd0 Bugfixes für install.sh: 1) Zustandsvariable statt Exit-Code für Updates, 2) Stash-Mechanismus für git checkout mit lokalen Änderungen 2026-06-04 06:10:42 +02:00
Hermes Agent 70008660fc SKILL.md aktualisiert: FAKT→DocStore, Subscription-Validierung, DocumentationStore dokumentiert 2026-06-03 22:38:30 +02:00
Hermes Agent ccce90fdb0 FAKT ist Dokumentation, keine Kommunikation — nie in Chat-Räume routen
Vier harte Änderungen:
1. config.py: ARCHIVAR_FAKT_ROOM existiert nicht mehr. FAKT wird
   niemals in ROOM_MAPPING aufgenommen — Env-Variable obsolet.
2. router.py: FAKT-Entscheidungen werden VOR der Subscription-
   Validierung als is_unrouteable markiert. Kein if/else, kein
   Ermessensspielraum.
3. adapter_integration.py: classify_and_route() legt FAKT automatisch
   im DocumentationStore ab (existiert bereits).
4. Env-Variable ARCHIVAR_FAKT_ROOM aus systemd env.conf entfernt.

Resultat: Nur FRAGE und ALARM werden jemals in Chat-Räume geroutet.
FAKT-Nachrichten wie 'CPU-Last bei 92%' sind reine Dokumentation —
sie landen als Markdown unter data/archivar_docs/fakt/
2026-06-03 22:11:25 +02:00
Hermes Agent 886e566e77 Doc-Store: Messages in nicht abonnierte Räume werden im Filesystem abgelegt
Harte Durchsetzung: Der Archivar darf NUR in Räume routen, die der Bot
tatsächlich abonniert hat. Alles andere ist ein Architekturfehler.

Neu:
- doc_store.py: DocumentationStore — speichert unrouteable Nachrichten
  als Markdown mit YAML-Frontmatter unter data/archivar_docs/{category}/
- router.py: RoutingDecision.is_unrouteable + unrouteable_reason,
  MessageRouter.set_subscribed_room_ids(), Zielraum-Validierung
- adapter_integration.py: ArchivarMessageHandler.set_subscribed_room_ids(),
  classify_and_route() leitet bei is_unrouteable in doc_store um
- adapter.py: set_subscribed_room_ids() wird nach connect() mit den
  realen subscribed rooms gefüttert

Verhalten: Wenn jemand 'ALARM: Server down' in einem Raum schreibt,
den der Bot nicht abonniert hat, wird die Nachricht KLASSIFIZIERT,
aber NICHT geroutet — sie landet im doc_store mit Begründung.
2026-06-03 22:06:30 +02:00
Hermes Agent abe93cc2dc Arbeitspakete A+B: Hausinterne Begriffe durch generische Beispiele ersetzt
- room-topic-map.md: BAT-Team → Support-Team, Protonbridge-Plugin → Mail-Bridge-Plugin,
  andreas/Bernd → Admin, personenbezogene Namen anonymisiert
- OPTION_C_SESSION_SHARING.md: BAT-Team → Support-Team, andreas → admin
- BUTTON_GUIDE.md: rocketchat:protonbridge → rocketchat:my-room (3 Stellen)
- plugin/archivar/__init__.py: /home/bernd/ → docs/

Alle Beispiele sind jetzt generisch und unabhängig vom LLM nutzbar.
2026-06-03 21:55:22 +02:00
Hermes Agent 1c7b82e27f feat: Archivar-Universalisierung A–E — env-vars, SKILL.md, Pipeline-Integration, file-download
A: config.py auf Env-Vars umgestellt (ARCHIVAR_FAKT_ROOM, _FRAGE_ROOM, _ALARM_ROOM, _CATCHALL_ROOM, _PROJECT_ROOMS)
B: adapter.py-Kommentare von BAT-Terminologie auf generisch umgeschrieben
C: archivar/SKILL.md — Hermes-Skill-Schema mit Triggern, Architektur, Konfiguration, Pitfalls
D: classify_and_route() + send_callback in _process_incoming() integriert, chat_name mit [KATEGORIE] angereichert
E: RocketChatREST.download_file() — authentifizierter Datei-Download via X-Auth-Token, kein Security-Scanner-Trigger mehr
    _download_and_inline_files() inlined [FILE]-Inhalte direkt in den Prompt
2026-06-03 20:14:40 +02:00
Hermes Agent 7a0abc465a fix: template .env aufgeraeumt — nur OLLAMA_API_KEY, kein HERMES_API_KEY 2026-06-03 18:34:35 +02:00
Hermes Agent d01eded6ff fix: drei /API-KEY-Bugs — install.sh jetzt komplett productionsicher
Bug #12: /usr/bin/bash-Expansion im Passwort verhindert — cat <<'EOF' (single-quoted delimiter)
         + Platzhalter-Ersetzung via python3 (sed expandiert hBcZeichen in double quotes)
Bug #10: OLLAMA_BASE_URL aus rocketchat.env entfernt — überschreibt sonst Cloud-Provider-URL
Bug #11: OLLAMA_API_KEY via env var setzbar (OLLAMA_API_KEY=...) statt hartem Platzhalter
2026-06-03 17:37:13 +02:00
Hermes Agent 13a87fb233 fix: template now uses ollama-cloud as built-in provider + home_channel placeholders
Root cause: 'ollama-cloud' is a built-in Hermes provider. Putting it under
custom_providers with api_key_env broke key resolution. Built-in providers
use their own env-var conventions (OLLAMA_API_KEY, not HERMES_API_KEY).

Changes:
- template: model.provider=ollama-cloud, base_url=ollama.com/v1 (no custom_providers)
- template: gateway.platforms.rocketchat.home_channel with PLACEHOLDER vars
- install.sh: sed-replace placeholders with actual RC_URL/RC_HOME_CHANNEL
- template: .env now uses OLLAMA_API_KEY (what ollama-cloud actually reads)
- Bug #11 (export prefix in rocketchat.env) still needs push
2026-06-03 14:05:22 +02:00
Hermes Agent d6b30d8d87 fix: remove export prefix from rocketchat.env (systemd compatibility)
EnvironmentFile in systemd drop-ins parses KEY=VALUE only.
'export' prefix caused systemd to silently ignore all vars,
leaving the Gateway with 'No messaging platforms enabled'.

Bug found during .45 test run #2.
2026-06-03 12:31:15 +02:00
Hermes Agent f54f90be5b fix: provision config.yaml/.env + systemd EnvironmentFile drop-in
Fixes #9 (custom_providers missing — fresh installs had no config.yaml/.env,
so gateway had no provider to connect to) and #10 (systemd unit had no
EnvironmentFile, so gateway couldn't read rocketchat.env/.env → crash-loop).

Templates provisioned on first install only (no overwrites):
- templates/config.yaml: minimal working config with ollama-cloud provider
- templates/.env: API key placeholder
- templates/hermes-gateway-env.conf: systemd drop-in wiring rocketchat.env + .env
2026-06-03 12:24:08 +02:00
Hermes Agent bb8623aed5 fix: binary corruption in adapter.py + absolute→relative imports in archivar/
- adapter.py: recopied from production (write_file corrupted the em-dash on line 8)
- All archivar/*.py: from archivar.X → from .X for plugin-context compatibility
2026-06-03 10:17:03 +02:00
Hermes Agent e3dc543af5 fix: install.sh line 318 — don't zero out env vars before --non-interactive reads them
The local initialization RC_URL="" on line 318 was destroying
environment variables before the non-interactive block (line 330+)
could read them via ${RC_URL:-${ROCKETCHAT_BASE_URL:-}}.

Fix: use ${RC_URL:-} to preserve values already set in the environment.
2026-06-03 10:14:07 +02:00
Hermes Agent 88b7149dd1 feat: Archivar delivery + install.sh v2.2 — full function set
- Add archivar/ submodule to plugin/ (5 files, relative imports)
- Update adapter.py with relative Archivar import from .archivar.adapter_integration
- install.sh: fix --non-interactive env-var reading (Z.316-318, Bug #7)
- install.sh: recursive file copy (was 4 flat files, now entire plugin/ tree incl. submodules)
- install.sh: Ollama presence check + nomic-embed-text pull
- install.sh: write OLLAMA_BASE_URL to rocketchat.env
- install.sh: add new message keys (collama_check, nomic_pull, nomic_ok, nomic_fail, copied)

Closes: Archivar delivery gap (2026-06-03)
Reviewed-by: Bernd (Advisor)
2026-06-03 10:12:47 +02:00
Hermes Agent e6eddcd3da docs: add Troubleshooting section — absolute import pitfall (archivar) + tools import crash 2026-06-03 06:50:35 +02:00
62 changed files with 20257 additions and 328 deletions
+4
View File
@@ -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.
File diff suppressed because it is too large Load Diff
+124 -163
View File
@@ -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.*
+202 -26
View File
@@ -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
@@ -37,27 +86,42 @@ The installer will ask for:
### Options
```
./install.sh --help # Show all options
./install.sh --lang en # English
./install.sh --lang de # German (default)
./install.sh --non-interactive # Batch mode (reads from env vars)
./install.sh --help # Show all options
./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
Executable
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
#
# Hermes Rocket.Chat Plugin — Bootstrap (One-Command Installer)
# https://gitea.thomander.de/andreas/Hermes_rocket.chat_Plugin
#
# Usage (fresh VM, no repo cloned yet):
# curl -sSL https://192.168.180.47/Andreas/Hermes_rocket.chat_Plugin/raw/branch/main/bootstrap.sh | bash
#
# Or locally:
# ./bootstrap.sh [install.sh arguments...]
#
# What this does:
# 1. ssh-keyscan: ensures Gitea host key is in known_hosts (M12 fix)
# 2. git clone: clones the plugin repo (SSH → HTTP fallback)
# 3. exec: hands off to install.sh with all arguments preserved
#
set -euo pipefail
GITEA_HOST="192.168.180.47"
GITEA_PORT="222"
REPO_PATH="Andreas/Hermes_rocket.chat_Plugin"
CLONE_TARGET="$HOME/Hermes_rocket.chat_Plugin"
# ── Step 1: ssh-keyscan (M12 — muss VOR git clone laufen) ──
echo "🔑 Ensuring Gitea host key is in known_hosts..."
mkdir -p "$HOME/.ssh"
chmod 700 "$HOME/.ssh"
if ! grep -q "${GITEA_HOST}" "$HOME/.ssh/known_hosts" 2>/dev/null; then
ssh-keyscan -p "${GITEA_PORT}" "${GITEA_HOST}" >> "$HOME/.ssh/known_hosts" 2>/dev/null || {
echo "⚠️ ssh-keyscan failed — git clone via SSH may fail, HTTP fallback will be used"
}
echo " Host key added."
else
echo " Host key already present."
fi
# ── Step 2: Clone repo (falls nicht vorhanden) ──
if [ -d "$CLONE_TARGET/.git" ] && [ -d "$CLONE_TARGET/plugin" ]; then
echo "✅ Repo already present at $CLONE_TARGET"
elif [ -d "$CLONE_TARGET/.git" ]; then
echo "⚠️ Broken clone detected — removing and re-cloning..."
rm -rf "$CLONE_TARGET"
fi
if [ ! -d "$CLONE_TARGET/.git" ]; then
echo "📦 Cloning plugin repo..."
SSH_URL="git@${GITEA_HOST}:${REPO_PATH}.git"
HTTP_URL="https://${GITEA_HOST}/${REPO_PATH}.git"
if git clone "$SSH_URL" "$CLONE_TARGET" 2>/dev/null; then
echo "✅ Clone via SSH successful"
elif git clone "$HTTP_URL" "$CLONE_TARGET" 2>/dev/null; then
echo "✅ Clone via HTTP (fallback) successful"
else
echo "❌ Clone failed — SSH key for Gitea (${GITEA_HOST}:${GITEA_PORT}) or HTTP access required"
echo " Manual: git clone $SSH_URL $CLONE_TARGET"
exit 1
fi
fi
# ── Step 3: Hand off to install.sh ──
echo "🚀 Starting install.sh..."
exec "$CLONE_TARGET/install.sh" "$@"
+3 -3
View File
@@ -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",
+5 -5
View File
@@ -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
+446
View File
@@ -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?
+273
View File
@@ -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.
+107
View File
@@ -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.
+278
View File
@@ -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
+224
View File
@@ -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
+144
View File
@@ -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
+212
View File
@@ -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
+55
View File
@@ -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
+296
View File
@@ -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
+43
View File
@@ -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.
+109
View File
@@ -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
View File
@@ -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
+1016 -50
View File
File diff suppressed because it is too large Load Diff
+9 -2
View File
@@ -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
+2282 -50
View File
File diff suppressed because it is too large Load Diff
+107
View File
@@ -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 |
+38
View File
@@ -0,0 +1,38 @@
"""
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
from .conversation_history import ConversationHistory, MessageEntry
__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",
"ConversationHistory",
"MessageEntry",
]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+227
View File
@@ -0,0 +1,227 @@
"""
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()
def cleanup_orphaned_rooms(self, valid_room_ids: set) -> int:
"""M13: Bereinigt das Keyword-Mapping für gelöschte Räume.
Baut das interne ``_keyword_to_rooms``-Mapping komplett neu aus
der aktuellen RoomMap. Da die RoomMap bereits durch M13 bereinigt
wurde, enthält das neue Mapping nur noch gültige Räume.
Args:
valid_room_ids: Set von Raum-IDs, die behalten werden sollen
(wird für Konsistenz-Logging verwendet, die eigentliche
Bereinigung erfolgt durch Neuaufbau aus der RoomMap).
Returns:
Anzahl der Keywords im neuen Mapping (0 wenn keine Räume übrig).
"""
before = len(self._keyword_to_rooms)
self._build_mapping()
after = len(self._keyword_to_rooms)
if before != after:
logger.info(
"KeywordBooster GC: mapping rebuilt — %d → %d keywords "
"(%d orphaned keyword entries removed)",
before, after, before - after,
)
return after
+717
View File
@@ -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)
+265
View File
@@ -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.
+237
View File
@@ -0,0 +1,237 @@
"""
ConversationHistory — Ring-Buffer für Konversationshistorie pro Raum.
Sub-Feature B5v6.5: Blocker für V7-3 (Verfall) und V7-4 (rekursive Einleitungen).
Speichert die letzten N=10 Nachrichten pro Raum als In-Memory Ring-Buffer.
Thread-safe via asyncio.Lock. Nicht persistent — nach Neustart beginnt
die Historie neu (akzeptiert von Andreas: 'jetzt' verblasst ohnehin).
Usage::
history = ConversationHistory(max_size=10)
history.add("room-123", "user", "Was ist der Status?")
history.add("room-123", "agent", "Alles grün.")
recent = history.get("room-123") # → letzte 10 Nachrichten
history.set_topic_hint("room-123", "Deployment-Status")
hint = history.get_topic_hint("room-123") # → "Deployment-Status"
"""
from __future__ import annotations
import asyncio
import logging
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
@dataclass
class MessageEntry:
"""Ein einzelner Eintrag im Ring-Buffer."""
role: str
"""'user' oder 'agent'."""
text: str
"""Nachrichtentext."""
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
"""Zeitstempel der Nachricht (UTC)."""
def to_dict(self) -> Dict[str, Any]:
"""Serialisiere für externe Nutzung (z.B. Prompt-Bau)."""
return {
"role": self.role,
"text": self.text,
"timestamp": self.timestamp.isoformat(),
}
class ConversationHistory:
"""Ring-Buffer für Konversationshistorie pro Raum.
Thread-safe via asyncio.Lock. In-Memory, nicht persistent.
"""
def __init__(self, max_size: int = 10) -> None:
"""Initialisiere den Ring-Buffer.
Args:
max_size: Maximale Anzahl Nachrichten pro Raum (default: 10).
"""
if max_size < 1:
raise ValueError(f"max_size must be >= 1, got {max_size}")
self._max_size = max_size
self._lock = asyncio.Lock()
# room_id → deque[MessageEntry] (maxlen=self._max_size)
self._buffers: Dict[str, deque[MessageEntry]] = {}
# room_id → topic string
self._topic_hints: Dict[str, str] = {}
# ── Public API ──────────────────────────────────────────────────────
async def add(
self,
room_id: str,
role: str,
text: str,
timestamp: Optional[datetime] = None,
) -> None:
"""Füge eine Nachricht zum Ring-Buffer hinzu.
Wenn der Buffer voll ist (max_size erreicht), fällt die älteste
Nachricht automatisch heraus (deque mit maxlen).
Args:
room_id: Rocket.Chat Raum-ID.
role: 'user' oder 'agent'.
text: Nachrichtentext.
timestamp: Optionaler Zeitstempel (default: jetzt UTC).
"""
if not room_id:
return
if not text or not text.strip():
return
entry = MessageEntry(
role=role,
text=text.strip(),
timestamp=timestamp or datetime.now(timezone.utc),
)
async with self._lock:
if room_id not in self._buffers:
self._buffers[room_id] = deque(maxlen=self._max_size)
self._buffers[room_id].append(entry)
async def get(
self,
room_id: str,
limit: Optional[int] = None,
) -> List[Dict[str, Any]]:
"""Liefere die letzten N Nachrichten für einen Raum.
Args:
room_id: Rocket.Chat Raum-ID.
limit: Maximale Anzahl zurückzugebender Nachrichten.
None oder > max_size → alle im Buffer (max max_size).
Returns:
Liste von dicts mit 'role', 'text', 'timestamp' (ISO-Format),
neueste zuletzt. Leere Liste wenn Raum nicht existiert.
"""
async with self._lock:
buf = self._buffers.get(room_id)
if buf is None:
return []
entries = list(buf)
if limit is not None and limit < len(entries):
entries = entries[-limit:]
return [e.to_dict() for e in entries]
async def get_topic_hint(self, room_id: str) -> Optional[str]:
"""Liefere das letzte bekannte Thema für einen Raum.
Args:
room_id: Rocket.Chat Raum-ID.
Returns:
Thema-String oder None wenn kein Thema gesetzt.
"""
async with self._lock:
return self._topic_hints.get(room_id)
async def set_topic_hint(self, room_id: str, topic: str) -> None:
"""Setze das Thema für einen Raum.
Wird vom Router gesetzt, wenn das LLM ein Thema erkennt.
Überschreibt ein vorheriges Thema.
Args:
room_id: Rocket.Chat Raum-ID.
topic: Thema-String (z.B. 'Deployment-Status').
"""
if not room_id or not topic:
return
async with self._lock:
self._topic_hints[room_id] = topic.strip()
logger.debug(
"Topic hint set for room %s: %s",
room_id[:8],
topic[:60],
)
async def clear(self, room_id: str) -> None:
"""Lösche die Historie für einen Raum (M13 GC).
Args:
room_id: Rocket.Chat Raum-ID.
"""
async with self._lock:
self._buffers.pop(room_id, None)
self._topic_hints.pop(room_id, None)
logger.debug("Conversation history cleared for room %s", room_id[:8])
async def cleanup_orphaned_rooms(self, active_room_ids: set) -> int:
"""Entferne Räume, die nicht mehr aktiv sind (M13 GC).
Thread-safe via asyncio.Lock.
Args:
active_room_ids: Set von Raum-IDs, die noch aktiv sind
(aus room-map.json nach M13-Bereinigung).
Returns:
Anzahl der entfernten Räume.
"""
async with self._lock:
return self.cleanup_orphaned_rooms_sync(active_room_ids)
def cleanup_orphaned_rooms_sync(self, active_room_ids: set) -> int:
"""Sync-Variante für M13 GC (Startup, kein Concurrent-Access).
Args:
active_room_ids: Set von Raum-IDs, die noch aktiv sind.
Returns:
Anzahl der entfernten Räume.
"""
orphaned = [
rid
for rid in self._buffers
if rid not in active_room_ids
]
for rid in orphaned:
del self._buffers[rid]
self._topic_hints.pop(rid, None)
if orphaned:
logger.info(
"ConversationHistory GC: %d orphaned rooms removed (%d remaining)",
len(orphaned),
len(self._buffers),
)
return len(orphaned)
# ── Utility ─────────────────────────────────────────────────────────
@property
def max_size(self) -> int:
"""Maximale Anzahl Nachrichten pro Raum."""
return self._max_size
@property
def room_count(self) -> int:
"""Anzahl der Räume mit Historie (nicht thread-safe, für Debug)."""
return len(self._buffers)
async def get_room_count(self) -> int:
"""Thread-safe: Anzahl der Räume mit Historie."""
async with self._lock:
return len(self._buffers)
+133
View File
@@ -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
+232
View File
@@ -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
+75
View File
@@ -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
}
+630
View File
@@ -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),
}
+642
View File
@@ -0,0 +1,642 @@
"""
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,
butler_mode: str = "cognitive",
) -> 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
self._butler_mode = butler_mode # Fix C v7: 'cognitive' | 'strict' | 'off'
# ── 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
@property
def butler_mode(self) -> str:
"""Fix C v7: Butler-Mode - 'cognitive', 'strict', or 'off'."""
return self._butler_mode
def set_butler_mode(self, mode: str) -> None:
"""Fix C v7: Setze den Butler-Mode und persistiere.
Args:
mode: 'cognitive', 'strict', or 'off'.
"""
if mode not in ("cognitive", "strict", "off"):
raise ValueError(f"Invalid butler_mode: {mode}")
self._butler_mode = mode
# ── 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 is_100_percent_match(self, text: str, room: RoomEntry) -> bool:
"""Check if *text* contains any 100%-evidence keywords for *room*.
Returns True if at least one keywords_100 entry matches (case-insensitive).
Used by the router to distinguish 100% keyword matches (auto-route, no Butler)
from context keyword matches (Butler asks, learning opportunity).
"""
text_lower = text.lower()
return any(kw.lower() in text_lower for kw in room.keywords_100)
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
# Version erhöhen, damit is_stale() im FAISS-Index erkennt,
# dass die RoomMap geändert wurde und der Index neu gebaut werden muss.
self._version += 1
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
self._butler_mode = new_map._butler_mode # Fix C v7
@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),
"butler_mode": room_map._butler_mode, # Fix C v7
}
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"))
)
butler_mode = data.get("butler_mode", "cognitive") # Fix C v7
return cls(
rooms=rooms,
excluded_room_ids=excluded,
fact_store_path=fact_store,
version=version,
butler_mode=butler_mode,
)
# ── 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"),
}
File diff suppressed because it is too large Load Diff
+134
View File
@@ -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,499 @@
"""
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()
# ═══════════════════════════════════════════════════════════════════════════
# M13: cleanup_orphaned_rooms Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestArchivarStateCleanup(unittest.TestCase):
"""M13: Tests für cleanup_orphaned_rooms()."""
def setUp(self):
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):
if os.path.exists(self.state_file_path):
os.unlink(self.state_file_path)
def _seed_state(self):
"""Befüllt den State mit Testdaten für 3 Räume."""
now = datetime.now().isoformat()
# Room states
self.state._rooms = {
"room_keep": type('RoomState', (), {
'stay_decision': 'always',
'decided_at': now,
'decided_by': 'andreas',
})(),
"room_orphan": type('RoomState', (), {
'stay_decision': 'never_route',
'decided_at': now,
'decided_by': 'andreas',
})(),
}
# Keyword weights
self.state._keyword_weights = {
"plugin": {
"room_keep": KeywordWeightEntry(
weight=0.8, last_updated=now,
confirmation_count=3, rejection_count=0,
last_confirmation=now,
),
"room_orphan": KeywordWeightEntry(
weight=0.5, last_updated=now,
confirmation_count=1, rejection_count=0,
last_confirmation=None,
),
},
"docker": {
"room_orphan": KeywordWeightEntry(
weight=0.7, last_updated=now,
confirmation_count=2, rejection_count=0,
last_confirmation=now,
),
},
}
# Sticky keywords
self.state._sticky_keywords = {
"plugin": ["room_orphan", "room_keep"],
"docker": ["room_orphan"],
}
# Manual overrides
self.state._manual_overrides = {
"plugin": {
"room_orphan": ManualOverride(
override_weight=0.9,
override_reason="test",
override_date=now,
override_by="admin",
),
},
}
# Promotion candidates
self.state._promotion_candidates = {
"plugin": {
"room_orphan": {"score": 3.8, "last_updated": now},
"room_keep": {"score": 4.2, "last_updated": now},
},
}
def test_cleanup_removes_orphaned_room_state(self):
"""Room state für orphaned Raum wird entfernt."""
self._seed_state()
self.assertIn("room_orphan", self.state._rooms)
self.assertIn("room_keep", self.state._rooms)
removed = self.state.cleanup_orphaned_rooms({"room_keep"})
self.assertGreater(removed, 0)
self.assertNotIn("room_orphan", self.state._rooms)
self.assertIn("room_keep", self.state._rooms)
def test_cleanup_removes_orphaned_keyword_weights(self):
"""Keyword weights für orphaned Raum werden entfernt."""
self._seed_state()
self.state.cleanup_orphaned_rooms({"room_keep"})
# "plugin" hat nur noch room_keep
self.assertIn("plugin", self.state._keyword_weights)
self.assertIn("room_keep", self.state._keyword_weights["plugin"])
self.assertNotIn("room_orphan", self.state._keyword_weights["plugin"])
# "docker" hatte NUR room_orphan → ganzes Keyword gelöscht
self.assertNotIn("docker", self.state._keyword_weights)
def test_cleanup_removes_orphaned_sticky_keywords(self):
"""Sticky keywords für orphaned Raum werden entfernt."""
self._seed_state()
self.state.cleanup_orphaned_rooms({"room_keep"})
# "plugin" sticky: room_orphan entfernt, room_keep bleibt
self.assertIn("plugin", self.state._sticky_keywords)
self.assertEqual(self.state._sticky_keywords["plugin"], ["room_keep"])
# "docker" sticky: nur room_orphan → ganzes Keyword gelöscht
self.assertNotIn("docker", self.state._sticky_keywords)
def test_cleanup_removes_orphaned_manual_overrides(self):
"""Manual overrides für orphaned Raum werden entfernt."""
self._seed_state()
self.state.cleanup_orphaned_rooms({"room_keep"})
# "plugin" override: nur room_orphan → ganzes Keyword gelöscht
self.assertNotIn("plugin", self.state._manual_overrides)
def test_cleanup_removes_orphaned_promotion_candidates(self):
"""Promotion candidates für orphaned Raum werden entfernt."""
self._seed_state()
self.state.cleanup_orphaned_rooms({"room_keep"})
# "plugin" promotion: room_orphan entfernt, room_keep bleibt
self.assertIn("plugin", self.state._promotion_candidates)
self.assertIn("room_keep", self.state._promotion_candidates["plugin"])
self.assertNotIn("room_orphan", self.state._promotion_candidates["plugin"])
def test_cleanup_no_orphans_returns_zero(self):
"""Keine verwaisten Räume → removed=0, State unverändert."""
self._seed_state()
removed = self.state.cleanup_orphaned_rooms({"room_keep", "room_orphan"})
self.assertEqual(removed, 0)
self.assertIn("room_orphan", self.state._rooms)
self.assertIn("room_keep", self.state._rooms)
def test_cleanup_empty_state_no_error(self):
"""Leerer State → cleanup_orphaned_rooms() wirft keinen Fehler."""
removed = self.state.cleanup_orphaned_rooms({"room_keep"})
self.assertEqual(removed, 0)
def test_cleanup_persists_to_disk(self):
"""Nach cleanup_orphaned_rooms() ist der bereinigte State auf Disk."""
self._seed_state()
self.state.cleanup_orphaned_rooms({"room_keep"})
# Reload von Disk
new_state = ArchivarState(self.state_file_path)
new_state.load()
self.assertNotIn("room_orphan", new_state._rooms)
self.assertIn("room_keep", new_state._rooms)
self.assertNotIn("docker", new_state._keyword_weights)
@@ -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()
+206
View File
@@ -0,0 +1,206 @@
"""
Fix C v7: Butler-Mode Tests — cognitive, strict, off.
Tests für:
- RoomMap.butler_mode property + set_butler_mode()
- RoomMap.save/load/reload mit butler_mode
- Router._resolve_move_request() für alle drei Modi
- Router-Integration: move_request_sent je nach Butler-Mode
- Onboarding: butler_mode Phase
"""
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from room_map import RoomMap, RoomEntry
class TestButlerModeRoomMap(unittest.TestCase):
"""Fix C v7: RoomMap butler_mode Tests."""
def setUp(self):
self.temp_file = tempfile.NamedTemporaryFile(
delete=False, suffix='.json'
)
self.temp_file.close()
self.map_path = Path(self.temp_file.name)
def tearDown(self):
if self.map_path.exists():
self.map_path.unlink(missing_ok=True)
def _write_map(self, butler_mode="cognitive"):
data = {
"version": 1,
"rooms": {
"r1": {
"name": "#Test",
"theme": "test",
"keywords_100": ["test"],
"keywords_context": [],
"catch_all": True,
}
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
"butler_mode": butler_mode,
}
with open(self.map_path, "w") as f:
json.dump(data, f)
def test_default_butler_mode_is_cognitive(self):
"""Default butler_mode ist 'cognitive'."""
rm = RoomMap(rooms={}, excluded_room_ids=set(),
fact_store_path=Path("/tmp"))
self.assertEqual(rm.butler_mode, "cognitive")
def test_load_butler_mode_cognitive(self):
"""butler_mode 'cognitive' wird korrekt geladen."""
self._write_map("cognitive")
rm = RoomMap.load(self.map_path)
self.assertEqual(rm.butler_mode, "cognitive")
def test_load_butler_mode_strict(self):
"""butler_mode 'strict' wird korrekt geladen."""
self._write_map("strict")
rm = RoomMap.load(self.map_path)
self.assertEqual(rm.butler_mode, "strict")
def test_load_butler_mode_off(self):
"""butler_mode 'off' wird korrekt geladen."""
self._write_map("off")
rm = RoomMap.load(self.map_path)
self.assertEqual(rm.butler_mode, "off")
def test_load_missing_butler_mode_defaults_to_cognitive(self):
"""Fehlendes butler_mode-Feld → default 'cognitive'."""
data = {
"version": 1,
"rooms": {
"r1": {
"name": "#Test",
"theme": "test",
"keywords_100": ["test"],
"keywords_context": [],
"catch_all": True,
}
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
with open(self.map_path, "w") as f:
json.dump(data, f)
rm = RoomMap.load(self.map_path)
self.assertEqual(rm.butler_mode, "cognitive")
def test_set_butler_mode_valid(self):
"""set_butler_mode mit gültigen Werten."""
rm = RoomMap(rooms={}, excluded_room_ids=set(),
fact_store_path=Path("/tmp"))
rm.set_butler_mode("strict")
self.assertEqual(rm.butler_mode, "strict")
rm.set_butler_mode("off")
self.assertEqual(rm.butler_mode, "off")
rm.set_butler_mode("cognitive")
self.assertEqual(rm.butler_mode, "cognitive")
def test_set_butler_mode_invalid_raises(self):
"""set_butler_mode mit ungültigem Wert → ValueError."""
rm = RoomMap(rooms={}, excluded_room_ids=set(),
fact_store_path=Path("/tmp"))
with self.assertRaises(ValueError):
rm.set_butler_mode("invalid")
def test_save_persists_butler_mode(self):
"""RoomMap.save() persistiert butler_mode."""
self._write_map("strict")
rm = RoomMap.load(self.map_path)
rm.set_butler_mode("off")
RoomMap.save(rm, self.map_path)
# Reload und prüfen
rm2 = RoomMap.load(self.map_path)
self.assertEqual(rm2.butler_mode, "off")
def test_reload_updates_butler_mode(self):
"""RoomMap.reload() aktualisiert butler_mode."""
self._write_map("cognitive")
rm = RoomMap.load(self.map_path)
self.assertEqual(rm.butler_mode, "cognitive")
# Datei ändern
self._write_map("strict")
rm.reload(self.map_path)
self.assertEqual(rm.butler_mode, "strict")
# ── Router-Integration Tests ──────────────────────────────────────────────
class TestButlerModeRouter(unittest.TestCase):
"""Fix C v7: Router._resolve_move_request() Tests."""
def setUp(self):
from room_map import RoomMap, RoomEntry
self.room_map = RoomMap(
rooms={
"r1": RoomEntry(
room_id="r1", name="#Test", theme="test",
keywords_100=["test"], keywords_context=[],
catch_all=True,
)
},
excluded_room_ids=set(),
fact_store_path=Path("/tmp"),
butler_mode="cognitive",
)
def _make_router(self, butler_mode="cognitive"):
# Use the same import pattern as test_router.py
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.router import BidirectionalRouter
from plugin.archivar.archivar_state import ArchivarState
from unittest.mock import MagicMock
self.room_map._butler_mode = butler_mode
classifier = MagicMock()
classifier.is_initialized = True
state = ArchivarState()
state._loaded = True
return BidirectionalRouter(self.room_map, classifier, state)
def test_resolve_move_request_cognitive_passes_through(self):
"""cognitive: move_request_sent wird durchgereicht."""
router = self._make_router("cognitive")
self.assertTrue(router._resolve_move_request(True))
self.assertFalse(router._resolve_move_request(False))
def test_resolve_move_request_strict_passes_through(self):
"""strict: move_request_sent wird durchgereicht (100% Keywords
werden bereits vorher auf False gesetzt)."""
router = self._make_router("strict")
self.assertTrue(router._resolve_move_request(True))
self.assertFalse(router._resolve_move_request(False))
def test_resolve_move_request_off_always_false(self):
"""off: move_request_sent ist IMMER False."""
router = self._make_router("off")
self.assertFalse(router._resolve_move_request(True))
self.assertFalse(router._resolve_move_request(False))
def test_resolve_move_request_off_blocks_butler(self):
"""off: Auch wenn der Router Butler senden würde → False."""
router = self._make_router("off")
# Simuliere: Router würde Butler senden
result = router._resolve_move_request(True)
self.assertFalse(result, "Butler muss bei 'off' immer False sein")
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,415 @@
"""
Unit-Tests für ConversationHistory (B5v6.5).
Testet:
- add + get (Ring-Buffer Verhalten, älteste fällt raus)
- topic_hint (set, get, clear)
- cleanup_orphaned_rooms (sync + async)
- Thread-safety (concurrent adds)
- Edge cases: leerer Raum, nicht-existenter Raum
"""
import asyncio
import os
import sys
import unittest
# Add the parent directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from conversation_history import ConversationHistory, MessageEntry
class TestConversationHistoryAddGet(unittest.TestCase):
"""Tests für add() und get() — Ring-Buffer-Verhalten."""
def setUp(self):
self.history = ConversationHistory(max_size=5)
def test_add_and_get_single_message(self):
"""Eine Nachricht hinzufügen und abrufen."""
async def run():
await self.history.add("room-1", "user", "Hallo Welt")
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 1)
self.assertEqual(msgs[0]["role"], "user")
self.assertEqual(msgs[0]["text"], "Hallo Welt")
asyncio.run(run())
def test_add_and_get_multiple_messages(self):
"""Mehrere Nachrichten — neueste zuletzt."""
async def run():
for i in range(3):
await self.history.add("room-1", "user", f"Msg {i}")
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 3)
self.assertEqual(msgs[0]["text"], "Msg 0")
self.assertEqual(msgs[2]["text"], "Msg 2")
asyncio.run(run())
def test_ring_buffer_overflow(self):
"""Wenn max_size=5 überschritten, fällt die älteste Nachricht raus."""
async def run():
for i in range(7):
await self.history.add("room-1", "user", f"Msg {i}")
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 5)
# Älteste (Msg 0, Msg 1) sind rausgefallen
self.assertEqual(msgs[0]["text"], "Msg 2")
self.assertEqual(msgs[4]["text"], "Msg 6")
asyncio.run(run())
def test_ring_buffer_exact_max(self):
"""Genau max_size Nachrichten — keine verworfen."""
async def run():
for i in range(5):
await self.history.add("room-1", "user", f"Msg {i}")
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 5)
self.assertEqual(msgs[0]["text"], "Msg 0")
self.assertEqual(msgs[4]["text"], "Msg 4")
asyncio.run(run())
def test_get_with_limit(self):
"""get() mit limit-Parameter."""
async def run():
for i in range(10):
await self.history.add("room-1", "user", f"Msg {i}")
msgs = await self.history.get("room-1", limit=3)
self.assertEqual(len(msgs), 3)
self.assertEqual(msgs[0]["text"], "Msg 7")
self.assertEqual(msgs[2]["text"], "Msg 9")
asyncio.run(run())
def test_get_limit_larger_than_buffer(self):
"""limit > buffer size → alle Nachrichten."""
async def run():
for i in range(3):
await self.history.add("room-1", "user", f"Msg {i}")
msgs = await self.history.get("room-1", limit=100)
self.assertEqual(len(msgs), 3)
asyncio.run(run())
def test_get_nonexistent_room(self):
"""get() für nicht-existierenden Raum → leere Liste."""
async def run():
msgs = await self.history.get("nonexistent")
self.assertEqual(msgs, [])
asyncio.run(run())
def test_add_empty_room_id(self):
"""add() mit leerem room_id → no-op, kein Crash."""
async def run():
await self.history.add("", "user", "Test")
self.assertEqual(await self.history.get_room_count(), 0)
asyncio.run(run())
def test_add_empty_text(self):
"""add() mit leerem Text → no-op."""
async def run():
await self.history.add("room-1", "user", "")
await self.history.add("room-1", "user", " ")
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 0)
asyncio.run(run())
def test_multiple_rooms_independent(self):
"""Verschiedene Räume haben unabhängige Buffer."""
async def run():
await self.history.add("room-A", "user", "A1")
await self.history.add("room-B", "user", "B1")
await self.history.add("room-A", "user", "A2")
msgs_a = await self.history.get("room-A")
msgs_b = await self.history.get("room-B")
self.assertEqual(len(msgs_a), 2)
self.assertEqual(len(msgs_b), 1)
self.assertEqual(msgs_a[0]["text"], "A1")
self.assertEqual(msgs_b[0]["text"], "B1")
asyncio.run(run())
def test_max_size_validation(self):
"""max_size < 1 → ValueError."""
with self.assertRaises(ValueError):
ConversationHistory(max_size=0)
with self.assertRaises(ValueError):
ConversationHistory(max_size=-1)
def test_max_size_one(self):
"""max_size=1: nur die letzte Nachricht bleibt."""
async def run():
hist = ConversationHistory(max_size=1)
await hist.add("room-1", "user", "First")
await hist.add("room-1", "user", "Second")
msgs = await hist.get("room-1")
self.assertEqual(len(msgs), 1)
self.assertEqual(msgs[0]["text"], "Second")
asyncio.run(run())
class TestConversationHistoryTopicHint(unittest.TestCase):
"""Tests für topic_hint (set, get, clear)."""
def setUp(self):
self.history = ConversationHistory(max_size=10)
def test_set_and_get_topic_hint(self):
"""Topic setzen und abrufen."""
async def run():
await self.history.set_topic_hint("room-1", "Deployment-Status")
hint = await self.history.get_topic_hint("room-1")
self.assertEqual(hint, "Deployment-Status")
asyncio.run(run())
def test_get_topic_hint_nonexistent(self):
"""Topic für nicht-existierenden Raum → None."""
async def run():
hint = await self.history.get_topic_hint("nonexistent")
self.assertIsNone(hint)
asyncio.run(run())
def test_set_topic_hint_overwrite(self):
"""Zweites set_topic_hint überschreibt das erste."""
async def run():
await self.history.set_topic_hint("room-1", "Erstes Thema")
await self.history.set_topic_hint("room-1", "Zweites Thema")
hint = await self.history.get_topic_hint("room-1")
self.assertEqual(hint, "Zweites Thema")
asyncio.run(run())
def test_set_topic_hint_empty(self):
"""set_topic_hint mit leerem room_id oder topic → no-op."""
async def run():
await self.history.set_topic_hint("", "Thema")
await self.history.set_topic_hint("room-1", "")
self.assertIsNone(await self.history.get_topic_hint(""))
self.assertIsNone(await self.history.get_topic_hint("room-1"))
asyncio.run(run())
def test_clear_removes_topic_hint(self):
"""clear() entfernt auch den topic_hint."""
async def run():
await self.history.set_topic_hint("room-1", "Thema")
await self.history.clear("room-1")
hint = await self.history.get_topic_hint("room-1")
self.assertIsNone(hint)
asyncio.run(run())
def test_topic_hint_independent_per_room(self):
"""Topic hints sind unabhängig pro Raum."""
async def run():
await self.history.set_topic_hint("room-A", "Thema A")
await self.history.set_topic_hint("room-B", "Thema B")
self.assertEqual(await self.history.get_topic_hint("room-A"), "Thema A")
self.assertEqual(await self.history.get_topic_hint("room-B"), "Thema B")
asyncio.run(run())
class TestConversationHistoryCleanup(unittest.TestCase):
"""Tests für cleanup_orphaned_rooms (sync + async)."""
def setUp(self):
self.history = ConversationHistory(max_size=10)
def test_cleanup_sync_removes_orphaned(self):
"""Sync-Cleanup entfernt Räume, die nicht in active_room_ids sind."""
async def run():
await self.history.add("room-1", "user", "Msg")
await self.history.add("room-2", "user", "Msg")
await self.history.add("room-3", "user", "Msg")
await self.history.set_topic_hint("room-1", "T1")
await self.history.set_topic_hint("room-2", "T2")
asyncio.run(run())
removed = self.history.cleanup_orphaned_rooms_sync({"room-1"})
self.assertEqual(removed, 2) # room-2 und room-3 entfernt
async def check():
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 1) # room-1 bleibt
msgs2 = await self.history.get("room-2")
self.assertEqual(len(msgs2), 0) # room-2 entfernt
hint = await self.history.get_topic_hint("room-2")
self.assertIsNone(hint) # topic_hint auch entfernt
asyncio.run(check())
def test_cleanup_sync_no_orphans(self):
"""Sync-Cleanup wenn alle Räume aktiv sind → 0 entfernt."""
async def run():
await self.history.add("room-1", "user", "Msg")
await self.history.add("room-2", "user", "Msg")
asyncio.run(run())
removed = self.history.cleanup_orphaned_rooms_sync({"room-1", "room-2"})
self.assertEqual(removed, 0)
def test_cleanup_sync_empty_active_set(self):
"""Sync-Cleanup mit leerem active_room_ids → alle entfernt."""
async def run():
await self.history.add("room-1", "user", "Msg")
await self.history.add("room-2", "user", "Msg")
asyncio.run(run())
removed = self.history.cleanup_orphaned_rooms_sync(set())
self.assertEqual(removed, 2)
def test_cleanup_async_removes_orphaned(self):
"""Async-Cleanup (via Lock) entfernt verwaiste Räume."""
async def run():
await self.history.add("room-1", "user", "Msg")
await self.history.add("room-2", "user", "Msg")
removed = await self.history.cleanup_orphaned_rooms({"room-1"})
self.assertEqual(removed, 1)
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 1)
msgs2 = await self.history.get("room-2")
self.assertEqual(len(msgs2), 0)
asyncio.run(run())
def test_cleanup_async_no_orphans(self):
"""Async-Cleanup wenn alle Räume aktiv → 0 entfernt."""
async def run():
await self.history.add("room-1", "user", "Msg")
removed = await self.history.cleanup_orphaned_rooms({"room-1"})
self.assertEqual(removed, 0)
asyncio.run(run())
class TestConversationHistoryThreadSafety(unittest.TestCase):
"""Tests für Thread-safety (concurrent adds)."""
def setUp(self):
self.history = ConversationHistory(max_size=100)
def test_concurrent_adds_same_room(self):
"""Viele concurrent adds in denselben Raum — keine Korruption."""
async def add_many(room_id, prefix, count):
for i in range(count):
await self.history.add(room_id, "user", f"{prefix}-{i}")
async def run():
tasks = [
add_many("room-1", "A", 50),
add_many("room-1", "B", 50),
add_many("room-1", "C", 50),
]
await asyncio.gather(*tasks)
msgs = await self.history.get("room-1")
# 150 adds, max_size=100 → 100 messages
self.assertEqual(len(msgs), 100)
asyncio.run(run())
def test_concurrent_adds_different_rooms(self):
"""Concurrent adds in verschiedene Räume — keine Cross-Contamination."""
async def add_many(room_id, count):
for i in range(count):
await self.history.add(room_id, "user", f"msg-{i}")
async def run():
tasks = [
add_many("room-A", 30),
add_many("room-B", 30),
add_many("room-C", 30),
]
await asyncio.gather(*tasks)
self.assertEqual(len(await self.history.get("room-A")), 30)
self.assertEqual(len(await self.history.get("room-B")), 30)
self.assertEqual(len(await self.history.get("room-C")), 30)
asyncio.run(run())
def test_concurrent_add_and_get(self):
"""Gleichzeitiges add() und get() — keine Deadlocks."""
async def adder():
for i in range(50):
await self.history.add("room-1", "user", f"msg-{i}")
await asyncio.sleep(0)
async def reader():
for _ in range(25):
await self.history.get("room-1")
await asyncio.sleep(0)
async def run():
await asyncio.gather(adder(), reader())
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 50)
asyncio.run(run())
class TestConversationHistoryEdgeCases(unittest.TestCase):
"""Edge-Case-Tests."""
def setUp(self):
self.history = ConversationHistory(max_size=10)
def test_clear_nonexistent_room(self):
"""clear() für nicht-existierenden Raum → no-op, kein Crash."""
async def run():
await self.history.clear("nonexistent")
self.assertEqual(await self.history.get_room_count(), 0)
asyncio.run(run())
def test_clear_then_reuse_room(self):
"""Nach clear() kann derselbe Raum wieder verwendet werden."""
async def run():
await self.history.add("room-1", "user", "Msg 1")
await self.history.clear("room-1")
await self.history.add("room-1", "user", "Msg 2")
msgs = await self.history.get("room-1")
self.assertEqual(len(msgs), 1)
self.assertEqual(msgs[0]["text"], "Msg 2")
asyncio.run(run())
def test_room_count_property(self):
"""room_count Property (nicht thread-safe, für Debug)."""
async def run():
self.assertEqual(self.history.room_count, 0)
await self.history.add("room-1", "user", "Msg")
self.assertEqual(self.history.room_count, 1)
await self.history.add("room-2", "user", "Msg")
self.assertEqual(self.history.room_count, 2)
asyncio.run(run())
def test_get_room_count_async(self):
"""Thread-safe get_room_count()."""
async def run():
self.assertEqual(await self.history.get_room_count(), 0)
await self.history.add("room-1", "user", "Msg")
self.assertEqual(await self.history.get_room_count(), 1)
asyncio.run(run())
def test_messageentry_to_dict(self):
"""MessageEntry.to_dict() liefert korrekte Struktur."""
from datetime import datetime, timezone
ts = datetime(2026, 7, 13, 12, 0, 0, tzinfo=timezone.utc)
entry = MessageEntry(role="user", text="Test", timestamp=ts)
d = entry.to_dict()
self.assertEqual(d["role"], "user")
self.assertEqual(d["text"], "Test")
self.assertTrue(d["timestamp"].startswith("2026-07-13"))
def test_messageentry_default_timestamp(self):
"""MessageEntry ohne timestamp → jetzt UTC."""
entry = MessageEntry(role="user", text="Test")
self.assertIsNotNone(entry.timestamp)
d = entry.to_dict()
self.assertIn("timestamp", d)
def test_add_with_custom_timestamp(self):
"""add() mit explizitem timestamp."""
from datetime import datetime, timezone
async def run():
ts = datetime(2025, 1, 1, tzinfo=timezone.utc)
await self.history.add("room-1", "user", "Old msg", timestamp=ts)
msgs = await self.history.get("room-1")
self.assertEqual(msgs[0]["timestamp"], "2025-01-01T00:00:00+00:00")
asyncio.run(run())
def test_max_size_property(self):
"""max_size Property."""
self.assertEqual(self.history.max_size, 10)
hist2 = ConversationHistory(max_size=3)
self.assertEqual(hist2.max_size, 3)
if __name__ == "__main__":
unittest.main()
+511
View File
@@ -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()
+524
View File
@@ -0,0 +1,524 @@
"""
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 asyncio
import json
import tempfile
from pathlib import Path
from typing import List, Optional
from unittest.mock import AsyncMock, MagicMock
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
# ── V7-2: Thematisches never_route ────────────────────────────────────────
class TestNeverRouteThematic:
"""V7-2: never_route ist thematisch, nicht räumlich.
Ein never_route für 'lan-dokumentation' blockt NICHT 'protonbridge'
im selben Raum. Der Butler darf bei einem anderen Thema wieder fragen.
"""
@pytest.fixture
def state(self) -> ArchivarState:
"""ArchivarState mit v7 never_route Schema."""
s = ArchivarState()
s._loaded = True # Skip file I/O
return s
def test_never_route_topic_blocks_same_topic(self, state):
"""never_route für 'lan-dokumentation' blockt 'lan-dokumentation'."""
room_id = "test_room_123"
state.set_never_route(room_id, "lan-dokumentation")
# Gleiches Thema → blockiert
assert state.is_never_route(room_id, "lan-dokumentation") is True
def test_never_route_topic_allows_different_topic(self, state):
"""never_route für 'lan-dokumentation' blockt NICHT 'protonbridge'."""
room_id = "test_room_123"
state.set_never_route(room_id, "lan-dokumentation")
# Anderes Thema → nicht blockiert
assert state.is_never_route(room_id, "protonbridge") is False
def test_never_route_topic_allows_unknown_topic(self, state):
"""never_route für 'lan-dokumentation' blockt NICHT None/leer."""
room_id = "test_room_123"
state.set_never_route(room_id, "lan-dokumentation")
# Kein Thema → nicht blockiert (Butler darf fragen)
assert state.is_never_route(room_id, None) is False
def test_never_route_multiple_topics_same_room(self, state):
"""Mehrere Themen im selben Raum: jedes unabhängig."""
room_id = "test_room_123"
state.set_never_route(room_id, "lan-dokumentation")
state.set_never_route(room_id, "devops")
# Beide gesetzten Themen blockiert
assert state.is_never_route(room_id, "lan-dokumentation") is True
assert state.is_never_route(room_id, "devops") is True
# Anderes Thema nicht blockiert
assert state.is_never_route(room_id, "protonbridge") is False
def test_never_route_different_room_not_affected(self, state):
"""never_route in Raum A betrifft Raum B nicht."""
state.set_never_route("room_a", "lan-dokumentation")
# Gleiches Thema in anderem Raum → nicht blockiert
assert state.is_never_route("room_b", "lan-dokumentation") is False
def test_router_check_never_route_topic_blocks_matched_room(self):
"""Router._check_never_route_topic blockt wenn Thema in never_route."""
json_str = _make_map_json(
rooms=[
{"room_id": "r_lan", "name": "#LAN-Dokumentation",
"theme": "lan docs", "keywords": ["lan", "dokumentation", "netzwerk"]},
{"room_id": "r_proton", "name": "#ProtonBridge",
"theme": "proton mail bridge", "keywords": ["protonbridge", "protonmail", "bridge"]},
{"room_id": "r_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
],
)
path = _tmp_map(json_str)
try:
room_map = RoomMap.load(path)
state = ArchivarState()
state._loaded = True
# Setze never_route für 'lan-dokumentation' im Ursprungsraum
origin_room = "r_proton" # User ist im #ProtonBridge-Raum
state.set_never_route(origin_room, "lan-dokumentation")
router = BidirectionalRouter(room_map, None, state) # type: ignore
# Nachricht matcht #LAN-Dokumentation → sollte geblockt werden
lan_room = room_map.get_room_by_id("r_lan")
assert lan_room is not None
blocked = router._check_never_route_topic(origin_room, lan_room)
assert blocked is True, (
"never_route für 'lan-dokumentation' sollte LAN-Match blocken"
)
finally:
path.unlink(missing_ok=True)
def test_router_check_never_route_topic_allows_other_topic(self):
"""Router._check_never_route_topic erlaubt anderes Thema im selben Raum."""
json_str = _make_map_json(
rooms=[
{"room_id": "r_lan", "name": "#LAN-Dokumentation",
"theme": "lan docs", "keywords": ["lan", "dokumentation", "netzwerk"]},
{"room_id": "r_proton", "name": "#ProtonBridge",
"theme": "proton mail bridge", "keywords": ["protonbridge", "protonmail", "bridge"]},
{"room_id": "r_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
],
)
path = _tmp_map(json_str)
try:
room_map = RoomMap.load(path)
state = ArchivarState()
state._loaded = True
# Setze never_route für 'lan-dokumentation' im Ursprungsraum
origin_room = "r_proton"
state.set_never_route(origin_room, "lan-dokumentation")
router = BidirectionalRouter(room_map, None, state) # type: ignore
# Nachricht matcht #ProtonBridge (anderes Thema) → NICHT geblockt
proton_room = room_map.get_room_by_id("r_proton")
assert proton_room is not None
blocked = router._check_never_route_topic(origin_room, proton_room)
assert blocked is False, (
"never_route für 'lan-dokumentation' sollte ProtonBridge-Match "
"NICHT blocken — anderes Thema!"
)
finally:
path.unlink(missing_ok=True)
def test_room_name_to_topic_conversion(self):
"""room_name_to_topic konvertiert Raum-Namen korrekt."""
from plugin.archivar.router import room_name_to_topic
assert room_name_to_topic("#LAN-Dokumentation") == "lan-dokumentation"
assert room_name_to_topic("LAN-Dokumentation") == "lan-dokumentation"
assert room_name_to_topic("#ProtonBridge") == "protonbridge"
assert room_name_to_topic("#DevOps") == "devops"
# _room_name_to_topic stripped nur '#', nicht Whitespace
assert room_name_to_topic("Mein Raum") == "mein-raum"
# ── P0-BUGFIX: Meta-Patterns restriktiver ──────────────────────────────────
class TestMetaPatternsP0:
"""P0-BUGFIX: _META_PATTERNS dürfen nicht zu breit matchen.
Bug: Pattern 3 matchte JEDES Vorkommen von 'Archivar', auch in
Sachfragen wie 'Was hat der Archivar empfohlen?' → is_meta=True →
100%-Keyword-Match wurde nie geprüft.
Fix: 'archivar' nur in Kombination mit System-Operationsverben
(klassifiziert, routet, leitet weiter, arbeitet, funktioniert, macht).
"""
def test_archivar_allein_kein_meta(self):
"""'Archivar' als Fachbegriff in Sachfrage → KEIN Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
# Der ursprüngliche Bug-Fall
assert not BidirectionalRouter._is_meta_question(
"Was hat der Archivar aufgrund des Keywords Rocketchat empfohlen?"
)
def test_archivar_mit_verb_ist_meta(self):
"""'Archivar klassifiziert' → Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Wie klassifiziert der Archivar meine Nachricht?"
)
def test_archivar_routet_ist_meta(self):
"""'Archivar routet' → Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Wohin routet der Archivar diese Frage?"
)
def test_archivar_funktioniert_ist_meta(self):
"""'Archivar funktioniert' → Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Wie funktioniert der Archivar?"
)
def test_archivar_empfohlen_kein_meta(self):
"""'Archivar hat empfohlen' → KEIN Meta-Match (Sachfrage)."""
from plugin.archivar.router import BidirectionalRouter
assert not BidirectionalRouter._is_meta_question(
"Der Archivar hat empfohlen, das so zu machen"
)
def test_archivar_gesagt_kein_meta(self):
"""'Archivar hat gesagt' → KEIN Meta-Match (Sachfrage)."""
from plugin.archivar.router import BidirectionalRouter
assert not BidirectionalRouter._is_meta_question(
"Der Archivar hat gesagt, ich soll das hier dokumentieren"
)
def test_klassifikation_allein_ist_meta(self):
"""'Klassifikation' ohne 'archivar' → Meta-Match (eigenständiges Signal)."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Warum wurde meine Nachricht so klassifiziert?"
)
def test_routing_allein_ist_meta(self):
"""'Routing' ohne 'archivar' → Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Wie funktioniert das Routing hier?"
)
def test_weiterleitung_allein_ist_meta(self):
"""'Weiterleitung' ohne 'archivar' → Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Kann ich die Weiterleitung beeinflussen?"
)
def test_wohin_wurde_ist_meta(self):
"""'Wohin wurde' → Meta-Match (Pattern 1)."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Wohin wurde meine letzte Nachricht geroutet?"
)
def test_warum_ist_meine_nachricht_ist_meta(self):
"""'Warum ist meine Nachricht' → Meta-Match (Pattern 2)."""
from plugin.archivar.router import BidirectionalRouter
assert BidirectionalRouter._is_meta_question(
"Warum ist meine Nachricht im falschen Raum gelandet?"
)
def test_normale_frage_kein_meta(self):
"""Normale Sachfrage ohne System-Bezug → KEIN Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
assert not BidirectionalRouter._is_meta_question(
"Wie konfiguriere ich den NGINX für HTTPS?"
)
def test_keyword_rocketchat_kein_meta(self):
"""Frage mit Keyword 'Rocketchat' → KEIN Meta-Match."""
from plugin.archivar.router import BidirectionalRouter
assert not BidirectionalRouter._is_meta_question(
"Was hat der Archivar aufgrund des Keywords Rocketchat empfohlen?"
)
# ── P0-BUGFIX: target_room bei stay_in_room ─────────────────────────────────
class TestTargetRoomStayInRoomP0:
"""P0-BUGFIX: target_room=origin_room_id bei stay_in_room=True.
Bug: Bei stay_in_room=True wurde target_room=catch_all_id (DM) gesetzt.
Das leakt in _THEMATIC_TARGET_ROOM → Agent-Prompt bekommt falschen Raum
→ Agent denkt er sei im DM.
Fix: target_room=origin_room_id bei stay_in_room=True.
Adapter-Guard: _THEMATIC_TARGET_ROOM nur setzen wenn NICHT stay_in_room.
"""
def test_meta_question_target_room_is_origin(self):
"""Meta-Frage: target_room muss origin_room_id sein, nicht catch_all."""
import json
import tempfile
from pathlib import Path
json_str = _make_map_json(
rooms=[
{"room_id": "r_plugin", "name": "#Plugin",
"theme": "plugin dev", "keywords": ["plugin", "adapter"]},
{"room_id": "r_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
],
)
path = _tmp_map(json_str)
try:
from plugin.archivar.room_map import RoomMap
from plugin.archivar.archivar_state import ArchivarState
room_map = RoomMap.load(path)
state = ArchivarState()
state._loaded = True
router = BidirectionalRouter(room_map, None, state) # type: ignore
# Meta-Frage aus dem Plugin-Raum
decision = asyncio.run(
router.route(
"Wie funktioniert der Archivar?",
origin_room_id="r_plugin",
)
)
assert decision.is_meta, "Sollte als Meta-Frage erkannt werden"
assert decision.stay_in_room, "Meta-Fragen sollen stay_in_room sein"
assert decision.target_room == "r_plugin", (
f"target_room sollte origin_room_id='r_plugin' sein, "
f"nicht catch_all_id='{decision.target_room}'"
)
finally:
path.unlink(missing_ok=True)
def test_smalltalk_target_room_empty(self):
"""Smalltalk: target_room bleibt '' (kein Routing)."""
import json
import tempfile
from pathlib import Path
json_str = _make_map_json(
rooms=[
{"room_id": "r_plugin", "name": "#Plugin",
"theme": "plugin dev", "keywords": ["plugin"]},
{"room_id": "r_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
],
)
path = _tmp_map(json_str)
try:
from plugin.archivar.room_map import RoomMap
from plugin.archivar.archivar_state import ArchivarState
room_map = RoomMap.load(path)
state = ArchivarState()
state._loaded = True
# Mock classifier needed — router crashes with None
mock_classifier = MagicMock()
mock_classifier.is_initialized = True
mock_classifier.classify = AsyncMock(return_value=None)
mock_classifier._llm_raw = AsyncMock(return_value="STAY")
router = BidirectionalRouter(room_map, mock_classifier, state)
# Smalltalk aus dem Plugin-Raum
decision = asyncio.run(
router.route(
"Hallo, wie geht's?",
origin_room_id="r_plugin",
)
)
assert decision.stay_in_room, "Smalltalk soll stay_in_room sein"
# target_room ist '' bei Smalltalk (kein Routing-Ziel)
assert decision.target_room == "", (
f"Smalltalk target_room sollte '' sein, nicht '{decision.target_room}'"
)
finally:
path.unlink(missing_ok=True)
def test_archivar_sachfrage_nicht_meta(self):
"""'Was hat der Archivar empfohlen?' → KEIN Meta, normaler Flow."""
import json
import tempfile
from pathlib import Path
json_str = _make_map_json(
rooms=[
{"room_id": "r_plugin", "name": "#Plugin",
"theme": "plugin dev", "keywords": ["plugin", "adapter", "rocketchat"]},
{"room_id": "r_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
],
)
path = _tmp_map(json_str)
try:
from plugin.archivar.room_map import RoomMap
from plugin.archivar.archivar_state import ArchivarState
room_map = RoomMap.load(path)
state = ArchivarState()
state._loaded = True
router = BidirectionalRouter(room_map, None, state) # type: ignore
# Sachfrage mit 'Archivar' als Fachbegriff
decision = asyncio.run(
router.route(
"Was hat der Archivar aufgrund des Keywords Rocketchat empfohlen?",
origin_room_id="r_plugin",
)
)
# Darf NICHT is_meta sein
assert not decision.is_meta, (
"Sachfrage mit 'Archivar' als Fachbegriff darf NICHT "
"als Meta-Frage erkannt werden"
)
finally:
path.unlink(missing_ok=True)
+517
View File
@@ -0,0 +1,517 @@
"""
V7-3: Drei-Zustands-Logik Tests — AKTIV → VERBLASST → WIEDERHERGESTELLT → AKTIV
Tests für:
- 24h Timeout (hard limit)
- Adaptive Pause (Median × 3)
- is_never_route prüft nur AKTIV
- extend_never_route (Verlängerung)
- restore_never_route (Wiederherstellung)
- VERBLASST erlaubt Butler (is_never_route → False)
- Themenwechsel-Erkennung
"""
import os
import sys
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from archivar_state import ArchivarState
class TestV7_3_ExpireStaleEntries(unittest.TestCase):
"""V7-3: expire_stale_entries() Tests."""
def setUp(self):
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)
self.state._loaded = True
def tearDown(self):
if os.path.exists(self.state_file_path):
os.unlink(self.state_file_path)
def test_24h_timeout_expires_active_entry(self):
"""24h Timeout: AKTIV → VERBLASST wenn last_extended > 24h."""
room_id = "room_test_24h"
topic = "lan-dokumentation"
# Setze never_route mit last_extended = 25h in der Vergangenheit
old_time = (datetime.now() - timedelta(hours=25)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "AKTIV",
"timestamp": old_time,
"last_extended": old_time,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(now=datetime.now())
self.assertEqual(expired, 1)
entry = self.state._never_route[room_id][topic]
self.assertEqual(entry["state"], "VERBLASST")
def test_24h_timeout_does_not_expire_recent_entry(self):
"""Eintrag < 24h alt bleibt AKTIV."""
room_id = "room_test_recent"
topic = "devops"
recent_time = (datetime.now() - timedelta(hours=1)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "AKTIV",
"timestamp": recent_time,
"last_extended": recent_time,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(now=datetime.now())
self.assertEqual(expired, 0)
entry = self.state._never_route[room_id][topic]
self.assertEqual(entry["state"], "AKTIV")
def test_24h_timeout_skips_already_verblasst(self):
"""Bereits VERBLASST-Einträge werden nicht erneut verarbeitet."""
room_id = "room_test_verblasst"
topic = "protonbridge"
old_time = (datetime.now() - timedelta(hours=48)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "VERBLASST",
"timestamp": old_time,
"last_extended": old_time,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(now=datetime.now())
self.assertEqual(expired, 0) # Kein neuer Verfall
def test_24h_timeout_exactly_24h(self):
"""Genau 24h: Grenzfall — > 24h ist expired, == 24h nicht."""
room_id = "room_test_exact"
topic = "docker"
# Verwende einen festen now-Wert um Microsecond-Drift zu vermeiden
now = datetime.now()
exact_24h = (now - timedelta(hours=24)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "AKTIV",
"timestamp": exact_24h,
"last_extended": exact_24h,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(now=now)
# Genau 24h ist NICHT > 24h → kein Verfall
self.assertEqual(expired, 0)
def test_multiple_entries_mixed_expiry(self):
"""Mehrere Einträge: nur abgelaufene verfallen."""
room_id = "room_test_mixed"
old = (datetime.now() - timedelta(hours=30)).isoformat()
recent = (datetime.now() - timedelta(hours=1)).isoformat()
self.state._never_route[room_id] = {
"lan-dokumentation": {
"state": "AKTIV",
"timestamp": old,
"last_extended": old,
"extension_count": 0,
},
"devops": {
"state": "AKTIV",
"timestamp": recent,
"last_extended": recent,
"extension_count": 0,
},
"protonbridge": {
"state": "VERBLASST",
"timestamp": old,
"last_extended": old,
"extension_count": 0,
},
}
expired = self.state.expire_stale_entries(now=datetime.now())
self.assertEqual(expired, 1) # Nur lan-dokumentation
self.assertEqual(
self.state._never_route[room_id]["lan-dokumentation"]["state"],
"VERBLASST",
)
self.assertEqual(
self.state._never_route[room_id]["devops"]["state"],
"AKTIV",
)
self.assertEqual(
self.state._never_route[room_id]["protonbridge"]["state"],
"VERBLASST",
)
class TestV7_3_AdaptivePause(unittest.TestCase):
"""V7-3: Adaptive Pause Tests (Median × 3)."""
def setUp(self):
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)
self.state._loaded = True
def tearDown(self):
if os.path.exists(self.state_file_path):
os.unlink(self.state_file_path)
def _make_mock_history(self, timestamps):
"""Erstelle eine Mock-ConversationHistory mit gegebenen Timestamps."""
from collections import deque
from dataclasses import dataclass, field
@dataclass
class MockEntry:
role: str = "user"
text: str = "test"
timestamp: datetime = field(default_factory=datetime.now)
class MockHistory:
def __init__(self, entries):
self._buffers = {"room_test": deque(entries, maxlen=10)}
entries = [MockEntry(timestamp=ts) for ts in timestamps]
return MockHistory(entries)
def test_adaptive_pause_expires_when_gap_exceeds_median_x3(self):
"""Adaptive Pause: gap > median × 3 → VERBLASST."""
room_id = "room_test"
topic = "lan-dokumentation"
# Nachrichten: Abstände 10s, 10s, 10s → median = 10s
# last_extended vor 40s → gap=40s > 10s × 3 = 30s → VERBLASST
now = datetime.now()
timestamps = [
now - timedelta(seconds=100),
now - timedelta(seconds=90),
now - timedelta(seconds=80),
now - timedelta(seconds=70),
]
mock_history = self._make_mock_history(timestamps)
last_extended = (now - timedelta(seconds=40)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "AKTIV",
"timestamp": last_extended,
"last_extended": last_extended,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(
now=now, conversation_history=mock_history,
)
self.assertEqual(expired, 1)
self.assertEqual(
self.state._never_route[room_id][topic]["state"],
"VERBLASST",
)
def test_adaptive_pause_does_not_expire_when_gap_small(self):
"""Adaptive Pause: gap < median × 3 → bleibt AKTIV."""
room_id = "room_test"
topic = "devops"
now = datetime.now()
# Nachrichten: Abstände 100s, 100s, 100s → median = 100s
# last_extended vor 200s → gap=200s < 100s × 3 = 300s → kein Verfall
timestamps = [
now - timedelta(seconds=500),
now - timedelta(seconds=400),
now - timedelta(seconds=300),
now - timedelta(seconds=200),
]
mock_history = self._make_mock_history(timestamps)
last_extended = (now - timedelta(seconds=200)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "AKTIV",
"timestamp": last_extended,
"last_extended": last_extended,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(
now=now, conversation_history=mock_history,
)
self.assertEqual(expired, 0)
self.assertEqual(
self.state._never_route[room_id][topic]["state"],
"AKTIV",
)
def test_adaptive_pause_fallback_fewer_than_3_messages(self):
"""Weniger als 3 Nachrichten → keine adaptive Pause (nur 24h)."""
room_id = "room_test"
topic = "protonbridge"
now = datetime.now()
# Nur 2 Nachrichten → median_gap = None → kein adaptiver Verfall
timestamps = [
now - timedelta(seconds=100),
now - timedelta(seconds=50),
]
mock_history = self._make_mock_history(timestamps)
last_extended = (now - timedelta(hours=2)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "AKTIV",
"timestamp": last_extended,
"last_extended": last_extended,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(
now=now, conversation_history=mock_history,
)
# Kein 24h-Verfall (2h < 24h), keine adaptive Pause (< 3 Nachrichten)
self.assertEqual(expired, 0)
def test_adaptive_pause_no_history_uses_24h_only(self):
"""Ohne conversation_history → nur 24h Timeout."""
room_id = "room_test"
topic = "docker"
old_time = (datetime.now() - timedelta(hours=25)).isoformat()
self.state._never_route[room_id] = {
topic: {
"state": "AKTIV",
"timestamp": old_time,
"last_extended": old_time,
"extension_count": 0,
}
}
expired = self.state.expire_stale_entries(
now=datetime.now(), conversation_history=None,
)
self.assertEqual(expired, 1) # 24h greift
class TestV7_3_IsNeverRouteStateCheck(unittest.TestCase):
"""V7-3: is_never_route prüft nur AKTIV."""
def setUp(self):
self.state = ArchivarState()
self.state._loaded = True
def test_is_never_route_blocks_aktiv(self):
"""AKTIV → is_never_route = True."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
self.assertTrue(self.state.is_never_route(room_id, topic))
def test_is_never_route_allows_verblasst(self):
"""VERBLASST → is_never_route = False (Butler darf fragen)."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
# Manuell auf VERBLASST setzen
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
self.assertFalse(self.state.is_never_route(room_id, topic))
def test_is_never_route_allows_unknown_topic(self):
"""Unbekanntes Thema → False."""
room_id = "room_test"
self.state.set_never_route(room_id, "lan-dokumentation")
self.assertFalse(self.state.is_never_route(room_id, "unbekannt"))
def test_is_never_route_allows_unknown_room(self):
"""Unbekannter Raum → False."""
self.assertFalse(self.state.is_never_route("unbekannt", "lan-dokumentation"))
class TestV7_3_ExtendNeverRoute(unittest.TestCase):
"""V7-3: extend_never_route Tests."""
def setUp(self):
self.state = ArchivarState()
self.state._loaded = True
def test_extend_updates_last_extended(self):
"""extend_never_route aktualisiert last_extended."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
old_extended = self.state._never_route[room_id][topic]["last_extended"]
old_count = self.state._never_route[room_id][topic]["extension_count"]
result = self.state.extend_never_route(room_id, topic)
self.assertTrue(result)
new_extended = self.state._never_route[room_id][topic]["last_extended"]
new_count = self.state._never_route[room_id][topic]["extension_count"]
self.assertNotEqual(old_extended, new_extended)
self.assertEqual(new_count, old_count + 1)
def test_extend_fails_for_verblasst(self):
"""extend_never_route schlägt fehl für VERBLASST."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
result = self.state.extend_never_route(room_id, topic)
self.assertFalse(result)
def test_extend_fails_for_unknown(self):
"""extend_never_route schlägt fehl für unbekannten Eintrag."""
result = self.state.extend_never_route("unknown", "unknown")
self.assertFalse(result)
class TestV7_3_RestoreNeverRoute(unittest.TestCase):
"""V7-3: restore_never_route Tests (Wiederherstellungs-Stub)."""
def setUp(self):
self.state = ArchivarState()
self.state._loaded = True
def test_restore_verblasst_to_aktiv(self):
"""VERBLASST → AKTIV via restore_never_route."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
result = self.state.restore_never_route(room_id, topic)
self.assertTrue(result)
entry = self.state._never_route[room_id][topic]
self.assertEqual(entry["state"], "AKTIV")
self.assertGreater(entry["extension_count"], 0)
def test_restore_already_aktiv_returns_false(self):
"""Bereits AKTIV → restore_never_route = False."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
result = self.state.restore_never_route(room_id, topic)
self.assertFalse(result)
def test_restore_unknown_returns_false(self):
"""Unbekannter Eintrag → False."""
result = self.state.restore_never_route("unknown", "unknown")
self.assertFalse(result)
def test_restore_updates_last_extended(self):
"""Wiederherstellung aktualisiert last_extended."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
old_extended = self.state._never_route[room_id][topic]["last_extended"]
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
self.state.restore_never_route(room_id, topic)
new_extended = self.state._never_route[room_id][topic]["last_extended"]
self.assertNotEqual(old_extended, new_extended)
class TestV7_3_MedianGap(unittest.TestCase):
"""V7-3: _compute_median_message_gap Tests."""
def setUp(self):
self.state = ArchivarState()
self.state._loaded = True
def _make_mock_history(self, timestamps):
from collections import deque
from dataclasses import dataclass, field
@dataclass
class MockEntry:
role: str = "user"
text: str = "test"
timestamp: datetime = field(default_factory=datetime.now)
class MockHistory:
def __init__(self, entries):
self._buffers = {"room_test": deque(entries, maxlen=10)}
entries = [MockEntry(timestamp=ts) for ts in timestamps]
return MockHistory(entries)
def test_median_odd_count(self):
"""Median bei ungerader Anzahl von Gaps."""
now = datetime.now()
timestamps = [
now - timedelta(seconds=100),
now - timedelta(seconds=80),
now - timedelta(seconds=50),
now - timedelta(seconds=10),
]
# Gaps: 20, 30, 40 → median = 30
mock = self._make_mock_history(timestamps)
median = self.state._compute_median_message_gap(mock, "room_test")
self.assertEqual(median, 30.0)
def test_median_even_count(self):
"""Median bei gerader Anzahl von Gaps."""
now = datetime.now()
timestamps = [
now - timedelta(seconds=100),
now - timedelta(seconds=80),
now - timedelta(seconds=50),
now - timedelta(seconds=30),
now - timedelta(seconds=10),
]
# Sorted timestamps: 100, 80, 50, 30, 10
# Gaps: 20, 30, 20, 20 → sorted: 20, 20, 20, 30
# n=4 (even) → median = (gaps[1] + gaps[2]) / 2 = (20+20)/2 = 20
mock = self._make_mock_history(timestamps)
median = self.state._compute_median_message_gap(mock, "room_test")
self.assertEqual(median, 20.0)
def test_median_fewer_than_3_messages(self):
"""Weniger als 3 Nachrichten → None."""
now = datetime.now()
timestamps = [now - timedelta(seconds=100), now - timedelta(seconds=50)]
mock = self._make_mock_history(timestamps)
median = self.state._compute_median_message_gap(mock, "room_test")
self.assertIsNone(median)
def test_median_unknown_room(self):
"""Unbekannter Raum → None."""
now = datetime.now()
timestamps = [now - timedelta(seconds=100)]
mock = self._make_mock_history(timestamps)
median = self.state._compute_median_message_gap(mock, "unknown_room")
self.assertIsNone(median)
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,651 @@
"""
V7-4: Rekursive Einleitungen erkennen + Wiederherstellung Tests.
Tests für:
- Heuristische Marker-Erkennung (alle RECURSIVE_MARKERS)
- Kein Marker → kein LLM-Check (Performance)
- Rekursiver Bezug → restore_never_route (VERBLASST → AKTIV)
- 'Lass uns nochmal auf X zurückkommen' → REKURSIV → restore
- 'Ich habe eine neue Frage zu X' → NEU → Butler darf fragen
- Rekursiver Bezug bei bereits AKTIV → extend
- Rekursiver Bezug ohne never_route Eintrag → normaler Flow
- LLM-Timeout → Fallback NEU
- LLM-Fehler → Fallback NEU
"""
import asyncio
import os
import sys
import tempfile
import unittest
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from archivar_state import ArchivarState
# router.py uses relative imports, so we must import via the package path
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.router import (
BidirectionalRouter,
RECURSIVE_MARKERS,
_RECURSIVE_DETECTION_PROMPT,
)
# ── Helpers ────────────────────────────────────────────────────────────────
def _make_mock_room_map():
"""Erstelle eine Mock-RoomMap mit Test-Räumen."""
from room_map import RoomMap, RoomEntry
rooms = {
"r_lan": RoomEntry(
room_id="r_lan",
name="#LAN-Dokumentation",
theme="lan docs",
keywords_100=["lan", "dokumentation", "netzwerk"],
keywords_context=[],
catch_all=False,
),
"r_proton": RoomEntry(
room_id="r_proton",
name="#ProtonBridge",
theme="proton mail bridge",
keywords_100=["protonbridge", "protonmail", "bridge"],
keywords_context=[],
catch_all=False,
),
"r_admin": RoomEntry(
room_id="r_admin",
name="DM Admin",
theme="admin",
keywords_100=[],
keywords_context=[],
catch_all=True,
),
}
rm = MagicMock(spec=RoomMap)
rm.rooms = rooms
rm.catch_all_room = rooms["r_admin"]
rm.get_room_by_id = lambda rid: rooms.get(rid)
rm.is_excluded = lambda rid: False
rm.find_room_by_keywords = MagicMock(return_value=None)
rm.is_100_percent_match = MagicMock(return_value=False)
return rm
def _make_mock_classifier():
"""Erstelle einen Mock-IntentClassifier."""
classifier = MagicMock()
classifier.is_initialized = True
classifier._llm_raw = AsyncMock(return_value="NEU")
classifier._llm_client = None
classifier._llm_enabled = True
return classifier
def _make_mock_conversation_history(room_id="room_test", messages=None, topic_hint=None):
"""Erstelle eine Mock-ConversationHistory."""
from collections import deque
from dataclasses import dataclass, field
@dataclass
class MockEntry:
role: str = "user"
text: str = "test"
timestamp: datetime = field(default_factory=datetime.now)
class MockHistory:
def __init__(self, entries, topic_hint=None):
self._buffers = {room_id: deque(entries, maxlen=10)}
self._topic_hints = {room_id: topic_hint} if topic_hint else {}
if messages is None:
messages = [
MockEntry(role="user", text="Kannst du die LAN-Doku aktualisieren?"),
MockEntry(role="assistant", text="Ja, mache ich."),
MockEntry(role="user", text="Danke!"),
]
return MockHistory(messages, topic_hint=topic_hint)
# ── Tests: Heuristische Marker-Erkennung ──────────────────────────────────
class TestV7_4_RecursiveMarkers(unittest.TestCase):
"""V7-4: Heuristische Marker-Erkennung (Ebene 1)."""
def test_all_markers_are_detected(self):
"""Jeder RECURSIVE_MARKER wird erkannt."""
for marker in RECURSIVE_MARKERS:
text = f"Lass uns {marker} auf das Thema zurückkommen"
result = BidirectionalRouter._has_recursive_marker(text)
self.assertTrue(
result,
f"Marker '{marker}' wurde nicht erkannt in: '{text}'",
)
def test_marker_case_insensitive(self):
"""Marker-Erkennung ist case-insensitive."""
text = "Lass uns NOCHMAL auf das Thema zurückkommen"
self.assertTrue(BidirectionalRouter._has_recursive_marker(text))
text = "Lass uns Nochmal auf das Thema zurückkommen"
self.assertTrue(BidirectionalRouter._has_recursive_marker(text))
def test_marker_in_middle_of_text(self):
"""Marker wird auch mitten im Text erkannt."""
text = "Ich würde gerne nochmal auf die LAN-Doku zurückkommen"
self.assertTrue(BidirectionalRouter._has_recursive_marker(text))
def test_no_marker_returns_false(self):
"""Ohne Marker → False."""
text = "Ich habe eine neue Frage zur LAN-Dokumentation"
self.assertFalse(BidirectionalRouter._has_recursive_marker(text))
def test_no_marker_simple_question(self):
"""Einfache Frage ohne Marker → False."""
text = "Wie funktioniert das Routing?"
self.assertFalse(BidirectionalRouter._has_recursive_marker(text))
def test_no_marker_empty_text(self):
"""Leerer Text → False."""
self.assertFalse(BidirectionalRouter._has_recursive_marker(""))
def test_marker_substring_match(self):
"""Marker werden als Substring erkannt (nicht nur als Wort)."""
# 'nochmal' ist in 'nochmalig' enthalten
text = "Eine nochmalige Betrachtung wäre gut"
self.assertTrue(BidirectionalRouter._has_recursive_marker(text))
def test_all_specified_markers_from_requirements(self):
"""Alle in der Anforderung genannten Marker sind enthalten."""
required = [
"nochmal", "zurückkommen", "zurück gehen", "eingefallen",
"wie wir", "als du", "davor", "gerade", "vorhin", "nochmal auf",
]
for marker in required:
self.assertIn(marker, RECURSIVE_MARKERS,
f"Marker '{marker}' fehlt in RECURSIVE_MARKERS")
# ── Tests: _detect_recursive_reference (ohne LLM) ─────────────────────────
class TestV7_4_DetectRecursiveReference(unittest.TestCase):
"""V7-4: _detect_recursive_reference Tests (mit Mock-LLM)."""
def setUp(self):
self.room_map = _make_mock_room_map()
self.classifier = _make_mock_classifier()
self.state = ArchivarState()
self.state._loaded = True
def _make_router(self, conversation_history=None):
return BidirectionalRouter(
self.room_map,
self.classifier,
self.state,
conversation_history=conversation_history,
)
def test_no_marker_returns_none_no_llm_call(self):
"""Ohne Marker → None, kein LLM-Call (Performance)."""
router = self._make_router()
result = asyncio.run(
router._detect_recursive_reference(
"Ich habe eine neue Frage", "room_test"
)
)
self.assertIsNone(result)
# LLM wurde NICHT aufgerufen
self.classifier._llm_raw.assert_not_called()
def test_marker_triggers_llm_check(self):
"""Marker gefunden → LLM wird aufgerufen."""
router = self._make_router()
self.classifier._llm_raw.return_value = "NEU"
result = asyncio.run(
router._detect_recursive_reference(
"Lass uns nochmal auf LAN-Doku zurückkommen", "room_test"
)
)
self.assertIsNone(result) # LLM sagt NEU
self.classifier._llm_raw.assert_called_once()
def test_llm_says_rekursiv_with_topic(self):
"""LLM sagt REKURSIV: lan-dokumentation → Topic wird returned."""
router = self._make_router()
self.classifier._llm_raw.return_value = "REKURSIV: lan-dokumentation"
result = asyncio.run(
router._detect_recursive_reference(
"Lass uns nochmal auf LAN-Doku zurückkommen", "room_test"
)
)
self.assertEqual(result, "lan-dokumentation")
def test_llm_says_rekursiv_without_topic_uses_old_topic(self):
"""LLM sagt REKURSIV ohne Topic → old_topic aus Historie."""
history = _make_mock_conversation_history(
room_id="room_test",
topic_hint="lan-dokumentation",
)
router = self._make_router(conversation_history=history)
self.classifier._llm_raw.return_value = "REKURSIV"
result = asyncio.run(
router._detect_recursive_reference(
"Lass uns nochmal darauf zurückkommen", "room_test"
)
)
self.assertEqual(result, "lan-dokumentation")
def test_llm_says_neu(self):
"""LLM sagt NEU → None."""
router = self._make_router()
self.classifier._llm_raw.return_value = "NEU"
result = asyncio.run(
router._detect_recursive_reference(
"Ich habe eine neue Frage zu LAN-Doku", "room_test"
)
)
self.assertIsNone(result)
def test_llm_timeout_fallback_neu(self):
"""LLM-Timeout → Fallback NEU (None)."""
router = self._make_router()
self.classifier._llm_raw.side_effect = asyncio.TimeoutError()
result = asyncio.run(
router._detect_recursive_reference(
"Lass uns nochmal auf LAN-Doku zurückkommen", "room_test"
)
)
self.assertIsNone(result)
def test_llm_error_fallback_neu(self):
"""LLM-Fehler → Fallback NEU (None)."""
router = self._make_router()
self.classifier._llm_raw.side_effect = Exception("Ollama down")
result = asyncio.run(
router._detect_recursive_reference(
"Lass uns nochmal auf LAN-Doku zurückkommen", "room_test"
)
)
self.assertIsNone(result)
def test_llm_returns_none_fallback_neu(self):
"""LLM returned None → Fallback NEU."""
router = self._make_router()
self.classifier._llm_raw.return_value = None
result = asyncio.run(
router._detect_recursive_reference(
"Lass uns nochmal auf LAN-Doku zurückkommen", "room_test"
)
)
self.assertIsNone(result)
def test_with_conversation_history_context(self):
"""Konversationshistorie wird in den Prompt eingebaut."""
history = _make_mock_conversation_history(
room_id="room_test",
messages=[
MagicMock(role="user", text="Alte Frage"),
MagicMock(role="assistant", text="Alte Antwort"),
],
)
router = self._make_router(conversation_history=history)
self.classifier._llm_raw.return_value = "NEU"
asyncio.run(
router._detect_recursive_reference(
"Lass uns nochmal zurückkommen", "room_test"
)
)
# Prüfe dass der Prompt die Historie enthält
call_args = self.classifier._llm_raw.call_args[0][0]
self.assertIn("Alte Frage", call_args)
self.assertIn("Alte Antwort", call_args)
self.assertIn("Lass uns nochmal zurückkommen", call_args)
# ── Tests: Wiederherstellung (VERBLASST → AKTIV) ──────────────────────────
class TestV7_4_RestoreOnRecursiveReference(unittest.TestCase):
"""V7-4: Wiederherstellung bei rekursivem Bezug."""
def setUp(self):
self.room_map = _make_mock_room_map()
self.classifier = _make_mock_classifier()
self.state = ArchivarState()
self.state._loaded = True
def _make_router(self, conversation_history=None):
return BidirectionalRouter(
self.room_map,
self.classifier,
self.state,
conversation_history=conversation_history,
)
def test_restore_verblasst_on_recursive_reference(self):
"""Rekursiver Bezug auf VERBLASST → restore + stay_in_room."""
room_id = "r_proton"
topic = "lan-dokumentation"
# Setze VERBLASSTEN never_route Eintrag
self.state.set_never_route(room_id, topic)
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
# LLM sagt REKURSIV
self.classifier._llm_raw.return_value = f"REKURSIV: {topic}"
router = self._make_router()
decision = asyncio.run(
router.route(
"Lass uns nochmal auf LAN-Doku zurückkommen",
origin_room_id=room_id,
)
)
# Soll stay_in_room sein (Butler NICHT auslösen)
self.assertTrue(decision.stay_in_room)
# Eintrag sollte wieder AKTIV sein
entry = self.state._never_route[room_id][topic]
self.assertEqual(entry["state"], "AKTIV")
def test_extend_already_aktiv_on_recursive_reference(self):
"""Rekursiver Bezug auf bereits AKTIV → extend + stay_in_room."""
room_id = "r_proton"
topic = "lan-dokumentation"
# Setze AKTIVEN never_route Eintrag
self.state.set_never_route(room_id, topic)
old_count = self.state._never_route[room_id][topic]["extension_count"]
# LLM sagt REKURSIV
self.classifier._llm_raw.return_value = f"REKURSIV: {topic}"
router = self._make_router()
decision = asyncio.run(
router.route(
"Lass uns nochmal auf LAN-Doku zurückkommen",
origin_room_id=room_id,
)
)
# Soll stay_in_room sein
self.assertTrue(decision.stay_in_room)
# extension_count sollte erhöht sein
new_count = self.state._never_route[room_id][topic]["extension_count"]
self.assertEqual(new_count, old_count + 1)
def test_no_never_route_entry_normal_flow(self):
"""Rekursiver Bezug ohne never_route Eintrag → normaler Flow."""
room_id = "r_proton"
# LLM sagt REKURSIV aber es gibt keinen Eintrag
self.classifier._llm_raw.return_value = "REKURSIV: lan-dokumentation"
router = self._make_router()
# Sollte nicht crashen — normaler Flow geht weiter
decision = asyncio.run(
router.route(
"Lass uns nochmal auf LAN-Doku zurückkommen",
origin_room_id=room_id,
)
)
# Sollte nicht None sein
self.assertIsNotNone(decision)
def test_new_question_allows_butler(self):
"""'Ich habe eine neue Frage zu X' → NEU → Butler darf fragen."""
room_id = "r_proton"
topic = "lan-dokumentation"
# Setze VERBLASSTEN never_route Eintrag
self.state.set_never_route(room_id, topic)
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
# LLM sagt NEU
self.classifier._llm_raw.return_value = "NEU"
router = self._make_router()
decision = asyncio.run(
router.route(
"Ich habe eine neue Frage zu LAN-Doku",
origin_room_id=room_id,
)
)
# Sollte NICHT stay_in_room durch never_route sein
# (normaler Flow: kann Butler auslösen oder stay_in_room durch
# andere Guards, aber nicht durch restore)
# Der Eintrag bleibt VERBLASST
entry = self.state._never_route[room_id][topic]
self.assertEqual(entry["state"], "VERBLASST")
def test_recursive_reference_updates_topic_hint(self):
"""Rekursiver Bezug aktualisiert topic_hint in conversation_history."""
room_id = "r_proton"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
self.classifier._llm_raw.return_value = f"REKURSIV: {topic}"
history = _make_mock_conversation_history(
room_id=room_id,
topic_hint="altes-thema",
)
router = self._make_router(conversation_history=history)
asyncio.run(
router.route(
"Lass uns nochmal auf LAN-Doku zurückkommen",
origin_room_id=room_id,
)
)
# topic_hint sollte aktualisiert sein
self.assertEqual(
history._topic_hints.get(room_id),
topic,
)
def test_recursive_reference_butler_not_triggered(self):
"""Bei rekursivem Bezug wird Butler NICHT ausgelöst."""
room_id = "r_proton"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
self.classifier._llm_raw.return_value = f"REKURSIV: {topic}"
router = self._make_router()
decision = asyncio.run(
router.route(
"Lass uns nochmal auf LAN-Doku zurückkommen",
origin_room_id=room_id,
)
)
# move_request_sent muss False sein (Butler nicht ausgelöst)
self.assertFalse(decision.move_request_sent)
self.assertTrue(decision.stay_in_room)
# ── Tests: LLM-Prompt ─────────────────────────────────────────────────────
class TestV7_4_LLMPrompt(unittest.TestCase):
"""V7-4: LLM-Prompt für rekursive Erkennung."""
def test_prompt_contains_required_sections(self):
"""Prompt enthält alle erforderlichen Abschnitte."""
self.assertIn("KONVERSATIONSHISTORIE", _RECURSIVE_DETECTION_PROMPT)
self.assertIn("AKTUELLE NACHRICHT", _RECURSIVE_DETECTION_PROMPT)
self.assertIn("ALTES THEMA", _RECURSIVE_DETECTION_PROMPT)
self.assertIn("REKURSIV", _RECURSIVE_DETECTION_PROMPT)
self.assertIn("NEU", _RECURSIVE_DETECTION_PROMPT)
def test_prompt_has_format_placeholders(self):
"""Prompt hat die richtigen Format-Platzhalter."""
self.assertIn("{history}", _RECURSIVE_DETECTION_PROMPT)
self.assertIn("{current_message}", _RECURSIVE_DETECTION_PROMPT)
self.assertIn("{old_topic}", _RECURSIVE_DETECTION_PROMPT)
def test_prompt_distinguishes_recursive_vs_new(self):
"""Prompt enthält die kritische Unterscheidung."""
self.assertIn(
"Lass uns nochmal auf X zurückkommen",
_RECURSIVE_DETECTION_PROMPT,
)
self.assertIn(
"Ich habe eine neue Frage zu X",
_RECURSIVE_DETECTION_PROMPT,
)
def test_prompt_formats_correctly(self):
"""Prompt.format() funktioniert mit allen Platzhaltern."""
formatted = _RECURSIVE_DETECTION_PROMPT.format(
history="Test History",
current_message="Test Message",
old_topic="test-topic",
)
self.assertIn("Test History", formatted)
self.assertIn("Test Message", formatted)
self.assertIn("test-topic", formatted)
# ── Tests: _detect_topic_change (V7-3 Lücke) ──────────────────────────────
class TestV7_3_TopicChangeDetection(unittest.TestCase):
"""V7-3: _detect_topic_change Tests (Lücke aus V7-3 Review)."""
def setUp(self):
self.room_map = _make_mock_room_map()
self.classifier = _make_mock_classifier()
self.state = ArchivarState()
self.state._loaded = True
def _make_router(self, conversation_history=None):
return BidirectionalRouter(
self.room_map,
self.classifier,
self.state,
conversation_history=conversation_history,
)
def test_topic_change_verblasst_old_topic(self):
"""Themenwechsel: altes AKTIV → VERBLASST."""
room_id = "room_test"
old_topic = "lan-dokumentation"
new_topic = "protonbridge"
# Setze AKTIVEN never_route für altes Thema
self.state.set_never_route(room_id, old_topic)
history = _make_mock_conversation_history(
room_id=room_id,
topic_hint=old_topic,
)
router = self._make_router(conversation_history=history)
router._detect_topic_change(room_id, new_topic)
# Altes Thema sollte VERBLASST sein
old_entry = self.state._never_route[room_id][old_topic]
self.assertEqual(old_entry["state"], "VERBLASST")
def test_same_topic_extends(self):
"""Gleiches Thema → extend_never_route."""
room_id = "room_test"
topic = "lan-dokumentation"
self.state.set_never_route(room_id, topic)
old_count = self.state._never_route[room_id][topic]["extension_count"]
history = _make_mock_conversation_history(
room_id=room_id,
topic_hint=topic,
)
router = self._make_router(conversation_history=history)
router._detect_topic_change(room_id, topic)
new_count = self.state._never_route[room_id][topic]["extension_count"]
self.assertEqual(new_count, old_count + 1)
def test_no_old_topic_sets_new_topic_hint(self):
"""Kein altes Thema → topic_hint wird gesetzt."""
room_id = "room_test"
new_topic = "lan-dokumentation"
history = _make_mock_conversation_history(
room_id=room_id,
topic_hint=None,
)
router = self._make_router(conversation_history=history)
router._detect_topic_change(room_id, new_topic)
self.assertEqual(
history._topic_hints.get(room_id),
new_topic,
)
def test_no_conversation_history_no_error(self):
"""Ohne conversation_history → kein Fehler."""
router = self._make_router(conversation_history=None)
# Sollte nicht crashen
router._detect_topic_change("room_test", "lan-dokumentation")
def test_topic_change_updates_topic_hint(self):
"""Themenwechsel aktualisiert topic_hint."""
room_id = "room_test"
old_topic = "lan-dokumentation"
new_topic = "protonbridge"
self.state.set_never_route(room_id, old_topic)
history = _make_mock_conversation_history(
room_id=room_id,
topic_hint=old_topic,
)
router = self._make_router(conversation_history=history)
router._detect_topic_change(room_id, new_topic)
self.assertEqual(
history._topic_hints.get(room_id),
new_topic,
)
if __name__ == "__main__":
unittest.main()
+7 -17
View File
@@ -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
+79
View File
@@ -958,6 +958,84 @@ ROCKETCHAT_FILES_SCHEMA = {
}
# ── Proaktiver Raum-Broadcast (B6) ──────────────────────────────────────
# Cooldown-Tracking: verhindert Spam bei vielen kleinen Aktionen.
# Nur "Fertig"-Markierungen triggern einen Broadcast.
_broadcast_cooldowns: Dict[str, float] = {} # room_id → timestamp
_BROADCAST_COOLDOWN_SECONDS: float = 300.0 # 5 Minuten
def _handle_rocketchat_broadcast(args: dict, **kw) -> str:
"""Sende einen proaktiven Status-Broadcast in einen Projektraum.
Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.'
Cooldown: 5 Minuten pro Raum — verhindert Spam bei vielen kleinen Aktionen.
Nur bei expliziten "Fertig"-Markierungen verwenden, nicht bei jeder kleinen Aktion.
Args:
room_id: Zielraum-ID (aus room-map.json oder ROCKETCHAT.MAP.md)
text: Der Broadcast-Text (menschenähnlich, kein Bot-Ton)
"""
global _broadcast_cooldowns
client = _rc_client()
if not client:
return _rc_error()
room_id = str(args.get("room_id") or "").strip()
text = str(args.get("text") or "").strip()
if not room_id:
return tool_error("room_id is required for rocketchat_broadcast")
if not text:
return tool_error("text is required for rocketchat_broadcast")
# Cooldown-Check
now = time.time()
last = _broadcast_cooldowns.get(room_id, 0.0)
if now - last < _BROADCAST_COOLDOWN_SECONDS:
remaining = int(_BROADCAST_COOLDOWN_SECONDS - (now - last))
return tool_result({
"success": False,
"cooldown": True,
"message": f"Broadcast-Cooldown aktiv: noch {remaining}s für Raum {room_id[:8]}...",
})
try:
result = client.send_message(room_id, text)
if result.get("success"):
_broadcast_cooldowns[room_id] = now
return tool_result({
"success": True,
"room_id": room_id,
"text": text[:200],
})
else:
return tool_error(f"Broadcast failed: {result.get('error', 'unknown error')}")
except Exception as exc:
return tool_error(f"rocketchat_broadcast failed: {type(exc).__name__}: {exc}")
ROCKETCHAT_BROADCAST_SCHEMA = {
"name": "rocketchat_broadcast",
"description": (
"Send a proactive status broadcast to a project room. "
"Use this after completing a task to inform the team. "
"Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.' "
"Cooldown: 5 minutes per room to prevent spam. "
"Only use for explicit 'done' markers, not for every small action."
),
"parameters": {
"type": "object",
"properties": {
"room_id": {"type": "string", "description": "Target project room ID (from room-map.json)"},
"text": {"type": "string", "description": "Broadcast message (human-like, not bot-like)"},
},
"required": ["room_id", "text"],
},
}
# ---------------------------------------------------------------------------
# Registration helpers for the plugin register() function
# ---------------------------------------------------------------------------
@@ -970,6 +1048,7 @@ _TOOLS = (
("rocketchat_upload", ROCKETCHAT_UPLOAD_SCHEMA, _handle_rocketchat_upload, "📎"),
("rocketchat_download", ROCKETCHAT_DOWNLOAD_SCHEMA, _handle_rocketchat_download, "📥"),
("rocketchat_files", ROCKETCHAT_FILES_SCHEMA, _handle_rocketchat_files, "📁"),
("rocketchat_broadcast", ROCKETCHAT_BROADCAST_SCHEMA, _handle_rocketchat_broadcast, "📢"),
)
+130
View File
@@ -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"
}
+28
View File
@@ -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())
+73
View File
@@ -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())
+57
View File
@@ -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())
+3
View File
@@ -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
+39
View File
@@ -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
+5
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
{
"version": 1,
"rooms": {},
"excluded_rooms": [],
"fact_store_path": "PLACEHOLDER_VAULT_PATH"
}
+604
View File
@@ -0,0 +1,604 @@
"""
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
# ═══════════════════════════════════════════════════════════════════════════
# M13: cleanup_orphaned_rooms Tests
# ═══════════════════════════════════════════════════════════════════════════
class TestBoosterCleanup:
"""M13: Tests für KeywordBooster.cleanup_orphaned_rooms()."""
@pytest.fixture
def booster(self) -> KeywordBooster:
return KeywordBooster(_make_booster_room_map())
def test_cleanup_rebuilds_mapping(self, booster: KeywordBooster) -> None:
"""cleanup_orphaned_rooms() baut das Mapping aus der aktuellen RoomMap neu."""
before = len(booster._keyword_to_rooms)
# Entferne room_b aus der RoomMap (simuliert GC)
del booster._room_map._rooms["room_b"]
# Cleanup mit nur noch room_a + room_catchall als gültig
after = booster.cleanup_orphaned_rooms({"room_a", "room_catchall"})
# Mapping sollte kleiner sein (room_b's unique keywords sind weg)
assert after < before
# "bat" war unique für room_b → sollte nicht mehr im Mapping sein
assert "bat" not in booster._keyword_to_rooms
# "plugin" war unique für room_a → sollte noch da sein
assert "plugin" in booster._keyword_to_rooms
assert booster._keyword_to_rooms["plugin"] == {"room_a"}
def test_cleanup_no_orphans_returns_same_count(self, booster: KeywordBooster) -> None:
"""Keine orphaned Räume → Mapping bleibt gleich groß."""
before = len(booster._keyword_to_rooms)
after = booster.cleanup_orphaned_rooms({"room_a", "room_b", "room_catchall"})
assert after == before
def test_cleanup_all_rooms_removed_returns_zero(self, booster: KeywordBooster) -> None:
"""Alle nicht-catch-all Räume entfernt → leeres Mapping."""
# Entferne ALLE nicht-catch-all Räume
del booster._room_map._rooms["room_a"]
del booster._room_map._rooms["room_b"]
# room_catchall bleibt (catch_all=True, wird von _build_mapping ignoriert)
after = booster.cleanup_orphaned_rooms({"room_catchall"})
assert after == 0
assert len(booster._keyword_to_rooms) == 0
def test_cleanup_then_boost_still_works(self, booster: KeywordBooster) -> None:
"""Nach Cleanup: Boost funktioniert korrekt mit bereinigtem Mapping."""
# Entferne room_b
del booster._room_map._rooms["room_b"]
booster.cleanup_orphaned_rooms({"room_a", "room_catchall"})
scores: list[tuple[str, float]] = [
("room_a", 0.80),
("room_catchall", 0.60),
]
result = booster.boost("plugin bug", scores)
# "plugin" ist unique für room_a → +0.10 (tatsächlicher Boost-Wert)
assert result[0][0] == "room_a"
assert result[0][1] == pytest.approx(0.90)
+510
View File
@@ -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
@@ -0,0 +1,19 @@
{
"rooms": {},
"keyword_weights": {},
"sticky_keywords": {},
"manual_overrides": {},
"promotion_candidates": {},
"stay_tracker": {},
"onboarding_state": {},
"never_route": {
"r_proton": {
"lan-dokumentation": {
"state": "AKTIV",
"timestamp": "2026-07-13T20:34:20.149597",
"last_extended": "2026-07-13T20:34:20.149597",
"extension_count": 0
}
}
}
}