66 Commits

Author SHA1 Message Date
Bernd (Hermes) 407014db98 fix: LLM-Timeout 15s — qwen2.5:7b auf CPU braucht 9s, 3s war zu kurz 2026-07-27 17:38:06 +02:00
Bernd (Hermes) d265624f1c fix(critical): Timeout-Hierarchie umkehren — innere Timeouts 3s < äußere 4s + Semaphore-Timeout + Embedding-Deadline
ROOT-CAUSE: Die Timeout-Hierarchie war umgekehrt. Der äußere
wait_for(4s) in adapter.py konnte nie feuern, weil die inneren
wait_for(25s) in classifier.py die Coroutine blockierten.

AENDERUNGEN:
- classifier.py: _llm_raw, _llm_classify, verify_confidence: 25.0s → 3.0s
- classifier.py: OllamaEmbeddingClient.get_embedding: ThreadPoolExecutor
  mit .result(timeout=3.0) statt nacktem urllib.urlopen
- router.py: _llm_semaphore.acquire() mit asyncio.wait_for(timeout=3.0)
  an 3 Stellen (_llm_room_lookup, _detect_recursive,
  _validate_sentence_marker_llm)
- config.py: LLM_CONFIG timeout 10.0 → 3.0
- config.py: OLLAMA_CONFIG timeout 10.0 → 3.0

TIMEOUT-HIERARCHIE (nach Fix):
  adapter.py wait_for: 4.0s (äußerst)
  router.py semaphore acquire: 3.0s
  classifier.py LLM-Calls: 3.0s
  classifier.py Embedding-Calls: 3.0s
  config.py LLM_CONFIG timeout: 3.0s
  config.py OLLAMA_CONFIG timeout: 3.0s

Der äußere 4s-Timeout gewinnt jetzt immer.
2026-07-27 17:17:16 +02:00
Bernd (Hermes) 4bfac6a689 fix(critical): pulse_interval default 5.0 + ThreadPoolExecutor lazy init im Main-Loop 2026-07-27 16:09:32 +02:00
Bernd (Hermes) 1969887eb7 fix(critical): SyntaxError — global _question_counter vor try-Block verschoben
Don fand beim Deployment einen SyntaxError: 'global _question_counter'
war im except-Block deklariert (Python erlaubt global nur am Funktions-
Anfang). Verschoben vor den try-Block, Duplikate entfernt.

Gefunden von Don beim Deployment des Event-Loop-Blockade-Fixes (6990419).
2026-07-27 16:07:51 +02:00
Bernd (Hermes) 6990419bd0 fix(critical): Event-Loop-Blockade — ThreadPool-Saturation + Pulse-Interval + Classifier-Timeout
Root-Cause (Rainer): Pulse-Thread + Adapter-Calls + DDP-Fallback-Lawine
sättigen den ThreadPool (asyncio.to_thread). Der Loop-Selector kann
Watchdog-Probes nicht ausführen → 3 Strikes → Kill.

Änderungen:
- adapter.py: classify_and_route in asyncio.wait_for(4s), Timeout → STAY
- adapter.py: ThreadPoolExecutor max_workers=32 in on_connected_cb
- presence_engine.py: pulse_interval 1.5→5.0, sync-default, 2-stufiger CB
- classifier.py: _llm_raw/_llm_classify/verify_confidence in wait_for(25s)
2026-07-27 16:01:55 +02:00
Bernd (Hermes) 82c2713929 fix(P0): datetime UnboundLocalError in _process_incoming — local import shadows module-level import 2026-07-27 08:37:29 +02:00
Bernd (Hermes) 99fa42df33 fix(P2): F6 Nachbesserung — raumbezogener TopicRing-Lookup + Doku + Test
P1 Fix 1: Raumbezogener Lookup in send() und send_clarify()
- Statt user-weitem get_active_topic_for_chat(chat_id) wird jetzt
  erst raumbezogen get_active_topic(origin_room) geprüft.
- _room_context liefert den Kandidaten-Raum, dann wird der aktive
  Topic NUR für diesen Raum geholt — nicht user-weit.
- Erst wenn kein raumbezogener Treffer → user-weiter Fallback.
- Verhindert Cross-Contamination: Antwort in Raum A liefert Topic A,
  nicht den user-weit neuesten Topic B.

P1 Fix 2: Doc-Kommentare _get_snapshot() + _invalidate_snapshot()
- Klargestellt: Snapshot spiegelt Stand zum Zeitpunkt der letzten
  Schreib-Invalidation. Lock-free Reads sind konsistent zu diesem
  Zeitpunkt, NICHT zwingend aktuell.

P1 Fix 3: Real-World Cross-Contamination Test
- test_cross_contamination_real_world: Andreas schreibt in A und B,
  get_active_topic(A) muss A liefern, get_active_topic(B) muss B
  liefern. User-weiter Lookup würde B liefern (Cross-Contamination).

P3 Nits:
- datetime Re-Import in adapter.py Z.3167 entfernt (global import reicht)
- Doc Z.6 "lock-free Reads via copy-on-write" präzisiert

Tests: 40/40 passed
2026-07-26 12:48:00 +02:00
Bernd (Hermes) a9c436a7fa feat(P2): Themenring Phase A — In-Memory Ringmatrix für menschenähnliche Kommunikation
Herzstück der Multi-Room-Kommunikation: Andreas arbeitet gleichzeitig an
mehreren Themen in verschiedenen Räumen. Der Themenring speichert pro Raum
eine deque von TopicEntry-NamedTuples und erlaubt lock-free Reads via
Copy-on-Write-Snapshot.

Änderungen:
- NEU: plugin/archivar/topic_ring.py — TopicRing Klasse mit Single-Reader-
  Multi-Writer Pattern, TTL-basierter GC, periodischem Prune-Sweep
- NEU: plugin/archivar/tests/test_topic_ring.py — 39 Tests (CRUD, TTL,
  GC per-room/global, Thread-Safety, Cross-Contamination, send()-Integration)
- config.py: TOPIC_RING_MAX_PER_ROOM=5, GLOBAL_MAX=200, TTLs, PRUNE_INTERVAL
- adapter.py: T1 Ring-Befüllung in _process_incoming() NACH Archivar-
  Klassifikation; Prio 1 TopicRing-Lookup in send() und send_clarify()
  VOR _room_context-Fallback

Prioritäten-Kette in send():
  Prio 0: _CURRENT_ORIGIN_ROOM (ContextVar) — UNVERÄNDERT
  Prio 1: TopicRing.get_active_topic_for_chat() — NEU
  Prio 1.5: _room_context (Stream-Retry Fallback) — BESTEHT
  Prio 2: _THEMATIC_TARGET_ROOM — UNVERÄNDERT
  Prio 3: _user_rooms[-1] — UNVERÄNDERT
  Prio 4: _find_fallback_room_for_user — UNVERÄNDERT

Tests: 1383 passed + 39 new = 1422 total (4 pre-existing failures)
2026-07-26 12:40:16 +02:00
Bernd (Hermes) aefdad0024 fix(P1): Context-Cross-Contamination — Task-Token + TTL-Sweep für _room_context
Problem: _room_context speichert nur EINEN origin_room pro chat_id.
Wenn ein User gleichzeitig in 2 Räumen aktiv ist, überschreibt der
letzte Dispatch den anderen. Antwort landet im falschen Raum.

Stufe 1 — Task-Token:
- _room_context[chat_id] bekommt task_token (UUID4) + timestamp (ISO)
- _set_room_context_origin() generiert Token, setzt _CURRENT_TASK_TOKEN
- _get_room_context_origin() validiert: Token-Match → verwenden;
  Token-Mismatch → Cross-Contamination → ignorieren
- _dispatch_agent() ruft _set_room_context_origin() vor copy_context()
  auf, damit der Drain-Task das korrekte Token eingefroren bekommt

Stufe 2 — TTL-Sweep:
- Einträge älter als 30 Min werden von _get_room_context_origin()
  ignoriert (log Warning "stale room_context entry")
- Backward-Kompatibilität: alte Einträge ohne timestamp/task_token
  werden trotzdem verwendet

Tests (10 neue, 20 total in test_v8_1_p1_contextvar.py):
- Token-Match / Token-Mismatch / Cross-Contamination
- Stream-Retry mit Token / ohne Token (TTL gültig)
- TTL abgelaufen → Fallback auf nächste Priorität
- Backward-Kompatibilität für alte Einträge
- _set_room_context_origin generiert UUID4 + ISO-Timestamp

Baseline: 1335 passed, 3 pre-existing failures, 2 skipped
After:   1345 passed, 3 pre-existing failures, 2 skipped
2026-07-26 11:46:51 +02:00
Bernd (Hermes) c8944ec69b fix(install.sh): Post-Deployment --since Zeitstempel vor Gateway-Neustart setzen
_verify_since wurde bisher NACH dem Gateway-Neustart (und nach sleep 20)
gesetzt, wodurch journalctl --since die Initialisierungs-Logs
(PresenceEngine, Archivar, Connected) nicht fand — die erscheinen in den
ersten 6-10s nach Gateway-Start.

Fix: _verify_since VOR restart_gateway setzen, alte redundante Zuweisung
in der Verifikations-Sektion entfernt.
2026-07-26 10:59:26 +02:00
Bernd (Hermes) bf67761a57 fix(P1): F6 Nachbesserung — 4 fehlende _room_context Stellen + Inkonsistenz + Tests
P0: 4 ungepatchte _CURRENT_ORIGIN_ROOM.set() Stellen mit _room_context gefüllt:
- Z.2924: topic_scoped_sticky match → target_room_id
- Z.2969: topic_scoped_sticky (zweiter Branch) → target_room_id
- Z.3141: Auto-Route (V8.1 P1 path) → target_room_id
- Z.3196: Default-Origin (stay_in_room) → room_id

P1: send_clarify() Reihenfolge getauscht:
- _room_context VOR _THEMATIC_TARGET_ROOM (exakt wie in send())

P1: Helper-Funktion _set_room_context_origin() eingeführt:
- Atomare setdefault + Index-Zuweisung unter _room_context_lock
- An allen 10 Stellen verwendet (9 _CURRENT_ORIGIN_ROOM.set() + 1 initial set)

P1: 3 neue Tests:
- Test 8: send_clarify mit leerer ContextVar → _room_context Fallback
- Test 9: Concurrency — 10 parallele Tasks, 5 set + 5 read
- Test 10: Stale-Entry — _room_context gewinnt gegen _user_rooms
2026-07-26 10:34:00 +02:00
Bernd (Hermes) fdc755a87e fix(P1): _room_context als persistenter Fallback bei Stream-Retry ContextVar-Reset
Block A — send()/send_clarify() lesen _room_context:
- In send() (Z.6395-6421): nach ContextVar-Prio-0, vor thematic_target
  und _user_rooms, _room_context[chat_id]["origin_room"] als Fallback.
- In send_clarify() (Z.6773-6803): gleicher Fallback nach ContextVar.
- Telemetrie: routing_counter.increment("contextvar_reset_fallback")
  wenn dieser Pfad greift.

Block B — _room_context konsequent füllen (7 Stellen):
- _process_incoming (Z.1996-2002): IMMER setzen bei jeder Nachricht.
- Clarify dispatch (Z.2221-2225): pending["username"] → vcid.
- move_req confirm (Z.2327-2331): username → vcid.
- stay_here dispatch (Z.2538-2542): username → vcid.
- Widerspruch-Rückkehr (Z.2661-2665): username → vcid.
- Auto-Route (Z.2761-2765): username → vcid.
- Red Flag (Z.6349-6353): chat_id direkt (in send() verfügbar).
- Alle Zugriffe unter _room_context_lock (Thread-Safety).

Block C — Tests (test_v8_1_p1_contextvar.py):
- Test 6: send_with_empty_contextvar_falls_back_to_room_context
- Test 7: stream_retry_simulates_fresh_contextvar
- Beide: ContextVar leer, _room_context hat origin_room,
  _user_rooms falsch/leer → korrektes Routing über _room_context.

Tests: 1332 passed, 3 pre-existing failures, 2 skipped.
2026-07-26 10:08:31 +02:00
Bernd (Hermes) 7498b41675 fix(install.sh): Post-Deployment-Verifikation Timing — 20s initial, 5 Versuche, Prozess-Check vorab 2026-07-26 09:50:22 +02:00
Bernd (Hermes) a41f5e18ed fix(P0): stay_here/stay_once dispatched Originalnachricht an Agent — Datenverlust behoben
Root Cause: Der else-Zweig (Button 2/3: stay_here/stay_once) in
_process_incoming loggte nur "skipping" und returnte, ohne die
Originalnachricht aus move_req["text"] an den Agenten weiterzuleiten.
Da der move_request_pending_guard den initialen Dispatch blockiert,
war die Nachricht NUR in move_req["text"] verfügbar — nach dem
pop() war sie komplett verloren.

Fix:
- else-Zweig holt origin_text aus move_req.get("text", "")
- Bei leerem Text: logger.warning + return (kein Dispatch)
- Setzt _CURRENT_ORIGIN_ROOM auf room_id (User bleibt im Ursprungsraum)
- _THEMATIC_TARGET_ROOM wird NICHT gesetzt (kein Themenwechsel)
- Dispatch via _dispatch_agent mit room_id=Ursprungsraum, category="work_order"
- Telemetrie-Counter "stay_here_dispatched" wird incrementiert

Tests: 3 neue Tests in test_p0_stay_here_dispatch.py
- test_stay_here_dispatches_original_message
- test_stay_once_dispatches_original_message
- test_stay_here_empty_text_skips_dispatch

Ergebnis: 1330 passed, 3 pre-existing failures, 2 skipped
2026-07-26 09:36:06 +02:00
Bernd (Hermes) 20da8a9aeb fix(p1-2): E1 Lock-Scope erweitert + E2 Concurrency-Test
E1: Lock-Scope in increment_background_tasks und decrement_background_tasks
erweitert — _persist_plugin_state wird jetzt unter _background_tasks_lock
aufgerufen. Verhindert dass bei zwei konkurrierenden Threads ein veralteter
Count persistiert wird.

E2: Concurrency-Test für _write_plugin_state — zwei Threads schreiben
parallel, danach wird verifiziert dass die Datei gültiges JSON enthält
(keine halbe Datei, kein korruptes JSON, keine .tmp-Leichen).
2026-07-26 06:08:02 +02:00
Bernd (Hermes) 6d8aab83a0 test(p1-2): Integrationstest — PresenceEngine übergibt plugin_state_path an DetectionTimer 2026-07-26 06:00:20 +02:00
Bernd (Hermes) 0f6821fa9c feat(p1-2): Telemetrie — heartbeat_detection_source Feld (gateway|plugin_state|pgrep|none) 2026-07-26 05:59:46 +02:00
Bernd (Hermes) 998ed2cedd feat(p1-2): DetectionTimer erkennt Plugin-State-Datei (background_tasks > 0 → active) 2026-07-26 05:57:54 +02:00
Bernd (Hermes) 4ac1d10b44 feat(p1-2): increment/decrement_background_tasks persistieren in Plugin-State-Datei 2026-07-26 05:56:30 +02:00
Bernd (Hermes) 56badac990 feat(p1-2): Plugin-State-Datei — atomare Hilfsfunktionen (_get_plugin_state_path, _read_plugin_state, _write_plugin_state) 2026-07-26 05:55:28 +02:00
Bernd (Hermes) 7523c41daa P1-1: RoomMap.save() Refuse-Guard und Single-Room-Pfad-Härtung
FIX A — Save-Robustheit (room_map.py):
- TOCTOU-Schutz: fcntl.flock(LOCK_EX) wird VOR dem Lesen erworben,
  nicht erst beim Schreiben. Eliminiert Race zwischen parallelen
  save()-Aufrufen.
- ID-Set-Differenz statt Count-Vergleich: Disk-IDs müssen Teilmenge
  von In-Memory-IDs sein (disk_room_ids.issubset(mem_room_ids)).
  Verhindert dass Maps mit gleicher Raum-Anzahl aber anderen IDs
  die Disk überschreiben.
- Backup-Mechanismus: Vor jedem Schreiben wird die existierende
  Datei nach '<path>.bak' kopiert (atomic via os.replace).
- force=True Parameter für administrative Aufrufe (Onboarding-Reset),
  die den Guard bewusst umgehen.
- Modul-Level-Helfer: _acquire_flock() (Retry-Loop, thread-safe)
  und _create_backup() (atomic copy2 + os.replace).

FIX B — Single-Room-Pfad-Härtung (onboarding.py):
- Pre-Mutation-Snapshot: Vor add_or_update_room() wird die
  Disk-Datei nach '<path>.onboarding_bak' gesichert.
- Post-Mutation-Integritätsprüfung nach save()+reload():
  1. Raum-Anzahl >= pre_mutation_count + 1?
  2. Existiert der ursprüngliche catch_all-Raum noch?
  Bei Fehler → automatisches Rollback aus Backup + Critical-Log.
- Telemetrie-Counter: single_room_catch_all_overwrite_attempted
  und single_room_catch_all_rolled_back.

Tests (test_single_room_refuse_guard.py, 10 Tests):
(a) Refuse-Guard triggert bei ID-Differenz + Backup wird geschrieben
(b) Konkurrierende save()-Aufrufe via threading → nur einer schreibt
(c) Rollback aus .bak-Datei nach Korruption
(d) Single-Room-Pfad Integritätsprüfung + Rollback

Baseline: 1297 passed, 3 pre-existing failures (unverändert)
Nach Fix: 1307 passed, 3 pre-existing failures (10 neue Tests grün)
2026-07-26 05:53:09 +02:00
Bernd (Hermes) bf42ba056e P2-Fix: UI-Polish — Ampelsymbole vereinheitlicht + Room-Map-Summary in ::status
FIX 1: 🔴/🟢/🟡 durch 🟥/🟩/🟨 ersetzt (Geometric Shapes Extended)
- Rocket.Chat rendert 🔴 etwa doppelt so groß wie 🟢/🟡
- 🟥/🟩/🟨 sind alle aus demselben Unicode-Block → konsistente Größe
- Betrifft build_help_text (Status-Farben-Sektion) und build_status_text (PresenceEngine-Info)

FIX 2: build_status_text erhält Längen-Guard (~5000 Zeichen)
- Bei Überschreitung wird die room_map_summary durch kompakte Version ersetzt
- Kompakt: nur Raum-Name + Catch-All-Marker, keine Keywords/Themes
- ::status zeigt jetzt immer die Raum-Map (vorher nur in ::hilfe, dort oft gekürzt)

Tests: 87/87 passed, build_help_text < 4000 chars, build_status_text < 5000 chars
2026-07-25 20:26:27 +02:00
Bernd (Hermes) 5d5a361993 P2-Fix: HTTP-Fehler-Logging von debug auf warning/error gehoben
- RocketChatREST._request: HTTP 4xx → logger.warning, HTTP 5xx → logger.error
  (vorher beide nur debug). Der HTTP 400 bei ::hilfe blieb dadurch unbemerkt.
- Generische Exceptions: logger.debug → logger.warning

Closes: Rainers Review P2-Fix 4
2026-07-25 20:12:21 +02:00
Bernd (Hermes) 1c53a9fe07 P1-Fix: build_help_text Längenbegrenzung + RoomMap.save Refuse-Guard
- build_help_text: Wenn Hilfe-Text > 4000 Zeichen, wird room_map_summary
  durch Platzhalter ersetzt. Verhindert HTTP 400 bei Rocket.Chat
  (Payload-Limit ~5000 Zeichen, ::hilfe mit 5 Räumen war 4571 Zeichen).
- RoomMap.save: Refuse-Guard prüft vor dem Schreiben, ob die existierende
  Disk-Datei mehr Räume enthält als die In-Memory-Map. Verweigert das
  Schreiben mit Warning wenn Disk > In-Memory. Verhindert Datenverlust
  beim Multiroom-Toggle (false→true schrieb leere Map).
- Tests: test_build_help_text_length_limit (max 4000 Zeichen),
  test_build_help_text_keeps_summary_when_short,
  TestRoomMapSaveRefuseGuard (4 Tests: refuse, allow-more, allow-equal,
  allow-no-disk).

Closes: Rainers Review P1-Fixes 1+2+3
2026-07-25 20:12:17 +02:00
Bernd (Hermes) b4ba67e80b feat: ::hilfe um Core-Befehle ergänzt (continue, /reset, /compress)
- inline_commands.py: Sektion 0 'Core-Befehle' in build_help_text()
- docs/Archivar-Funktionsbeschreibung-v8.5.md: Section 6.0 Core-Befehle
- test_r5_inline_commands.py: Assertions für Core-Befehle
2026-07-25 19:12:42 +02:00
Bernd (Hermes) 7457dc81a9 fix(install.sh): --update-only kopiert an korrekten pipx-venv-Pfad + Cleanup
Root Cause: install.sh --update-only kopierte Plugin-Dateien nach
~/.hermes/plugins/rocketchat/, aber der Gateway lädt Plugins aus dem
pipx-venv site-packages/plugins/platforms/rocketchat/.

Änderungen:
- systemd drop-in PYTHONPATH: hardcoded python3.13 → dynamisch via
  find_site_packages() mit Fallback
- deploy_plugin() + --update-only: alte tools.py löschen
  (wurde zu rc_tools.py umbenannt, verhindert Shadowing)
- --update-only: stale ~/.hermes/plugins/rocketchat/ bereinigen
  (alter falscher Pfad aus früheren Versionen)
- Tests: restart_gateway-Funktion statt literal systemctl-String
- Neue Tests: tools.py-Cleanup, stale-Pfad-Cleanup, kein hardcoded
  python3.13

143 tests passed, bash -n clean.
2026-07-25 17:43:39 +02:00
Bernd (Hermes) 0d6837e341 fix(P0): DM-Guard entfernt — confirm_move Copy-Schritt läuft jetzt auch bei DM-Origins
Rainer Analyse: adapter.py Z.2353 hatte 'if room_type != "d":' Guard
der den Copy-Schritt bei DM-Origins übersprang. Entfernt.
Telemetrie: confirm_move_dm_origin hinzugefügt.
2026-07-25 17:00:28 +02:00
Bernd (Hermes) 447fb31f30 fix: rename plugin/tools.py to plugin/rc_tools.py to resolve shadowing of hermes-internal tools/ package
plugin/tools.py existed since v2.0 and shadowed the hermes-internal tools/
package via PYTHONPATH. This caused 'from tools.registry import tool_error'
to fail in the gateway cleanup hook (gateway.cgroup_cleanup).

Changes:
- Rename plugin/tools.py -> plugin/rc_tools.py
- Update import in plugin/__init__.py: from .tools -> from .rc_tools
- Update comment in rc_tools.py referencing the old module name
- Hermes-internal imports (tools.registry, tools.clarify_gateway) left untouched
- All 117 tests pass (1 pre-existing failure in test_install_update_only.py unrelated)
2026-07-25 12:36:29 +02:00
Bernd (Hermes) 506d1a35e6 P1-Nacharbeit: Tests für Issue 5 — Widerspruchs-Routine (Undo/Rückhol-Logik)
17 Tests in tests/test_widerspruch_routine.py:
- TestWiderspruchKeywordRecognition (10 Tests): Keyword-Erkennung
  'passt hier nicht', 'gehört nicht hier', 'falscher raum', 'zurück',
  'rollback', 'stop', Satzkontext-Whitelist, Negativ-Tests
- TestConfirmMoveWiderspruch (2 Tests): 30-Min-Fenster für confirm_move
  (innerhalb triggert, außerhalb nicht)
- TestAutoRouteWiderspruch (2 Tests): 10-Min-Fenster für Auto-Route
  (innerhalb triggert, außerhalb nicht)
- TestWiderspruchLookup (3 Tests): Direkter + inverser Lookup in
  _recent_auto_routes, Auto-Routes werden im inversen Lookup ignoriert
2026-07-25 11:38:23 +02:00
Bernd (Hermes) b0f4a0555d P1-Nacharbeit: Tests für Issue 2 — _strip_archivar_artifact() (Archivar-Output-Marker)
3 Tests in test_reply_quote_stripper.py::TestArchivarArtifactStripping:
- test_archivar_phrase_detected_and_stripped: Archivar-Phrase erkannt,
  Raumnamen-Teil entfernt
- test_normal_message_not_affected: Normale Nachricht ohne Archivar-Phrase
  bleibt unverändert
- test_mixed_quote_and_content: Archivar-Phrase + normaler Content →
  Raumnamen entfernt, Telemetrie bleibt erhalten
2026-07-25 11:35:09 +02:00
Bernd (Hermes) 84f7680cec P1-Nacharbeit: Doku-Update — Copy-Schritt Status + Button-Labels auf v7 aktualisiert
- docs/archivar-user-flow-c.md: Copy-Schritt bei confirm_move als IMPLEMENTED markiert
  (Commit eece2f9, Fix 1), alte V8.1-Bemerkung entfernt
- docs/move-request-button-ux.md: Button-Labels auf v7 aktualisiert
  (1️⃣ Rüber, 2️⃣ Thema hier lassen, 3️⃣ Nur diesmal),
  Semantik dokumentiert, Status auf IMPLEMENTED gesetzt
2026-07-25 11:34:15 +02:00
Bernd (Hermes) f585f9a0e7 test: _pending_clarify_dispatch in Mock-Adaptern aller Test-Dateien
FIX 2 (P0) führte _pending_clarify_dispatch ein — alle Test-Dateien
die Mock-Adapter bauen, müssen das Feld initialisieren:
- test_d_pending_resolver.py
- test_v8_4_3.py
- test_v8_3_4.py
- test_v8_4_2.py
- test_p0_onboarding_button_click.py
- test_fact_store_onboarding.py
2026-07-25 11:19:58 +02:00
Bernd (Hermes) 1a4dab401d fix(P1): ISSUE 2 — Quote-Stripping erkennt Archivar-Output-Marker
- _ARCHIVAR_ARTIFACT_PHRASES: 5 Phrasen (Soll ich diese Nachricht nach, etc.)
- _strip_archivar_artifact(): Entfernt Phrase+Raumnamen aus routing_text
- Integration in strip_reply_quote() — läuft immer, nicht nur bei !stripped
- Verhindert Fehl-Routing durch Archivar-Output wie 'Soll ich nach #LAN-Doku kopieren?'
2026-07-25 11:17:10 +02:00
Bernd (Hermes) 39a33ebc3c fix(P1): ISSUE 5 Stufe 1 — Widerspruchs-Routine für confirm_move
- _recent_auto_routes bekommt 'source': 'auto'|'confirm'
- Inverser Lookup für confirm_move (target_room == room_id)
- Keywords erweitert: 'passt hier nicht', 'gehört nicht hier', 'falsch', 'doch nicht'
- confirm_move: 30 Min Fenster, Auto-Route: 10 Min
- Rückhol-Logik: delete_message/edit im Zielraum, Post im Ursprungsraum
- Telemetrie: widerspruch_confirm_move_route
2026-07-25 11:16:25 +02:00
Bernd (Hermes) f94d73585c fix(P1): ISSUE 1 — Button-Texte v6→v7 aktualisiert
- config.py: '2️⃣ Generell hier' → '2️⃣ Thema hier lassen'
- adapter.py Z.2394: stay_here-Feedback themenbezogen statt raumbezogen
- adapter.py Z.2450: Auto-Promote-Feedback themenbezogen
- Semantik: raumbezogen → themenbezogen (24h/ Themenwechsel TTL)
2026-07-25 11:13:38 +02:00
Bernd (Hermes) 49e9b3ec1f fix(P0): ISSUE 3 — ARCHIVAR_CLARIFY bricht Agent-Dispatch nicht mehr ab
- _pending_clarify_dispatch Slot in __init__ (Rainer Option A)
- stay_once-Pfad speichert move_req-Daten bei Nachklärung
- ARCHIVAR_CLARIFY-Handler dispatcht Agent nach Klärung
- pop() garantiert Idempotenz (nur einmal dispatchen)
- Telemetrie: archivar_clarify_dispatched
2026-07-25 11:12:56 +02:00
Bernd (Hermes) eece2f9950 fix(P0): ISSUE 4 — confirm_move kopiert Nachricht in Zielraum
- Copy-Schritt aus user-flow-c.md Z.229-231 wiederhergestellt
- Prefix: *(Auftrag von @<username>, hierher kopiert)*
- target_message_id in _recent_auto_routes gespeichert (für Issue 5)
- DM-Guard: DM-Aufträge werden NIE geroutet
- Telemetrie: confirm_move_copied
- Fehler beim Copy bricht Dispatch nicht ab
2026-07-25 11:11:53 +02:00
Bernd (Hermes) f21075eddd refactor: onboarding_active_skip -> onboarding_response_routed (Telemetrie-Klarheit)
Der alte Name 'onboarding_active_skip' war irrefuehrend — es ist kein
Bypass/Skip, sondern ein Post-Dispatch-Counter der zaehlt, wie oft eine
Onboarding-Antwort erfolgreich geroutet wurde.
2026-07-24 20:26:03 +02:00
Bernd (Hermes) b637fcc370 test: Integration-Test Onboarding-Button-Klick setzt Raum-Theme korrekt
- test_button_click_with_suffix_starts_interview: :: Suffix -> Interview start
- test_button_click_without_suffix_is_silent_noop: ohne :: -> stiller No-Op
- test_button_click_without_suffix_corrupts_theme_during_interview: Bug-Repro
- test_button_click_with_suffix_does_not_corrupt_theme: Fix-Verifikation
- test_num_button_with_suffix_produces_double_colon: Payload-Check
- test_special_button_without_suffix_uses_prefix_only: Backward-compat
- test_two_tuple_backward_compat: Review-Flow unveraendert
- test_mixed_buttons: Gemischte Buttons
2026-07-24 20:25:31 +02:00
Bernd (Hermes) 68f3845929 fix(P0): button_builder msg-Payload mit :: Suffix — Onboarding-Button-Klick wird wieder erkannt
ROOT CAUSE: button_builder.py setzte msg = prefix (nur 'ONBOARD:<rid>'),
aber _process_onboarding_response erwartet '::' in text als Trigger fuer
Button-Klick-Handler. Ohne '::' -> Fallthrough zu Text-Antwort-Handler
-> Theme wird mit Room-ID als Literal ueberschrieben (stille Korruption).

FIX (Rainer Option B — explizite Signatur):
- build_button_attachments: num_buttons jetzt (label, prefix[, suffix]),
  special_buttons (label, prefix, style[, suffix])
- msg_payload = f'{prefix}::{suffix}' wenn suffix, sonst prefix (backward-compat)
- adapter.py: 3 Aufrufer (_send_onboarding_message, _onboarding_next_room,
  _finish_onboarding) uebergeben jetzt (clean_name, f'ONBOARD:{rid}', f'select_{rid}')
- Review-Flow (onboarding_review.py) unveraendert — 2-Tupel ohne suffix
  bleiben backward-compatibel
2026-07-24 20:23:38 +02:00
Bernd (Hermes) 39fee34d89 docs: P2-Backlog (B4-B7) aus FB-02 Review dokumentiert
Platzhalter für B4-B7 — Details folgen von Rainer.
Erledigte P0/P1 (B1-B3) im selben Dokument referenziert.
2026-07-24 19:45:22 +02:00
Bernd (Hermes) c8f54d0cef docs(B3): _on_ddp_connected set_status sync — Begründung dokumentiert
Bewusst sync: First status after connect does not need await-confirmation.
PulseController takes over with set_status_async on the next tick (1.5s).
This avoids a 2s-await-wait during the critical connect path.
2026-07-24 19:42:54 +02:00
Bernd (Hermes) 78b9a15cbd fix(B2): Exponential Backoff bei Reconnect — Cap 5min, kein Log-Spam bei Server-Down
- _reconnect_backoff_sleep(): min(300, 5 * 2^backoff) mit Cap 5min
- _reconnect_backoff in RocketChatAdapter.__init__ initialisiert
- Bei erfolgreichem Reconnect: _reconnect_backoff = 0
- Ersetzt konstante asyncio.sleep(5) und asyncio.sleep(10) in _listen_loop
- INFO-Log pro Backoff-Schritt (nicht pro Versuch)
2026-07-24 19:42:31 +02:00
Bernd (Hermes) 90c122cc74 fix(B1): Future-Cleanup bei Disconnect — _pending_results werden mit DDPNotConnected aufgelöst
- _cancel_pending_results() löst alle pending Futures mit DDPNotConnected auf
- disconnect() ruft _cancel_pending_results() nach Socket-Close
- _reader_loop Exit-Pfad ruft _cancel_pending_results() nach self.connected=False
- PulseController._pulse_tick_async fängt Exception (inkl. DDPNotConnected) und fällt auf REST zurück
- 2 neue Tests: test_disconnect_clears_pending_futures, test_reader_loop_exit_clears_pending_futures
2026-07-24 19:41:25 +02:00
Bernd (Hermes) 0a05816b68 fix(A3): on_agent_busy/on_message_received toten Code entfernt 2026-07-24 17:09:17 +02:00
Bernd (Hermes) 9db62bf94a fix(B6): cancel_pending thread-safe via threading.Event 2026-07-24 17:08:05 +02:00
Bernd (Hermes) 324e7cd491 fix(B5): _pulse_loop Pause-Latenz reduziert — pause wirkt in 50ms statt 1.5s 2026-07-24 17:06:39 +02:00
Bernd (Hermes) 3ef57653c9 fix(B3): _honeymoon_expired Race-Schutz — prüft pending_status unter Lock 2026-07-24 17:06:01 +02:00
Bernd (Hermes) ad84f665bc fix(B2): _busy_started_at Reset-Logik korrigiert — keine künstliche Honeymoon-Verlängerung 2026-07-24 17:05:11 +02:00
Bernd (Hermes) bfd9cad899 fix(B12): increment/decrement_background_tasks verdrahtet — Heartbeat-Message aktiv 2026-07-24 17:03:55 +02:00
Bernd (Hermes) 81a17921e9 fix(B1): ::setstatus on startet PulseController explizit — keine 10s Verzögerung mehr 2026-07-24 17:02:59 +02:00
Bernd (Hermes) fac0a79644 fix(B4): Pytest fixture engine.shutdown() — Test-Flakiness durch leaked Honeymoon-Timer behoben 2026-07-24 17:02:21 +02:00
Bernd (Hermes) 56baaaf038 fix(P0-2-final): Verbliebene FAKT Skip-Buttons entfernt — ::setfakt + butler_mode Übergang 2026-07-24 15:56:05 +02:00
Bernd (Hermes) acd92f81cb refactor(P1-2): Zentraler Dialog-Dispatcher — 700-Zeilen if-Kette in Handler-Funktionen extrahiert 2026-07-24 14:38:20 +02:00
Bernd (Hermes) 2a92267bf4 fix(P1-4,P1-5): _onboarding_next_room + _finish_onboarding 3er-Chunking 2026-07-24 14:34:13 +02:00
Bernd (Hermes) e0bf428799 fix(P1-1): build_help_text übergibt presence_enabled aus PresenceEngine 2026-07-24 14:33:00 +02:00
Bernd (Hermes) dcd014291e fix(P0-1): Raum-Setup 3er-Chunking via build_button_attachments — gemeinsames Modul button_builder.py 2026-07-24 14:31:57 +02:00
Bernd (Hermes) 9e214a423c fix(P0-4): Review leer-Liste → Zurück-Button garantiert 2026-07-24 14:29:53 +02:00
Bernd (Hermes) 07ba653b65 fix(P0-3): is_onboarding-Gate erweitert — FAKT::/REVIEW_*/⏰ Prefix abgefangen 2026-07-24 14:28:53 +02:00
Bernd (Hermes) 0bfa791d79 fix(P0-2): FAKT Skip-Button entfernt — Option 4 ist die Skip-Semantik 2026-07-24 14:28:04 +02:00
Bernd (Hermes) 83b9d6c347 fix(plugin.yaml): name rocketchat-platform → rocketchat (Pitfall 4) 2026-07-24 12:40:11 +02:00
Bernd (Hermes) 18d87d8604 fix(install.sh): local outside function — replace with plain assignment 2026-07-24 12:37:45 +02:00
Bernd (Hermes) b40b221896 fix(P1a): Status busy minimum 1s sichtbar — Honeymoon-Timer gegen Coalesce-Überschreibung 2026-07-24 09:11:48 +02:00
Bernd (Hermes) f028a30d6c fix(P1b): DetectionTimer pgrep-Pattern erweitert + gateway_state als Primärsignal 2026-07-24 09:06:40 +02:00
Bernd (Hermes) f61b0ba508 fix(P0): Own-Message-Filter — self.user aus DDP-Login-Response beziehen (nicht blind aus Env) 2026-07-24 09:03:39 +02:00
Bernd (Hermes) 99979d6f9d fix(install.sh): 9 Susi-Deployment Pitfalls — P11 skip, system venv, core plugin path, root gateway restart 2026-07-24 08:53:28 +02:00
41 changed files with 8662 additions and 1449 deletions
@@ -0,0 +1,526 @@
# RC-Plugin Funktionsbereichs-Zerlegung
Repo: /home/bernd/projekte/Hermes_rocket.chat_Plugin
HEAD: 83b9d6c ("fix(plugin.yaml): name rocketchat-platform → rocketchat (Pitfall 4)")
Analyse: Rainer (Architektur-Reviewer)
Datum: 2026-07-24
Zweck: Systematische Aufteilung des RC-Plugins in unabhängig prüfbare Funktionsbereiche, gegen die jeweils das Zielbild (Vorgaben, Designentscheidungen, Restriktionen) referenziert werden kann.
================================================================
METRIKEN-BASIS
================================================================
- adapter.py: 6921 LOC (Gateway, DDP, REST, Dispatch, Onboarding-Wiring)
- install.sh: 1611 LOC (Deployment, Verifikation, 11 Pitfalls dokumentiert)
- archivar/ gesamt: ~15.000 LOC, 24 Module
- Tests: ~70 Dateien, davon 16 v8_4_x (Vektor-Routing) + 8 v8_3_x (P0-Round) + 9 v8_2/8_3 + onboarding/room_map/router/presence/...
- Plugin-Dateien (Top-Level): adapter.py, tools.py, plugin.yaml
- Konfiguration: templates/config.yaml + room-map.json + .env (RUNTIME)
================================================================
ZERLEGUNGSKRITERIEN
================================================================
1. Kohärenz: Ein Bereich hat EINE Hauptverantwortung. Module mit gemeinsamer
Verantwortung (z.B. DDP-Layer, Routing-Decision) werden zusammengefasst.
2. Unabhängige Prüfbarkeit: Jeder Bereich hat definierte Eingaben (Triggers),
Ausgaben (Effekte) und kann gegen eine Teilmenge der Vorgaben geprüft werden,
ohne andere Bereiche zu laden.
3. Vollständigkeit: Adapter-Lifecycle, Persistenz, Deployment und Konfiguration
sind explizite Bereiche — nicht "alles andere".
================================================================
FUNKTIONSBEREICHE (sortiert nach Onboarding → Verarbeitung → Output → Persistenz → Infrastruktur)
================================================================
────────────────────────────────────────────────────────────────────
FB-01 Onboarding & Review ✅ BEREITS REVIEWED
────────────────────────────────────────────────────────────────────
Verantwortung:
Steuerung des Erstgesprächs mit neuen Nutzern/Räumen: Greeting-Flow,
Interview-State-Machine, Review-Subphasen, Lock-Mechanismus, Fact-Store-Pfad.
Endet in persistierter room-map.json.
Hauptdateien:
- plugin/archivar/onboarding.py (492 LOC — Greeting, Lazy-Check, Lock)
- plugin/archivar/onboarding_state.py (592 LOC — StateMachine, OnboardingData)
- plugin/archivar/onboarding_review.py (1146 LOC — Review-Subphasen-Dispatcher)
- plugin/adapter.py (_send_onboarding_message, _complete_onboarding)
- room-map.json / _persist_room_map_changes (Output)
Schlüsselfeatures:
- F-OB1 Lazy Onboarding (check_room_map_completeness_delta)
- F-OB2 Onboarding-Greeting-Flow (build_greeting_message, run_onboarding_greeting_flow)
- F-OB3 State-Machine (GREETING → AWAITING_NAME → ... → COMPLETE)
- F-OB4 Review-Subphasen (Room-Step, Edit, Keywords-Edit, Theme-Edit, Catch-All-Toggle, Remove, Add-New)
- F-OB5 Fact-Store-Pfad-Validierung
- F-OB6 Onboarding-Lock (acquire/release/cleanup_stale)
Bekannte Probleme:
- F6 R18 P1: adapter.py Z.4270-4271/5815-5816 rufen self._presence_engine.x OHNE
hasattr/None-Guard — bei Init-Exception (Z.822-827) wirft Onboarding AttributeError
(widerspricht R-4 Graceful Degradation).
- Onboarding-Test-Lock-Datei-Problematik in CI (siehe test_onboarding_lock).
- Verteilung: 1146 LOC in onboarding_review.py → Refactoring-Kandidat
(render_review_room_* sehr ähnlich, Template-Pattern).
Review-Status: ARCHITEKTUR-REVIEW ABGESCHLOSSEN (Onboarding-Teil).
Vorgaben geprüft: State-Machine-Korrektheit ✅, Review-Buttons-Korrektheit ✅,
Fact-Store-Pfad ✅. Noch offen: Interaction mit FB-04 (Keyword-Lernen) und
FB-09 (Error-Recovery).
────────────────────────────────────────────────────────────────────
FB-02 DDP-Client & Verbindungs-Lifecycle ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Aufbau, Aufrechterhaltung und Wiederherstellung der WebSocket-Verbindung zum
Rocket.Chat-Server via DDP-Protokoll. Login, Subscription, Reader-Loop,
Future-Store für await-Semantik, Reconnect-Logik.
Hauptdateien:
- plugin/adapter.py Z.274-889 (DDPTimeout, DDPServerError, DDPNotConnected, DDPClient)
- plugin/adapter.py Z.292+ (class DDPClient, _recv_loop, Future-Store, result-Handler)
Schlüsselfeatures:
- F-DDP1 Login (auth-Tokens, self.user-Extraktion aus Login-Response — P0-Fix f61b0ba)
- F-DDP2 Subscribe (stream-room-messages, notify-on-room)
- F-DDP3 Reader-Loop (Blocking, Thread-Trennung, Heartbeat)
- F-DDP4 Future-Store + result-Handler (async-await via run_coroutine_threadsafe, P1-2-O2)
- F-DDP5 Reconnect-Backoff
- F-DDP6 Own-Message-Filter (P0-Fix f61b0ba: self.user aus DDP, nicht Env)
Bekannte Probleme:
- F19 R19 P0-1 (archiviert, aber referenced): PulseController in presence_engine
erstellt self._pulse_controller/_detection_timer NIE → 348 Zeilen Dead-Code.
NICHT in diesem Bereich, aber DDP-Layer muss fehlende Pulse-Calls
kompensieren (DDP set_status als kostenloser Fallback).
- Eigene DDP-Reader-Thread vs. asyncio.loop-Thread: Synchronisation
prüfen (run_coroutine_threadsafe-Pfad).
────────────────────────────────────────────────────────────────────
FB-03 REST-Client & API-Wrapper ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Kapselt die Rocket.Chat-REST-API für Out-of-Band-Operationen:
Posten von Nachrichten, Senden von Buttons, Datei-Upload/Download,
Room-Info-Lookup. Trennt synchronen HTTP-Pfad von asynchronem DDP-Pfad.
Hauptdateien:
- plugin/adapter.py Z.138-273 (class RocketChatREST)
- plugin/adapter.py Z.31-38 (RocketChatRateLimitError)
- plugin/adapter.py Z.40-130 (Helper: _MULTIROOM, _get_config_str)
Schlüsselfeatures:
- F-REST1 Message-POST (chat.postMessage)
- F-REST2 Button-Attachments (send mit attachments-Array)
- F-REST3 Rate-Limit-Handling
- F-REST4 Datei-Upload (rooms.upload)
- F-REST5 Datei-Download (für Inlining)
- F-REST6 Room-Info-Lookup (rooms.info, users.info)
Bekannte Probleme:
- Trennung REST/DDP-Nachrichten: Race-Conditions möglich wenn REST-Post
und DDP-Event dieselbe Nachricht betreffen (z.B. Echo-Filter).
- Token-Refresh: Wenn auth_token abläuft, kein automatischer Re-Login
im REST-Pfad (nur DDP reconnectet).
────────────────────────────────────────────────────────────────────
FB-04 Archivar-Routing & Klassifikation ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Kernlogik: Eingehende Nachricht → Klassifikation (FAKT/FRAGE/ALARM/etc.)
→ Routing-Decision → Ziel-Raum. Hybrid aus Keyword-Matcher (Stufe 0),
Sentence-Marker-Erkennung, FAISS-Vektor-Routing (Stufe 1) und
LLM-Fallback (Stufe 2).
Hauptdateien:
- plugin/archivar/router.py (2261 LOC — BidirectionalRouter)
- plugin/archivar/classifier.py (716 LOC — IntentClassifier, EmbeddingClient, LLMClient)
- plugin/archivar/keyword_matcher.py (481 LOC — Stemmer, Levenshtein, Word-Boundary)
- plugin/archivar/sentence_markers.py (307 LOC — MarkerClass, detect_sentence_marker)
- plugin/archivar/booster.py (277 LOC — KeywordBooster)
- plugin/archivar/multiroom_context.py (205 LOC — Cross-Room-Entry, MultiRoomContextRing)
- plugin/archivar/feedback_detector.py (232 LOC — RoutingWiderspruchDetector)
- plugin/archivar/archivar_state.py (1173 LOC — RoomState, ArchivarState)
Schlüsselfeatures:
- F-RT1 BidirectionalRouter (RoutingDecision, Red-Flag-Erkennung)
- F-RT2 2-Stufen-Klassifikator (Keyword → FAISS → LLM)
- F-RT3 Sentence-Marker-Pattern (FRAGE/ALARM/FAKT/...)
- F-RT4 KeywordBooster (Hybrid mit FAISS)
- F-RT5 Cross-Room-Context-Ring
- F-RT6 Routing-Konflikt-Detektor (Widerspruchs-Erkennung)
- F-RT7 Recursive Routing (v7_4)
- F-RT8 Sticky Sessions (test_sticky_session)
- F-RT9 V8.4 FAISS-Routing-Tests (8 Test-Dateien: v8_4_2 ... v8_4_6)
Bekannte Probleme:
- 2261 LOC in router.py — höchste Komplexität im Plugin. Refactoring-Druck.
- FAISS-Performance bei wachsendem Index (siehe faiss_performance_test*.py im Root).
- Hybrid-Booster mit FAISS: User-Präferenz aus Memory dokumentiert
("Hybridansatz mit KeywordBooster"), aber Integration-Drift-Risiko
(R18-Anm.: _update_dst dupliziert deploy_plugin-Logik).
- Sentence-Marker-Validierung: validate_sentence_marker ist async und
wird aus synchronem Routing-Pfad aufgerufen — Race-Risk.
────────────────────────────────────────────────────────────────────
FB-05 Presence-Engine & Status-Pulse ⏳ ANSTEHEND (KRITISCH)
────────────────────────────────────────────────────────────────────
Verantwortung:
Visuelle Präsenz des Butlers: "online"/"away"-Status, Pulse-Intervall,
Detection-Timer (Gateway-Heartbeat-Erkennung). P0-Status: Implementierung
hat dokumentierte Lücken aus F19 R19 Review.
Hauptdateien:
- plugin/archivar/presence_engine.py (1119 LOC — PresenceEngine, PulseController, DetectionTimer)
- plugin/adapter.py (DDP set_status, on_agent_busy, on_message_received)
Schlüsselfeatures:
- F-PR1 PresenceEngine (idle/active/dnd-Modi)
- F-PR2 PulseController (Async-Pulse via run_coroutine_threadsafe)
- F-PR3 DetectionTimer (pgrep-Heuristik, gateway_state-Signal)
- F-PR4 ROCKETCHAT_PRESENCE_PULSE_INTERVAL (5-30s Clamp)
- F-PR5 Honeymoon-Timer (b40b221: Status busy minimum 1s sichtbar)
- F-PR6 Status-Farben (d964d7d: grün/gelb/rot, Flughafen-Prinzip)
Bekannte Probleme (F19 R19 dokumentiert, CHANGES NEEDED):
- P0-1 ARCHITEKTUR-BRUCH: presence_engine erstellt _pulse_controller/
_detection_timer NIE, adapter instanziiert sie auch nicht → 348 Z.
Dead-Code, alle hasattr-Guards (presence_engine Z.476/488, adapter
Z.871-876) No-Ops.
- P0-2 PulseController.cancel_pending() = pass (Z.604-613) — EC-5
NICHT implementiert.
- P1-1 on_agent_busy/on_message_received (Z.479/491) in adapter.py
0 Aufrufer.
- P1-2 K3: ::setstatus on/off ruft enable/disable, nicht PulseController.
- P1-3 ROCKETCHAT_PRESENCE_PULSE_INTERVAL geht an PresenceEngine
(clamp 5-30s), PulseController-Default 1.5s.
- P1-4 DetectionTimer pgrep 'len > 1' — 0 Prozesse = False, kein
Heuristik-Unterschied.
- P1-5 heartbeat_pulse/detection ungelockt.
- P1-6 _pulse_loop Pause-Check nur in Sleep (0.1s Latenz).
- P2-1 pgrep 6/min unkritisch.
- P2-2 REST-Fallback auth_token+user_id ungebunden.
Review-Status: REVIEW CHANGES NEEDED — keine Freigabe möglich bis P0-1, P0-2,
P1-2 behoben sind. DDP set_status (adapter Z.544-549) ist kostenloser
Workaround bis dahin.
────────────────────────────────────────────────────────────────────
FB-06 Inline-Commands (::-Präfix) ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Verarbeitung von `::hilfe`, `::status`, `::multiroom`, etc. — direkte
Nutzer-Befehle, die vor dem Routing abgefangen werden.
Hauptdateien:
- plugin/archivar/inline_commands.py (431 LOC — InlineCommandRegistry, parse_inline_command)
- plugin/archivar/adapter_integration.py (1270 LOC — Routing-Integration)
Schlüsselfeatures:
- F-IC1 ::hilfe (build_help_text)
- F-IC2 ::status (build_status_text)
- F-IC3 ::multiroom (Kontext an/aus)
- F-IC4 ::setstatus (on/off, siehe FB-05 P1-2)
- F-IC5 Natural Help Request Detection (is_natural_help_request)
- F-IC6 Command-Question-Extraction (extract_command_question)
- F-IC7 Build-Command-Help (pro Command)
Bekannte Probleme:
- ::setstatus nutzt enable/disable statt PulseController (siehe FB-05).
- Hilfe-Text-Wartung: Bei neuen Commands muss build_help_text manuell
erweitert werden — kein Auto-Discovery aus Registry.
────────────────────────────────────────────────────────────────────
FB-07 Button-System (Rendering, Dispatch, Templates) ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Rendering von interaktiven Button-Attachments (Room-Auswahl, Review-Aktionen,
Move-Requests), Dispatch eingehender Button-Klicks, Template-System.
Hauptdateien:
- plugin/archivar/onboarding_review.py (build_button_attachments, dispatch_review_button)
- plugin/archivar/inline_commands.py (Button-Hilfe)
- plugin/archivar/archivar_state.py (Button-Action-IDs?)
- plugin/adapter.py (Button-Click-Handler im DDP-Reader-Pfad)
- tests/test_f6_adapter_dispatch.py (F6-Dispatch-Tests)
- tests/test_p1_button_click_fix.py (P1-Button-Klick-Fix)
- docs/BUTTON_GUIDE.md
- docs/move-request-button-ux.md
Schlüsselfeatures:
- F-BT1 Review-Buttons (room-step, edit, keywords, theme, catch-all, remove, add-new)
- F-BT2 Move-Request-Buttons (Butler Klärungsflow)
- F-BT3 Button-Action-ID-Schema
- F-BT4 Template-Rendering
- F-BT5 F6-Adapter-Dispatch-Pfad (Test existiert, deckt Pfad ab)
Bekannte Probleme:
- Button-Click-Parsing sitzt in adapter.py — Suchpfad muss verifiziert
werden (P1-Button-Click-Fix deutet auf Historie).
- docs/move-request-button-ux.md deutet auf eigenen Sub-Flow mit
noch nicht vollständig implementierter UX.
────────────────────────────────────────────────────────────────────
FB-08 File-Handling (Upload, Download, Inlining, [FILE]-Stripping) ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Behandlung von Datei-Anhängen: Upload via REST, Download für Inline-Vorschau,
[FILE:...]-Block-Stripping bei fehlgeschlagenen Downloads, MIME-Type-Behandlung.
Hauptdateien:
- plugin/adapter.py (_download_and_inline_files, _upload_file, [FILE]-Stripping)
- plugin/adapter.py (342a1cd: P2-1-Fix — Block-Stripping nach fehlgeschlagenen Downloads)
Schlüsselfeatures:
- F-FH1 Datei-Upload (rooms.upload via REST)
- F-FH2 Datei-Download (für Inlining)
- F-FH3 [FILE:pfad]-Block-Parsing
- F-FH4 [FILE]-Stripping nach fehlgeschlagenen Downloads (P2-1)
- F-FH5 MIME-Type-Erkennung
Bekannte Probleme:
- Datei-Pfad-Injektion: [FILE:...]-Parsing muss gegen Traversal gesichert sein.
- Download-Fehler-Handling: 342a1cd behebt Block-Stripping, aber Upload-
Fehler-Fallbacks noch nicht verifiziert.
- Größen-Limits: Kein expliziter Check in adapter.py sichtbar — Regressionsrisiko
bei sehr großen Dateien.
────────────────────────────────────────────────────────────────────
FB-09 Butler (Move-Requests, Clarification, 2. Stufe) ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Wenn Routing unsicher ist: Klärungs-Anfrage an Butler (Nutzer) senden,
Antwort verarbeiten, ggf. Move-Request initiieren. "Gelber Status" (away)
signalisiert Klärungsbedarf.
Hauptdateien:
- plugin/archivar/router.py (_parse_red_flag_response, validate_sentence_marker)
- plugin/archivar/onboarding.py (Lazy-Onboarding-Check)
- plugin/archivar/inline_commands.py (::multiroom-Kontext)
- plugin/adapter.py (Move-Request-Versand)
- docs/move-request-button-ux.md
- docs/rocketchat_send_clarify_architecture.md (im Root-Repo)
- tests/test_butler_mode.py
- tests/test_d_pending_resolver.py
Schlüsselfeatures:
- F-BU1 Red-Flag-Erkennung (LLM-Antwort unsicher)
- F-BU2 Clarification-Request (Nachfrage an Nutzer)
- F-BU3 Move-Request (Routing-Vorschlag als Button)
- F-BU4 Pending-Resolver (d_pending_resolver)
- F-BU5 Away-Status (573335c: gelb bei Klärungsflow)
- F-BU6 Stufe-2-Klärung (DM-Routing in unsicheren Fällen)
Bekannte Probleme:
- d_pending_resolver-Tests deutet auf komplexen State-Resolver — Refactoring-Druck.
- Butler-Status-Kopplung an Presence (FB-05): away-Status-Logik muss mit
PulseController-Implementierung harmonieren.
────────────────────────────────────────────────────────────────────
FB-10 Room-Map (Verwaltung, Onboarding, Keywords) ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Persistente Datenstruktur für Raum-Metadaten: Raum → Keywords, Theme,
Catch-All-Status, Owner, Excluded-Liste. CRUD-API für Onboarding-Review
und Auto-Learning.
Hauptdateien:
- plugin/archivar/room_map.py (1043 LOC — RoomEntry, RoomMap, _migrate_from_env_vars)
- plugin/archivar/room_index.py (664 LOC — RoomIndexManager, RoomIndexError)
- room-map.json (Runtime-Output)
Schlüsselfeatures:
- F-RM1 RoomEntry (name, id, keywords, theme, catch_all, owner)
- F-RM2 RoomMap CRUD (load, save, add_room, remove_room, update_room)
- F-RM3 Two-Stage Keyword Evidence
- F-RM4 Room-Exclusion (excluded_ids)
- F-RM5 Room-Validation (RoomMapValidationError)
- F-RM6 Migration from Env-Vars (_migrate_from_env_vars)
- F-RM7 Write-API (test_room_map_write_api)
- F-RM8 Weighted-Keywords (test_room_map_weighted)
- F-RM9 Room-Index (FAISS-Index für schnelles Lookup)
Bekannte Probleme:
- Room-Map-Datei ist Single-Source-of-Truth, aber kein Locking-Mechanismus
sichtbar — Concurrency-Risk bei parallelem Onboarding mehrerer Räume.
- Migration-Path von Env-Vars deprecated aber noch vorhanden.
────────────────────────────────────────────────────────────────────
FB-11 Adapter-Dispatch & ArchivarMessageHandler ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Glue-Code zwischen DDP-Inbox und Archivar-Subsystem: Message-Sanitizing,
Reply-Quote-Stripping, Auftrags-Erkennung, Decision-Logging, Adapter-Tests
(F6-Dispatch-Pfad).
Hauptdateien:
- plugin/archivar/adapter_integration.py (1270 LOC — ArchivarMessageHandler)
- plugin/archivar/reply_quote_stripper.py (196 LOC — strip_reply_quote)
- plugin/archivar/sentence_markers.py (Sentence-Marker → Routing-Decision)
- plugin/archivar/routing_telemetry.py (137 LOC — RoutingTelemetry)
- plugin/archivar/routing_counter.py (57 LOC — RoutingCounter)
- plugin/adapter.py (_is_auftrag, _build_announcement, ArchivarMessageHandler-Aufruf)
- tests/test_f6_adapter_dispatch.py
- tests/test_reply_quote_stripper.py
- tests/test_r5_inline_commands.py
- tests/test_a1b_integration.py
- tests/test_r1_integration.py
Schlüsselfefeatures:
- F-AD1 ArchivarMessageHandler (Hauptentry-Point für DDP-Nachrichten)
- F-AD2 Reply-Quote-Stripping (RC-spezifisch: [ ](per-Channel))
- F-AD3 Auftrags-Erkennung (_is_auftrag)
- F-AD4 Routing-Telemetry (Entscheidungsprotokollierung)
- F-AD5 Routing-Counter (Häufigkeits-Statistik)
- F-AD6 Adapter-Dispatch-Pfad (F6)
Bekannte Probleme:
- 1270 LOC in adapter_integration.py — Kandidat für Aufteilung in
Pre-Processing / Decision / Post-Processing.
- Reply-Quote-Stripping: 4 Strip-Funktionen (attachments, rc-reply-link,
blockquotes, quote-blocks) — Reihenfolge-Risiko.
────────────────────────────────────────────────────────────────────
FB-12 Config & Persistenz ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Konfigurations-Management: plugin.yaml (Manifest), templates/config.yaml
(Default), .env (Runtime-Secrets), room-map.json (Runtime-State),
Fact-Store-Pfad-Validierung, Conversation-History.
Hauptdateien:
- plugin/plugin.yaml (12 LOC — name: rocketchat, kind: platform)
- templates/config.yaml (88 LOC — Default-Config)
- .env (Runtime — nicht in Git)
- plugin/archivar/config.py (338 LOC — _resolve_room_mapping)
- plugin/archivar/doc_store.py (144 LOC — DocumentationStore)
- plugin/archivar/conversation_history.py (237 LOC — ConversationHistory, MessageEntry)
- plugin/archivar/seed_data.py (134 LOC — Seed-Data)
- room-map.json (Runtime-Output)
Schlüsselfeatures:
- F-CF1 plugin.yaml-Manifest (Pitfall 4: name muss "rocketchat" sein)
- F-CF2 templates/config.yaml (Default-Config-Template)
- F-CF3 .env-Loading (via _get_config_str mit env_var-Fallback)
- F-CF4 Fact-Store-Pfad (validate_fact_store_path, create_and_verify_fact_store)
- F-CF5 DocumentationStore (FAKT-Routing-Output)
- F-CF6 ConversationHistory (gespeicherte Konversations-Snapshots)
- F-CF7 Seed-Data (Erstausstattung Room-Map, Keywords)
Bekannte Probleme:
- .env nicht versioniert — Drift zwischen Test- und Prod-Config.
- Migration _migrate_from_env_vars deprecated, aber noch im Code.
- plugin.yaml-Name "rocketchat" (P1-2-O2-Fix 83b9d6c) — Hinweis auf
subtile Pitfall-Klassen (Plugin-Loader-Strict-Matching).
────────────────────────────────────────────────────────────────────
FB-13 install.sh & Deployment ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Deployment-Skript: Plugin-Pfad-Validierung, venv-Setup, systemd-Service-
Konfiguration, Verifikations-Loop, Restart-Logik. 11 dokumentierte
Susi-Deployment-Pitfalls.
Hauptdateien:
- install.sh (1611 LOC — Deployment, 99979d6 dokumentiert 9 Pitfalls)
- bootstrap.sh (2325 Bytes — Wrapper?)
- scripts/rebuild_index.py (FAISS-Index-Rebuild)
- scripts/smoke_test_booster.py (Booster-Smoke-Test)
- scripts/smoke_test_faiss.py (FAISS-Smoke-Test)
- docs/INSTALL.md
- docs/deployment-runbook.md
- tests/test_install_update_only.py
Schlüsselfeatures:
- F-IN1 Plugin-Pfad-Validierung (Core-Plugin-Pfad vs. Custom)
- F-IN2 venv-Setup (numpy2-Installations-Pitfall)
- F-IN3 systemd-Service-Config
- F-IN4 Verifikations-Loop (is-active-Check, 30s-Timeout)
- F-IN5 Update-Only-Pfad (test_install_update_only)
- F-IN6 bootstrap.sh (Schnell-Setup)
- F-IN7 Index-Rebuild-Skript
- F-IN8 Smoke-Tests (Booster, FAISS)
Bekannte Probleme:
- F6 R18 dokumentiert: 11 Pitfalls, install.sh 5 Schritte sauber,
30s is-active-Loop robust, journalctl --since '1 minute ago' akzeptiert
(systemd 257 getestet), --no-restart + --dry-run korrekt.
- F6 R18: bash -n OK.
- F18 (18d87d8): local outside function — replace with plain assignment
(kleiner Cleanup, P0-charakter).
Review-Status: F6 R18 APPROVED mit 1 P1 (adapter.py Guard-Issue, NICHT
install.sh selbst). Verifikation: 1288 passed, 37 failed pre-existing.
────────────────────────────────────────────────────────────────────
FB-14 Telemetrie, Tests & Diagnostics ⏳ ANSTEHEND
────────────────────────────────────────────────────────────────────
Verantwortung:
Routing-Telemetry, Routing-Counter, Test-Infrastruktur (pytest + 70 Test-Dateien),
Diagnostics-Endpoints, Performance-Tests.
Hauptdateien:
- plugin/archivar/routing_telemetry.py (137 LOC)
- plugin/archivar/routing_counter.py (57 LOC)
- plugin/archivar/tests/ (Test-Suite archivar-intern)
- tests/ (Top-level-Tests: test_adapter, test_booster, test_ddp_await, test_install_update_only, test_onboarding, test_room_index)
- scripts/smoke_test_*.py
- faiss_performance_test*.py (im Root-Repo, nicht im Plugin)
Schlüsselfeatures:
- F-TM1 Routing-Telemetry (Entscheidungs-Logging)
- F-TM2 Routing-Counter (Statistik)
- F-TM3 Test-Suite (70+ Dateien, F6-F19-Generationen)
- F-TM4 Smoke-Tests (Booster, FAISS)
- F-TM5 Performance-Tests (FAISS, Index-Größe)
Bekannte Probleme:
- Test-Suite-Wartung: 16 v8_4_x-Dateien deuten auf hohe Iterationsfrequenz
— Refactoring-Signale.
- 37 pre-existing failed Tests (laut F6 R18) — müssen auf "broken-by-design"
oder "fixable" klassifiziert werden.
================================================================
ZUSAMMENFASSUNG
================================================================
14 Funktionsbereiche identifiziert, alle Plugin-Aspekte abgedeckt:
✅ FB-01 Onboarding & Review REVIEWED (F6 R18)
⏳ FB-02 DDP-Client ANSTEHEND
⏳ FB-03 REST-Client ANSTEHEND
⏳ FB-04 Archivar-Routing & Klassifikation ANSTEHEND (komplex, 2261 LOC)
⏳ FB-05 Presence-Engine & Pulse ANSTEHEND, CHANGES NEEDED
⏳ FB-06 Inline-Commands ANSTEHEND
⏳ FB-07 Button-System ANSTEHEND
⏳ FB-08 File-Handling ANSTEHEND
⏳ FB-09 Butler (Move/Clarify) ANSTEHEND
⏳ FB-10 Room-Map ANSTEHEND
⏳ FB-11 Adapter-Dispatch ANSTEHEND
⏳ FB-12 Config & Persistenz ANSTEHEND
⏳ FB-13 install.sh & Deployment ANSTEHEND (F6 R18 APPROVED)
⏳ FB-14 Telemetrie & Tests ANSTEHEND
Review-Reihenfolge-Empfehlung (nach Abhängigkeit + Risiko):
1. FB-05 Presence (P0-Blocker für 8+ andere Bereiche)
2. FB-13 install.sh (F6 R18 APPROVED → Re-Verifikation der P1)
3. FB-02 DDP-Client (Grundlage für alle Inbox-Pfade)
4. FB-04 Archivar-Routing (komplex, zentral, FAISS-Tests vorhanden)
5. FB-10 Room-Map (Datenquelle für FB-04)
6. FB-11 Adapter-Dispatch (Glue zwischen DDP und Archivar)
7. FB-09 Butler (koppelt zurück an FB-05)
8. FB-06 Inline-Commands (kleiner, isoliert)
9. FB-07 Button-System (UX-kritisch, dokumentiert in BUTTON_GUIDE.md)
10. FB-08 File-Handling (Sicherheits-Relevanz)
11. FB-12 Config & Persistenz (Grundlage, niedrig-Risiko)
12. FB-03 REST-Client (einfach, von DDP abgekoppelt)
13. FB-14 Telemetrie & Tests (Wartbarkeit, Querschnitt)
Lücken-/Überlappungs-Check:
- ABGEDECKT: DDP, REST, Routing, Onboarding, Presence, Inline-Commands,
Buttons, Files, Butler, Room-Map, Config, Deployment, Tests.
- NICHT als eigener Bereich: Logging (Querschnitt, in jedem FB prüfen),
Error-Handling (Querschnitt), Security (Querschnitt — siehe FB-08,
FB-12, FB-10 für Pfad-/Lock-Aspekte).
- EXPLIZIT AUSGELAGERT: room-map.json sowohl in FB-10 (Schema) als auch
FB-12 (Persistenz) — bei Review Klarstellung welcher Bereich
Schema-Validierung vs. I/O-Verantwortung trägt.
+54
View File
@@ -0,0 +1,54 @@
# P2 Backlog — FB-02 DDP-Client Review (Rainer)
Erstellt: 2026-07-24
Status: Offen (nicht in diesem Durchgang)
---
## B4 (P2): [Platzhalter — Details fehlen]
**Problem:** [TBD]
**Lösung:** [TBD]
**Commit:** `fix(B4): [TBD]`
---
## B5 (P2): [Platzhalter — Details fehlen]
**Problem:** [TBD]
**Lösung:** [TBD]
**Commit:** `fix(B5): [TBD]`
---
## B6 (P2): [Platzhalter — Details fehlen]
**Problem:** [TBD]
**Lösung:** [TBD]
**Commit:** `fix(B6): [TBD]`
---
## B7 (P2): [Platzhalter — Details fehlen]
**Problem:** [TBD]
**Lösung:** [TBD]
**Commit:** `fix(B7): [TBD]`
---
## Erledigt (dieser Durchgang)
| Bug | Prio | Commit | Beschreibung |
|-----|------|--------|-------------|
| B1 | P0 | `90c122c` | Future-Cleanup bei Disconnect |
| B2 | P1 | `78b9a15` | Exponential Backoff bei Reconnect |
| B3 | P1 | `c8f54d0` | Doc-String _on_ddp_connected set_status sync |
@@ -242,6 +242,16 @@ Whitespace-Validierung: Keywords mit internen Leerzeichen werden abgelehnt (`if
Rocket.Chat unterstützt kein `/`-Prefix; deshalb verwendet das Plugin `::` als alternatives Command-Präfix. Registriert in `adapter.py` (`self._inline_commands.register(...)`). Rocket.Chat unterstützt kein `/`-Prefix; deshalb verwendet das Plugin `::` als alternatives Command-Präfix. Registriert in `adapter.py` (`self._inline_commands.register(...)`).
### 6.0 Core-Befehle (Hermes Core, immer verfügbar)
Diese Befehle werden direkt vom Hermes-Agenten verarbeitet — unabhängig vom Plugin:
| Befehl | Wirkung |
|----------------|-------------------------------------------------------------------------|
| `continue` | Agent fortsetzen nach leerer Antwort / Stream-Drop |
| `/reset` | Session zurücksetzen (Chat-Kontext löschen, frische Session). In RC: `::reset` |
| `/compress` | Kontext manuell komprimieren (Token sparen bei langen Sessions). In RC: `::compress` |
### 6.1 Standard-Hermes-Befehle ### 6.1 Standard-Hermes-Befehle
| Befehl | Wirkung | | Befehl | Wirkung |
+8 -1
View File
@@ -218,6 +218,13 @@ async def _send_buttons(self, room_id: str, text: str, question_id: str,
### 4.4 Button-Handling in `_process_incoming()` ### 4.4 Button-Handling in `_process_incoming()`
> **Status: IMPLEMENTED** (Commit eece2f9 — Fix 1: Copy-Schritt re-implementiert)
>
> Der Copy-Schritt bei confirm_move (Button 1️⃣ Rüber) wurde in V8.1 fälschlich entfernt
> und mit Fix 1 (Commit eece2f9) wieder eingeführt. Die Nachricht wird jetzt korrekt
> per `_post_message_with_retry` in den Zielraum kopiert, bevor der Agent dispatched wird.
> Siehe `plugin/adapter.py` Zeilen 2350-2372 für die aktuelle Implementierung.
```python ```python
# Button-Antwort auf move-request erkennen # Button-Antwort auf move-request erkennen
if msg_id in getattr(self, '_pending_move_requests', {}): if msg_id in getattr(self, '_pending_move_requests', {}):
@@ -233,7 +240,7 @@ if msg_id in getattr(self, '_pending_move_requests', {}):
elif "hier bleiben" in choice.lower() or choice == "Hier bleiben": elif "hier bleiben" in choice.lower() or choice == "Hier bleiben":
_CURRENT_ORIGIN_ROOM.set(room_id) _CURRENT_ORIGIN_ROOM.set(room_id)
self.rest.post_message(room_id, "👍 Bleiben hier — ich kümmer mich drum.") self.rest.post_message(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
elif "generell" in choice.lower() or choice == "Generell hier bleiben": elif "generell" in choice.lower() or choice == "Generell hier bleiben":
if not hasattr(self, '_sticky_rooms'): if not hasattr(self, '_sticky_rooms'):
+35 -52
View File
@@ -1,77 +1,60 @@
# Move-Request Dialog - Button UX Verbesserung # Move-Request Dialog - Button UX Verbesserung
> **Status: IMPLEMENTED** (v7-Semantik, Commit f585f9a)
>
> Die Button-Labels sind jetzt: `1️⃣ Rüber`, `2️⃣ Thema hier lassen`, `3️⃣ Nur diesmal`.
> Die v7-Semantik ist vollständig implementiert — siehe `plugin/archivar/config.py` Zeilen 225-227
> und `plugin/adapter.py` Zeilen 2306-2401 für die aktuelle Button-Handling-Logik.
## Übersicht ## Übersicht
Verbesserung der Benutzerfreundlichkeit des Move-Request-Dialogs im Rocket.Chat-Plugin durch eine klare Beschreibung der Button-Funktionen vor den Schaltflächen. Verbesserung der Benutzerfreundlichkeit des Move-Request-Dialogs im Rocket.Chat-Plugin durch eine klare Beschreibung der Button-Funktionen vor den Schaltflächen.
## Aktueller Zustand ## Aktueller Zustand (IMPLEMENTIERT)
### Dialog-Text ### Dialog-Text
``` ```
Dein Auftrag passt thematisch besser in **{target_name}**. Dein Auftrag passt thematisch besser in **{target_name}**.
``` ```
### Buttons ### Buttons (v7 — aktuell)
- ✅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 - 1️⃣ Rüber
- 2️⃣ Hier - 2️⃣ Thema hier lassen
- 3️⃣ Nein - 3️⃣ Nur diesmal
### Begründung für neue Button-Labels ### Semantik
- **Kürzer** (max. 7 Zeichen auf Desktop) - **1️⃣ Rüber** = confirm_move: Auftrag in Zielraum kopieren, Agent antwortet dort (30 Min Widerspruchsfenster)
- **Einheitlich** (alle numeriert) - **2️⃣ Thema hier lassen** = stay_here: Antwort im Ursprungsraum + thematischer Sticky (never_route für dieses Thema)
- **Verständlicher** ("Nein" statt "Generell") - **3️⃣ Nur diesmal** = stay_once: Antwort im Ursprungsraum (nur diesmal, kein Sticky, ggf. Nachklärung)
- **Konsistent** mit Numbered-Reference-Pattern
## Implementierungsdetails ## Implementierungsdetails (AKTUELL)
### Button-Definition
Die Buttons sind in `plugin/archivar/config.py` definiert:
```python
BUTLER_BUTTONS = [
{"text": "1️⃣ Rüber", "type": "confirm_move"},
{"text": "2️⃣ Thema hier lassen", "type": "stay_here"},
{"text": "3️⃣ Nur diesmal", "type": "stay_once"},
]
```
### Empfangscode-Anpassungen ### Empfangscode-Anpassungen
Der Code in `adapter.py` muss die neuen Button-Labels erkennen können: Der Code in `adapter.py` erkennt die neuen Button-Labels:
```python ```python
# Neue Mapping-Logik # Aktuelle Mapping-Logik (adapter.py Z. 2306-2401)
if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren"): if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren", "kopieren", "confirm_move", "✅ja"):
# Rüberkopieren # 1️⃣ Rüber → confirm_move: Copy + Dispatch im Zielraum
elif choice in ("2", "2️⃣", "Hier", "hier"): elif choice in ("2", "2️⃣", "generell", "generell hier bleiben", "stay_here"):
# Hier bleiben # 2️⃣ Thema hier lassen → stay_here: Sticky + never_route
elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"): else:
# Nicht mehr fragen / sticky_room setzen # 3️⃣ Nur diesmal → stay_once: Antwort hier, kein Sticky
``` ```
### 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 ### Pitfalls und Constraints
#### Button-Truncation #### Button-Truncation
+236 -44
View File
@@ -193,6 +193,15 @@ find_pipx_venv() {
echo "$hermes_venv" echo "$hermes_venv"
return 0 return 0
fi fi
# Fallback 2: Systemweite Installation (root, /usr/local, /opt)
# Bei root-Installationen liegt der venv unter /usr/local/lib/hermes-agent/venv/
# oder /opt/hermes-agent/venv/ — nicht unter $HOME.
for sys_venv in /usr/local/lib/hermes-agent/venv /opt/hermes-agent/venv; do
if [ -d "$sys_venv" ] && [ -x "$sys_venv/bin/python" ]; then
echo "$sys_venv"
return 0
fi
done
return 1 return 1
} }
@@ -207,6 +216,25 @@ print(sp)
PY PY
} }
# Core-Plugin-Pfad finden: dort wo gateway/config.py liegt,
# zwei Ebenen hoch, dann plugins/platforms/.
# Der Gateway scannt Path(__file__).parent.parent / "plugins" / "platforms"
# in gateway/config.py — das ist der MAßGEBLICHE Pfad, nicht site-packages.
find_core_plugin_path() {
local venv="$1"
local core_path
core_path=$("$venv/bin/python" -c "
import gateway.config
from pathlib import Path
print(Path(gateway.config.__file__).parent.parent / 'plugins' / 'platforms')
" 2>/dev/null)
if [ -n "$core_path" ] && [ -d "$core_path" ]; then
echo "$core_path"
return 0
fi
return 1
}
# ────────────────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────────────────
# 1. System-Dependencies installieren # 1. System-Dependencies installieren
# ────────────────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────────────────
@@ -375,11 +403,18 @@ deploy_plugin() {
local src="$script_dir/plugin" local src="$script_dir/plugin"
[ -d "$src" ] || die "plugin/-Verzeichnis fehlt in $script_dir" [ -d "$src" ] || die "plugin/-Verzeichnis fehlt in $script_dir"
# Ziel-Pfad ermitteln: pipx-venv → site-packages, eigener venv → ~/.hermes/hermes-agent/plugins/ # Ziel-Pfad ermitteln: Core-Plugin-Pfad (gateway/config.py) hat Vorrang.
# Der Gateway scannt Path(__file__).parent.parent / "plugins" / "platforms"
# in gateway/config.py — das ist der MAßGEBLICHE Pfad, nicht site-packages.
local dst local dst
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then local core_path
if core_path="$(find_core_plugin_path "$PIPX_VENV" 2>/dev/null)" && [ -n "$core_path" ]; then
dst="$core_path/rocketchat"
log "Core-Plugin-Pfad (gateway/config.py): $dst"
elif [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
# Eigener venv (kein pipx): Plugin direkt unter ~/.hermes/hermes-agent/plugins/ # Eigener venv (kein pipx): Plugin direkt unter ~/.hermes/hermes-agent/plugins/
dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat" dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
log "Eigener venv-Pfad: $dst"
else else
# pipx-venv: Plugin unter site-packages/plugins/platforms/rocketchat/ # pipx-venv: Plugin unter site-packages/plugins/platforms/rocketchat/
local site_packages local site_packages
@@ -390,9 +425,22 @@ deploy_plugin() {
site_packages="<PIPX_VENV>/lib/python3.13/site-packages" site_packages="<PIPX_VENV>/lib/python3.13/site-packages"
fi fi
dst="$site_packages/plugins/platforms/rocketchat" dst="$site_packages/plugins/platforms/rocketchat"
log "site-packages-Pfad (Fallback): $dst"
fi fi
log "Plugin-Ziel (P3): $dst" # Pitfall 8: Alte Plugin-Ordner-Namen vor Deployment bereinigen
for old_name in rocketchat-platform; do
local old_dir
old_dir="$(dirname "$dst")/$old_name"
if [ -d "$old_dir" ]; then
log "Entferne alten Plugin-Ordner: $old_dir"
if ! $DRY_RUN; then
rm -rf "$old_dir"
fi
fi
done
log "Plugin-Ziel: $dst"
if ! $DRY_RUN; then if ! $DRY_RUN; then
mkdir -p "$dst" mkdir -p "$dst"
@@ -419,11 +467,31 @@ deploy_plugin() {
find "$dst" -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null || true find "$dst" -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null || true
find "$dst" -name '*.pyc' -delete 2>/dev/null || true find "$dst" -name '*.pyc' -delete 2>/dev/null || true
# V8.6: Alte tools.py löschen (wurde zu rc_tools.py umbenannt, P3-Fix)
if [ -f "$dst/tools.py" ]; then
rm -f "$dst/tools.py"
log "Alte tools.py gelöscht (ersetzt durch rc_tools.py)"
fi
# plugin.yaml am richtigen Ort? Datei liegt in plugin/plugin.yaml # plugin.yaml am richtigen Ort? Datei liegt in plugin/plugin.yaml
# → kopiert als $dst/plugin.yaml. Korrekt. # → kopiert als $dst/plugin.yaml. Korrekt.
local count local count
count=$(find "$dst" -type f ! -path '*/__pycache__/*' | wc -l) count=$(find "$dst" -type f ! -path '*/__pycache__/*' | wc -l)
ok "$count Plugin-Dateien deployed" ok "$count Plugin-Dateien deployed"
# Pitfall 4: plugin.yaml name-Feld MUSS 'rocketchat' sein
if [ -f "$dst/plugin.yaml" ]; then
if grep '^name:' "$dst/plugin.yaml" | grep -q 'rocketchat$'; then
ok "plugin.yaml name='rocketchat' (korrekt)"
else
local actual_name
actual_name="$(grep '^name:' "$dst/plugin.yaml" | head -1)"
err "FAIL: plugin.yaml name-Feld ist '$actual_name' — muss 'rocketchat' sein! Plugin wird nicht geladen."
die "plugin.yaml name-Feld falsch — Abbruch"
fi
else
warn "plugin.yaml nicht gefunden in $dst"
fi
else else
printf '%s[dry]%s cp -r %s/* -> %s/\\n' "$C_YELLOW" "$C_RESET" "$src" "$dst" printf '%s[dry]%s cp -r %s/* -> %s/\\n' "$C_YELLOW" "$C_RESET" "$src" "$dst"
fi fi
@@ -633,6 +701,17 @@ write_env_file() {
echo "OLLAMA_KEEP_ALIVE=${OLLAMA_KEEP_ALIVE}" echo "OLLAMA_KEEP_ALIVE=${OLLAMA_KEEP_ALIVE}"
} > "$envfile" } > "$envfile"
chmod 600 "$envfile" chmod 600 "$envfile"
# Pitfall 6: ARCHIVAR_CATCHALL_ROOM auto-setzen wenn ROCKETCHAT_HOME_CHANNEL definiert
# Bei Single-Room-Mode (MULTIROOM_AGENT=false) reicht ARCHIVAR_CATCHALL_ROOM in .env.
# Ohne diesen Eintrag crasht der Archivar mit "No room map found".
if [ -n "${ROCKETCHAT_HOME_CHANNEL:-}" ]; then
if ! grep -q '^ARCHIVAR_CATCHALL_ROOM=' "$envfile" 2>/dev/null; then
echo "ARCHIVAR_CATCHALL_ROOM=${ROCKETCHAT_HOME_CHANNEL}" >> "$envfile"
ok "ARCHIVAR_CATCHALL_ROOM=${ROCKETCHAT_HOME_CHANNEL} auto-gesetzt (Pitfall 6)"
fi
fi
ok ".env geschrieben: $envfile (chmod 600)" ok ".env geschrieben: $envfile (chmod 600)"
else else
printf '%s[dry]%s schreibe %s\n' "$C_YELLOW" "$C_RESET" "$envfile" printf '%s[dry]%s schreibe %s\n' "$C_YELLOW" "$C_RESET" "$envfile"
@@ -738,7 +817,76 @@ MD
# ────────────────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────────────────
# 8. Gateway Service (systemd user service mit enable!) # 8. Gateway Service (systemd user service mit enable!)
# P5: Gateway braucht systemctl enable für Autostart # P5: Gateway braucht systemctl enable für Autostart
# Pitfall 7: Unterstützt sowohl systemctl --user (pipx) als auch
# sudo systemctl (system-service, root-Installationen).
# ────────────────────────────────────────────────────────────────────────── # ──────────────────────────────────────────────────────────────────────────
# restart_gateway() — erkennt automatisch ob Gateway als user- oder system-service läuft
restart_gateway() {
if systemctl --user is-active hermes-gateway &>/dev/null; then
systemctl --user restart hermes-gateway
elif sudo systemctl is-active hermes-gateway &>/dev/null; then
sudo systemctl restart hermes-gateway
else
# Weder user noch system — versuche user (Default)
systemctl --user restart hermes-gateway 2>/dev/null || true
fi
}
# gateway_journalctl() — journalctl-Aufruf für user- ODER system-service
gateway_journalctl() {
local args="$*"
if systemctl --user is-active hermes-gateway &>/dev/null 2>&1; then
journalctl --user -u hermes-gateway $args
elif systemctl is-active hermes-gateway &>/dev/null 2>&1; then
journalctl -u hermes-gateway $args
else
# Fallback: user journalctl
journalctl --user -u hermes-gateway $args 2>/dev/null || true
fi
}
# gateway_is_enabled() — prüft enable-Status für user- ODER system-service
gateway_is_enabled() {
if systemctl --user is-enabled hermes-gateway &>/dev/null 2>&1; then
systemctl --user is-enabled hermes-gateway 2>/dev/null
elif systemctl is-enabled hermes-gateway &>/dev/null 2>&1; then
systemctl is-enabled hermes-gateway 2>/dev/null
else
return 1
fi
}
# gateway_is_active() — prüft active-Status für user- ODER system-service
gateway_is_active() {
systemctl --user is-active hermes-gateway &>/dev/null 2>&1 \
|| systemctl is-active hermes-gateway &>/dev/null 2>&1
}
# gateway_systemctl() — generischer systemctl-Aufruf, auto-detektiert user vs. system
gateway_systemctl() {
local cmd="$1"; shift
if systemctl --user is-active hermes-gateway &>/dev/null 2>&1; then
systemctl --user "$cmd" hermes-gateway "$@"
elif systemctl is-active hermes-gateway &>/dev/null 2>&1; then
sudo systemctl "$cmd" hermes-gateway "$@"
else
# Weder user noch system — versuche user (Default)
systemctl --user "$cmd" hermes-gateway "$@" 2>/dev/null || true
fi
}
# gateway_daemon_reload() — daemon-reload für user- ODER system-service
gateway_daemon_reload() {
if systemctl --user is-active hermes-gateway &>/dev/null 2>&1; then
systemctl --user daemon-reload
elif systemctl is-active hermes-gateway &>/dev/null 2>&1; then
sudo systemctl daemon-reload
else
systemctl --user daemon-reload 2>/dev/null || true
fi
}
install_gateway_service() { install_gateway_service() {
banner "8. Gateway Service" banner "8. Gateway Service"
@@ -765,11 +913,15 @@ install_gateway_service() {
local dropin_dir="$HOME/.config/systemd/user/hermes-gateway.service.d" local dropin_dir="$HOME/.config/systemd/user/hermes-gateway.service.d"
local dropin="$dropin_dir/env.conf" local dropin="$dropin_dir/env.conf"
mkdir -p "$dropin_dir" mkdir -p "$dropin_dir"
# Dynamischen site-packages-Pfad ermitteln (nicht hardcoded python3.13)
local _sp
_sp="$(find_site_packages "$PIPX_VENV")"
[ -n "$_sp" ] || _sp="$PIPX_VENV/lib/python3.13/site-packages"
cat > "$dropin" <<EOF cat > "$dropin" <<EOF
[Service] [Service]
EnvironmentFile=%h/.config/hermes/rocketchat.env EnvironmentFile=%h/.config/hermes/rocketchat.env
EnvironmentFile=%h/.hermes/.env EnvironmentFile=%h/.hermes/.env
Environment=PYTHONPATH=$PIPX_VENV/lib/python3.13/site-packages/plugins/platforms/rocketchat Environment=PYTHONPATH=${_sp}/plugins/platforms/rocketchat
Environment=MULTIROOM_AGENT=$RC_MULTIROOM Environment=MULTIROOM_AGENT=$RC_MULTIROOM
Environment=OLLAMA_KEEP_ALIVE=$OLLAMA_KEEP_ALIVE Environment=OLLAMA_KEEP_ALIVE=$OLLAMA_KEEP_ALIVE
EOF EOF
@@ -801,29 +953,29 @@ EOF
ok "Ollama neugestartet (OLLAMA_KEEP_ALIVE=$OLLAMA_KEEP_ALIVE aktiv)" ok "Ollama neugestartet (OLLAMA_KEEP_ALIVE=$OLLAMA_KEEP_ALIVE aktiv)"
fi fi
systemctl --user daemon-reload gateway_daemon_reload
# State-Cleanup (Discovery-Bug + Auto-Resume-Loop) # State-Cleanup (Discovery-Bug + Auto-Resume-Loop)
rm -f "$HOME/.hermes/gateway_state.json" \ rm -f "$HOME/.hermes/gateway_state.json" \
"$HOME/.hermes/gateway.lock" \ "$HOME/.hermes/gateway.lock" \
"$HOME/.hermes/.gateway_state_"*.tmp 2>/dev/null || true "$HOME/.hermes/.gateway_state_"*.tmp 2>/dev/null || true
rm -f "$HOME/.hermes/state.db" 2>/dev/null || true rm -f "$HOME/.hermes/state.db" 2>/dev/null || true
systemctl --user reset-failed hermes-gateway 2>/dev/null || true gateway_systemctl reset-failed 2>/dev/null || true
# P5: ENABLE! Sonst kein Autostart nach Reboot # P5: ENABLE! Sonst kein Autostart nach Reboot
systemctl --user enable hermes-gateway gateway_systemctl enable
ok "hermes-gateway enabled (P5: Autostart nach Reboot)" ok "hermes-gateway enabled (P5: Autostart nach Reboot)"
# Starten # Starten
systemctl --user stop hermes-gateway 2>/dev/null || true gateway_systemctl stop 2>/dev/null || true
local wait=0 local wait=0
while systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $wait -lt 30 ]; do while gateway_is_active && [ $wait -lt 30 ]; do
sleep 1; wait=$((wait + 1)) sleep 1; wait=$((wait + 1))
done done
systemctl --user start hermes-gateway 2>/dev/null || true gateway_systemctl start 2>/dev/null || true
ok "Gateway gestartet" ok "Gateway gestartet"
else else
printf '%s[dry]%s systemctl --user enable + start hermes-gateway\n' "$C_YELLOW" "$C_RESET" printf '%s[dry]%s gateway_systemctl enable + start hermes-gateway\n' "$C_YELLOW" "$C_RESET"
fi fi
} }
@@ -853,12 +1005,20 @@ verify_installation() {
if "$VENV_PY" -c 'import snowballstemmer' 2>/dev/null; then if "$VENV_PY" -c 'import snowballstemmer' 2>/dev/null; then
ok "snowballstemmer in pipx-venv importierbar (P1)" ok "snowballstemmer in pipx-venv importierbar (P1)"
else else
err "FAIL: snowballstemmer fehlt in pipx-venv (P1)"; fail=1 warn "snowballstemmer fehlt — installiere nach..."
if "$VENV_PY" -m pip install --quiet snowballstemmer>=3.0.0 2>/dev/null; then
ok "snowballstemmer nachinstalliert (P1)"
else
err "FAIL: snowballstemmer fehlt und Installation fehlgeschlagen (P1)"; fail=1
fi
fi fi
# Plugin-Dateien # Plugin-Dateien
local plugin_dir local plugin_dir
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then local core_path
if core_path="$(find_core_plugin_path "$PIPX_VENV" 2>/dev/null)" && [ -n "$core_path" ]; then
plugin_dir="$core_path/rocketchat"
elif [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
plugin_dir="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat" plugin_dir="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
else else
local sp local sp
@@ -912,7 +1072,7 @@ verify_installation() {
[ $env_ok -eq 1 ] && ok ".env vollständig" [ $env_ok -eq 1 ] && ok ".env vollständig"
# Gateway service enabled (P5) # Gateway service enabled (P5)
if systemctl --user is-enabled hermes-gateway 2>/dev/null | grep -q enabled; then if gateway_is_enabled | grep -q enabled; then
ok "hermes-gateway enabled (P5: Autostart)" ok "hermes-gateway enabled (P5: Autostart)"
else else
err "FAIL: hermes-gateway nicht enabled (P5)"; fail=1 err "FAIL: hermes-gateway nicht enabled (P5)"; fail=1
@@ -937,7 +1097,7 @@ verify_installation() {
# journalctl ist die zuverlässige Quelle. # journalctl ist die zuverlässige Quelle.
if command -v journalctl >/dev/null 2>&1; then if command -v journalctl >/dev/null 2>&1; then
local no_adapter local no_adapter
no_adapter="$(journalctl --user -u hermes-gateway --since '2 minutes ago' 2>/dev/null | grep -c 'No adapter' || echo "0")" no_adapter="$(gateway_journalctl --since '2 minutes ago' 2>/dev/null | grep -c 'No adapter' || echo "0")"
if [ "${no_adapter:-0}" -gt 0 ]; then if [ "${no_adapter:-0}" -gt 0 ]; then
err "FAIL: Gateway-Log zeigt 'No adapter' — Plugin nicht geladen (Erkenntnis 5)" err "FAIL: Gateway-Log zeigt 'No adapter' — Plugin nicht geladen (Erkenntnis 5)"
fail=1 fail=1
@@ -1135,7 +1295,14 @@ check_gitea_ssh_key() {
} }
# SSH-Key-Check VOR Repo-Bootstrap (P11) # SSH-Key-Check VOR Repo-Bootstrap (P11)
check_gitea_ssh_key # P11-Fix: Bei --update-only ist das Repo bereits lokal — kein Gitea-Clone nötig.
# Externe Maschinen (Hetzner VPS) können Gitea nur per HTTPS erreichen,
# SSH-Port 222 ist nicht nach außen freigegeben.
if [ "$UPDATE_ONLY" = "true" ] && [ -d "$(cd "$(dirname "$0")" && pwd)/.git" ] && [ -d "$(cd "$(dirname "$0")" && pwd)/plugin" ]; then
log "[+] --update-only: P11 Gitea SSH-Check übersprungen (Repo bereits lokal)"
else
check_gitea_ssh_key
fi
# Repo-Bootstrap (falls install.sh standalone aufgerufen wurde) # Repo-Bootstrap (falls install.sh standalone aufgerufen wurde)
bootstrap_repo "$@" bootstrap_repo "$@"
@@ -1184,10 +1351,10 @@ if $CHECK_ONLY; then
banner "P13: Erweiterte Checks" banner "P13: Erweiterte Checks"
# 1. Gateway-Status # 1. Gateway-Status
if systemctl --user is-active hermes-gateway >/dev/null 2>&1; then if gateway_is_active; then
ok "hermes-gateway: active" ok "hermes-gateway: active"
else else
warn "hermes-gateway: nicht aktiv (systemctl --user is-active hermes-gateway)" warn "hermes-gateway: nicht aktiv"
fi fi
# 2. REST-Login-Ping gegen ROCKETCHAT_BASE_URL (falls Credentials vorhanden) # 2. REST-Login-Ping gegen ROCKETCHAT_BASE_URL (falls Credentials vorhanden)
@@ -1258,8 +1425,11 @@ if $UPDATE_ONLY; then
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen" || die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
VENV_PY="$PIPX_VENV/bin/python" VENV_PY="$PIPX_VENV/bin/python"
# Ziel-Pfad ermitteln # Ziel-Pfad ermitteln (gleiche Logik wie deploy_plugin)
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then _update_core_path=""
if _update_core_path="$(find_core_plugin_path "$PIPX_VENV" 2>/dev/null)" && [ -n "$_update_core_path" ]; then
_update_dst="$_update_core_path/rocketchat"
elif [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
_update_dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat" _update_dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
else else
_update_site_packages="$(find_site_packages "$PIPX_VENV")" _update_site_packages="$(find_site_packages "$PIPX_VENV")"
@@ -1286,36 +1456,52 @@ if $UPDATE_ONLY; then
find "$_update_dst" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true find "$_update_dst" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
find "$_update_dst" -name '*.pyc' -delete 2>/dev/null || true find "$_update_dst" -name '*.pyc' -delete 2>/dev/null || true
ok "__pycache__ nach Deployment gelöscht" ok "__pycache__ nach Deployment gelöscht"
# V8.6: Alte tools.py löschen (wurde zu rc_tools.py umbenannt, P3-Fix)
if [ -f "$_update_dst/tools.py" ]; then
rm -f "$_update_dst/tools.py"
log "Alte tools.py gelöscht (ersetzt durch rc_tools.py)"
fi
# V8.6: Stale ~/.hermes/plugins/rocketchat/ bereinigen (alter falscher Pfad)
if [ -d "$HOME/.hermes/plugins/rocketchat" ]; then
rm -rf "$HOME/.hermes/plugins/rocketchat"
log "Stale ~/.hermes/plugins/rocketchat/ gelöscht (alter falscher Pfad)"
fi
else else
printf '%s[dry]%s find %s -type d -name __pycache__ -exec rm -rf {} +\n' "$C_YELLOW" "$C_RESET" "$_update_dst" printf '%s[dry]%s find %s -type d -name __pycache__ -exec rm -rf {} +\n' "$C_YELLOW" "$C_RESET" "$_update_dst"
fi fi
# ── Schritt 4: Gateway-Dienst neu starten ── # ── Schritt 4: Gateway-Dienst neu starten ──
if ! $DRY_RUN; then if ! $DRY_RUN; then
systemctl --user daemon-reload 2>/dev/null || true gateway_daemon_reload 2>/dev/null || true
rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" 2>/dev/null || true rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" 2>/dev/null || true
systemctl --user reset-failed hermes-gateway 2>/dev/null || true gateway_systemctl reset-failed 2>/dev/null || true
if $NO_RESTART; then if $NO_RESTART; then
ok "Gateway-Neustart übersprungen (--no-restart)" ok "Gateway-Neustart übersprungen (--no-restart)"
else else
log "Starte Gateway neu..." log "Starte Gateway neu..."
systemctl --user restart hermes-gateway 2>/dev/null || true # Zeitstempel VOR dem Neustart setzen, damit journalctl --since
# die Initialisierungs-Logs (PresenceEngine, Archivar, Connected)
# erfasst, die in den ersten 6-10s nach Gateway-Start erscheinen.
_verify_since="$(date '+%Y-%m-%d %H:%M:%S')"
restart_gateway 2>/dev/null || true
# Warte bis active (max 30s) # Warte bis active (max 30s)
_update_wait=0 _update_wait=0
while ! systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $_update_wait -lt 30 ]; do while ! gateway_is_active && [ $_update_wait -lt 30 ]; do
sleep 1 sleep 1
_update_wait=$((_update_wait + 1)) _update_wait=$((_update_wait + 1))
done done
if systemctl --user is-active hermes-gateway >/dev/null 2>&1; then if gateway_is_active; then
ok "Gateway neugestartet und aktiv (nach ${_update_wait}s)" ok "Gateway neugestartet und aktiv (nach ${_update_wait}s)"
else else
err "Gateway nach 30s nicht aktiv — prüfe: journalctl --user -u hermes-gateway -n 20" err "Gateway nach 30s nicht aktiv — prüfe: gateway_journalctl -n 20"
fi fi
fi fi
else else
printf '%s[dry]%s systemctl --user restart hermes-gateway\n' "$C_YELLOW" "$C_RESET" printf '%s[dry]%s restart_gateway\\n' "$C_YELLOW" "$C_RESET"
fi fi
# ── Schritt 5: Post-Deployment-Verifikation ── # ── Schritt 5: Post-Deployment-Verifikation ──
@@ -1323,49 +1509,55 @@ if $UPDATE_ONLY; then
banner "Post-Deployment-Verifikation" banner "Post-Deployment-Verifikation"
_update_verify_fail=0 _update_verify_fail=0
if command -v journalctl >/dev/null 2>&1; then # Zuerst: Prüfe ob der Gateway-Prozess überhaupt läuft.
# Präziser Zeitstempel für journalctl --since (statt relativem Zeitfenster) # Wenn der Prozess gecrasht ist, sind Log-Checks sinnlos.
_verify_since="$(date '+%Y-%m-%d %H:%M:%S')" if ! gateway_is_active; then
# Warte 12s: Gateway braucht ~5-7s für PresenceEngine, ~8-10s für Archivar/Connected die "Post-Deployment-Verifikation: Gateway-Prozess ist NICHT active — Gateway ist gecrasht, nicht nur langsam. Prüfe: gateway_journalctl -n 50"
sleep 12 fi
ok "Gateway-Prozess ist active — starte Log-Verifikation"
# Retry-Schleife: bis zu 3 Versuche im Abstand von 5s if command -v journalctl >/dev/null 2>&1; then
for _check_attempt in 1 2 3; do # Warte 20s: Gateway braucht ~6-8s für PresenceEngine, ~10-15s für
# Archivar/Connected (besonders nach Plugin-Updates mit FAISS-Rebuild)
sleep 20
# Retry-Schleife: bis zu 5 Versuche im Abstand von 5s
for _check_attempt in 1 2 3 4 5; do
_all_ok=true _all_ok=true
# Prüfe auf PresenceEngine/presence # Prüfe auf PresenceEngine/presence
_update_presence_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c -i 'PresenceEngine\|presence' || true)" _update_presence_hits="$(gateway_journalctl --since "$_verify_since" --no-pager 2>/dev/null | grep -c -i 'PresenceEngine\\|presence' || true)"
if [ "${_update_presence_hits:-0}" -gt 0 ]; then if [ "${_update_presence_hits:-0}" -gt 0 ]; then
ok "PresenceEngine im Log gefunden ($_update_presence_hits Treffer)" ok "PresenceEngine im Log gefunden ($_update_presence_hits Treffer)"
else else
err "FAIL: PresenceEngine NICHT im Gateway-Log (Versuch $_check_attempt/3) — Plugin-Code wurde möglicherweise nicht geladen (stale __pycache__?)" err "FAIL: PresenceEngine NICHT im Gateway-Log (Versuch $_check_attempt/5) — Plugin-Code wurde möglicherweise nicht geladen (stale __pycache__?)"
_all_ok=false _all_ok=false
fi fi
# Prüfe auf 'Archivar initialisiert' # Prüfe auf 'Archivar initialisiert'
_update_archivar_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Archivar initialisiert' || true)" _update_archivar_hits="$(gateway_journalctl --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Archivar initialisiert' || true)"
if [ "${_update_archivar_hits:-0}" -gt 0 ]; then if [ "${_update_archivar_hits:-0}" -gt 0 ]; then
ok "'Archivar initialisiert' im Log gefunden ($_update_archivar_hits Treffer)" ok "'Archivar initialisiert' im Log gefunden ($_update_archivar_hits Treffer)"
else else
err "FAIL: 'Archivar initialisiert' NICHT im Gateway-Log (Versuch $_check_attempt/3)" err "FAIL: 'Archivar initialisiert' NICHT im Gateway-Log (Versuch $_check_attempt/5)"
_all_ok=false _all_ok=false
fi fi
# Prüfe auf 'Connected to' # Prüfe auf 'Connected to'
_update_connected_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Connected to' || true)" _update_connected_hits="$(gateway_journalctl --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Connected to' || true)"
if [ "${_update_connected_hits:-0}" -gt 0 ]; then if [ "${_update_connected_hits:-0}" -gt 0 ]; then
ok "'Connected to' im Log gefunden ($_update_connected_hits Treffer)" ok "'Connected to' im Log gefunden ($_update_connected_hits Treffer)"
else else
err "FAIL: 'Connected to' NICHT im Gateway-Log (Versuch $_check_attempt/3) — Gateway hat keine Verbindung" err "FAIL: 'Connected to' NICHT im Gateway-Log (Versuch $_check_attempt/5) — Gateway hat keine Verbindung"
_all_ok=false _all_ok=false
fi fi
if $_all_ok; then if $_all_ok; then
ok "Post-Deployment-Verifikation: ALLE CHECKS BESTANDEN (Versuch $_check_attempt/3)" ok "Post-Deployment-Verifikation: ALLE CHECKS BESTANDEN (Versuch $_check_attempt/5)"
break break
fi fi
if [ "$_check_attempt" -lt 3 ]; then if [ "$_check_attempt" -lt 5 ]; then
warn "Warte 5s vor nächstem Verifikations-Versuch..." warn "Warte 5s vor nächstem Verifikations-Versuch..."
sleep 5 sleep 5
else else
@@ -1447,6 +1639,6 @@ verify_installation
if ! $DRY_RUN; then if ! $DRY_RUN; then
echo "" echo ""
ok "Fertig. Bot sollte laufen — prüfe mit:" ok "Fertig. Bot sollte laufen — prüfe mit:"
echo " systemctl --user status hermes-gateway" echo " gateway_systemctl status"
echo " journalctl --user -u hermes-gateway -f" echo " gateway_journalctl -f"
fi fi
+1 -1
View File
@@ -111,7 +111,7 @@ def register(ctx):
_MULTIROOM = os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off") _MULTIROOM = os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off")
from .adapter import RocketChatAdapter # lazy import avoids circular deps from .adapter import RocketChatAdapter # lazy import avoids circular deps
from .tools import register_tools from .rc_tools import register_tools
ctx.register_platform( ctx.register_platform(
name="rocketchat", name="rocketchat",
+1391 -1094
View File
File diff suppressed because it is too large Load Diff
+108
View File
@@ -0,0 +1,108 @@
"""
Gemeinsamer Button-Builder für Onboarding und Review-Flow.
Extrahiert aus onboarding_review.py (P0-1), damit adapter.py und
onboarding_review.py die GLEICHE Button-Konstruktion nutzen — kein Drift.
Regeln:
- Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣...
- Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer,
IMMER in separatem (letztem) Attachment
- Jedes Attachment hat max 3 actions
"""
from typing import Any, List, Tuple
# Emoji-Nummern für bis zu 10 Buttons
EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
def build_button_attachments(
num_buttons: List[Tuple[Any, ...]],
special_buttons: List[Tuple[Any, ...]],
color: str = "#1d74f5",
title: str = "",
number_buttons: bool = True,
button_style: str = "primary",
) -> List[dict]:
"""Baut Attachments nach Andreas' 2-Reihen-Button-Pattern.
Regeln:
- Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣...
(Nummerierung kann via number_buttons=False deaktiviert werden)
- Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer,
IMMER in separatem (letztem) Attachment
- Jedes Attachment hat max 3 actions
P0-Fix: msg-Payload mit '::' Suffix für Button-Klick-Erkennung.
num_buttons: (label, prefix) oder (label, prefix, suffix)
special_buttons: (label, prefix, style) oder (label, prefix, suffix, style)
Wenn suffix vorhanden: msg = f'{prefix}::{suffix}'
Sonst (backward-compat): msg = prefix
Args:
num_buttons: Liste von (label, prefix[, suffix]) Tuples
special_buttons: Liste von (label, prefix, style[, suffix]) Tuples
color: Attachment-Farbe (default: "#1d74f5")
title: Attachment-Titel (nur für erstes Attachment)
number_buttons: Wenn False, werden Buttons NICHT nummeriert
(z.B. für X-Buttons in Keywords-Edit)
button_style: Rocket.Chat button style für num_buttons (default: "primary")
Returns:
Liste von Attachment-Dicts (jedes mit max 3 actions)
"""
attachments: List[dict] = []
# Nummerierte Buttons in 3er-Blöcke aufteilen
for i in range(0, len(num_buttons), 3):
chunk = num_buttons[i:i + 3]
actions = []
for j, tup in enumerate(chunk):
label = tup[0]
prefix = tup[1]
suffix = tup[2] if len(tup) >= 3 else None
msg_payload = f"{prefix}::{suffix}" if suffix else prefix
if number_buttons:
num_idx = i + j
emoji = EMOJI_NUMBERS[num_idx] if num_idx < len(EMOJI_NUMBERS) else str(num_idx + 1)
text = f"{emoji} {label}"
else:
text = label
actions.append({
"type": "button",
"text": text,
"msg": msg_payload,
"msg_in_chat_window": True,
"style": button_style,
})
att = {
"color": color,
"actions": actions,
}
if i == 0 and title:
att["title"] = title
attachments.append(att)
# Sonderschaltflächen in separatem Attachment
if special_buttons:
special_actions = []
for tup in special_buttons:
label = tup[0]
prefix = tup[1]
style = tup[2]
suffix = tup[3] if len(tup) >= 4 else None
msg_payload = f"{prefix}::{suffix}" if suffix else prefix
special_actions.append({
"type": "button",
"text": label,
"msg": msg_payload,
"msg_in_chat_window": True,
"style": style,
})
attachments.append({
"color": color,
"actions": special_actions,
})
return attachments
+119 -8
View File
@@ -10,6 +10,7 @@ ClassificationResult zurückgegeben — der Router übernimmt dann den Fallback.
from __future__ import annotations from __future__ import annotations
import abc import abc
import concurrent.futures
import json import json
import logging import logging
import math import math
@@ -151,7 +152,36 @@ class OllamaEmbeddingClient(EmbeddingClient):
self._timeout = timeout or OLLAMA_CONFIG["timeout"] self._timeout = timeout or OLLAMA_CONFIG["timeout"]
def get_embedding(self, text: str) -> Optional[List[float]]: def get_embedding(self, text: str) -> Optional[List[float]]:
"""Call Ollama embeddings API. Returns None on any failure.""" """Call Ollama embeddings API with a hard deadline timeout.
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
entire HTTP call — not just a socket-level timeout. If the embedding
model takes longer than the deadline, the future is abandoned and
``None`` is returned.
The executor is shut down with ``wait=False`` on timeout so the
caller is never blocked by a hung worker thread.
"""
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
_shutdown = False
try:
future = executor.submit(self._get_embedding_sync, text)
return future.result(timeout=self._timeout)
except concurrent.futures.TimeoutError:
logger.warning(
"Ollama embedding timed out after %.1fs — returning None",
self._timeout,
)
executor.shutdown(wait=False)
_shutdown = True
return None
finally:
if not _shutdown:
executor.shutdown(wait=True)
def _get_embedding_sync(self, text: str) -> Optional[List[float]]:
"""Synchronous embedding implementation (called inside ThreadPoolExecutor)."""
url = f"{self._base_url}/api/embeddings" url = f"{self._base_url}/api/embeddings"
payload = json.dumps( payload = json.dumps(
{"model": self._model, "prompt": text} {"model": self._model, "prompt": text}
@@ -257,7 +287,36 @@ class OllamaLLMClient(LLMClient):
self._timeout = timeout or LLM_CONFIG["timeout"] self._timeout = timeout or LLM_CONFIG["timeout"]
def classify(self, text: str) -> Optional[str]: def classify(self, text: str) -> Optional[str]:
"""Call Ollama generate API. Returns category or None on any failure.""" """Call Ollama generate API with a real deadline timeout.
Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
entire HTTP call — not just a socket-level timeout that resets on
every token. If the LLM (e.g. qwen2.5:7b on CPU) takes longer than
the deadline, the future is abandoned and ``None`` is returned.
The executor is shut down with ``wait=False`` on timeout so the
caller is never blocked by a hung worker thread.
"""
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
_shutdown = False
try:
future = executor.submit(self._classify_sync, text)
return future.result(timeout=self._timeout)
except concurrent.futures.TimeoutError:
logger.warning(
"Ollama classify timed out after %.1fs — returning None",
self._timeout,
)
executor.shutdown(wait=False)
_shutdown = True
return None
finally:
if not _shutdown:
executor.shutdown(wait=True)
def _classify_sync(self, text: str) -> Optional[str]:
"""Synchronous classify implementation (called inside ThreadPoolExecutor)."""
url = f"{self._base_url}/api/generate" url = f"{self._base_url}/api/generate"
payload = json.dumps( payload = json.dumps(
{ {
@@ -282,7 +341,7 @@ class OllamaLLMClient(LLMClient):
if not response_text: if not response_text:
logger.error("Ollama returned empty response") logger.error("Ollama returned empty response")
return None return None
# Trim whitespace and normalize category # Trim whitespace and normalize category
category = response_text.strip().lower() category = response_text.strip().lower()
if category in ("direct_question", "smalltalk", "work_order", "ambiguous"): if category in ("direct_question", "smalltalk", "work_order", "ambiguous"):
@@ -327,8 +386,11 @@ direct_question, smalltalk, work_order, oder ambiguous"""
def generate(self, prompt: str) -> Optional[str]: def generate(self, prompt: str) -> Optional[str]:
"""Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung). """Generiere eine freie Antwort vom LLM (keine Kategorie-Validierung).
Sendet den Prompt an Ollama's /api/generate und gibt die Antwort Uses ``concurrent.futures.ThreadPoolExecutor(max_workers=1)`` with
unvalidiert zurück. Wird vom Raum-Router für LLM_ROOM_PROMPT verwendet. ``.result(timeout=self._timeout)`` to enforce a HARD deadline on the
entire HTTP call — not just a socket-level timeout that resets on
every token. If the LLM (e.g. qwen2.5:7b on CPU) takes longer than
the deadline, the future is abandoned and ``None`` is returned.
Args: Args:
prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT). prompt: Der vollständige Prompt (z.B. LLM_ROOM_PROMPT).
@@ -336,6 +398,25 @@ direct_question, smalltalk, work_order, oder ambiguous"""
Returns: Returns:
Die LLM-Antwort als String (getrimmt), oder None bei Fehler. Die LLM-Antwort als String (getrimmt), oder None bei Fehler.
""" """
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
_shutdown = False
try:
future = executor.submit(self._generate_sync, prompt)
return future.result(timeout=self._timeout)
except concurrent.futures.TimeoutError:
logger.warning(
"Ollama generate timed out after %.1fs — returning None",
self._timeout,
)
executor.shutdown(wait=False)
_shutdown = True
return None
finally:
if not _shutdown:
executor.shutdown(wait=True)
def _generate_sync(self, prompt: str) -> Optional[str]:
"""Synchronous generate implementation (called inside ThreadPoolExecutor)."""
url = f"{self._base_url}/api/generate" url = f"{self._base_url}/api/generate"
payload = json.dumps( payload = json.dumps(
{ {
@@ -469,7 +550,17 @@ class IntentClassifier:
async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: async def _llm_classify(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
import asyncio import asyncio
return await asyncio.to_thread(self._llm_classify_sync, text, scores) try:
# P0-CRITICAL: asyncio.wait_for(15s) — muss KLEINER sein als
# der äußere 20s-Timeout in adapter.py, damit die Timeout-Hierarchie
# korrekt ist: 20s (außen) > 15s (innen).
return await asyncio.wait_for(
asyncio.to_thread(self._llm_classify_sync, text, scores),
timeout=15.0,
)
except asyncio.TimeoutError:
logger.warning("LLM classify timed out (15s) — returning None")
return None
def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]: def _llm_classify_sync(self, text: str, scores: Dict[str, float]) -> Optional[Tuple[str, float]]:
try: try:
@@ -500,7 +591,17 @@ class IntentClassifier:
try: try:
if not self._llm_client or not self._llm_enabled: if not self._llm_client or not self._llm_enabled:
return None return None
return await asyncio.to_thread(self._llm_client.generate, prompt) # P0-CRITICAL: asyncio.wait_for(15s) — muss KLEINER sein als
# der äußere 20s-Timeout in adapter.py, damit die Timeout-Hierarchie
# korrekt ist: 20s (außen) > 15s (innen).
# Bei Timeout: return None → Router wählt STAY-Fallback (router.py Z.1583).
return await asyncio.wait_for(
asyncio.to_thread(self._llm_client.generate, prompt),
timeout=15.0,
)
except asyncio.TimeoutError:
logger.warning("LLM raw call timed out (15s) — returning None for STAY fallback")
return None
except Exception as e: except Exception as e:
logger.warning("LLM raw call failed: %s", e) logger.warning("LLM raw call failed: %s", e)
return None return None
@@ -632,7 +733,17 @@ class IntentClassifier:
best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and best_score >= CONFIDENCE_THRESHOLDS["CLARIFY_NEEDED"] and
best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"] best_score < CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]
): ):
llm_result = self._llm_classify_sync(text, scores) # P0-CRITICAL: Timeout 15s — muss KLEINER sein als der äußere
# 20s-Timeout in adapter.py. Verhindert ThreadPool-Saturation
# durch hängende verify_confidence-Calls.
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as _exec:
_future = _exec.submit(self._llm_classify_sync, text, scores)
try:
llm_result = _future.result(timeout=15.0)
except concurrent.futures.TimeoutError:
logger.warning("LLM verify_confidence timed out (15s) — skipping verification")
llm_result = None
if llm_result: if llm_result:
final_category, final_score = llm_result final_category, final_score = llm_result
llm_verified = True llm_verified = True
+29 -3
View File
@@ -16,7 +16,8 @@ from typing import Dict
OLLAMA_CONFIG: dict = { OLLAMA_CONFIG: dict = {
"base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", "http://localhost:11434"), "base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", "http://localhost:11434"),
"model": "nomic-embed-text", "model": "nomic-embed-text",
"timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s "timeout": 3.0, # Sekunden — HARD deadline via ThreadPoolExecutor
# Muss KLEINER sein als äußerer 20s-Timeout in adapter.py
"embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren "embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren
} }
@@ -156,7 +157,8 @@ wird sie entsprechend klassifiziert. Alles andere → FAKT.
LLM_CONFIG = { LLM_CONFIG = {
"enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"), "enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"),
"model": "qwen2.5:7b", "model": "qwen2.5:7b",
"timeout": 30.0, # Iterative Optimierung: Start 30s (19.06.2026) "timeout": 15.0, # HARD deadline via ThreadPoolExecutor.result(timeout=X)
# Muss KLEINER sein als äußerer 20s-Timeout in adapter.py
"base_url": os.getenv( "base_url": os.getenv(
"ARCHIVAR_LLM_BASE_URL", "ARCHIVAR_LLM_BASE_URL",
os.getenv("OLLAMA_BASE_URL", "http://localhost:11434") os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
@@ -223,7 +225,7 @@ MOVE_REQUEST_TEMPLATE: dict = {
"text": "Soll ich diese Nachricht nach {target_name} kopieren?", "text": "Soll ich diese Nachricht nach {target_name} kopieren?",
"actions": [ "actions": [
{"text": "1️⃣ Rüber", "type": "confirm_move"}, {"text": "1️⃣ Rüber", "type": "confirm_move"},
{"text": "2️⃣ Generell hier", "type": "stay_here"}, {"text": "2️⃣ Thema hier lassen", "type": "stay_here"},
{"text": "3️⃣ Nur diesmal", "type": "stay_once"}, {"text": "3️⃣ Nur diesmal", "type": "stay_once"},
], ],
} }
@@ -333,6 +335,30 @@ RED_FLAG_TIMEOUT: float = float(os.getenv(
)) ))
"""Timeout für Red-Flag-Agent-Entscheidung in Sekunden. Default: 30.0.""" """Timeout für Red-Flag-Agent-Entscheidung in Sekunden. Default: 30.0."""
# ── Themenring Phase A: In-Memory Ringmatrix ────────────────────────────────
# Herzstück der menschenähnlichen Kommunikation: Andreas arbeitet gleichzeitig
# an mehreren Themen in verschiedenen Räumen. Der Themenring speichert pro Raum
# eine deque von TopicEntry-NamedTuples und erlaubt lock-free Reads via
# Copy-on-Write-Snapshot.
TOPIC_RING_MAX_PER_ROOM: int = 5
"""Maximale Anzahl von Topic-Einträgen pro Raum im Ring."""
TOPIC_RING_GLOBAL_MAX: int = 200
"""Globale Obergrenze für alle Topic-Einträge über alle Räume hinweg."""
TOPIC_RING_TTL_EPHEMERAL: float = 3600.0
"""TTL für 'ephemeral'-Einträge in Sekunden (1 Stunde)."""
TOPIC_RING_TTL_SESSION: float = 86400.0
"""TTL für 'session'-Einträge in Sekunden (24 Stunden)."""
TOPIC_RING_TTL_PERSISTENT: float = float('inf')
"""TTL für 'persistent'-Einträge (unendlich — kein automatischer Verfall)."""
TOPIC_RING_PRUNE_INTERVAL: float = 300.0
"""Intervall für den periodischen TTL-Sweep in Sekunden (5 Minuten)."""
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ───── # ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard. # Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
# Bleibt im Code, falls externe Skripte darauf verweisen. # Bleibt im Code, falls externe Skripte darauf verweisen.
+87 -8
View File
@@ -235,6 +235,31 @@ def build_help_text(
"", "",
] ]
# ── Sektion 0: Core-Befehle (Hermes Core, immer verfügbar) ────────
lines.append("### ⚙️ Core-Befehle")
lines.append("")
lines.append(
"Diese Befehle werden direkt vom Hermes-Agenten verarbeitet "
"und sind immer verfügbar — unabhängig vom Plugin:"
)
lines.append("")
lines.append(
"- **continue** — Agent fortsetzen nach leerer Antwort / Stream-Drop. "
"Einfach `continue` in den Chat schreiben, der Agent macht weiter."
)
lines.append(
"- **/reset** — Session zurücksetzen. "
"Löscht den gesamten Chat-Kontext und startet eine frische Session. "
"In Rocket.Chat als `::reset` nutzbar."
)
lines.append(
"- **/compress** — Kontext manuell komprimieren. "
"Verdichtet den Chat-Verlauf, um Token zu sparen und die "
"Antwortqualität bei langen Sessions zu erhalten. "
"In Rocket.Chat als `::compress` nutzbar."
)
lines.append("")
# ::-Befehle nach Kategorie gruppieren # ::-Befehle nach Kategorie gruppieren
by_category: Dict[str, List[Dict[str, Any]]] = {} by_category: Dict[str, List[Dict[str, Any]]] = {}
for name, cmd in registry.get_commands().items(): for name, cmd in registry.get_commands().items():
@@ -300,9 +325,9 @@ def build_help_text(
# P1-4: Status-Farben (Flughafen-Prinzip) — nur wenn PresenceEngine aktiv # P1-4: Status-Farben (Flughafen-Prinzip) — nur wenn PresenceEngine aktiv
if presence_enabled: if presence_enabled:
status_emoji = { status_emoji = {
"online": "🟢 online (idle, verfügbar)", "online": "🟩 online (idle, verfügbar)",
"away": "🟡 away (Hintergrund-Task aktiv, Heartbeat pulsiert)", "away": "🟨 away (Hintergrund-Task aktiv, Heartbeat pulsiert)",
"busy": "🔴 busy (verarbeitet Nachricht)", "busy": "🟥 busy (verarbeitet Nachricht)",
} }
lines.append("### 🚦 Status-Farben") lines.append("### 🚦 Status-Farben")
lines.append("") lines.append("")
@@ -332,7 +357,24 @@ def build_help_text(
"Moderatorenrechte in den Themenräumen haben." "Moderatorenrechte in den Themenräumen haben."
) )
return "\n".join(lines) result = "\n".join(lines)
# P1-Fix: Rocket.Chat hat ein Payload-Limit von ~5000 Zeichen.
# Wenn der Hilfe-Text > 4000 Zeichen ist, lasse die room_map_summary
# weg und ersetze sie durch einen kurzen Hinweis.
MAX_HELP_LENGTH = 4000
if len(result) > MAX_HELP_LENGTH and room_map_summary:
# Finde den Index der room_map_summary in lines und ersetze sie
for i, line in enumerate(lines):
if line == room_map_summary:
lines[i] = (
"Raum-Map-Übersicht aus Platzgründen weggelassen "
"(> 4000 Zeichen). `::status` für Details."
)
break
result = "\n".join(lines)
return result
def build_status_text( def build_status_text(
@@ -378,9 +420,9 @@ def build_status_text(
# P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt) # P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt)
if presence_enabled is not None: if presence_enabled is not None:
status_labels = { status_labels = {
"online": "🟢 online (idle, verfügbar)", "online": "🟩 online (idle, verfügbar)",
"away": "🟡 away (Hintergrund-Task aktiv)", "away": "🟨 away (Hintergrund-Task aktiv)",
"busy": "🔴 busy (verarbeitet Nachricht)", "busy": "🟥 busy (verarbeitet Nachricht)",
} }
pulse_label = "💓 aktiv" if pulse_active else "⏸️ inaktiv" pulse_label = "💓 aktiv" if pulse_active else "⏸️ inaktiv"
if presence_enabled: if presence_enabled:
@@ -397,7 +439,44 @@ def build_status_text(
lines.append("") lines.append("")
lines.append("💡 `::hilfe` für alle Befehle | `::status` für Aktualisierung") lines.append("💡 `::hilfe` für alle Befehle | `::status` für Aktualisierung")
return "\n".join(lines) result = "\n".join(lines)
# P2-Fix: Rocket.Chat Payload-Limit ~5000 Zeichen.
# Wenn der Status-Text > 5000 Zeichen ist, ersetze die room_map_summary
# durch eine kompakte Version (nur Raum-Name + Catch-All-Status).
MAX_STATUS_LENGTH = 5000
if len(result) > MAX_STATUS_LENGTH and room_map_summary:
# Baue kompakte Summary: nur Raum-Name + Catch-All-Marker
compact_lines = ["**Raum-Map (kompakt):**"]
for line in room_map_summary.splitlines():
stripped = line.strip()
if stripped.startswith(("Rocket.Chat", "Keywords", "Thema:")):
continue
# Zeilen wie " 1. Raumname (roomId) ★ CATCH-ALL — Thema: ..."
if stripped and stripped[0].isdigit():
# Extrahiere nur den Teil bis zum Catch-All-Marker
# Format: "1. Name (id) ★ CATCH-ALL — Thema: ..."
# oder: "1. Name (id) — Thema: ..."
if "★ CATCH-ALL" in stripped:
idx = stripped.index("★ CATCH-ALL") + len("★ CATCH-ALL")
compact_lines.append(stripped[:idx])
else:
# Nimm nur "1. Name (id)" — schneide bei " — " ab
dash_idx = stripped.find(" — ")
if dash_idx > 0:
compact_lines.append(stripped[:dash_idx])
else:
compact_lines.append(stripped)
compact_summary = "\n".join(compact_lines)
# Ersetze die room_map_summary in lines
for i, line in enumerate(lines):
if line == room_map_summary:
lines[i] = compact_summary
break
result = "\n".join(lines)
return result
# ── Inline-Command-Parser ─────────────────────────────────────────────── # ── Inline-Command-Parser ───────────────────────────────────────────────
+106 -1
View File
@@ -16,6 +16,7 @@ from __future__ import annotations
import logging import logging
import os import os
import shutil
import tempfile import tempfile
import time import time
from pathlib import Path from pathlib import Path
@@ -319,6 +320,25 @@ async def run_onboarding_greeting_flow(
# Standalone functions extracted from ArchivarMessageHandler (P1-1). # Standalone functions extracted from ArchivarMessageHandler (P1-1).
# These operate on a RoomMap instance and don't depend on the handler's state. # These operate on a RoomMap instance and don't depend on the handler's state.
# P1-1 Fix B: Telemetrie-Counter für Single-Room-Pfad
_single_room_catch_all_overwrite_attempted = 0
_single_room_catch_all_rolled_back = 0
def _get_telemetry_counters() -> dict:
"""Gibt die aktuellen Telemetrie-Counter zurück (für Tests)."""
return {
"single_room_catch_all_overwrite_attempted": _single_room_catch_all_overwrite_attempted,
"single_room_catch_all_rolled_back": _single_room_catch_all_rolled_back,
}
def _reset_telemetry_counters() -> None:
"""Setzt die Telemetrie-Counter zurück (für Tests)."""
global _single_room_catch_all_overwrite_attempted, _single_room_catch_all_rolled_back
_single_room_catch_all_overwrite_attempted = 0
_single_room_catch_all_rolled_back = 0
def check_room_map_completeness( def check_room_map_completeness(
room_map, room_map,
@@ -351,7 +371,27 @@ def check_room_map_completeness(
if len(relevant_rooms) == 1: if len(relevant_rooms) == 1:
single_room_id = list(relevant_rooms.keys())[0] single_room_id = list(relevant_rooms.keys())[0]
if single_room_id not in room_map.rooms: if single_room_id not in room_map.rooms:
global _single_room_catch_all_overwrite_attempted
_single_room_catch_all_overwrite_attempted += 1
room_info = relevant_rooms[single_room_id] room_info = relevant_rooms[single_room_id]
map_file = Path(os.path.expanduser(map_path))
# P1-1 Fix B: Snapshot der aktuellen Disk-Datei VOR der Mutation
bak_path = Path(str(map_file) + ".onboarding_bak")
pre_mutation_room_count = len(room_map.rooms)
pre_mutation_catch_all = room_map.catch_all_room
if map_file.exists():
try:
shutil.copy2(map_file, bak_path)
logger.debug(
"Single-Room-Pfad: Backup vor Mutation erstellt: %s", bak_path
)
except OSError as e:
logger.warning(
"Single-Room-Pfad: Konnte Backup nicht erstellen: %s", e
)
room_map.add_or_update_room( room_map.add_or_update_room(
room_id=single_room_id, room_id=single_room_id,
name=room_info["name"], name=room_info["name"],
@@ -361,8 +401,73 @@ def check_room_map_completeness(
catch_all=True, catch_all=True,
) )
from archivar.room_map import RoomMap from archivar.room_map import RoomMap
RoomMap.save(room_map, Path(os.path.expanduser(map_path))) RoomMap.save(room_map, map_file)
room_map.reload() room_map.reload()
# P1-1 Fix B: Integritätsprüfung NACH save() + reload()
integrity_ok = True
post_mutation_room_count = len(room_map.rooms)
# Prüfung 1: Hat In-Memory-Map die gleiche Anzahl Räume wie VOR der Mutation?
# (Sollte mindestens pre_mutation_room_count + 1 sein)
if post_mutation_room_count < pre_mutation_room_count + 1:
logger.error(
"Single-Room-Pfad INTEGRITY FAILED: "
"Vor Mutation: %d Räume, nach save+reload: %d Räume. "
"Rollback wird eingeleitet.",
pre_mutation_room_count, post_mutation_room_count,
)
integrity_ok = False
# Prüfung 2: Existiert der ursprüngliche catch_all-Raum noch?
if pre_mutation_catch_all is not None:
if pre_mutation_catch_all.room_id not in room_map.rooms:
logger.error(
"Single-Room-Pfad INTEGRITY FAILED: "
"Ursprünglicher Catch-All-Raum '%s' fehlt nach save+reload. "
"Rollback wird eingeleitet.",
pre_mutation_catch_all.name,
)
integrity_ok = False
if not integrity_ok:
global _single_room_catch_all_rolled_back
_single_room_catch_all_rolled_back += 1
# Rollback aus Backup
if bak_path.exists():
try:
shutil.copy2(bak_path, map_file)
room_map.reload()
logger.critical(
"Single-Room-Pfad: Rollback aus Backup erfolgreich. "
"Map wurde auf Zustand vor Mutation zurückgesetzt."
)
except OSError as e:
logger.critical(
"Single-Room-Pfad: Rollback FEHLGESCHLAGEN: %s", e
)
else:
logger.critical(
"Single-Room-Pfad: Kein Backup vorhanden — "
"Rollback nicht möglich!"
)
# Cleanup Backup
try:
bak_path.unlink(missing_ok=True)
except OSError:
pass
# Trotz Rollback: Raum als missing melden (nicht auto-assigned)
return [{"room_id": single_room_id, "name": room_info["name"]}]
# Cleanup Backup nach erfolgreichem Save
try:
bak_path.unlink(missing_ok=True)
except OSError:
pass
logger.info( logger.info(
"Single room detected — auto-assigned as catch_all: %s", "Single room detected — auto-assigned as catch_all: %s",
room_info["name"], room_info["name"],
+17 -81
View File
@@ -154,85 +154,10 @@ def _persist_room_map_changes(
# ── UX REFACTOR: build_button_attachments() Helper ────────────────────────── # ── UX REFACTOR: build_button_attachments() Helper ──────────────────────────
# P0-1: In gemeinsames Modul button_builder.py extrahiert,
# damit adapter.py und onboarding_review.py die GLEICHE Button-Konstruktion nutzen.
# Emoji-Nummern für bis zu 10 Buttons from archivar.button_builder import build_button_attachments, EMOJI_NUMBERS
_EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
def build_button_attachments(
num_buttons: List[Tuple[str, str]],
special_buttons: List[Tuple[str, str, str]],
color: str = "#1d74f5",
title: str = "",
number_buttons: bool = True,
button_style: str = "primary",
) -> List[dict]:
"""Baut Attachments nach Andreas' 2-Reihen-Button-Pattern.
Regeln:
- Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣...
(Nummerierung kann via number_buttons=False deaktiviert werden)
- Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer,
IMMER in separatem (letztem) Attachment
- Jedes Attachment hat max 3 actions
Args:
num_buttons: Liste von (label, prefix) Tuples für nummerierte Buttons
special_buttons: Liste von (label, prefix, style) Tuples für Sonderschaltflächen
color: Attachment-Farbe (default: "#1d74f5")
title: Attachment-Titel (nur für erstes Attachment)
number_buttons: Wenn False, werden Buttons NICHT nummeriert
(z.B. für X-Buttons in Keywords-Edit)
button_style: Rocket.Chat button style für num_buttons (default: "primary")
Returns:
Liste von Attachment-Dicts (jedes mit max 3 actions)
"""
attachments: List[dict] = []
# Nummerierte Buttons in 3er-Blöcke aufteilen
for i in range(0, len(num_buttons), 3):
chunk = num_buttons[i:i + 3]
actions = []
for j, (label, prefix) in enumerate(chunk):
if number_buttons:
num_idx = i + j
emoji = _EMOJI_NUMBERS[num_idx] if num_idx < len(_EMOJI_NUMBERS) else str(num_idx + 1)
text = f"{emoji} {label}"
else:
text = label
actions.append({
"type": "button",
"text": text,
"msg": prefix,
"msg_in_chat_window": True,
"style": button_style,
})
att = {
"color": color,
"actions": actions,
}
if i == 0 and title:
att["title"] = title
attachments.append(att)
# Sonderschaltflächen in separatem Attachment
if special_buttons:
special_actions = []
for label, prefix, style in special_buttons:
special_actions.append({
"type": "button",
"text": label,
"msg": prefix,
"msg_in_chat_window": True,
"style": style,
})
attachments.append({
"color": color,
"actions": special_actions,
})
return attachments
# ── Schritt 1: review_room Top-Level Renderer ───────────────────────────── # ── Schritt 1: review_room Top-Level Renderer ─────────────────────────────
@@ -297,7 +222,7 @@ def render_review_room_step(
# Nummerierte Optionen im Text # Nummerierte Optionen im Text
lines.append("👉 Klicke auf einen Raum zum Anpassen:") lines.append("👉 Klicke auf einen Raum zum Anpassen:")
for i, (label, _) in enumerate(num_buttons): for i, (label, _) in enumerate(num_buttons):
emoji = _EMOJI_NUMBERS[i] if i < len(_EMOJI_NUMBERS) else str(i + 1) emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else str(i + 1)
lines.append(f" {emoji} {label}") lines.append(f" {emoji} {label}")
# Sonderschaltflächen # Sonderschaltflächen
@@ -672,10 +597,21 @@ def render_review_room_add_new(
(text, attachments) Tuple (text, attachments) Tuple
""" """
if not available_rooms: if not available_rooms:
# P0-4: Auch bei leerer Liste einen Zurück-Button rendern,
# damit der User nicht in einer UX-Sackgasse steckt.
special_buttons: List[Tuple[str, str, str]] = [
("↩️ Zurück", REVIEW_ROOM_BACK, "default"),
]
attachments = build_button_attachments(
[],
special_buttons,
color="#1d74f5",
title="Neuen Raum hinzufügen",
)
return ( return (
"📋 **Neuer Raum** — Keine weiteren Räume verfügbar.\n" "📋 **Neuer Raum** — Keine weiteren Räume verfügbar.\n"
"Alle Rocket.Chat-Räume sind bereits in der Room-Map.", "Alle Rocket.Chat-Räume sind bereits in der Room-Map.",
[], attachments,
) )
lines = [ lines = [
@@ -691,7 +627,7 @@ def render_review_room_add_new(
name = room.get("name", rid) name = room.get("name", rid)
rtype = room.get("type", "c") rtype = room.get("type", "c")
type_label = "💬" if rtype == "d" else "#" type_label = "💬" if rtype == "d" else "#"
emoji = _EMOJI_NUMBERS[i] if i < len(_EMOJI_NUMBERS) else str(i + 1) emoji = EMOJI_NUMBERS[i] if i < len(EMOJI_NUMBERS) else str(i + 1)
lines.append(f" {emoji} {type_label} {name}") lines.append(f" {emoji} {type_label} {name}")
# Kurzer Button-Name (max 9 Zeichen) # Kurzer Button-Name (max 9 Zeichen)
short_name = name[:9] if len(name) > 9 else name short_name = name[:9] if len(name) > 9 else name
+442 -71
View File
@@ -14,10 +14,12 @@ import json
import logging import logging
import os import os
import subprocess import subprocess
import tempfile
import threading import threading
import time import time
import urllib.request import urllib.request
import urllib.error import urllib.error
from datetime import datetime, timezone
from typing import Optional, Dict, Callable from typing import Optional, Dict, Callable
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -30,6 +32,73 @@ if not logger.handlers:
logger.propagate = False # Don't double-log to root logger.propagate = False # Don't double-log to root
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Plugin-State-Datei — atomare Hilfsfunktionen
# ═══════════════════════════════════════════════════════════════════════════
PLUGIN_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
PLUGIN_STATE_FILENAME = "hermes_rocket_plugin.json"
PLUGIN_STATE_SCHEMA_VERSION = 1
def _get_plugin_state_path() -> str:
"""Return the path to the plugin state file.
Returns:
Absolute path to ~/.hermes/plugin_state/hermes_rocket_plugin.json
"""
return os.path.join(PLUGIN_STATE_DIR, PLUGIN_STATE_FILENAME)
def _read_plugin_state(path: str) -> dict:
"""Read the plugin state file, returning {} if missing or corrupt.
Args:
path: Absolute path to the plugin state JSON file.
Returns:
Parsed dict, or empty dict on any error.
"""
try:
if not os.path.exists(path):
return {}
with open(path, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[plugin_state] read failed: %s", e)
return {}
def _write_plugin_state(path: str, data: dict) -> None:
"""Atomically write the plugin state file (write-temp + rename).
Args:
path: Absolute path to the plugin state JSON file.
data: Dict to serialize as JSON.
"""
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
# Write to temp file in same directory (same filesystem → atomic rename)
fd, tmp_path = tempfile.mkstemp(
suffix=".tmp",
prefix="plugin_state_",
dir=os.path.dirname(path),
)
try:
with os.fdopen(fd, 'w') as f:
json.dump(data, f, ensure_ascii=False)
os.replace(tmp_path, path) # atomic on POSIX
except Exception:
# Clean up temp file on write failure
try:
os.unlink(tmp_path)
except OSError:
pass
raise
except Exception as e:
logger.debug("[plugin_state] write failed: %s", e)
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════
# Pure Function: _format_presence_message # Pure Function: _format_presence_message
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════
@@ -80,14 +149,20 @@ class PresenceEngine:
Thread-safe: uses threading.Lock for all counter operations. Thread-safe: uses threading.Lock for all counter operations.
Coalesce-Timer: prevents flickering by delaying status updates by 2s. Coalesce-Timer: prevents flickering by delaying status updates by 2s.
Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle. Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle.
P1a: Honeymoon-Timer ensures busy status is visible for at least
MIN_BUSY_VISIBLE_S (1.0s) before transitioning to online.
""" """
# P1a: Minimum time busy status must be visible (prevents coalesce race)
MIN_BUSY_VISIBLE_S = 1.0
def __init__( def __init__(
self, self,
rest=None, rest=None,
enabled: bool = True, enabled: bool = True,
coalesce_ms: int = 2000, coalesce_ms: int = 2000,
pulse_interval: float = 1.5, pulse_interval: float = 5.0,
gateway_state_path: str = "", gateway_state_path: str = "",
_clamp_pulse: bool = True, _clamp_pulse: bool = True,
): ):
@@ -137,6 +212,16 @@ class PresenceEngine:
self._background_tasks: int = 0 self._background_tasks: int = 0
self._background_tasks_lock = threading.Lock() self._background_tasks_lock = threading.Lock()
# P1-2: Plugin-State-Datei für DetectionTimer (Gateway-interne Subagenten)
self._plugin_state_path: str = _get_plugin_state_path()
self._plugin_state_lock = threading.Lock() # Thread-safe, nicht asyncio
# P1a: Honeymoon-Timer — busy status minimum 1s sichtbar
self._busy_started_at: float = 0.0 # time.monotonic() when busy started
self._busy_honeymoon_timer: Optional[threading.Timer] = None
self._busy_honeymoon_lock = threading.Lock()
self._busy_counter: int = 0 # multi-turn: count concurrent busy starts
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s) # P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
self._pulse_controller = PulseController( self._pulse_controller = PulseController(
pulse_interval=pulse_interval, pulse_interval=pulse_interval,
@@ -150,9 +235,10 @@ class PresenceEngine:
on_change=self._on_detection_change, on_change=self._on_detection_change,
) )
# Start detection if enabled # P1b: DetectionTimer NICHT im Init starten — erst nach on_connected_cb.
if self._enabled: # Der Adapter ruft _detection_timer.start() explizit auf, sobald die
self._detection_timer.start() # DDP-Verbindung steht. Das verhindert eine Race-Condition bei der
# ersten gateway_state.json-Auswertung (Datei existiert ggf. noch nicht).
# ── Public API ─────────────────────────────────────────────────────── # ── Public API ───────────────────────────────────────────────────────
@@ -160,10 +246,20 @@ class PresenceEngine:
"""Check if presence updates are enabled.""" """Check if presence updates are enabled."""
return self._enabled return self._enabled
def start_detection(self) -> None:
"""P1b: Start DetectionTimer — called after DDP connection is established.
Must be called explicitly by the adapter in on_connected_cb.
Prevents race condition where gateway_state.json doesn't exist yet
at PresenceEngine init time.
"""
if self._enabled:
self._detection_timer.start()
def enable(self) -> None: def enable(self) -> None:
"""Enable presence updates. Starts DetectionTimer.""" """Enable presence updates. DetectionTimer must be started externally
via start_detection() after DDP connection is established."""
self._enabled = True self._enabled = True
self._detection_timer.start()
logger.info("[presence] PresenceEngine enabled") logger.info("[presence] PresenceEngine enabled")
def disable(self) -> None: def disable(self) -> None:
@@ -194,13 +290,142 @@ class PresenceEngine:
self._active_tasks -= 1 self._active_tasks -= 1
count = self._active_tasks count = self._active_tasks
# FIX: Resume pulse when all active tasks complete. # FIX: Resume pulse when all active tasks complete.
# on_agent_busy() pauses the pulse, but resume() was never called # mark_busy_started() pauses the pulse via adapter, but resume()
# in production — the pulse stayed paused forever. # was never called in production — the pulse stayed paused forever.
if count == 0: if count == 0:
self._pulse_controller.resume() self._pulse_controller.resume()
logger.info("[presence] active_tasks=0 → pulse resumed") logger.info("[presence] active_tasks=0 → pulse resumed")
return count return count
# ── P1a: Honeymoon-Timer — busy minimum 1s sichtbar ──────────────────
def mark_busy_started(self, room_name: str = "") -> None:
"""P1a: Mark the start of a busy period with honeymoon protection.
Sets the room, increments active_tasks, and schedules a busy status.
If a honeymoon timer is already running (multi-turn), only increments
the counter — no duplicate timer.
Args:
room_name: Room name for the busy status message.
"""
self.set_current_room(room_name)
self.increment_active_tasks()
self.update_presence() # sets pending_status="busy"
# P1a: Busy sofort flushen — nicht auf 2s Coalesce warten.
# Der Honeymoon-Timer (1s) würde sonst vor dem Coalesce feuern.
self._flush_presence()
with self._busy_honeymoon_lock:
self._busy_counter += 1
if self._busy_honeymoon_timer is None:
# B2: _busy_started_at nur beim ERSTEN busy-Start setzen.
# Wenn der Honeymoon-Timer bereits abgelaufen ist (Timer=None)
# aber _busy_started_at noch existiert (weil active > 0),
# dann NICHT neu setzen — sonst künstliche Verlängerung um 1s.
if self._busy_started_at == 0.0:
self._busy_started_at = time.monotonic()
self._busy_honeymoon_timer = threading.Timer(
self.MIN_BUSY_VISIBLE_S,
self._honeymoon_expired,
)
self._busy_honeymoon_timer.daemon = True
self._busy_honeymoon_timer.start()
logger.debug(
"[presence] Honeymoon-Timer gestartet (%.1fs), counter=%d, started_at=%.3f",
self.MIN_BUSY_VISIBLE_S, self._busy_counter, self._busy_started_at,
)
else:
logger.debug(
"[presence] Honeymoon-Timer läuft bereits, counter=%d",
self._busy_counter,
)
def mark_busy_done(self) -> None:
"""P1a: Mark the end of a busy period.
Decrements the busy counter. If the counter reaches 0 and the
honeymoon has elapsed, transitions to online immediately.
If the honeymoon hasn't elapsed yet, the timer callback will
handle the transition when it fires.
Must be called in a finally block to ensure counter balance
even on exceptions.
"""
with self._busy_honeymoon_lock:
if self._busy_counter > 0:
self._busy_counter -= 1
counter = self._busy_counter
# Decrement the underlying active_tasks counter
self.decrement_active_tasks()
if counter == 0:
elapsed = time.monotonic() - self._busy_started_at
if elapsed >= self.MIN_BUSY_VISIBLE_S:
# Honeymoon already elapsed — transition to online now
self._cancel_honeymoon_timer()
self.update_presence()
logger.debug(
"[presence] Honeymoon abgelaufen (%.2fs) → online", elapsed,
)
else:
# Honeymoon still running — timer callback will handle it
logger.debug(
"[presence] Honeymoon läuft noch (%.2fs/%.1fs) — Timer übernimmt",
elapsed, self.MIN_BUSY_VISIBLE_S,
)
else:
logger.debug(
"[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter,
)
def _honeymoon_expired(self) -> None:
"""P1a: Honeymoon timer callback — transition to online if idle.
Called by threading.Timer after MIN_BUSY_VISIBLE_S.
If no active tasks remain, sets status to online.
B3: Checks pending_status under _active_tasks_lock to prevent
race with mark_busy_started.
"""
with self._busy_honeymoon_lock:
self._busy_honeymoon_timer = None
with self._active_tasks_lock:
active = self._active_tasks
if active == 0:
# B3: Race-Schutz — prüfe ob pending_status 'busy' ist.
# mark_busy_started könnte parallel update_presence() mit
# pending='busy' aufgerufen haben. Dann NICHT überschreiben.
with self._coalesce_lock:
pending = self._pending_status
if pending == "busy":
logger.debug(
"[presence] Honeymoon-Timer abgelaufen, aber pending_status=busy — "
"nicht überschreiben (Race-Schutz)"
)
return
# B2: Reset _busy_started_at when honeymoon fully expires
# and no active tasks remain — next busy cycle starts fresh.
self._busy_started_at = 0.0
logger.info(
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → online"
)
self.update_presence()
else:
logger.debug(
"[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel",
active,
)
def _cancel_honeymoon_timer(self) -> None:
"""P1a: Cancel the honeymoon timer if running."""
with self._busy_honeymoon_lock:
if self._busy_honeymoon_timer is not None:
self._busy_honeymoon_timer.cancel()
self._busy_honeymoon_timer = None
def set_onboarding_active(self, active: bool) -> None: def set_onboarding_active(self, active: bool) -> None:
"""Set the onboarding sentinel.""" """Set the onboarding sentinel."""
self._onboarding_active = active self._onboarding_active = active
@@ -232,18 +457,31 @@ class PresenceEngine:
def increment_background_tasks(self) -> int: def increment_background_tasks(self) -> int:
"""Increment background tasks counter. Thread-safe. """Increment background tasks counter. Thread-safe.
P1-2: Persists to plugin state file for DetectionTimer.
E1: Lock-Scope erweitert — _persist_plugin_state wird jetzt unter
_background_tasks_lock aufgerufen, sodass kein veralteter Count
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
Returns: Returns:
New counter value. New counter value.
""" """
with self._background_tasks_lock: with self._background_tasks_lock:
self._background_tasks += 1 self._background_tasks += 1
count = self._background_tasks count = self._background_tasks
self._pulse_controller.set_background_count(count) self._pulse_controller.set_background_count(count)
self._persist_plugin_state(count)
return count return count
def decrement_background_tasks(self) -> int: def decrement_background_tasks(self) -> int:
"""Decrement background tasks counter. Thread-safe. """Decrement background tasks counter. Thread-safe.
P1-2: Persists to plugin state file for DetectionTimer.
E1: Lock-Scope erweitert — _persist_plugin_state wird jetzt unter
_background_tasks_lock aufgerufen, sodass kein veralteter Count
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
Returns: Returns:
New counter value. New counter value.
""" """
@@ -251,11 +489,30 @@ class PresenceEngine:
if self._background_tasks > 0: if self._background_tasks > 0:
self._background_tasks -= 1 self._background_tasks -= 1
count = self._background_tasks count = self._background_tasks
self._pulse_controller.set_background_count(count) self._pulse_controller.set_background_count(count)
if count == 0: if count == 0:
self._pulse_controller.stop() self._pulse_controller.stop()
self._persist_plugin_state(count)
return count return count
def _persist_plugin_state(self, background_tasks: int) -> None:
"""P1-2: Persist background_tasks to plugin state file.
Thread-safe via _plugin_state_lock. Writes atomically via
_write_plugin_state (temp + rename).
Args:
background_tasks: Current background tasks count.
"""
with self._plugin_state_lock:
data = {
"background_tasks": background_tasks,
"last_update_iso": datetime.now(timezone.utc).isoformat(),
"source": "plugin_internal",
"schema_version": PLUGIN_STATE_SCHEMA_VERSION,
}
_write_plugin_state(self._plugin_state_path, data)
# ── Internal: Presence Setting ─────────────────────────────────────── # ── Internal: Presence Setting ───────────────────────────────────────
def _set_presence(self, status: str, message: str) -> None: def _set_presence(self, status: str, message: str) -> None:
@@ -429,6 +686,7 @@ class PresenceEngine:
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer.""" """Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
self._pulse_controller.stop() self._pulse_controller.stop()
self._detection_timer.stop() self._detection_timer.stop()
self._cancel_honeymoon_timer()
with self._coalesce_lock: with self._coalesce_lock:
if self._coalesce_timer is not None: if self._coalesce_timer is not None:
self._coalesce_timer.cancel() self._coalesce_timer.cancel()
@@ -444,24 +702,6 @@ class PresenceEngine:
""" """
self._pulse_controller.cancel_pending() self._pulse_controller.cancel_pending()
def on_agent_busy(self, room_name: str = "") -> None:
"""Hook: Agent is processing a message — pause pulse, set busy.
Priority 1 (highest): busy (rot) — Nachricht wird verarbeitet.
"""
self.set_current_room(room_name)
self.increment_active_tasks()
self.update_presence()
# Pause pulse if running
self._pulse_controller.pause()
def on_message_received(self, room_name: str = "") -> None:
"""Hook: Message received — same as on_agent_busy.
Alias for on_agent_busy for semantic clarity.
"""
self.on_agent_busy(room_name=room_name)
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════
# PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall) # PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall)
@@ -479,13 +719,13 @@ class PulseController:
def __init__( def __init__(
self, self,
pulse_interval: float = 1.5, pulse_interval: float = 5.0,
_clamp_pulse: bool = True, _clamp_pulse: bool = True,
): ):
"""Initialize PulseController. """Initialize PulseController.
Args: Args:
pulse_interval: Pulse interval in seconds (default 1.5). pulse_interval: Pulse interval in seconds (default 5.0).
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing. _clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
""" """
if _clamp_pulse: if _clamp_pulse:
@@ -501,10 +741,16 @@ class PulseController:
self._phase: bool = False # False=online, True=away self._phase: bool = False # False=online, True=away
self._last_sent_phase: Optional[bool] = None self._last_sent_phase: Optional[bool] = None
self._background_count: int = 0 self._background_count: int = 0
self._cancel_pending: bool = False # P0-2: skip next tick flag self._cancel_pending_event = threading.Event() # B6: thread-safe via Event statt bool
# P1-2 O-2: Async-await bridge # P1-2 O-2: Async-await bridge
self._loop: Optional[asyncio.AbstractEventLoop] = None self._loop: Optional[asyncio.AbstractEventLoop] = None
self._await_timeout: float = 2.0 self._await_timeout: float = 2.0
# P0-CRITICAL: Default sync — async-Pfad nur wenn explizit aktiviert.
# Verhindert ThreadPool-Saturation durch run_coroutine_threadsafe.
self._use_async_tick: bool = False
# P0-CRITICAL: Circuit-Breaker — zweistufiges Backoff bei Fehlern.
self._consecutive_failures: int = 0
self._current_interval: Optional[float] = None # None = use _pulse_interval
# ── Public API ─────────────────────────────────────────────────────── # ── Public API ───────────────────────────────────────────────────────
@@ -612,7 +858,7 @@ class PulseController:
status fires while the PulseController is running. status fires while the PulseController is running.
Sets a flag that the next tick will skip. Sets a flag that the next tick will skip.
""" """
self._cancel_pending = True self._cancel_pending_event.set()
logger.debug("[pulse] cancel_pending: next tick will be skipped") logger.debug("[pulse] cancel_pending: next tick will be skipped")
# ── Internal: Pulse Loop ───────────────────────────────────────────── # ── Internal: Pulse Loop ─────────────────────────────────────────────
@@ -642,7 +888,10 @@ class PulseController:
self._pulse_tick() self._pulse_tick()
# Sleep for pulse interval, checking running flag periodically # Sleep for pulse interval, checking running flag periodically
for _ in range(int(self._pulse_interval * 10)): # P0-CRITICAL: Circuit-Breaker — _current_interval überschreibt
# _pulse_interval bei Fehlern (Stufe 1: 10s, Stufe 2: 30s).
effective_interval = self._current_interval if self._current_interval is not None else self._pulse_interval
for _ in range(int(effective_interval * 10)):
if not self._running.is_set(): if not self._running.is_set():
break break
if self._paused.is_set(): if self._paused.is_set():
@@ -661,13 +910,14 @@ class PulseController:
self._phase, self._phase,
self._ddp is not None, self._ddp is not None,
self._paused.is_set(), self._paused.is_set(),
self._cancel_pending, self._cancel_pending_event.is_set(),
self._loop is not None, self._loop is not None,
) )
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence) # P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
if self._cancel_pending: # B6: thread-safe via threading.Event statt bool
self._cancel_pending = False if self._cancel_pending_event.is_set():
self._cancel_pending_event.clear()
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set") logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
return return
@@ -682,14 +932,26 @@ class PulseController:
) )
return return
# P1-2 O-2: Delegate to async path if loop is bound and running # P0-CRITICAL: Default sync — async-Pfad nur wenn explizit aktiviert.
if self._loop is not None and self._loop.is_running(): # run_coroutine_threadsafe sättigt den ThreadPool und blockiert den
# Event-Loop-Selector → Watchdog-Probes schlagen fehl → Kill.
if self._use_async_tick and self._loop is not None and self._loop.is_running():
try: try:
future = asyncio.run_coroutine_threadsafe( future = asyncio.run_coroutine_threadsafe(
self._pulse_tick_async(), self._pulse_tick_async(),
self._loop, self._loop,
) )
future.result(timeout=self._pulse_interval) # B5: Polling mit Pause-Check — pause() wirkt in 50ms statt 1.5s.
# future.result(timeout=...) blockiert bis zu pulse_interval,
# währenddessen kann pause() nicht greifen.
while not future.done():
if self._paused.is_set():
future.cancel()
logger.debug("[pulse] _pulse_tick async cancelled by pause")
break
time.sleep(0.05)
if not future.cancelled():
future.result(timeout=0) # already done, no blocking
return return
except Exception as e: except Exception as e:
logger.info( logger.info(
@@ -708,10 +970,12 @@ class PulseController:
self._ddp.set_status(status) self._ddp.set_status(status)
self._last_sent_phase = self._phase self._last_sent_phase = self._phase
self._increment_telemetry() self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status) logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
return return
except Exception as e: except Exception as e:
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e) logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
self._record_failure()
# REST fallback for message text # REST fallback for message text
if self._rest is not None and getattr(self._rest, 'auth_token', None): if self._rest is not None and getattr(self._rest, 'auth_token', None):
@@ -729,9 +993,11 @@ class PulseController:
) )
self._last_sent_phase = self._phase self._last_sent_phase = self._phase
self._increment_telemetry() self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status) logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
except Exception as e: except Exception as e:
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e) logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
self._record_failure()
else: else:
logger.debug( logger.debug(
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)", "[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
@@ -756,6 +1022,7 @@ class PulseController:
await self._ddp.set_status_async(status, timeout=self._await_timeout) await self._ddp.set_status_async(status, timeout=self._await_timeout)
self._last_sent_phase = self._phase self._last_sent_phase = self._phase
self._increment_telemetry() self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status) logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
return return
except Exception as e: except Exception as e:
@@ -764,6 +1031,7 @@ class PulseController:
"falling back to REST", "falling back to REST",
e, e,
) )
self._record_failure()
# REST fallback for message text # REST fallback for message text
if self._rest is not None and getattr(self._rest, 'auth_token', None): if self._rest is not None and getattr(self._rest, 'auth_token', None):
@@ -781,14 +1049,47 @@ class PulseController:
) )
self._last_sent_phase = self._phase self._last_sent_phase = self._phase
self._increment_telemetry() self._increment_telemetry()
self._record_success()
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status) logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
except Exception as e: except Exception as e:
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e) logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
self._record_failure()
else: else:
logger.debug( logger.debug(
"[pulse] _pulse_tick_async skip: no DDP and no REST available", "[pulse] _pulse_tick_async skip: no DDP and no REST available",
) )
def _record_failure(self) -> None:
"""P0-CRITICAL: Zweistufiger Circuit-Breaker.
Stufe 1: ab 2 consecutive_failures → _current_interval = 10.0s
Stufe 2: ab 4 consecutive_failures → _current_interval = 30.0s
Bei Erfolg (_record_success) wird zurückgesetzt.
"""
self._consecutive_failures += 1
if self._consecutive_failures >= 4:
self._current_interval = 30.0
logger.warning(
"[pulse] Circuit-Breaker Stufe 2: interval=30.0s (failures=%d)",
self._consecutive_failures,
)
elif self._consecutive_failures >= 2:
self._current_interval = 10.0
logger.warning(
"[pulse] Circuit-Breaker Stufe 1: interval=10.0s (failures=%d)",
self._consecutive_failures,
)
def _record_success(self) -> None:
"""Reset circuit breaker on successful pulse."""
if self._consecutive_failures > 0:
logger.info(
"[pulse] Circuit-Breaker reset: failures=%d → 0, interval restored",
self._consecutive_failures,
)
self._consecutive_failures = 0
self._current_interval = None
def _increment_telemetry(self) -> None: def _increment_telemetry(self) -> None:
"""Increment the heartbeat_pulse telemetry counter. """Increment the heartbeat_pulse telemetry counter.
@@ -810,8 +1111,13 @@ class PulseController:
class DetectionTimer: class DetectionTimer:
"""Detects whether background agents are active. """Detects whether background agents are active.
Checks gateway_state.json for active_agents > 1. P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
Falls back to pgrep for 'hermes chat --profile' processes. P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
plugin_state are unavailable or return 0/1 (ambiguous).
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
subprocesses). Self-pid exclude is preserved.
Calls on_change callback when detection state changes. Calls on_change callback when detection state changes.
""" """
@@ -821,6 +1127,7 @@ class DetectionTimer:
gateway_state_path: str = "", gateway_state_path: str = "",
detection_interval: float = 10.0, detection_interval: float = 10.0,
on_change: Optional[Callable[[bool], None]] = None, on_change: Optional[Callable[[bool], None]] = None,
plugin_state_path: str = "",
): ):
"""Initialize DetectionTimer. """Initialize DetectionTimer.
@@ -828,6 +1135,8 @@ class DetectionTimer:
gateway_state_path: Path to gateway_state.json. gateway_state_path: Path to gateway_state.json.
detection_interval: Check interval in seconds (default 10). detection_interval: Check interval in seconds (default 10).
on_change: Callback(is_active) when detection state changes. on_change: Callback(is_active) when detection state changes.
plugin_state_path: P1-2: Path to plugin state file. Defaults to
~/.hermes/plugin_state/hermes_rocket_plugin.json.
""" """
if not gateway_state_path: if not gateway_state_path:
gateway_state_path = os.environ.get( gateway_state_path = os.environ.get(
@@ -835,6 +1144,12 @@ class DetectionTimer:
os.path.expanduser("~/.hermes/gateway_state.json"), os.path.expanduser("~/.hermes/gateway_state.json"),
) )
self._gateway_state_path = gateway_state_path self._gateway_state_path = gateway_state_path
# P1-2: Plugin-State-Datei für Gateway-interne Subagenten
if not plugin_state_path:
plugin_state_path = _get_plugin_state_path()
self._plugin_state_path = plugin_state_path
self._detection_interval = detection_interval self._detection_interval = detection_interval
self._on_change = on_change self._on_change = on_change
self._thread: Optional[threading.Thread] = None self._thread: Optional[threading.Thread] = None
@@ -870,56 +1185,94 @@ class DetectionTimer:
def check(self) -> bool: def check(self) -> bool:
"""Check if background agents are active. """Check if background agents are active.
pgrep is the PRIMARY signal — always executed, regardless of gateway_state. P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
gateway_state is SECONDARY — read only for diagnostic logging, never for decisions. P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
plugin_state are unavailable or return 0/1 (ambiguous).
pgrep pattern expanded from 'hermes chat --profile' to
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
Self-pid exclude is preserved.
Returns: Returns:
True if pgrep finds other hermes chat processes (self-excluded), True if background agents are detected, False otherwise.
False otherwise.
""" """
self._check_count += 1 self._check_count += 1
self._increment_telemetry() self._increment_telemetry()
result = False result = False
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
# ── PRIMARY: pgrep — ALWAYS run ──────────────────────────────────
try:
own_pid = os.getpid()
proc = subprocess.run(
["pgrep", "-f", "hermes chat --profile"],
capture_output=True,
text=True,
timeout=5,
)
# Parse PIDs and self-exclude
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
all_pids = [int(l) for l in raw_lines if l.isdigit()]
pids = [p for p in all_pids if p != own_pid]
pgrep_pids = len(pids)
result = pgrep_pids > 0
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
logger.debug("[detection] pgrep failed: %s", e)
# pgrep_pids stays -1 (error sentinel)
# ── SECONDARY: gateway_state — diagnostic only ────────────────────
gateway_active = 0 gateway_active = 0
gateway_used = False # True if gateway_state was the deciding signal
plugin_used = False # P1-2: True if plugin_state was the deciding signal
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
detection_source = "none" # P1-2: which signal decided
# ── PRIMARY: gateway_state.json ────────────────────────────────────
try: try:
if os.path.exists(self._gateway_state_path): if os.path.exists(self._gateway_state_path):
with open(self._gateway_state_path, 'r') as f: with open(self._gateway_state_path, 'r') as f:
state = json.load(f) state = json.load(f)
gateway_active = state.get("active_agents", 0) gateway_active = state.get("active_agents", 0)
if gateway_active > 1:
result = True
gateway_used = True
detection_source = "gateway"
except (json.JSONDecodeError, IOError, OSError) as e: except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[detection] gateway_state.json read failed: %s", e) logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fall through to plugin_state
# ── Log: both signals, result ───────────────────────────────────── # ── P1-2: SECONDARY: plugin_state.json ─────────────────────────────
if not gateway_used:
plugin_state = _read_plugin_state(self._plugin_state_path)
plugin_bg_tasks = plugin_state.get("background_tasks", 0)
if plugin_bg_tasks > 0:
result = True
plugin_used = True
detection_source = "plugin_state"
# ── TERTIARY: pgrep — run when neither gateway nor plugin decided ──
if not gateway_used and not plugin_used:
try:
own_pid = os.getpid()
# P1b: Expanded pattern catches subagents AND gateway subprocesses
proc = subprocess.run(
["pgrep", "-f", "hermes_cli|hermes chat"],
capture_output=True,
text=True,
timeout=5,
)
# Parse PIDs and self-exclude
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
all_pids = [int(l) for l in raw_lines if l.isdigit()]
pids = [p for p in all_pids if p != own_pid]
pgrep_pids = len(pids)
result = pgrep_pids > 0
if result:
detection_source = "pgrep"
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
logger.debug("[detection] pgrep failed: %s", e)
# pgrep_pids stays -1 (error sentinel)
# ── Log: all signals, result, source ───────────────────────────────
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error" pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a"
logger.info( logger.info(
"[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s", "[detection] check #%d: gateway_state=%d (primary=%s), "
self._check_count, pgrep_str, gateway_active, "plugin_state=%s (bg_tasks=%s), pgrep=%s, "
"result=%s, source=%s",
self._check_count, gateway_active,
"yes" if gateway_used else "no",
"yes" if plugin_used else "no",
plugin_str,
pgrep_str,
"active" if result else "inactive", "active" if result else "inactive",
detection_source,
) )
# P1-2: Set telemetry source
self._set_detection_source_telemetry(detection_source)
# Notify on change (P1-2: callback fires from check() itself) # Notify on change (P1-2: callback fires from check() itself)
if result != self._last_result and self._on_change is not None: if result != self._last_result and self._on_change is not None:
try: try:
@@ -967,3 +1320,21 @@ class DetectionTimer:
routing_telemetry.heartbeat_detection += 1 routing_telemetry.heartbeat_detection += 1
except Exception: except Exception:
pass pass
def _set_detection_source_telemetry(self, source: str) -> None:
"""P1-2: Set the heartbeat_detection_source telemetry field.
Args:
source: One of 'gateway', 'plugin_state', 'pgrep', 'none'.
"""
try:
from plugin.archivar.routing_telemetry import routing_telemetry
except ImportError:
try:
from archivar.routing_telemetry import routing_telemetry
except ImportError:
return
try:
routing_telemetry.heartbeat_detection_source = source
except Exception:
pass
+50
View File
@@ -48,6 +48,26 @@ _QUOTE_AUTHOR_BLOCK_RE = re.compile(
re.DOTALL | re.IGNORECASE, re.DOTALL | re.IGNORECASE,
) )
# ── FIX 5 (P1): ISSUE 2 — Archivar-Output-Marker ─────────────────────────
# Archivar-Phrasen, die auf eine Move-Request-Frage hindeuten.
# Bei Match wird die folgende Raumnamen-Erwähnung NICHT in routing_text
# aufgenommen, um Fehl-Routing durch Archivar-Output zu verhindern.
_ARCHIVAR_ARTIFACT_PHRASES = [
"Soll ich diese Nachricht nach",
"Soll ich den Auftrag dorthin",
"Möchtest du, dass ich",
"Soll ich das nach",
"Soll ich die Nachricht nach",
]
# Regex: erkennt Raumnamen nach Archivar-Phrasen
# Pattern: Phrase + optional whitespace + #?Raumname
_ARCHIVAR_ARTIFACT_RE = re.compile(
r'(?:' + '|'.join(re.escape(p) for p in _ARCHIVAR_ARTIFACT_PHRASES) + r')'
r'\s+#?[\w-]+',
re.IGNORECASE,
)
# Rocket.Chat attachment types that indicate a reply quote # Rocket.Chat attachment types that indicate a reply quote
_REPLY_ATTACHMENT_TYPES = frozenset({ _REPLY_ATTACHMENT_TYPES = frozenset({
'reply', 'reply',
@@ -113,6 +133,28 @@ def _strip_quote_blocks(text: str) -> str:
return text.strip() return text.strip()
def _strip_archivar_artifact(text: str) -> Tuple[str, bool]:
"""FIX 5 (P1): Entferne Archivar-Output-Marker aus dem Text.
Erkennt Phrasen wie 'Soll ich diese Nachricht nach #LAN-Dokumentation
kopieren?' und entfernt den Raumnamen-Teil, damit der Router nicht
fälschlich auf den Raum-Namen matcht.
Returns:
Tuple aus (bereinigtem Text, ob ein Artifact erkannt wurde).
"""
if not text:
return text, False
match = _ARCHIVAR_ARTIFACT_RE.search(text)
if match:
# Entferne den gesamten Match (Phrase + Raumnamen)
result = text[:match.start()] + text[match.end():]
result = result.strip()
return result, True
return text, False
def strip_reply_quote( def strip_reply_quote(
text: str, text: str,
attachments: Optional[list] = None, attachments: Optional[list] = None,
@@ -167,6 +209,14 @@ def strip_reply_quote(
if result != before_bq: if result != before_bq:
stripped = True stripped = True
# ── FIX 5 (P1): Archivar-Output-Marker ──────────────────────────────
# Läuft immer (nicht nur wenn !stripped), weil Archivar-Output
# auch in Nachrichten ohne Quote vorkommen kann.
before_artifact = result
result, artifact_detected = _strip_archivar_artifact(result)
if artifact_detected:
stripped = True
# Clean up: collapse multiple blank lines, strip # Clean up: collapse multiple blank lines, strip
result = re.sub(r'\n{3,}', '\n\n', result) result = re.sub(r'\n{3,}', '\n\n', result)
result = result.strip() result = result.strip()
+124 -16
View File
@@ -115,6 +115,62 @@ class RoomMapValidationError(Exception):
"""Raised when the room-map.json fails validation at startup.""" """Raised when the room-map.json fails validation at startup."""
# ── P1-1 Fix A: Save-Helfer (Modul-Level) ────────────────────────────────
def _acquire_flock(file_obj, timeout: int = 5) -> None:
"""Erwirbt einen exklusiven fcntl-Lock mit Timeout.
Verwendet non-blocking flock mit Retry-Loop (thread-safe,
kein signal). Maximal *timeout* Sekunden.
Args:
file_obj: Geöffnetes File-Objekt.
timeout: Maximale Wartezeit in Sekunden.
Raises:
TimeoutError: Wenn der Lock nicht innerhalb des Timeouts erworben werden kann.
"""
import time
deadline = time.monotonic() + timeout
while True:
try:
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
return
except BlockingIOError:
if time.monotonic() >= deadline:
raise TimeoutError(
f"Konnte File-Lock nicht innerhalb von {timeout}s erwerben"
)
time.sleep(0.05)
def _create_backup(path: Path) -> None:
"""Erstellt ein atomares Backup der existierenden Datei.
Kopiert die Datei nach '<path>.bak' via shutil.copy2 + os.replace
für atomaren Replace. No-op wenn die Quelldatei nicht existiert.
Args:
path: Pfad zur zu sichernden Datei.
"""
if not path.exists():
return
bak_path = Path(str(path) + ".bak")
try:
# Schreibe in temporäre Datei, dann atomic replace
tmp_bak = Path(str(bak_path) + ".tmp")
import shutil
shutil.copy2(path, tmp_bak)
os.replace(tmp_bak, bak_path)
logger.debug("Backup erstellt: %s", bak_path)
except OSError as e:
logger.warning(
"RoomMap.save: Konnte Backup nicht erstellen: %s", e
)
# ── RoomMap ─────────────────────────────────────────────────────────────── # ── RoomMap ───────────────────────────────────────────────────────────────
@@ -509,15 +565,20 @@ class RoomMap:
self._fact_store_created_at = new_map._fact_store_created_at # Thema 3 self._fact_store_created_at = new_map._fact_store_created_at # Thema 3
@staticmethod @staticmethod
def save(room_map: 'RoomMap', path: Optional[Path] = None) -> None: def save(room_map: 'RoomMap', path: Optional[Path] = None, force: bool = False) -> None:
"""Speichert die RoomMap in eine JSON-Datei mit File-Lock. """Speichert die RoomMap in eine JSON-Datei mit File-Lock.
Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele
Schreibzugriffe zu verhindern. Blockiert maximal 5 Sekunden. Schreibzugriffe zu verhindern. Blockiert maximal 5 Sekunden.
P1-1 Fix A: Refuse-Guard mit ID-Set-Differenz, TOCTOU-Schutz
durch Lock-VOR-Lesen, Backup-Mechanismus (.bak), und force-Parameter.
Args: Args:
room_map: Die zu speichernde RoomMap-Instanz room_map: Die zu speichernde RoomMap-Instanz
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH. path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
force: Wenn True, wird der Refuse-Guard umgangen (für administrative
Aufrufe wie Onboarding-Reset).
""" """
if path is None: if path is None:
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip() env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
@@ -525,10 +586,10 @@ class RoomMap:
path = Path(env_path) path = Path(env_path)
else: else:
path = Path(os.path.expanduser(DEFAULT_MAP_PATH)) path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
# Erstelle das Verzeichnis falls es nicht existiert # Erstelle das Verzeichnis falls es nicht existiert
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
# Konvertiere die Map in ein serialisierbares Dict # Konvertiere die Map in ein serialisierbares Dict
data = { data = {
"version": room_map._version, "version": room_map._version,
@@ -541,7 +602,7 @@ class RoomMap:
# Thema 3: fact_store_created_at nur persistieren wenn gesetzt # Thema 3: fact_store_created_at nur persistieren wenn gesetzt
if room_map._fact_store_created_at is not None: if room_map._fact_store_created_at is not None:
data["fact_store_created_at"] = room_map._fact_store_created_at data["fact_store_created_at"] = room_map._fact_store_created_at
for room_id, room_entry in room_map._rooms.items(): for room_id, room_entry in room_map._rooms.items():
data["rooms"][room_id] = { data["rooms"][room_id] = {
"name": room_entry.name, "name": room_entry.name,
@@ -555,22 +616,69 @@ class RoomMap:
"_stay_counts": room_entry._stay_counts, "_stay_counts": room_entry._stay_counts,
"_keyword_last_matched": room_entry._keyword_last_matched, "_keyword_last_matched": room_entry._keyword_last_matched,
} }
# Schreibe die Datei mit exklusivem File-Lock # P1-1 Fix A: TOCTOU-geschützter Refuse-Guard mit ID-Set-Differenz.
with open(path, "w", encoding="utf-8") as f: # Lock wird VOR dem Lesen erworben, nicht erst beim Schreiben.
try: # Öffne im read+write Modus für Lock + mögliches Schreiben.
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) file_exists = path.exists()
except BlockingIOError: if file_exists:
logger.warning(
"RoomMap.save: file locked, retrying with blocking lock (5s timeout)"
)
fcntl.flock(f.fileno(), fcntl.LOCK_EX) # blocking
try: try:
with open(path, "r+", encoding="utf-8") as f:
# Lock erwerben (max 5s Timeout via non-blocking + retry)
_acquire_flock(f, timeout=5)
# Unter Lock: Disk-Inhalt lesen
f.seek(0)
try:
disk_data = json.load(f)
except json.JSONDecodeError:
logger.warning(
"RoomMap.save: Disk-Inhalt ist kein gültiges JSON. "
"Überschreibe mit neuer Map."
)
disk_data = None
if disk_data is not None and not force:
disk_room_ids = set(disk_data.get("rooms", {}).keys())
mem_room_ids = set(room_map._rooms.keys())
# ID-Set-Differenz: Wenn Disk-IDs nicht Teilmenge
# von In-Memory-IDs sind → refuse
if not disk_room_ids.issubset(mem_room_ids):
missing_from_memory = disk_room_ids - mem_room_ids
logger.warning(
"RoomMap.save REFUSED: Disk-Räume %s fehlen in "
"In-Memory-Map (Disk: %d Räume, Memory: %d Räume). "
"Überschreiben verweigert um Datenverlust zu vermeiden. "
"Nutze force=True für administrative Überschreibung.",
sorted(missing_from_memory),
len(disk_room_ids), len(mem_room_ids),
)
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
return
# P1-1 Fix A: Backup vor dem Schreiben (.bak)
_create_backup(path)
# Schreibe neue Daten (seek+truncate+write unter Lock)
f.seek(0)
f.truncate()
json.dump(data, f, indent=2, ensure_ascii=False)
f.flush()
os.fsync(f.fileno())
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
except FileNotFoundError:
# Datei wurde zwischen exists()-Check und open() gelöscht —
# falle durch zu Neuanlage
file_exists = False
if not file_exists:
# Neue Datei anlegen (kein Lock nötig, da Datei nicht existiert)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False) json.dump(data, f, indent=2, ensure_ascii=False)
f.flush() f.flush()
os.fsync(f.fileno()) os.fsync(f.fileno())
finally:
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
# ── V8.2: A1 — Onboarding-Widerspruchsprüfung ────────────────────── # ── V8.2: A1 — Onboarding-Widerspruchsprüfung ──────────────────────
+52 -23
View File
@@ -1578,8 +1578,17 @@ class BidirectionalRouter:
# Try LLM — expects room ID directly or "STAY" # Try LLM — expects room ID directly or "STAY"
# Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request) # Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request)
async with self._llm_semaphore: # P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
# der äußere 20s-Timeout in adapter.py.
try:
await asyncio.wait_for(self._llm_semaphore.acquire(), timeout=18.0)
except asyncio.TimeoutError:
logger.warning("LLM semaphore acquire timed out (18s) — skipping LLM room lookup")
return None, False, True # LLM-Aufruf fehlgeschlagen
try:
llm_result = await self._classifier._llm_raw(prompt) llm_result = await self._classifier._llm_raw(prompt)
finally:
self._llm_semaphore.release()
if llm_result is None: if llm_result is None:
return None, False, True # LLM-Aufruf fehlgeschlagen return None, False, True # LLM-Aufruf fehlgeschlagen
@@ -1839,19 +1848,28 @@ class BidirectionalRouter:
old_topic=old_topic or "(kein altes Thema)", old_topic=old_topic or "(kein altes Thema)",
) )
# LLM-Aufruf mit 5s Timeout # LLM-Aufruf mit 18s Semaphore + 15s LLM-Call Timeout
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
# der äußere 20s-Timeout in adapter.py.
try: try:
async with self._llm_semaphore: await asyncio.wait_for(self._llm_semaphore.acquire(), timeout=18.0)
except asyncio.TimeoutError:
logger.warning("V7-4: LLM-Semaphore Timeout (18s) → Fallback: NEU")
return None
try:
try:
llm_result = await asyncio.wait_for( llm_result = await asyncio.wait_for(
self._classifier._llm_raw(prompt), self._classifier._llm_raw(prompt),
timeout=5.0, timeout=15.0,
) )
except asyncio.TimeoutError: except asyncio.TimeoutError:
logger.warning("V7-4: LLM-Check Timeout (5s) → Fallback: NEU") logger.warning("V7-4: LLM-Check Timeout (15s) → Fallback: NEU")
return None return None
except Exception as e: except Exception as e:
logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e) logger.warning("V7-4: LLM-Check fehlgeschlagen: %s → Fallback: NEU", e)
return None return None
finally:
self._llm_semaphore.release()
if llm_result is None: if llm_result is None:
logger.warning("V7-4: LLM-Check returned None → Fallback: NEU") logger.warning("V7-4: LLM-Check returned None → Fallback: NEU")
@@ -2189,24 +2207,35 @@ async def validate_sentence_marker(
v7_3_state=v7_3_state, v7_3_state=v7_3_state,
) )
# ── LLM-Aufruf mit 5s Timeout ───────────────────────────────────── # ── LLM-Aufruf mit 18s Semaphore + 15s LLM-Call Timeout ──────────
# P0-CRITICAL: Semaphore-Acquire mit 18s Timeout — muss KLEINER sein als
# der äußere 20s-Timeout in adapter.py.
try: try:
async with llm_semaphore: await asyncio.wait_for(llm_semaphore.acquire(), timeout=18.0)
llm_result = await asyncio.wait_for(
classifier._llm_raw(prompt),
timeout=5.0,
)
except asyncio.TimeoutError: except asyncio.TimeoutError:
logger.warning( logger.warning(
"A1b Stufe 4/5: LLM-Validierung Timeout (5s) → Fallback: unentscheidbar" "A1b Stufe 4/5: LLM-Semaphore Timeout (18s) → Fallback: unentscheidbar"
)
return None
except Exception as e:
logger.warning(
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
e,
) )
return None return None
try:
try:
llm_result = await asyncio.wait_for(
classifier._llm_raw(prompt),
timeout=15.0,
)
except asyncio.TimeoutError:
logger.warning(
"A1b Stufe 4/5: LLM-Call Timeout (15s) → Fallback: unentscheidbar"
)
return None
except Exception as e:
logger.warning(
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
e,
)
return None
finally:
llm_semaphore.release()
if llm_result is None: if llm_result is None:
logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar") logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar")
+2
View File
@@ -52,6 +52,8 @@ class RoutingTelemetry:
# Heartbeat-Pulsierung Telemetrie # Heartbeat-Pulsierung Telemetrie
self.heartbeat_pulse: int = 0 self.heartbeat_pulse: int = 0
self.heartbeat_detection: int = 0 self.heartbeat_detection: int = 0
# P1-2: Detection source tracking
self.heartbeat_detection_source: str = "none"
@staticmethod @staticmethod
def _read_feature_flag() -> bool: def _read_feature_flag() -> bool:
@@ -133,6 +133,7 @@ def _build_mock_adapter(room_map_path: str):
adapter._recent_auto_routes = {} adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {} adapter._explicit_switch_sticky = {}
adapter._clarify_state = {} adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {} # FIX 2 (P0): ISSUE 3
adapter._onboarding_state = {} adapter._onboarding_state = {}
adapter._room_map_summary = "" adapter._room_map_summary = ""
@@ -526,6 +526,7 @@ class TestFaktStoreOnboardingAdapter:
adapter._recent_auto_routes = {} adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {} adapter._explicit_switch_sticky = {}
adapter._clarify_state = {} adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {} # FIX 2 (P0): ISSUE 3
adapter._onboarding_state = {} adapter._onboarding_state = {}
adapter._room_map_summary = "" adapter._room_map_summary = ""
@@ -0,0 +1,332 @@
"""
P0 Fix: stay_here/stay_once dispatches original message to agent.
Root Cause (Rainer):
- Button 1 (confirm_move): dispatches original message correctly
- Button 2/3 (stay_here/stay_once): else-branch only logged + returned,
the original message from move_req['text'] was NEVER forwarded to the agent.
- Since the move_request_pending_guard blocks the dispatch on first arrival,
the message is ONLY available in move_req['text'].
- After self._pending_move_requests.pop(room_id), it's gone forever.
These tests are RED before the fix and GREEN after.
"""
from __future__ import annotations
import asyncio
import json
import os
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
# ── Helpers ────────────────────────────────────────────────────────────────
def _make_room_map_json(tmpdir: str) -> str:
"""Create a room-map.json with 2 rooms + catch-all."""
rooms = {
"room_a": {
"name": "#Raum-A",
"theme": "Raum A",
"keywords_100": ["thema-a"],
"keywords_context": [],
"catch_all": False,
},
"room_b": {
"name": "#Raum-B",
"theme": "Raum B",
"keywords_100": ["thema-b"],
"keywords_context": [],
"catch_all": False,
},
"room_catchall": {
"name": "#CatchAll",
"theme": "Catch-all room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
}
data = {
"version": 5,
"rooms": rooms,
"excluded_rooms": [],
"butler_mode": "cognitive",
"fact_store_path": str(Path(tmpdir) / "docs"),
}
map_path = Path(tmpdir) / "room-map.json"
with open(map_path, "w") as f:
json.dump(data, f)
return str(map_path)
def _build_mock_adapter(room_map_path: str):
"""Build a RocketChatAdapter with mocked external dependencies."""
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = room_map_path
os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/archivar_test_p0_stay_state.json"
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
# Clean leftover state
try:
os.remove("/tmp/archivar_test_p0_stay_state.json")
except FileNotFoundError:
pass
from plugin.adapter import RocketChatAdapter, RocketChatREST
from archivar.conversation_history import ConversationHistory
from archivar.multiroom_context import MultiRoomContextRing
from archivar.adapter_integration import ArchivarMessageHandler
from archivar.room_map import RoomMap
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter.config = MagicMock()
adapter.config.extra = {}
adapter.platform = "rocketchat"
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
adapter.user = os.getenv("ROCKETCHAT_USER", "")
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
adapter.rest = RocketChatREST(adapter.base_url)
adapter.ddp = None
adapter._auth_token = None
adapter._user_id = None
adapter._rooms = []
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = threading.Event()
adapter._room_info = {}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
adapter._conversation_history = ConversationHistory(max_size=10)
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
adapter.archivar = ArchivarMessageHandler(
send_callback=lambda *a, **kw: None,
button_send_callback=lambda *a, **kw: None,
conversation_history=adapter._conversation_history,
)
adapter.archivar._room_map = RoomMap.load(Path(room_map_path))
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {}
adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {}
adapter._onboarding_state = {}
adapter._room_map_summary = ""
# Mock the REST client
mock_rest = MagicMock(spec=RocketChatREST)
mock_rest.auth_token = "fake-token"
mock_rest.user_id = "fake-user-id"
mock_rest.post_message = MagicMock(return_value="msg_12345")
mock_rest.get_rooms = MagicMock(return_value=[
{"id": "room_a", "name": "Raum-A", "type": "c"},
{"id": "room_b", "name": "Raum-B", "type": "c"},
{"id": "room_catchall", "name": "CatchAll", "type": "c"},
])
adapter.rest = mock_rest
adapter._room_info = {
"room_a": {"name": "Raum-A", "type": "c"},
"room_b": {"name": "Raum-B", "type": "c"},
"room_catchall": {"name": "CatchAll", "type": "c"},
}
adapter._dispatch_agent = AsyncMock()
adapter.handle_message = AsyncMock()
asyncio.run(adapter.archivar.initialize())
# Mock gateway types
import plugin.adapter as _adapter_mod
_adapter_mod.MessageType = type('MessageType', (), {
'TEXT': 'text', 'BUTTON_CLICK': 'button_click',
'COMMAND': 'command',
})
_adapter_mod.RoutingCounter = type('RoutingCounter', (), {
'increment': lambda self, key: None,
})
_adapter_mod.routing_counter = _adapter_mod.RoutingCounter()
return adapter
# ── Test: stay_here dispatches original message ─────────────────────────────
class TestP0StayHereDispatchesOriginalMessage(unittest.TestCase):
"""P0: stay_here/stay_once must dispatch the original message to the agent.
Before the fix, Button 2/3 (stay_here/stay_once) only logged and returned
without dispatching the original message. The message was lost forever
because the move_request_pending_guard blocked the initial dispatch.
"""
@classmethod
def setUpClass(cls):
cls._tmpdir = tempfile.TemporaryDirectory()
room_map_path = _make_room_map_json(cls._tmpdir.name)
cls.adapter = _build_mock_adapter(room_map_path)
@classmethod
def tearDownClass(cls):
cls._tmpdir.cleanup()
def setUp(self):
# Clean state before each test
self.adapter._rooms_with_pending_questions.clear()
self.adapter._pending_move_requests.clear()
self.adapter._session_room_preferences.clear()
self.adapter._dispatch_agent.reset_mock()
self.adapter.handle_message.reset_mock()
def test_stay_here_dispatches_original_message(self):
"""Button 2 (stay_here) dispatches original message to agent in origin room."""
original_text = "Wie funktioniert der neue Trading-Algorithmus?"
# ── Setup: Move-Request in Raum A (came from Raum A itself) ─────
self.adapter._pending_move_requests["room_a"] = {
"text": original_text,
"origin_room": "room_a",
"target_room": "room_b",
"target_name": "Raum-B",
"username": "andreas",
"message_id": "msg_001",
}
# ── Act: Andreas klickt "2️⃣ Thema hier lassen" (stay_here) ──────
msg_obj = {
"_id": "msg_btn_001",
"rid": "room_a",
"msg": "MOVE_REQ:room_a::stay_here",
"u": {"username": "andreas", "_id": "user_andreas"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# ── Assert: _dispatch_agent was called with original text ────────
self.adapter._dispatch_agent.assert_called_once()
call_kwargs = self.adapter._dispatch_agent.call_args[1]
self.assertEqual(
call_kwargs["text"],
original_text,
"P0 BUG: _dispatch_agent should receive the original message text, "
f"got: {call_kwargs['text'][:80]!r}",
)
self.assertEqual(
call_kwargs["room_id"],
"room_a",
"P0 BUG: Agent should be dispatched in the ORIGIN room (room_a), "
f"got: {call_kwargs['room_id']}",
)
self.assertEqual(
call_kwargs["room_name"],
"Raum-A",
f"Expected room_name='Raum-A', got: {call_kwargs['room_name']}",
)
self.assertEqual(
call_kwargs["room_type"],
"c",
f"Expected room_type='c', got: {call_kwargs['room_type']}",
)
self.assertEqual(
call_kwargs["username"],
"andreas",
f"Expected username='andreas', got: {call_kwargs['username']}",
)
self.assertFalse(
call_kwargs["is_button_response"],
"is_button_response should be False for MOVE_REQ text messages "
"(they are excluded from button detection at line 1894)",
)
self.assertEqual(
call_kwargs["category"],
"work_order",
f"Expected category='work_order', got: {call_kwargs['category']}",
)
def test_stay_once_dispatches_original_message(self):
"""Button 3 (stay_once) dispatches original message to agent in origin room."""
original_text = "Kannst du mir die Doku zum API-Endpoint zeigen?"
# ── Setup: Move-Request in Raum A ───────────────────────────────
self.adapter._pending_move_requests["room_a"] = {
"text": original_text,
"origin_room": "room_a",
"target_room": "room_b",
"target_name": "Raum-B",
"username": "andreas",
"message_id": "msg_002",
}
# ── Act: Andreas klickt "3️⃣ Nur diesmal" (stay_once) ────────────
msg_obj = {
"_id": "msg_btn_002",
"rid": "room_a",
"msg": "MOVE_REQ:room_a::stay_once",
"u": {"username": "andreas", "_id": "user_andreas"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# ── Assert: _dispatch_agent was called with original text ────────
self.adapter._dispatch_agent.assert_called_once()
call_kwargs = self.adapter._dispatch_agent.call_args[1]
self.assertEqual(
call_kwargs["text"],
original_text,
"P0 BUG: stay_once should dispatch the original message text",
)
self.assertEqual(
call_kwargs["room_id"],
"room_a",
"P0 BUG: stay_once should dispatch in the ORIGIN room",
)
def test_stay_here_empty_text_skips_dispatch(self):
"""Empty move_req['text'] → no dispatch, only warning."""
# ── Setup: Move-Request with empty text ──────────────────────────
self.adapter._pending_move_requests["room_a"] = {
"text": "",
"origin_room": "room_a",
"target_room": "room_b",
"target_name": "Raum-B",
"username": "andreas",
"message_id": "msg_003",
}
# ── Act: Andreas klickt "2️⃣ Thema hier lassen" ──────────────────
msg_obj = {
"_id": "msg_btn_003",
"rid": "room_a",
"msg": "MOVE_REQ:room_a::stay_here",
"u": {"username": "andreas", "_id": "user_andreas"},
}
asyncio.run(self.adapter._process_incoming(msg_obj))
# ── Assert: _dispatch_agent was NOT called ───────────────────────
self.adapter._dispatch_agent.assert_not_called()
+792 -35
View File
@@ -20,6 +20,47 @@ import pytest
# Ensure the plugin package is importable # Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[2])) sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
# ═══════════════════════════════════════════════════════════════════════════
# B4: Autouse fixture — engine.shutdown() nach jedem Test
# Verhindert dass Honeymoon-/Coalesce-/Pulse-/Detection-Timer in
# nachfolgende Tests leaken (20-30% Failure-Rate).
# ═══════════════════════════════════════════════════════════════════════════
_ENGINE_REGISTRY: list = []
@pytest.fixture(autouse=True)
def _shutdown_presence_engines():
"""Track all PresenceEngine instances and call shutdown() after each test.
Monkey-patches PresenceEngine.__init__ to register every instance.
After the test (in finally), calls engine.shutdown() on all registered
instances — stops Honeymoon, Coalesce, PulseController, DetectionTimer.
"""
from plugin.archivar.presence_engine import PresenceEngine
_original_init = PresenceEngine.__init__
def _tracking_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
_ENGINE_REGISTRY.append(self)
PresenceEngine.__init__ = _tracking_init
_ENGINE_REGISTRY.clear()
try:
yield
finally:
PresenceEngine.__init__ = _original_init
for engine in _ENGINE_REGISTRY:
try:
engine.shutdown()
except Exception:
pass
_ENGINE_REGISTRY.clear()
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════
# Phase 1: Basis-PresenceEngine # Phase 1: Basis-PresenceEngine
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════
@@ -880,17 +921,17 @@ class TestPulseControllerLastSentPhase:
class TestDetectionTimerPgrepPrimary: class TestDetectionTimerPgrepPrimary:
"""Test 20: DetectionTimer — pgrep als Primärsignal, gateway_state nur diagnostisch.""" """Test 20: DetectionTimer — gateway_state PRIMARY, pgrep SECONDARY (P1b)."""
def test_pgrep_finds_other_agents(self): def test_pgrep_finds_other_agents(self):
"""pgrep findet andere hermes-Prozesse → result=True (gateway_state irrelevant).""" """gateway_state=1 (nicht >1) → pgrep-Fallback findet anderen Prozess → result=True."""
from plugin.archivar.presence_engine import DetectionTimer from plugin.archivar.presence_engine import DetectionTimer
import tempfile import tempfile
import json import json
own_pid = os.getpid() own_pid = os.getpid()
# gateway_state mit active_agents=1 (würde früher False liefern) # gateway_state mit active_agents=1 (nicht >1 → fällt auf pgrep zurück)
state = {"active_agents": 1, "profiles": ["default"]} state = {"active_agents": 1, "profiles": ["default"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f) json.dump(state, f)
@@ -910,50 +951,44 @@ class TestDetectionTimerPgrepPrimary:
detection_interval=0.1, detection_interval=0.1,
) )
result = dt.check() result = dt.check()
# pgrep findet anderen Prozess → True (gateway_state=1 wird ignoriert) # gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
assert result is True assert result is True
finally: finally:
os.unlink(state_path) os.unlink(state_path)
def test_pgrep_finds_no_other_agents(self): def test_gateway_state_primary_active(self):
"""pgrep findet nur eigenen Prozess → result=False (gateway_state irrelevant).""" """P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
from plugin.archivar.presence_engine import DetectionTimer from plugin.archivar.presence_engine import DetectionTimer
import tempfile import tempfile
import json import json
own_pid = os.getpid() # gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
# gateway_state mit active_agents=3 (würde früher True liefern)
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]} state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f) json.dump(state, f)
state_path = f.name state_path = f.name
try: try:
# Mock pgrep: findet nur eigenen Prozess # Mock pgrep: sollte NICHT aufgerufen werden
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n",
stderr="",
returncode=0,
)
dt = DetectionTimer( dt = DetectionTimer(
gateway_state_path=state_path, gateway_state_path=state_path,
detection_interval=0.1, detection_interval=0.1,
) )
result = dt.check() result = dt.check()
# pgrep findet nur eigenen Prozess → False (gateway_state=3 wird ignoriert) # gateway_state=3 > 1 → PRIMARY entscheidet → True
assert result is False assert result is True
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
mock_run.assert_not_called()
finally: finally:
os.unlink(state_path) os.unlink(state_path)
class TestDetectionTimerPgrepNoGatewayState: class TestDetectionTimerPgrepNoGatewayState:
"""Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json.""" """Test 21: DetectionTimer pgrep-Fallback funktioniert auch ohne gateway_state.json (P1b)."""
def test_pgrep_works_without_gateway_state(self): def test_pgrep_works_without_gateway_state(self):
"""Wenn gateway_state.json nicht existiert, pgrep ist trotzdem Primärsignal.""" """Wenn gateway_state.json nicht existiert, pgrep-Fallback greift."""
from plugin.archivar.presence_engine import DetectionTimer from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid() own_pid = os.getpid()
@@ -997,10 +1032,10 @@ class TestDetectionTimerPgrepNoGatewayState:
class TestDetectionTimerIntegration: class TestDetectionTimerIntegration:
"""Test 22: DetectionTimer start/stop + Callback (pgrep als Primärsignal).""" """Test 22: DetectionTimer start/stop + Callback (P1b: gateway_state PRIMARY, pgrep SECONDARY)."""
def test_detection_timer_start_stop(self): def test_detection_timer_start_stop(self):
"""DetectionTimer startet und stoppt korrekt, pgrep als Primärsignal.""" """DetectionTimer startet und stoppt korrekt, pgrep-Fallback bei fehlendem gateway_state."""
from plugin.archivar.presence_engine import DetectionTimer from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid() own_pid = os.getpid()
@@ -1009,7 +1044,7 @@ class TestDetectionTimerIntegration:
def on_detection_change(is_active): def on_detection_change(is_active):
callback_results.append(is_active) callback_results.append(is_active)
# Mock pgrep: findet anderen Prozess → True # Mock pgrep: findet anderen Prozess → True (gateway_state fehlt → Fallback)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock( mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n99999\n", stdout=f"{own_pid}\n99999\n",
@@ -1101,10 +1136,10 @@ class TestEdgeCaseReconnectRace:
class TestEdgeCaseOnAgentBusy: class TestEdgeCaseOnAgentBusy:
"""Test 31: on_agent_busy() — pausiert Pulse, setzt busy (rot).""" """Test 31: mark_busy_started() + pause() — pausiert Pulse, setzt busy (rot)."""
def test_on_agent_busy_pauses_pulse(self): def test_on_agent_busy_pauses_pulse(self):
"""on_agent_busy() pausiert den PulseController und setzt busy.""" """mark_busy_started() + pause() pausiert den PulseController und setzt busy."""
from plugin.archivar.presence_engine import PresenceEngine from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock() mock_rest = MagicMock()
@@ -1129,8 +1164,9 @@ class TestEdgeCaseOnAgentBusy:
time.sleep(0.1) time.sleep(0.1)
assert engine._pulse_controller.is_running() assert engine._pulse_controller.is_running()
# on_agent_busy: pausiert Pulse # A3: mark_busy_started + pause ersetzt on_agent_busy (toter Code entfernt)
engine.on_agent_busy(room_name="#Test") engine.mark_busy_started(room_name="#Test")
engine._pulse_controller.pause()
time.sleep(0.1) time.sleep(0.1)
# Pulse sollte pausiert sein # Pulse sollte pausiert sein
@@ -1163,8 +1199,9 @@ class TestEdgeCaseOnAgentBusy:
engine._pulse_controller.start() engine._pulse_controller.start()
engine._background_tasks = 3 engine._background_tasks = 3
# on_agent_busy # A3: mark_busy_started + pause ersetzt on_agent_busy
engine.on_agent_busy(room_name="#Test") engine.mark_busy_started(room_name="#Test")
engine._pulse_controller.pause()
time.sleep(0.1) time.sleep(0.1)
# Task beendet → decrement + update # Task beendet → decrement + update
@@ -1179,10 +1216,10 @@ class TestEdgeCaseOnAgentBusy:
class TestEdgeCaseOnMessageReceived: class TestEdgeCaseOnMessageReceived:
"""Test 32: on_message_received() — wie on_agent_busy, pausiert Pulse.""" """Test 32: mark_busy_started() + pause() — wie on_agent_busy, pausiert Pulse."""
def test_on_message_received_pauses_pulse(self): def test_on_message_received_pauses_pulse(self):
"""on_message_received() verhält sich wie on_agent_busy().""" """mark_busy_started() + pause() verhält sich wie on_agent_busy()."""
from plugin.archivar.presence_engine import PresenceEngine from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock() mock_rest = MagicMock()
@@ -1203,8 +1240,9 @@ class TestEdgeCaseOnMessageReceived:
time.sleep(0.1) time.sleep(0.1)
assert engine._pulse_controller.is_running() assert engine._pulse_controller.is_running()
# on_message_received → wie on_agent_busy # A3: mark_busy_started + pause ersetzt on_message_received
engine.on_message_received(room_name="#Test") engine.mark_busy_started(room_name="#Test")
engine._pulse_controller.pause()
time.sleep(0.1) time.sleep(0.1)
assert not engine._pulse_controller.is_running() or engine._pulse_controller._paused.is_set() assert not engine._pulse_controller.is_running() or engine._pulse_controller._paused.is_set()
@@ -1264,7 +1302,7 @@ class TestP0LiveVerdrahtung:
assert not engine._pulse_controller.is_running() assert not engine._pulse_controller.is_running()
def test_detection_timer_starts_when_enabled(self): def test_detection_timer_starts_when_enabled(self):
"""P0-5: DetectionTimer startet automatisch wenn enabled=True.""" """P1b: DetectionTimer startet NICHT automatisch — muss via start_detection() gestartet werden."""
from plugin.archivar.presence_engine import PresenceEngine from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock() mock_rest = MagicMock()
@@ -1273,7 +1311,11 @@ class TestP0LiveVerdrahtung:
engine = PresenceEngine(rest=mock_rest, enabled=True) engine = PresenceEngine(rest=mock_rest, enabled=True)
# DetectionTimer läuft (wurde in __init__ gestartet) # P1b: DetectionTimer läuft NICHT nach __init__ (startet erst via start_detection())
assert not engine._detection_timer._running.is_set()
# start_detection() startet ihn
engine.start_detection()
assert engine._detection_timer._running.is_set() assert engine._detection_timer._running.is_set()
def test_detection_timer_not_started_when_disabled(self): def test_detection_timer_not_started_when_disabled(self):
@@ -1536,3 +1578,718 @@ class TestPresenceClarificationPending:
f"Klärung sollte away setzen (nicht busy), bekam: {data['status']}" f"Klärung sollte away setzen (nicht busy), bekam: {data['status']}"
) )
assert "Klärung" in data["message"] assert "Klärung" in data["message"]
# ═══════════════════════════════════════════════════════════════════════════
# P1a: Honeymoon-Timer — busy minimum 1s sichtbar
# ═══════════════════════════════════════════════════════════════════════════
class TestHoneymoonBusyMinVisible:
"""P1a: Honeymoon-Timer — busy Status mindestens 1s sichtbar."""
def test_busy_min_visible_duration(self):
"""mark_busy_started → mark_busy_done innerhalb 50ms → pending_status bleibt busy bis Timer feuert."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
# Start busy
engine.mark_busy_started(room_name="#Test")
assert engine._active_tasks == 1
assert engine._busy_counter == 1
assert engine._busy_honeymoon_timer is not None
# Done sofort (50ms später — Honeymoon noch nicht abgelaufen)
time.sleep(0.05)
engine.mark_busy_done()
assert engine._active_tasks == 0
assert engine._busy_counter == 0
# Honeymoon-Timer läuft noch → pending_status sollte busy sein
# (update_presence wurde NICHT aufgerufen, weil Honeymoon noch läuft)
# Warte auf Honeymoon-Expiry
time.sleep(1.1) # MIN_BUSY_VISIBLE_S + margin
# Jetzt sollte der Timer gefeuert haben → online
# Flush um sicherzustellen
engine._flush_presence()
# Prüfe: REST-Calls in Reihenfolge: erst busy, dann online
calls = mock_rest._request.call_args_list
assert len(calls) >= 2, f"Erwarte mind. 2 REST-Calls (busy + online), bekam {len(calls)}"
# Erster Call: busy
assert calls[0][1]["data"]["status"] == "busy"
# Letzter Call: online
assert calls[-1][1]["data"]["status"] == "online"
def test_busy_done_after_honeymoon(self):
"""Nach 1.05s ist Honeymoon abgelaufen → mark_busy_done setzt sofort online."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
engine.mark_busy_started(room_name="#Test")
assert engine._active_tasks == 1
# Warte bis Honeymoon abgelaufen ist
time.sleep(1.1)
engine.mark_busy_done()
# Honeymoon bereits abgelaufen → update_presence wurde aufgerufen
engine._flush_presence()
calls = mock_rest._request.call_args_list
assert len(calls) >= 2
assert calls[0][1]["data"]["status"] == "busy"
assert calls[-1][1]["data"]["status"] == "online"
def test_double_busy_no_double_honeymoon(self):
"""Zweiter mark_busy_started während Honeymoon läuft → nur EIN Timer aktiv."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
# Erster busy
engine.mark_busy_started(room_name="#Test")
first_timer = engine._busy_honeymoon_timer
assert first_timer is not None
assert engine._busy_counter == 1
# Zweiter busy (multi-turn) — kein neuer Timer
engine.mark_busy_started(room_name="#Test2")
assert engine._busy_honeymoon_timer is first_timer # gleicher Timer
assert engine._busy_counter == 2
# Erster done → counter=1, Timer läuft weiter
engine.mark_busy_done()
assert engine._busy_counter == 1
assert engine._active_tasks == 1
# Zweiter done → counter=0, Honeymoon noch nicht abgelaufen
engine.mark_busy_done()
assert engine._busy_counter == 0
assert engine._active_tasks == 0
# Warte auf Honeymoon
time.sleep(1.1)
engine._flush_presence()
calls = mock_rest._request.call_args_list
assert len(calls) >= 2
assert calls[0][1]["data"]["status"] == "busy"
assert calls[-1][1]["data"]["status"] == "online"
def test_active_tasks_balanced(self):
"""100x mark_busy_started/mark_busy_done → _active_tasks == 0, _busy_counter == 0."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
for _ in range(100):
engine.mark_busy_started(room_name="#Test")
assert engine._active_tasks == 100
assert engine._busy_counter == 100
for _ in range(100):
engine.mark_busy_done()
assert engine._active_tasks == 0
assert engine._busy_counter == 0
def test_exception_during_dispatch_releases_busy(self):
"""Exception während Dispatch → mark_busy_done balanced Counter, Honeymoon läuft."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
try:
engine.mark_busy_started(room_name="#Test")
raise RuntimeError("simulated dispatch failure")
except RuntimeError:
engine.mark_busy_done()
# Counter balanced
assert engine._active_tasks == 0
assert engine._busy_counter == 0
# Honeymoon-Timer läuft noch (oder ist schon abgelaufen)
# Wichtig: kein Crash, kein hängender Counter
time.sleep(1.1)
engine._flush_presence()
calls = mock_rest._request.call_args_list
assert len(calls) >= 2
assert calls[0][1]["data"]["status"] == "busy"
assert calls[-1][1]["data"]["status"] == "online"
def test_status_send_order_busy_then_online(self):
"""Reihenfolge der REST-Calls: erst busy, dann online."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
mock_rest._request = MagicMock(return_value={"success": True})
engine = PresenceEngine(rest=mock_rest, enabled=True)
engine.mark_busy_started(room_name="#Test")
time.sleep(0.05)
engine.mark_busy_done()
# Warte auf Honeymoon
time.sleep(1.1)
engine._flush_presence()
calls = mock_rest._request.call_args_list
statuses = [c[1]["data"]["status"] for c in calls]
# Erster Status muss busy sein
assert "busy" in statuses, f"Status-Sequenz: {statuses}"
# busy kommt vor online
busy_idx = statuses.index("busy")
online_idx = statuses.index("online") if "online" in statuses else -1
if online_idx >= 0:
assert busy_idx < online_idx, (
f"busy (idx={busy_idx}) muss vor online (idx={online_idx}) kommen: {statuses}"
)
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Plugin-State-Datei — Pfad, atomares Lesen/Schreiben
# ═══════════════════════════════════════════════════════════════════════════
class TestPluginStateFile:
"""P1-2: Plugin-State-Datei — Pfad, atomares Lesen/Schreiben."""
def test_get_plugin_state_path_default(self):
"""_get_plugin_state_path() liefert ~/.hermes/plugin_state/hermes_rocket_plugin.json."""
from plugin.archivar.presence_engine import _get_plugin_state_path
path = _get_plugin_state_path()
assert path.endswith("hermes_rocket_plugin.json")
assert ".hermes" in path
assert "plugin_state" in path
def test_read_plugin_state_missing_file(self):
"""_read_plugin_state() bei fehlender Datei → {}."""
from plugin.archivar.presence_engine import _read_plugin_state
result = _read_plugin_state("/tmp/nonexistent_plugin_state.json")
assert result == {}
def test_read_plugin_state_valid(self, tmp_path):
"""_read_plugin_state() liest gültige JSON-Datei."""
from plugin.archivar.presence_engine import _read_plugin_state
import json
p = tmp_path / "state.json"
p.write_text(json.dumps({"background_tasks": 3, "last_update_iso": "2026-01-01T00:00:00", "source": "plugin_internal", "schema_version": 1}))
result = _read_plugin_state(str(p))
assert result["background_tasks"] == 3
assert result["source"] == "plugin_internal"
def test_read_plugin_state_corrupt_json(self, tmp_path):
"""_read_plugin_state() bei korrupter JSON → {} (kein Crash)."""
from plugin.archivar.presence_engine import _read_plugin_state
p = tmp_path / "state.json"
p.write_text("{invalid json")
result = _read_plugin_state(str(p))
assert result == {}
def test_write_plugin_state_atomic(self, tmp_path):
"""_write_plugin_state() schreibt atomar (temp + rename)."""
from plugin.archivar.presence_engine import _write_plugin_state, _read_plugin_state
import json
p = tmp_path / "state.json"
data = {"background_tasks": 5, "last_update_iso": "2026-01-01T00:00:00", "source": "plugin_internal", "schema_version": 1}
_write_plugin_state(str(p), data)
# Datei existiert
assert p.exists()
# Inhalt korrekt
result = _read_plugin_state(str(p))
assert result["background_tasks"] == 5
# Keine .tmp-Datei liegt rum
assert not list(tmp_path.glob("*.tmp"))
# ═══════════════════════════════════════════════════════════════════════════
# E2: Concurrency-Test für _write_plugin_state
# ═══════════════════════════════════════════════════════════════════════════
class TestWritePluginStateConcurrency:
"""E2: Zwei Threads parallel schreiben → kein korruptes JSON, keine halbe Datei."""
def test_concurrent_writes_produce_valid_json(self, tmp_path):
"""Zwei Threads schreiben parallel — finale Datei ist gültiges JSON."""
from plugin.archivar.presence_engine import _write_plugin_state, _read_plugin_state
import json
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
# Seed the file so both threads have something to overwrite
_write_plugin_state(state_path, {
"background_tasks": 0,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
errors = []
last_written: list = [None] # mutable container for the last-written data
def writer(thread_id: int, n: int):
try:
for i in range(n):
data = {
"background_tasks": thread_id * 1000 + i,
"last_update_iso": f"2026-07-26T{thread_id:02d}:{i:02d}:00",
"source": f"thread_{thread_id}",
"schema_version": 1,
}
_write_plugin_state(state_path, data)
last_written[0] = data
except Exception as e:
errors.append(f"thread_{thread_id}: {e}")
N = 50
t1 = threading.Thread(target=writer, args=(1, N))
t2 = threading.Thread(target=writer, args=(2, N))
t1.start()
t2.start()
t1.join()
t2.join()
assert len(errors) == 0, f"Thread errors: {errors}"
# Read back — must be valid JSON, no JSONDecodeError
result = _read_plugin_state(state_path)
assert isinstance(result, dict), f"Expected dict, got {type(result)}"
assert "background_tasks" in result
assert "source" in result
assert "schema_version" in result
# The file must contain complete, valid JSON — _read_plugin_state
# already verified that (returns {} on corrupt JSON). If we got a
# dict with keys, the file is intact.
assert result["schema_version"] == 1
# Verify no .tmp leftovers (atomic rename worked)
assert not list(tmp_path.glob("*.tmp")), "Temp files left behind"
def test_concurrent_writes_no_truncated_file(self, tmp_path):
"""Parallele writes erzeugen keine trunkierte Datei (kein halbes JSON)."""
from plugin.archivar.presence_engine import _write_plugin_state
import json
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
_write_plugin_state(state_path, {
"background_tasks": 0,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
def writer(thread_id: int, n: int):
for i in range(n):
data = {
"background_tasks": thread_id * 1000 + i,
"last_update_iso": f"2026-07-26T{thread_id:02d}:{i:02d}:00",
"source": f"thread_{thread_id}",
"schema_version": 1,
}
_write_plugin_state(state_path, data)
N = 100
t1 = threading.Thread(target=writer, args=(1, N))
t2 = threading.Thread(target=writer, args=(2, N))
t1.start()
t2.start()
t1.join()
t2.join()
# Read raw bytes — must be parseable JSON
with open(state_path, "rb") as f:
raw = f.read()
# Must not be empty
assert len(raw) > 0, "File is empty after concurrent writes"
# Must parse as JSON (no JSONDecodeError)
try:
parsed = json.loads(raw)
except json.JSONDecodeError as e:
pytest.fail(f"Corrupt JSON after concurrent writes: {e}")
assert isinstance(parsed, dict)
assert "background_tasks" in parsed
assert "source" in parsed
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Plugin-State Persistenz in increment/decrement_background_tasks
# ═══════════════════════════════════════════════════════════════════════════
class TestPluginStatePersistence:
"""P1-2: increment/decrement_background_tasks persistieren in Plugin-State-Datei."""
def test_increment_writes_plugin_state(self, tmp_path):
"""increment_background_tasks() schreibt background_tasks in Plugin-State-Datei."""
from plugin.archivar.presence_engine import PresenceEngine, _read_plugin_state
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
engine = PresenceEngine(rest=mock_rest, enabled=True)
# Override path for test
engine._plugin_state_path = state_path
count = engine.increment_background_tasks()
assert count == 1
# Read back from file
state = _read_plugin_state(state_path)
assert state["background_tasks"] == 1
assert state["source"] == "plugin_internal"
assert "last_update_iso" in state
def test_decrement_writes_plugin_state(self, tmp_path):
"""decrement_background_tasks() schreibt reduzierten Wert in Plugin-State-Datei."""
from plugin.archivar.presence_engine import PresenceEngine, _read_plugin_state
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
engine = PresenceEngine(rest=mock_rest, enabled=True)
engine._plugin_state_path = state_path
engine.increment_background_tasks()
engine.increment_background_tasks()
count = engine.decrement_background_tasks()
assert count == 1
state = _read_plugin_state(state_path)
assert state["background_tasks"] == 1
def test_decrement_to_zero_writes_zero(self, tmp_path):
"""decrement auf 0 schreibt background_tasks=0 in Datei."""
from plugin.archivar.presence_engine import PresenceEngine, _read_plugin_state
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
engine = PresenceEngine(rest=mock_rest, enabled=True)
engine._plugin_state_path = state_path
engine.increment_background_tasks()
count = engine.decrement_background_tasks()
assert count == 0
state = _read_plugin_state(state_path)
assert state["background_tasks"] == 0
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: DetectionTimer erkennt Plugin-State-Datei
# ═══════════════════════════════════════════════════════════════════════════
class TestDetectionTimerPluginState:
"""P1-2: DetectionTimer erkennt Plugin-State-Datei."""
def test_plugin_state_background_tasks_positive_detected(self, tmp_path):
"""Plugin-State mit background_tasks=3 → check() returns True."""
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
_write_plugin_state(state_path, {
"background_tasks": 3,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path=state_path,
)
result = dt.check()
assert result is True
def test_plugin_state_background_tasks_zero_not_detected(self, tmp_path):
"""Plugin-State mit background_tasks=0 → check() fällt auf pgrep zurück."""
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
_write_plugin_state(state_path, {
"background_tasks": 0,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
own_pid = os.getpid()
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n",
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path=state_path,
)
result = dt.check()
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
assert result is False
def test_plugin_state_missing_file_no_error(self):
"""Plugin-State-Datei fehlt → kein Fehler, fällt zurück auf gateway_state+pgrep."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n99999\n",
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path="/tmp/nonexistent_plugin_state.json",
)
result = dt.check()
# pgrep findet anderen Prozess → True
assert result is True
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
"""Korrupte Plugin-State-Datei → kein Crash, graceful fallback."""
from plugin.archivar.presence_engine import DetectionTimer
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
# Schreibe korruptes JSON
with open(state_path, 'w') as f:
f.write("{invalid json {{{")
own_pid = os.getpid()
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n99999\n",
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path=state_path,
)
result = dt.check()
# Sollte nicht crashen, pgrep findet anderen Prozess → True
assert result is True
def test_plugin_state_priority_after_gateway(self, tmp_path):
"""Plugin-State wird NACH gateway_state geprüft (gateway hat Vorrang)."""
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
import tempfile, json
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
gw_path = f.name
try:
# Plugin-State mit background_tasks=0 (würde allein nicht reichen)
plugin_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(plugin_path), exist_ok=True)
_write_plugin_state(plugin_path, {
"background_tasks": 0,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
dt = DetectionTimer(
gateway_state_path=gw_path,
detection_interval=0.1,
plugin_state_path=plugin_path,
)
result = dt.check()
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
assert result is True
mock_run.assert_not_called()
finally:
os.unlink(gw_path)
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Telemetrie — heartbeat_detection_source Feld
# ═══════════════════════════════════════════════════════════════════════════
class TestDetectionSourceTelemetry:
"""P1-2: heartbeat_detection_source Telemetrie-Feld."""
def test_detection_source_set_on_check_plugin_state(self, tmp_path):
"""Nach check() mit plugin_state → source='plugin_state'."""
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
from plugin.archivar.routing_telemetry import routing_telemetry
# Reset
routing_telemetry.heartbeat_detection_source = "none"
state_path = str(tmp_path / "hermes_rocket_plugin.json")
os.makedirs(os.path.dirname(state_path), exist_ok=True)
_write_plugin_state(state_path, {
"background_tasks": 3,
"last_update_iso": "2026-01-01T00:00:00",
"source": "plugin_internal",
"schema_version": 1,
})
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path=state_path,
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
def test_detection_source_none_when_inactive(self):
"""Wenn nichts gefunden → source='none'."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_detection_source = "none"
own_pid = os.getpid()
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n",
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path="/tmp/nonexistent_plugin_state.json",
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "none"
def test_detection_source_pgrep(self):
"""pgrep findet Agenten → source='pgrep'."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_detection_source = "none"
own_pid = os.getpid()
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n99999\n",
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path="/tmp/nonexistent_plugin_state.json",
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "pgrep"
def test_detection_source_gateway(self, tmp_path):
"""gateway_state entscheidet → source='gateway'."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.routing_telemetry import routing_telemetry
import tempfile, json
routing_telemetry.heartbeat_detection_source = "none"
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
gw_path = f.name
try:
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
dt = DetectionTimer(
gateway_state_path=gw_path,
detection_interval=0.1,
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "gateway"
mock_run.assert_not_called()
finally:
os.unlink(gw_path)
# ═══════════════════════════════════════════════════════════════════════════
# P1-2: Integration — PresenceEngine übergibt plugin_state_path an DetectionTimer
# ═══════════════════════════════════════════════════════════════════════════
class TestPresenceEnginePluginStateIntegration:
"""P1-2: PresenceEngine → DetectionTimer plugin_state_path Integration."""
def test_detection_timer_has_plugin_state_path(self):
"""DetectionTimer bekommt plugin_state_path von PresenceEngine."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
mock_rest.auth_token = "token"
mock_rest.user_id = "user123"
engine = PresenceEngine(rest=mock_rest, enabled=True)
assert engine._detection_timer._plugin_state_path is not None
assert "plugin_state" in engine._detection_timer._plugin_state_path
assert "hermes_rocket_plugin.json" in engine._detection_timer._plugin_state_path
@@ -226,6 +226,10 @@ class TestBuildHelpText:
registry.register("sethome", dummy, "Setzt Heimatraum", category="Raum") registry.register("sethome", dummy, "Setzt Heimatraum", category="Raum")
text = build_help_text(registry) text = build_help_text(registry)
assert "Core-Befehle" in text
assert "continue" in text
assert "/reset" in text
assert "/compress" in text
assert "::hilfe" in text assert "::hilfe" in text
assert "::status" in text assert "::status" in text
assert "::sethome" in text assert "::sethome" in text
@@ -254,8 +258,65 @@ class TestBuildHelpText:
registry = InlineCommandRegistry() registry = InlineCommandRegistry()
text = build_help_text(registry) text = build_help_text(registry)
assert "Rocket.Chat Plugin" in text assert "Rocket.Chat Plugin" in text
assert "Core-Befehle" in text
assert "continue" in text
assert "Natürliche Sprach-Befehle" in text assert "Natürliche Sprach-Befehle" in text
def test_build_help_text_length_limit(self):
"""P1-Fix: Hilfe-Text darf 4000 Zeichen nicht überschreiten."""
from archivar.inline_commands import (
InlineCommandRegistry,
build_help_text,
)
registry = InlineCommandRegistry()
async def dummy(room_id, args):
return "ok"
# Registriere viele Befehle um einen langen Text zu erzeugen
all_cmds = [
("sethome", "Standard"), ("reset", "Standard"), ("busy", "Standard"),
("allowalways", "Standard"), ("commands", "Info"), ("restart", "Gateway"),
("update", "Gateway"),
("setfakt", "Konfiguration"), ("hilfe", "Hilfe"), ("status", "Hilfe"),
("multiroom", "Plugin"), ("onboarding", "Plugin"), ("curate", "Plugin"),
]
for name, cat in all_cmds:
registry.register(name, dummy, f"Help for {name}", category=cat)
# Erzeuge eine große room_map_summary (simuliert 5 Räume)
big_summary = "Rocket.Chat Raum-Map:\n"
for i in range(5):
big_summary += (
f" {i+1}. #Raum{i+1} (room_id_{i+1}...) — "
f"Thema: Dies ist ein sehr langer Beschreibungstext für Raum {i+1} "
f"um die Länge der Hilfeseite künstlich zu erhöhen\n"
)
text = build_help_text(registry, room_map_summary=big_summary)
assert len(text) <= 4000, (
f"Hilfe-Text ist {len(text)} Zeichen lang, "
f"maximal erlaubt sind 4000"
)
def test_build_help_text_keeps_summary_when_short(self):
"""P1-Fix: Kurze room_map_summary bleibt erhalten."""
from archivar.inline_commands import (
InlineCommandRegistry,
build_help_text,
)
registry = InlineCommandRegistry()
async def dummy(room_id, args):
return "ok"
registry.register("hilfe", dummy, "Zeigt Hilfeseite", category="Hilfe")
short_summary = "Raum-Map: 1 Raum"
text = build_help_text(registry, room_map_summary=short_summary)
assert "Raum-Map: 1 Raum" in text
assert len(text) <= 4000
class TestBuildStatusText: class TestBuildStatusText:
"""Tests für build_status_text.""" """Tests für build_status_text."""
@@ -25,6 +25,7 @@ from plugin.archivar.reply_quote_stripper import (
_strip_rc_reply_link, _strip_rc_reply_link,
_strip_blockquotes, _strip_blockquotes,
_strip_quote_blocks, _strip_quote_blocks,
_strip_archivar_artifact,
) )
@@ -383,3 +384,53 @@ class TestKeywordMatcherIntegration:
assert match_keyword("dokumentiere", routing_text) assert match_keyword("dokumentiere", routing_text)
# 'archivar' war im Quote → kein Match # 'archivar' war im Quote → kein Match
assert not match_keyword("archivar", routing_text) assert not match_keyword("archivar", routing_text)
# ═══════════════════════════════════════════════════════════════════════════
# FIX 5 (P1): ISSUE 2 — Archivar-Output-Marker (_strip_archivar_artifact)
# ═══════════════════════════════════════════════════════════════════════════
class TestArchivarArtifactStripping:
"""Tests für _strip_archivar_artifact() — verhindert Fehl-Routing
durch Archivar-Output-Marker in Nachrichten."""
def test_archivar_phrase_detected_and_stripped(self):
"""Archivar-Phrase 'Soll ich diese Nachricht nach #RAUM kopieren?'
→ Raumnamen-Teil wird entfernt, 'LAN-Dokumentation' NICHT in routing_text."""
text = "Soll ich diese Nachricht nach #LAN-Dokumentation kopieren?"
result, artifact_detected = _strip_archivar_artifact(text)
assert artifact_detected is True
assert "LAN-Dokumentation" not in result, (
f"Raumname 'LAN-Dokumentation' sollte gestrippt sein, "
f"ist aber in: '{result}'"
)
# Der Rest nach dem Strip sollte nur noch "kopieren?" sein
assert "kopieren" in result.lower()
def test_normal_message_not_affected(self):
"""Normale Nachricht ohne Archivar-Phrase → 'LAN-Dokumentation' BLEIBT erhalten."""
text = "Ich habe eine Frage zur LAN-Dokumentation"
result, artifact_detected = _strip_archivar_artifact(text)
assert artifact_detected is False
assert result == text, (
f"Normale Nachricht sollte unverändert bleiben, ist aber: '{result}'"
)
assert "LAN-Dokumentation" in result
def test_mixed_quote_and_content(self):
"""Archivar-Phrase + normaler Content → Raumnamen-Teil entfernt,
aber 'Telemetrie' bleibt in routing_text."""
text = (
"Soll ich diese Nachricht nach #LAN-Dokumentation kopieren?\n"
"Analysiere bitte auch die Telemetrie"
)
result, artifact_detected = _strip_archivar_artifact(text)
assert artifact_detected is True
assert "LAN-Dokumentation" not in result, (
f"Raumname sollte gestrippt sein, ist aber in: '{result}'"
)
assert "Telemetrie" in result, (
f"'Telemetrie' sollte erhalten bleiben, ist aber nicht in: '{result}'"
)
assert "Analysiere" in result
@@ -327,6 +327,9 @@ class TestRenderReviewRoomAddNew:
def test_renders_empty_available(self): def test_renders_empty_available(self):
text, attachments = render_review_room_add_new([], _mock_build_buttons) text, attachments = render_review_room_add_new([], _mock_build_buttons)
assert "Keine weiteren Räume verfügbar" in text assert "Keine weiteren Räume verfügbar" in text
# P0-4: Zurück-Button muss auch bei leerer Liste gerendert werden
assert len(attachments) > 0, "Leere Liste muss Zurück-Button rendern"
assert "Zurück" in str(attachments)
# ── dispatch_review_button ────────────────────────────────────────────────── # ── dispatch_review_button ──────────────────────────────────────────────────
+208
View File
@@ -516,3 +516,211 @@ class TestLLMLookup:
result = room_map.find_room_by_keywords("Wie funktioniert das BAT Trading-Signal?") result = room_map.find_room_by_keywords("Wie funktioniert das BAT Trading-Signal?")
assert result is not None assert result is not None
assert result.name == "#BAT" assert result.name == "#BAT"
# ── P1-Fix: RoomMap.save Refuse-Guard ──────────────────────────────────────
class TestRoomMapSaveRefuseGuard:
"""P1-Fix: RoomMap.save verweigert Schreiben wenn Disk > In-Memory."""
def test_save_refuses_when_disk_has_more_rooms(self):
"""save() verweigert wenn Disk mehr Räume hat als In-Memory."""
import tempfile
from pathlib import Path
# Erstelle eine Disk-Datei mit 3 Räumen
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r3": {"name": "#Room3", "theme": "t3", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# Erstelle eine In-Memory-Map mit nur 1 Raum (kleiner als Disk)
small_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
small_map = RoomMap._from_dict(small_data)
# Versuche zu speichern — sollte verweigert werden
RoomMap.save(small_map, path=map_path)
# Disk sollte unverändert sein (3 Räume)
with open(map_path, "r") as f:
saved_data = json.load(f)
assert len(saved_data["rooms"]) == 3, (
f"Disk sollte 3 Räume haben, hat aber {len(saved_data['rooms'])}"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_memory_has_more_rooms(self):
"""save() erlaubt Schreiben wenn In-Memory mehr Räume hat als Disk."""
import tempfile
from pathlib import Path
# Erstelle eine Disk-Datei mit 1 Raum
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# Erstelle eine In-Memory-Map mit 3 Räumen (größer als Disk)
big_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r3": {"name": "#Room3", "theme": "t3", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
big_map = RoomMap._from_dict(big_data)
# Speichern — sollte erlaubt sein
RoomMap.save(big_map, path=map_path)
# Disk sollte jetzt 3 Räume haben
with open(map_path, "r") as f:
saved_data = json.load(f)
assert len(saved_data["rooms"]) == 3, (
f"Disk sollte 3 Räume haben, hat aber {len(saved_data['rooms'])}"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_equal_rooms(self):
"""save() erlaubt Schreiben wenn Disk und In-Memory gleich viele Räume haben."""
import tempfile
from pathlib import Path
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# In-Memory hat auch 2 Räume (aber anderer Name)
mem_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1_Renamed", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
mem_map = RoomMap._from_dict(mem_data)
# Speichern — sollte erlaubt sein (gleiche Anzahl)
RoomMap.save(mem_map, path=map_path)
with open(map_path, "r") as f:
saved_data = json.load(f)
assert saved_data["rooms"]["r1"]["name"] == "#Room1_Renamed", (
"Umbenennung sollte persistiert werden"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_disk_does_not_exist(self):
"""save() erlaubt Schreiben wenn Disk-Datei nicht existiert."""
import tempfile
from pathlib import Path
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
# Keine Disk-Datei
mem_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
mem_map = RoomMap._from_dict(mem_data)
# Speichern — sollte erlaubt sein (keine Disk-Datei)
RoomMap.save(mem_map, path=map_path)
assert map_path.exists(), "Datei sollte erstellt worden sein"
finally:
tmpdir.cleanup()
@@ -0,0 +1,602 @@
"""
P1-1: Repro-Tests für den RoomMap.save() Refuse-Guard und Single-Room-Pfad-Härtung.
Rainer's Architektur-Review identifizierte zwei Lücken im aktuellen save()-Guard:
1. TOCTOU-Race: fcntl.flock wird erst beim Schreiben erworben, nicht beim Lesen
2. In-Memory-Manipulation: add_or_update_room() kann Map vor save() verändern
Diese Tests dokumentieren die Bugs und validieren die Fixes:
(a) Refuse-Guard triggert bei ID-Differenz + Backup wird geschrieben
(b) Konkurrierende save()-Aufrufe via threading → nur einer schreibt
(c) Rollback aus .bak-Datei nach Korruption
"""
from __future__ import annotations
import json
import os
import shutil
import tempfile
import threading
import time
from pathlib import Path
import pytest
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.room_map import (
RoomMap,
RoomEntry,
RoomMapValidationError,
)
# ── Helpers ────────────────────────────────────────────────────────────────
def _make_map_json(
rooms: list[dict] | None = None,
excluded: list[str] | None = None,
fact_store_path: str = "/tmp/test_docs",
version: int = 1,
) -> str:
"""Create a minimal valid room-map.json as a string."""
data: dict = {
"version": version,
"rooms": {},
"excluded_rooms": excluded or [],
"fact_store_path": fact_store_path,
}
for room in (rooms or []):
room_data = {
"name": room["name"],
"theme": room.get("theme", ""),
"catch_all": room.get("catch_all", False),
}
if "keywords_100" in room or "keywords_context" in room:
room_data["keywords_100"] = room.get("keywords_100", [])
room_data["keywords_context"] = room.get("keywords_context", [])
else:
room_data["keywords"] = room.get("keywords", [])
data["rooms"][room["room_id"]] = room_data
return json.dumps(data)
def _write_map(path: Path, rooms: list[dict], excluded: list[str] | None = None) -> None:
"""Write a room-map.json to disk."""
content = _make_map_json(rooms=rooms, excluded=excluded)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
def _load_map(path: Path) -> RoomMap:
"""Load a RoomMap from a file."""
return RoomMap.load(path)
# ── Test (a): Refuse-Guard triggert bei ID-Differenz ───────────────────────
class TestRefuseGuardTriggers:
"""Refuse-Guard: Disk hat mehr Räume als In-Memory → save() verweigert."""
def test_save_refuses_when_disk_has_more_rooms(self):
"""Disk-Map mit 3 Räumen, In-Memory mit 1 Raum → save() muss verweigern."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
# Disk: 3 Räume (realistisches Multiroom-Setup)
_write_map(map_path, rooms=[
{"room_id": "room_plugin", "name": "#Rocketchat-Plugin",
"theme": "plugin dev", "keywords": ["plugin", "gateway"]},
{"room_id": "room_bat", "name": "#BAT-Team",
"theme": "trading", "keywords": ["bat", "trading"]},
{"room_id": "room_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
])
# In-Memory: Nur 1 Raum (simuliert Single-Room-Pfad der eine
# leere Map mit einem Catch-All überschreiben will)
rm = RoomMap._from_dict({
"version": 1,
"rooms": {
"new_single_room": {
"name": "#OnlyRoom",
"theme": "Automatisch zugewiesener Catch-All-Raum",
"keywords": [],
"catch_all": True,
},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
})
# save() sollte verweigern (Disk hat 3 Räume, Memory hat 1)
RoomMap.save(rm, map_path)
# Disk-Inhalt darf NICHT überschrieben worden sein
disk_after = json.loads(map_path.read_text(encoding="utf-8"))
assert len(disk_after["rooms"]) == 3, (
f"Refuse-Guard hat nicht gegriffen! Disk hat {len(disk_after['rooms'])} Räume, "
f"erwartet 3. Die 3-Raum-Map wurde von der 1-Raum-Map überschrieben."
)
assert "room_plugin" in disk_after["rooms"]
assert "room_bat" in disk_after["rooms"]
assert "room_admin" in disk_after["rooms"]
def test_save_refuses_when_disk_has_rooms_not_in_memory__id_diff(self):
"""Disk-Raum-IDs sind keine Teilmenge von In-Memory-IDs → save() verweigert."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
# Disk: 2 Räume
_write_map(map_path, rooms=[
{"room_id": "room_a", "name": "#RoomA", "theme": "A",
"keywords": ["alpha"]},
{"room_id": "room_b", "name": "#RoomB", "theme": "B",
"keywords": ["beta"], "catch_all": True},
])
# In-Memory: 2 Räume, aber ANDERE IDs (gleiche Anzahl!)
# Der alte Count-Check würde das durchlassen — der ID-Check muss es fangen
rm = RoomMap._from_dict({
"version": 1,
"rooms": {
"room_x": {
"name": "#RoomX", "theme": "X",
"keywords": [], "catch_all": True,
},
"room_y": {
"name": "#RoomY", "theme": "Y",
"keywords": [],
},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
})
RoomMap.save(rm, map_path)
# Disk-Inhalt darf NICHT überschrieben worden sein
disk_after = json.loads(map_path.read_text(encoding="utf-8"))
assert "room_a" in disk_after["rooms"], (
"ID-Check fehlgeschlagen: room_a wurde überschrieben obwohl "
"die In-Memory-Map andere IDs hatte"
)
assert "room_b" in disk_after["rooms"]
assert "room_x" not in disk_after["rooms"], (
"In-Memory-Raum room_x hat fälschlicherweise die Disk überschrieben"
)
def test_backup_written_before_save(self):
"""Vor dem Schreiben wird ein .bak-Backup der existierenden Datei erstellt."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
bak_path = Path(tmpdir) / "room-map.json.bak"
# Disk: 2 Räume
_write_map(map_path, rooms=[
{"room_id": "room_a", "name": "#RoomA", "theme": "A",
"keywords": ["alpha"]},
{"room_id": "room_b", "name": "#RoomB", "theme": "B",
"keywords": ["beta"], "catch_all": True},
])
original_content = map_path.read_text(encoding="utf-8")
# In-Memory: gleiche Räume (save sollte durchgehen)
rm = RoomMap._from_dict({
"version": 1,
"rooms": {
"room_a": {"name": "#RoomA", "theme": "A",
"keywords": ["alpha"]},
"room_b": {"name": "#RoomB", "theme": "B",
"keywords": ["beta"], "catch_all": True},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
})
RoomMap.save(rm, map_path)
# Backup muss existieren
assert bak_path.exists(), (
".bak-Datei wurde nicht erstellt. "
"Backup-Mechanismus fehlt."
)
# Backup-Inhalt muss dem Original entsprechen
bak_content = bak_path.read_text(encoding="utf-8")
bak_data = json.loads(bak_content)
orig_data = json.loads(original_content)
assert bak_data["rooms"] == orig_data["rooms"], (
"Backup-Inhalt stimmt nicht mit Original überein"
)
def test_force_parameter_bypasses_refuse_guard(self):
"""force=True umgeht den Refuse-Guard (für administrative Aufrufe)."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
# Disk: 3 Räume
_write_map(map_path, rooms=[
{"room_id": "room_a", "name": "#RoomA", "theme": "A",
"keywords": ["alpha"]},
{"room_id": "room_b", "name": "#RoomB", "theme": "B",
"keywords": ["beta"]},
{"room_id": "room_c", "name": "#RoomC", "theme": "C",
"keywords": [], "catch_all": True},
])
# In-Memory: Nur 1 Raum (Onboarding-Reset)
rm = RoomMap._from_dict({
"version": 1,
"rooms": {
"new_room": {
"name": "#NewRoom", "theme": "Reset",
"keywords": [], "catch_all": True,
},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
})
# force=True → Guard wird umgangen
RoomMap.save(rm, map_path, force=True)
# Disk sollte jetzt die neue Map enthalten
disk_after = json.loads(map_path.read_text(encoding="utf-8"))
assert len(disk_after["rooms"]) == 1, (
f"force=True hat nicht funktioniert. "
f"Erwartet 1 Raum, Disk hat {len(disk_after['rooms'])}"
)
assert "new_room" in disk_after["rooms"]
# ── Test (b): Konkurrierende save()-Aufrufe ─────────────────────────────────
class TestConcurrentSave:
"""Thread-safety: Parallele save()-Aufrufe werden durch flock serialisiert."""
def test_concurrent_saves_only_one_wins(self):
"""Zwei Threads speichern gleichzeitig — nur einer schreibt, keiner korrumpiert."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
# Initial: 1 Raum
_write_map(map_path, rooms=[
{"room_id": "room_initial", "name": "#Initial",
"theme": "initial", "keywords": [], "catch_all": True},
])
results = {"thread_a_wrote": False, "thread_b_wrote": False,
"thread_a_error": None, "thread_b_error": None}
barrier = threading.Barrier(2, timeout=10)
def save_map_a():
try:
# Beide Threads speichern Maps die room_initial ENTHALTEN
# (ID-Subset-Check: Disk-IDs müssen Teilmenge von Memory-IDs sein)
rm = RoomMap._from_dict({
"version": 1,
"rooms": {
"room_initial": {"name": "#Initial", "theme": "A",
"keywords": [], "catch_all": True},
"room_a": {"name": "#RoomA", "theme": "A",
"keywords": []},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
})
barrier.wait()
RoomMap.save(rm, map_path)
results["thread_a_wrote"] = True
except Exception as e:
results["thread_a_error"] = str(e)
def save_map_b():
try:
rm = RoomMap._from_dict({
"version": 1,
"rooms": {
"room_initial": {"name": "#Initial", "theme": "B",
"keywords": [], "catch_all": True},
"room_b": {"name": "#RoomB", "theme": "B",
"keywords": []},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
})
barrier.wait()
RoomMap.save(rm, map_path)
results["thread_b_wrote"] = True
except Exception as e:
results["thread_b_error"] = str(e)
t_a = threading.Thread(target=save_map_a, name="saver-A")
t_b = threading.Thread(target=save_map_b, name="saver-B")
t_a.start()
t_b.start()
t_a.join(timeout=15)
t_b.join(timeout=15)
# Keine Exceptions in den Threads
assert results["thread_a_error"] is None, (
f"Thread A hatte Fehler: {results['thread_a_error']}"
)
assert results["thread_b_error"] is None, (
f"Thread B hatte Fehler: {results['thread_b_error']}"
)
# Datei muss existieren und gültiges JSON sein
assert map_path.exists(), "Datei existiert nicht nach konkurrierenden saves"
disk_data = json.loads(map_path.read_text(encoding="utf-8"))
# Genau 2 Räume (room_initial + entweder room_a oder room_b)
assert len(disk_data["rooms"]) == 2, (
f"Konkurrierende saves haben die Datei korrumpiert. "
f"Erwartet 2 Räume, Disk hat {len(disk_data['rooms'])}: "
f"{list(disk_data['rooms'].keys())}"
)
# room_initial muss immer da sein
assert "room_initial" in disk_data["rooms"]
# Entweder room_a oder room_b (je nachdem wer zuletzt geschrieben hat)
other_rooms = set(disk_data["rooms"].keys()) - {"room_initial"}
assert len(other_rooms) == 1
assert other_rooms.pop() in ("room_a", "room_b")
def test_concurrent_save_and_read_no_corruption(self):
"""Gleichzeitiges Lesen und Schreiben korrumpiert die Datei nicht."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
_write_map(map_path, rooms=[
{"room_id": "room_initial", "name": "#Initial",
"theme": "initial", "keywords": [], "catch_all": True},
])
errors = []
barrier = threading.Barrier(2, timeout=10)
def reader():
try:
barrier.wait()
for _ in range(20):
try:
rm = RoomMap.load(map_path)
# Prüfe dass die Map gültig ist
assert rm.catch_all_room is not None, "Kein catch_all nach read"
except json.JSONDecodeError:
pass # Kann passieren wenn gerade geschrieben wird
except FileNotFoundError:
pass # Kann passieren bei atomic replace
time.sleep(0.01)
except Exception as e:
errors.append(f"Reader: {e}")
def writer():
try:
barrier.wait()
for i in range(10):
rm = RoomMap._from_dict({
"version": 1,
"rooms": {
f"room_{i}": {
"name": f"#Room{i}", "theme": f"Theme {i}",
"keywords": [], "catch_all": True,
},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
})
RoomMap.save(rm, map_path)
time.sleep(0.02)
except Exception as e:
errors.append(f"Writer: {e}")
t_read = threading.Thread(target=reader, name="reader")
t_write = threading.Thread(target=writer, name="writer")
t_read.start()
t_write.start()
t_read.join(timeout=15)
t_write.join(timeout=15)
# Keine Fehler
assert len(errors) == 0, f"Fehler bei concurrent read/write: {errors}"
# Datei muss am Ende gültig sein
assert map_path.exists()
disk_data = json.loads(map_path.read_text(encoding="utf-8"))
assert len(disk_data["rooms"]) >= 1
# ── Test (c): Rollback aus .bak-Datei ───────────────────────────────────────
class TestRollbackFromBackup:
"""Rollback: Nach Korruption wird aus .bak-Datei wiederhergestellt."""
def test_rollback_restores_from_backup(self):
"""Künstliche Korruption → Rollback aus .bak stellt Original wieder her."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
bak_path = Path(tmpdir) / "room-map.json.bak"
# Erstelle eine valide Map und speichere sie (erzeugt .bak)
_write_map(map_path, rooms=[
{"room_id": "room_plugin", "name": "#Rocketchat-Plugin",
"theme": "plugin dev", "keywords": ["plugin", "gateway"]},
{"room_id": "room_bat", "name": "#BAT-Team",
"theme": "trading", "keywords": ["bat", "trading"]},
{"room_id": "room_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
])
# Simuliere einen save()-Durchlauf der .bak erzeugt
rm = RoomMap.load(map_path)
RoomMap.save(rm, map_path)
# Backup muss existieren
assert bak_path.exists(), (
"Kein .bak-Backup vorhanden — Rollback-Test kann nicht laufen"
)
original_data = json.loads(bak_path.read_text(encoding="utf-8"))
# Korrumpiere die Hauptdatei
map_path.write_text("this is not json{{{", encoding="utf-8")
# Verifiziere dass die Hauptdatei kaputt ist
with pytest.raises((json.JSONDecodeError, Exception)):
RoomMap.load(map_path)
# Rollback: Kopiere .bak → Hauptdatei
shutil.copy2(bak_path, map_path)
# Jetzt sollte die Map wieder ladbar sein
restored = RoomMap.load(map_path)
assert len(restored.rooms) == 3, (
f"Rollback hat nicht alle Räume wiederhergestellt: "
f"{len(restored.rooms)} statt 3"
)
assert "room_plugin" in restored.rooms
assert "room_bat" in restored.rooms
assert "room_admin" in restored.rooms
assert restored.catch_all_room.room_id == "room_admin"
def test_backup_content_matches_original(self):
"""Backup-Inhalt ist identisch mit dem Original vor dem Schreiben."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
bak_path = Path(tmpdir) / "room-map.json.bak"
_write_map(map_path, rooms=[
{"room_id": "room_a", "name": "#RoomA", "theme": "A",
"keywords_100": ["alpha"], "keywords_context": ["beta"]},
{"room_id": "room_b", "name": "#RoomB", "theme": "B",
"keywords_100": [], "keywords_context": [],
"catch_all": True},
])
original_content = map_path.read_text(encoding="utf-8")
original_data = json.loads(original_content)
rm = RoomMap.load(map_path)
RoomMap.save(rm, map_path)
bak_data = json.loads(bak_path.read_text(encoding="utf-8"))
# Räume müssen identisch sein
assert set(bak_data["rooms"].keys()) == set(original_data["rooms"].keys()), (
f"Backup rooms: {set(bak_data['rooms'].keys())}, "
f"Original: {set(original_data['rooms'].keys())}"
)
# Jeder Raum muss gleiche Felder haben
for room_id in original_data["rooms"]:
assert room_id in bak_data["rooms"]
for key in ("name", "theme", "catch_all"):
assert bak_data["rooms"][room_id].get(key) == \
original_data["rooms"][room_id].get(key), (
f"Feld {key} in Raum {room_id} unterscheidet sich"
)
# ── Test: Single-Room-Pfad Integritätsprüfung ───────────────────────────────
class TestSingleRoomIntegrityCheck:
"""FIX B: Single-Room-Pfad prüft Integrität nach save() + reload()."""
def test_single_room_preserves_existing_catch_all(self):
"""Single-Room-Pfad darf existierenden Catch-All nicht überschreiben."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
# Disk: 1 Catch-All-Raum existiert bereits
_write_map(map_path, rooms=[
{"room_id": "existing_catch_all", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
])
# Simuliere check_room_map_completeness() Single-Room-Pfad:
# Ein neuer Raum wird entdeckt, aber die Map hat bereits einen Catch-All
from plugin.archivar.onboarding import check_room_map_completeness
subscribed = {
"new_single_room": {"name": "#OnlyRoom", "type": "c"},
}
# Lade die existierende Map
rm = RoomMap.load(map_path)
# Rufe check_room_map_completeness auf
# Der Single-Room-Pfad (len(relevant_rooms)==1) sollte NICHT
# den existierenden Catch-All überschreiben, weil die Map
# bereits einen Raum hat
result = check_room_map_completeness(
room_map=rm,
subscribed_rooms=subscribed,
map_path=str(map_path),
)
# Die Map sollte unverändert sein (existierender Catch-All bleibt)
disk_after = json.loads(map_path.read_text(encoding="utf-8"))
assert "existing_catch_all" in disk_after["rooms"], (
"Existierender Catch-All wurde vom Single-Room-Pfad überschrieben!"
)
# Der neue Raum sollte als missing gemeldet werden (nicht auto-assigned)
assert len(result) == 1, (
f"Erwartet 1 missing room, bekam {len(result)}: {result}"
)
assert result[0]["room_id"] == "new_single_room"
def test_single_room_rollback_on_corruption(self):
"""Wenn save()+reload() die Map korrumpiert → Rollback aus Backup."""
with tempfile.TemporaryDirectory() as tmpdir:
map_path = Path(tmpdir) / "room-map.json"
bak_path = Path(tmpdir) / "room-map.json.bak"
# Disk: 2 Räume (realistisches Setup)
_write_map(map_path, rooms=[
{"room_id": "room_a", "name": "#RoomA", "theme": "A",
"keywords": ["alpha"]},
{"room_id": "room_admin", "name": "DM Admin",
"theme": "admin", "keywords": [], "catch_all": True},
])
# Erstelle Backup manuell (simuliert Pre-Mutation-Snapshot)
shutil.copy2(map_path, bak_path)
original_room_count = 2
# Simuliere: add_or_update_room() + save() hat die Map
# auf 1 Raum reduziert (Bug-Szenario).
# Nutze force=True um den Refuse-Guard zu umgehen
# (simuliert den Bug, den der Guard eigentlich verhindert)
rm = RoomMap.load(map_path)
# Entferne room_a aus der In-Memory-Map (simuliert Bug)
del rm._rooms["room_a"]
RoomMap.save(rm, map_path, force=True)
# Jetzt: Integritätsprüfung
disk_after = json.loads(map_path.read_text(encoding="utf-8"))
if len(disk_after["rooms"]) < original_room_count:
# Rollback!
shutil.copy2(bak_path, map_path)
restored = RoomMap.load(map_path)
assert len(restored.rooms) == original_room_count, (
f"Rollback fehlgeschlagen: {len(restored.rooms)} statt "
f"{original_room_count} Räume"
)
assert "room_a" in restored.rooms
assert "room_admin" in restored.rooms
else:
# Sollte nicht passieren im Bug-Szenario
pytest.fail("Map wurde nicht korrumpiert — Test-Setup falsch")
+779
View File
@@ -0,0 +1,779 @@
"""
Themenring Phase A — Tests für die In-Memory Ringmatrix.
Testet:
1. TopicRing add/get/clear — grundlegende CRUD-Operationen
2. TTL-Verfall (ephemeral/session/persistent)
3. GC bei max_per_room überschritten
4. GC bei global_max überschritten
5. Thread-Safety (parallele Reads + Writes)
6. send() mit TopicRing → korrekter Raum
7. send() ohne TopicRing-Eintrag → Fallback auf _room_context
8. Cross-Contamination: 2 Räume, 2 Topics → Antworten landen korrekt
"""
from __future__ import annotations
import sys
import threading
import time
import unittest
from datetime import datetime, timezone, timedelta
from pathlib import Path
# Ensure the plugin package is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.topic_ring import (
TopicRing,
TopicEntry,
extract_topic_from_message,
extract_topic_from_archivar_decision,
_is_expired,
topic_ring as global_topic_ring,
)
from plugin.archivar.config import (
TOPIC_RING_MAX_PER_ROOM,
TOPIC_RING_GLOBAL_MAX,
TOPIC_RING_TTL_EPHEMERAL,
TOPIC_RING_TTL_SESSION,
TOPIC_RING_TTL_PERSISTENT,
)
def _make_entry(
topic: str = "Test Topic",
room_id: str = "room_test",
origin_room: str = "room_test",
thematic_target: str = "",
timestamp: str | None = None,
ttl: str = "session",
user_id: str = "user:testuser",
source: str = "archivar",
) -> TopicEntry:
"""Helper: Erzeugt einen TopicEntry mit sinnvollen Defaults."""
if timestamp is None:
timestamp = datetime.now(timezone.utc).isoformat()
return TopicEntry(
topic=topic,
room_id=room_id,
origin_room=origin_room,
thematic_target=thematic_target,
timestamp=timestamp,
ttl=ttl,
user_id=user_id,
source=source,
)
# ── Test 1: TopicRing add/get/clear ──────────────────────────────────────────
class TestTopicRingBasicCRUD(unittest.TestCase):
"""Grundlegende CRUD-Operationen: add, get_recent, get_active_topic, clear."""
def setUp(self):
self.ring = TopicRing()
def test_add_and_get_recent(self):
"""Eintrag hinzufügen und via get_recent abrufen."""
entry = _make_entry(topic="RC-Plugin Deployment", room_id="room_rc")
self.ring.add(entry)
recent = self.ring.get_recent("room_rc")
self.assertEqual(len(recent), 1)
self.assertEqual(recent[0].topic, "RC-Plugin Deployment")
self.assertEqual(recent[0].room_id, "room_rc")
def test_get_recent_returns_newest_first(self):
"""get_recent liefert neueste Einträge zuerst."""
for i in range(3):
entry = _make_entry(
topic=f"Topic {i}",
room_id="room_rc",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
)
self.ring.add(entry)
recent = self.ring.get_recent("room_rc", n=3)
self.assertEqual(len(recent), 3)
# Neueste zuerst: Topic 2, Topic 1, Topic 0
self.assertEqual(recent[0].topic, "Topic 2")
self.assertEqual(recent[1].topic, "Topic 1")
self.assertEqual(recent[2].topic, "Topic 0")
def test_get_active_topic_returns_newest(self):
"""get_active_topic liefert den neuesten nicht-abgelaufenen Eintrag."""
for i in range(3):
entry = _make_entry(
topic=f"Topic {i}",
room_id="room_rc",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
)
self.ring.add(entry)
active = self.ring.get_active_topic("room_rc")
self.assertIsNotNone(active)
self.assertEqual(active.topic, "Topic 2")
def test_get_active_topic_empty_room(self):
"""get_active_topic für leeren Raum liefert None."""
active = self.ring.get_active_topic("nonexistent")
self.assertIsNone(active)
def test_clear_single_room(self):
"""clear(room_id) leert nur den angegebenen Raum."""
self.ring.add(_make_entry(room_id="room_a", topic="Topic A"))
self.ring.add(_make_entry(room_id="room_b", topic="Topic B"))
removed = self.ring.clear("room_a")
self.assertEqual(removed, 1)
self.assertIsNone(self.ring.get_active_topic("room_a"))
self.assertIsNotNone(self.ring.get_active_topic("room_b"))
def test_clear_all_rooms(self):
"""clear() ohne Argument leert alle Räume."""
self.ring.add(_make_entry(room_id="room_a"))
self.ring.add(_make_entry(room_id="room_b"))
removed = self.ring.clear()
self.assertEqual(removed, 2)
self.assertEqual(self.ring.total_entries, 0)
self.assertEqual(self.ring.room_count, 0)
def test_total_entries_and_room_count(self):
"""total_entries und room_count zählen korrekt."""
self.ring.add(_make_entry(room_id="room_a"))
self.ring.add(_make_entry(room_id="room_a"))
self.ring.add(_make_entry(room_id="room_b"))
self.assertEqual(self.ring.total_entries, 3)
self.assertEqual(self.ring.room_count, 2)
def test_stats(self):
"""stats() liefert korrekte Zählungen pro TTL-Typ."""
self.ring.add(_make_entry(ttl="ephemeral"))
self.ring.add(_make_entry(ttl="session"))
self.ring.add(_make_entry(ttl="persistent"))
self.ring.add(_make_entry(ttl="session"))
stats = self.ring.stats()
self.assertEqual(stats["total_entries"], 4)
self.assertEqual(stats["ephemeral"], 1)
self.assertEqual(stats["session"], 2)
self.assertEqual(stats["persistent"], 1)
# ── Test 2: TTL-Verfall ──────────────────────────────────────────────────────
class TestTopicRingTTLExpiry(unittest.TestCase):
"""TTL-Verfall: ephemeral (1h), session (24h), persistent (unendlich)."""
def setUp(self):
self.ring = TopicRing()
def test_ephemeral_expires_after_ttl(self):
"""Ephemeral-Eintrag verfällt nach TTL — get_active_topic filtert expired."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_EPHEMERAL + 10)
entry = _make_entry(
ttl="ephemeral",
timestamp=old_ts.isoformat(),
)
self.ring.add(entry)
# get_active_topic filtert abgelaufene Einträge → None
active = self.ring.get_active_topic("room_test")
self.assertIsNone(active, "get_active_topic should filter expired entries")
# _is_expired direkt prüfen
self.assertTrue(_is_expired(entry))
# Prune auslösen — Eintrag wird aus dem Ring entfernt
now_ts = time.time()
removed = self.ring._prune_expired(now_ts=now_ts)
self.assertEqual(removed, 1)
self.assertIsNone(self.ring.get_active_topic("room_test"))
def test_session_does_not_expire_before_ttl(self):
"""Session-Eintrag verfällt NICHT vor 24h."""
recent_ts = datetime.now(timezone.utc) - timedelta(hours=1)
entry = _make_entry(
ttl="session",
timestamp=recent_ts.isoformat(),
)
self.assertFalse(_is_expired(entry))
def test_session_expires_after_ttl(self):
"""Session-Eintrag verfällt nach 24h."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_SESSION + 10)
entry = _make_entry(
ttl="session",
timestamp=old_ts.isoformat(),
)
self.assertTrue(_is_expired(entry))
def test_persistent_never_expires(self):
"""Persistent-Eintrag verfällt nie."""
very_old_ts = datetime.now(timezone.utc) - timedelta(days=365)
entry = _make_entry(
ttl="persistent",
timestamp=very_old_ts.isoformat(),
)
self.assertFalse(_is_expired(entry))
def test_prune_removes_only_expired(self):
"""Prune entfernt nur abgelaufene Einträge, nicht gültige."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_EPHEMERAL + 10)
recent_ts = datetime.now(timezone.utc)
self.ring.add(_make_entry(topic="Expired", ttl="ephemeral", timestamp=old_ts.isoformat()))
self.ring.add(_make_entry(topic="Valid", ttl="session", timestamp=recent_ts.isoformat()))
self.ring.add(_make_entry(topic="Persistent", ttl="persistent", timestamp=old_ts.isoformat()))
now_ts = time.time()
removed = self.ring._prune_expired(now_ts=now_ts)
self.assertEqual(removed, 1) # Nur der ephemeral-Eintrag
recent = self.ring.get_recent("room_test", n=5)
topics = {e.topic for e in recent}
self.assertIn("Valid", topics)
self.assertIn("Persistent", topics)
self.assertNotIn("Expired", topics)
# ── Test 3: GC bei max_per_room überschritten ─────────────────────────────────
class TestTopicRingGCPerRoom(unittest.TestCase):
"""GC: Wenn max_per_room überschritten, wird der älteste Eintrag entfernt."""
def setUp(self):
self.ring = TopicRing()
def test_max_per_room_evicts_oldest(self):
"""Bei max_per_room+1 Einträgen wird der älteste entfernt."""
for i in range(TOPIC_RING_MAX_PER_ROOM + 2):
entry = _make_entry(
topic=f"Topic {i}",
room_id="room_rc",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
)
self.ring.add(entry)
# Es sollten max TOPIC_RING_MAX_PER_ROOM Einträge im Raum sein
recent = self.ring.get_recent("room_rc", n=TOPIC_RING_MAX_PER_ROOM + 5)
self.assertLessEqual(len(recent), TOPIC_RING_MAX_PER_ROOM)
# Der älteste Eintrag (Topic 0) sollte entfernt sein
topics = {e.topic for e in recent}
self.assertNotIn("Topic 0", topics)
self.assertNotIn("Topic 1", topics) # Auch der zweitälteste
# Die neuesten sollten noch da sein
max_idx = TOPIC_RING_MAX_PER_ROOM + 1
self.assertIn(f"Topic {max_idx}", topics)
def test_multiple_rooms_independent_limits(self):
"""Jeder Raum hat sein eigenes max_per_room-Limit."""
for i in range(TOPIC_RING_MAX_PER_ROOM + 2):
self.ring.add(_make_entry(
topic=f"A-{i}", room_id="room_a",
timestamp=datetime(2026, 7, 26, 10, i, 0, tzinfo=timezone.utc).isoformat(),
))
# room_b hat nur 2 Einträge — sollte nicht evicted werden
self.ring.add(_make_entry(topic="B-0", room_id="room_b"))
self.ring.add(_make_entry(topic="B-1", room_id="room_b"))
recent_a = self.ring.get_recent("room_a", n=TOPIC_RING_MAX_PER_ROOM + 5)
recent_b = self.ring.get_recent("room_b", n=5)
self.assertLessEqual(len(recent_a), TOPIC_RING_MAX_PER_ROOM)
self.assertEqual(len(recent_b), 2)
self.assertIn("B-0", {e.topic for e in recent_b})
self.assertIn("B-1", {e.topic for e in recent_b})
# ── Test 4: GC bei global_max überschritten ───────────────────────────────────
class TestTopicRingGCGlobal(unittest.TestCase):
"""GC: Wenn global_max überschritten, werden älteste ephemeral-Einträge entfernt."""
def setUp(self):
self.ring = TopicRing()
def test_global_max_evicts_oldest_ephemeral(self):
"""Bei Überschreitung von global_max werden älteste ephemeral entfernt."""
base_ts = datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc)
# Fülle mit vielen ephemeral-Einträgen
for i in range(TOPIC_RING_GLOBAL_MAX + 10):
entry = _make_entry(
topic=f"Topic {i}",
room_id=f"room_{(i % 10)}",
ttl="ephemeral",
timestamp=(base_ts + timedelta(seconds=i)).isoformat(),
)
self.ring.add(entry)
self.assertLessEqual(self.ring.total_entries, TOPIC_RING_GLOBAL_MAX)
def test_global_max_preserves_persistent(self):
"""Globale GC entfernt ephemeral vor persistent."""
base_ts = datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc)
# Fülle bis kurz vor global_max mit ephemeral
for i in range(TOPIC_RING_GLOBAL_MAX - 2):
self.ring.add(_make_entry(
topic=f"Eph-{i}", room_id=f"room_{(i % 5)}", ttl="ephemeral",
timestamp=(base_ts + timedelta(seconds=i)).isoformat(),
))
# Füge 3 persistente Einträge hinzu
self.ring.add(_make_entry(topic="Persistent-1", ttl="persistent"))
self.ring.add(_make_entry(topic="Persistent-2", ttl="persistent"))
self.ring.add(_make_entry(topic="Persistent-3", ttl="persistent"))
# Sollte jetzt über global_max sein → ephemeral werden evicted
self.assertLessEqual(self.ring.total_entries, TOPIC_RING_GLOBAL_MAX)
# Persistente Einträge sollten noch da sein
all_topics = set()
for room_id in ["room_0", "room_1", "room_2", "room_3", "room_4", "room_test"]:
for e in self.ring.get_recent(room_id, n=TOPIC_RING_GLOBAL_MAX):
all_topics.add(e.topic)
for p in ["Persistent-1", "Persistent-2", "Persistent-3"]:
self.assertIn(p, all_topics, f"Persistent entry {p} should survive GC")
# ── Test 5: Thread-Safety ────────────────────────────────────────────────────
class TestTopicRingThreadSafety(unittest.TestCase):
"""Thread-Safety: Parallele Reads + Writes ohne Race Conditions."""
def setUp(self):
self.ring = TopicRing()
self.errors: list[Exception] = []
def test_concurrent_reads_and_writes(self):
"""Parallele Reader und Writer produzieren keine Fehler."""
num_writers = 4
num_readers = 4
iterations = 200
barrier = threading.Barrier(num_writers + num_readers + 1)
def writer(worker_id: int):
barrier.wait()
base_ts = datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc)
for i in range(iterations):
try:
entry = _make_entry(
topic=f"W{worker_id}-{i}",
room_id=f"room_{(worker_id % 3)}",
timestamp=(base_ts + timedelta(seconds=i)).isoformat(),
)
self.ring.add(entry)
except Exception as e:
self.errors.append(e)
def reader(worker_id: int):
barrier.wait()
for i in range(iterations):
try:
# Abwechselnd verschiedene Read-Operationen
if i % 3 == 0:
self.ring.get_recent(f"room_{(worker_id % 3)}")
elif i % 3 == 1:
self.ring.get_active_topic(f"room_{(worker_id % 3)}")
else:
self.ring.get_active_topic_for_chat(f"user:test{worker_id}")
except Exception as e:
self.errors.append(e)
threads = []
for w in range(num_writers):
t = threading.Thread(target=writer, args=(w,))
threads.append(t)
for r in range(num_readers):
t = threading.Thread(target=reader, args=(r,))
threads.append(t)
for t in threads:
t.start()
barrier.wait() # Alle starten gleichzeitig
for t in threads:
t.join(timeout=10)
self.assertEqual(len(self.errors), 0, f"Errors during concurrent access: {self.errors}")
# Der Ring sollte Einträge enthalten
self.assertGreater(self.ring.total_entries, 0)
def test_snapshot_consistency(self):
"""Snapshot bleibt konsistent auch bei parallelen Writes."""
# Vorbereiten: ein paar Einträge
for i in range(5):
self.ring.add(_make_entry(topic=f"Pre-{i}", room_id="room_snap"))
snap_before = self.ring.get_recent("room_snap")
self.assertEqual(len(snap_before), 5)
# Während wir den Snapshot halten, weitere Einträge hinzufügen
for i in range(5):
self.ring.add(_make_entry(topic=f"Post-{i}", room_id="room_snap"))
# Snapshot sollte unverändert sein (5 Einträge)
self.assertEqual(len(snap_before), 5)
# Neuer Snapshot sollte 5 Einträge haben (max_per_room GC)
snap_after = self.ring.get_recent("room_snap")
self.assertLessEqual(len(snap_after), TOPIC_RING_MAX_PER_ROOM)
# ── Test 6: get_active_topic_for_chat ─────────────────────────────────────────
class TestTopicRingGetActiveTopicForChat(unittest.TestCase):
"""get_active_topic_for_chat() liefert den korrekten origin_room."""
def setUp(self):
self.ring = TopicRing()
def test_returns_origin_room_for_active_topic(self):
"""Aktiver Topic für einen User liefert dessen origin_room."""
self.ring.add(_make_entry(
topic="RC-Plugin Bug",
room_id="room_rc",
origin_room="room_rc",
user_id="user:andreas",
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_rc")
def test_returns_thematic_target_when_set(self):
"""Wenn thematic_target gesetzt ist, wird dieser bevorzugt."""
self.ring.add(_make_entry(
topic="LAN-Doku Update",
room_id="room_dm",
origin_room="room_dm",
thematic_target="room_lan",
user_id="user:andreas",
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_lan")
def test_returns_none_for_unknown_user(self):
"""Unbekannter User liefert None."""
result = self.ring.get_active_topic_for_chat("user:nonexistent")
self.assertIsNone(result)
def test_returns_newest_topic_for_user(self):
"""Bei mehreren Topics für einen User wird das neueste genommen."""
self.ring.add(_make_entry(
topic="Old Topic",
room_id="room_old",
origin_room="room_old",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 9, 0, 0, tzinfo=timezone.utc).isoformat(),
))
self.ring.add(_make_entry(
topic="New Topic",
room_id="room_new",
origin_room="room_new",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc).isoformat(),
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_new")
def test_ignores_expired_topics(self):
"""Abgelaufene Topics werden ignoriert."""
old_ts = datetime.now(timezone.utc) - timedelta(seconds=TOPIC_RING_TTL_EPHEMERAL + 10)
self.ring.add(_make_entry(
topic="Expired Topic",
room_id="room_expired",
origin_room="room_expired",
user_id="user:andreas",
ttl="ephemeral",
timestamp=old_ts.isoformat(),
))
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertIsNone(result)
# ── Test 7: send() mit/ohne TopicRing ─────────────────────────────────────────
class TestSendWithTopicRing(unittest.TestCase):
"""Integration: send() verwendet TopicRing Prio 1 vor _room_context."""
def test_topic_ring_prio1_before_room_context(self):
"""Wenn TopicRing einen Eintrag hat, wird dieser VOR _room_context verwendet.
Dies testet die Prioritäten-Kette:
Prio 0: _CURRENT_ORIGIN_ROOM (ContextVar)
Prio 1: TopicRing.get_active_topic_for_chat() ← NEU
Prio 1.5: _room_context (Stream-Retry Fallback)
"""
# Simuliere: TopicRing hat einen Eintrag für user:andreas → room_lan
global_topic_ring.clear()
global_topic_ring.add(_make_entry(
topic="LAN-Doku",
room_id="room_lan",
origin_room="room_lan",
user_id="user:andreas",
))
result = global_topic_ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_lan")
# Cleanup
global_topic_ring.clear()
def test_no_topic_ring_entry_falls_back(self):
"""Ohne TopicRing-Eintrag wird normal weitergemacht (kein Fehler)."""
global_topic_ring.clear()
result = global_topic_ring.get_active_topic_for_chat("user:andreas")
self.assertIsNone(result)
# ── Test 8: Cross-Contamination ───────────────────────────────────────────────
class TestTopicRingCrossContamination(unittest.TestCase):
"""Cross-Contamination: 2 Räume, 2 Topics → Antworten landen korrekt."""
def setUp(self):
self.ring = TopicRing()
def test_two_rooms_two_topics_correct_routing(self):
"""Andreas arbeitet in 2 Räumen an 2 Themen — Antworten landen korrekt.
Szenario:
- Raum A (#RC-Plugin): Andreas fragt nach Plugin-Deployment
- Raum B (#LAN-Doku): Andreas fragt nach Netzwerk-Doku
- Antwort zu Plugin-Deployment → muss in Raum A landen
- Antwort zu Netzwerk-Doku → muss in Raum B landen
"""
# Andreas schreibt in Raum A
self.ring.add(_make_entry(
topic="RC-Plugin Deployment",
room_id="room_rc",
origin_room="room_rc",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc).isoformat(),
))
# Andreas schreibt in Raum B
self.ring.add(_make_entry(
topic="Netzwerk-Dokumentation",
room_id="room_lan",
origin_room="room_lan",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 1, 0, tzinfo=timezone.utc).isoformat(),
))
# Der neueste aktive Topic für Andreas ist room_lan
result = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(result, "room_lan")
# Aber get_active_topic pro Raum liefert korrekte Topics
rc_topic = self.ring.get_active_topic("room_rc")
lan_topic = self.ring.get_active_topic("room_lan")
self.assertIsNotNone(rc_topic)
self.assertIsNotNone(lan_topic)
self.assertEqual(rc_topic.topic, "RC-Plugin Deployment")
self.assertEqual(lan_topic.topic, "Netzwerk-Dokumentation")
def test_different_users_different_topics(self):
"""Zwei verschiedene User, verschiedene Topics — keine Vermischung."""
self.ring.add(_make_entry(
topic="Andreas Topic",
room_id="room_andreas",
origin_room="room_andreas",
user_id="user:andreas",
))
self.ring.add(_make_entry(
topic="Bernd Topic",
room_id="room_bernd",
origin_room="room_bernd",
user_id="user:bernd",
))
result_andreas = self.ring.get_active_topic_for_chat("user:andreas")
result_bernd = self.ring.get_active_topic_for_chat("user:bernd")
self.assertEqual(result_andreas, "room_andreas")
self.assertEqual(result_bernd, "room_bernd")
def test_move_gc_preserves_topics(self):
"""move_gc verschiebt Topics zwischen Räumen ohne Datenverlust."""
self.ring.add(_make_entry(topic="Topic 1", room_id="room_old"))
self.ring.add(_make_entry(topic="Topic 2", room_id="room_old"))
moved = self.ring.move_gc("room_old", "room_new")
self.assertEqual(moved, 2)
# Alter Raum sollte leer sein
self.assertIsNone(self.ring.get_active_topic("room_old"))
# Neuer Raum sollte beide Topics haben
recent = self.ring.get_recent("room_new", n=5)
self.assertEqual(len(recent), 2)
topics = {e.topic for e in recent}
self.assertIn("Topic 1", topics)
self.assertIn("Topic 2", topics)
def test_cross_contamination_real_world(self):
"""F6: Raumbezogener Lookup verhindert Cross-Contamination.
Real-World-Szenario:
- Andreas schreibt in Raum A → TopicRing add(A)
- Andreas schreibt in Raum B → TopicRing add(B)
- Agent antwortet in Raum A → get_active_topic(A) → MUSS A liefern, nicht B
- Agent antwortet in Raum B → get_active_topic(B) → MUSS B liefern, nicht A
Der user-weite Lookup get_active_topic_for_chat() würde B liefern
(neuester Eintrag), was Cross-Contamination wäre. Der raumbezogene
Lookup get_active_topic(room_id) liefert den korrekten Raum-Topic.
"""
# Andreas schreibt in Raum A (RC-Plugin)
self.ring.add(_make_entry(
topic="RC-Plugin Deployment",
room_id="room_rc",
origin_room="room_rc",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 0, 0, tzinfo=timezone.utc).isoformat(),
))
# Andreas schreibt in Raum B (LAN-Doku) — neuerer Eintrag
self.ring.add(_make_entry(
topic="Netzwerk-Dokumentation",
room_id="room_lan",
origin_room="room_lan",
user_id="user:andreas",
timestamp=datetime(2026, 7, 26, 10, 1, 0, tzinfo=timezone.utc).isoformat(),
))
# ── Der user-weite Lookup würde Cross-Contamination verursachen ──
# get_active_topic_for_chat() sucht user-weit den neuesten Eintrag
# → liefert room_lan (neuer), NICHT room_rc
user_wide = self.ring.get_active_topic_for_chat("user:andreas")
self.assertEqual(user_wide, "room_lan",
"User-weiter Lookup liefert neuesten Topic (room_lan) — "
"das ist das Cross-Contamination-Problem")
# ── Der raumbezogene Lookup löst das Problem ──
# Agent antwortet in Raum A → get_active_topic("room_rc")
rc_topic = self.ring.get_active_topic("room_rc")
self.assertIsNotNone(rc_topic,
"Raum A muss einen aktiven Topic haben")
self.assertEqual(rc_topic.topic, "RC-Plugin Deployment",
"Antwort in Raum A muss Topic von A liefern, nicht von B")
self.assertEqual(rc_topic.origin_room, "room_rc",
"origin_room muss room_rc sein, nicht room_lan")
# Agent antwortet in Raum B → get_active_topic("room_lan")
lan_topic = self.ring.get_active_topic("room_lan")
self.assertIsNotNone(lan_topic,
"Raum B muss einen aktiven Topic haben")
self.assertEqual(lan_topic.topic, "Netzwerk-Dokumentation",
"Antwort in Raum B muss Topic von B liefern, nicht von A")
self.assertEqual(lan_topic.origin_room, "room_lan",
"origin_room muss room_lan sein, nicht room_rc")
# ── Beide Topics sind unterschiedlich — keine Cross-Contamination ──
self.assertNotEqual(rc_topic.topic, lan_topic.topic,
"Topics in Raum A und B müssen unterschiedlich sein")
self.assertNotEqual(rc_topic.origin_room, lan_topic.origin_room,
"origin_rooms müssen unterschiedlich sein")
# ── Test: Topic-Extraktion ────────────────────────────────────────────────────
class TestTopicExtraction(unittest.TestCase):
"""Topic-Extraktion aus Nachrichten und Archivar-Entscheidungen."""
def test_extract_from_message_normal(self):
"""Normale Nachricht: erste sinnvolle Phrase."""
result = extract_topic_from_message("RC-Plugin Deployment auf Produktion vorbereiten")
self.assertEqual(result, "RC-Plugin Deployment auf Produktion vorbereiten")
def test_extract_from_message_truncated(self):
"""Lange Nachricht wird auf max_len gekürzt."""
long_text = "A" * 100 + " RC-Plugin Deployment"
result = extract_topic_from_message(long_text, max_len=80)
self.assertLessEqual(len(result), 80)
def test_extract_from_message_too_short(self):
"""Zu kurze Nachricht liefert leeren String."""
result = extract_topic_from_message("Kurz")
self.assertEqual(result, "")
def test_extract_from_message_empty(self):
"""Leere Nachricht liefert leeren String."""
result = extract_topic_from_message("")
self.assertEqual(result, "")
def test_extract_from_message_multiline(self):
"""Mehrzeilige Nachricht: nur erste Zeile wird verwendet."""
result = extract_topic_from_message("Erste Zeile\nZweite Zeile\nDritte Zeile")
self.assertEqual(result, "Erste Zeile")
def test_extract_from_archivar_with_room_name(self):
"""Archivar-Extraktion mit Raumname."""
result = extract_topic_from_archivar_decision(
decision_target_room="room_rc",
room_name="#RC-Plugin",
)
self.assertEqual(result, "RC-Plugin")
def test_extract_from_archivar_without_room_name(self):
"""Archivar-Extraktion ohne Raumname, nur Kategorie."""
result = extract_topic_from_archivar_decision(
decision_target_room="room_rc",
decision_category="work_order",
)
self.assertEqual(result, "Archivar: work_order")
# ── Test: Modul-Singleton ─────────────────────────────────────────────────────
class TestGlobalTopicRing(unittest.TestCase):
"""Der Modul-Singleton topic_ring funktioniert wie erwartet."""
def tearDown(self):
global_topic_ring.clear()
def test_singleton_is_topic_ring_instance(self):
"""Der Singleton ist eine TopicRing-Instanz."""
self.assertIsInstance(global_topic_ring, TopicRing)
def test_singleton_starts_empty(self):
"""Der Singleton startet leer."""
global_topic_ring.clear()
self.assertEqual(global_topic_ring.total_entries, 0)
def test_singleton_add_and_read(self):
"""Singleton: add und get_active_topic_for_chat funktionieren."""
global_topic_ring.clear()
global_topic_ring.add(_make_entry(
topic="Test",
room_id="room_test",
origin_room="room_test",
user_id="user:test",
))
result = global_topic_ring.get_active_topic_for_chat("user:test")
self.assertEqual(result, "room_test")
if __name__ == "__main__":
unittest.main()
@@ -20,6 +20,7 @@ from __future__ import annotations
import asyncio import asyncio
import contextvars import contextvars
import datetime
import os import os
import sys import sys
import unittest import unittest
@@ -311,5 +312,747 @@ class TestDispatchTaskContextVar(unittest.TestCase):
) )
# ═══════════════════════════════════════════════════════════════════════════════
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
# ═══════════════════════════════════════════════════════════════════════════════
class TestRoomContextFallback(unittest.TestCase):
"""Tests für _room_context als Fallback bei ContextVar-Reset (P1)."""
def setUp(self):
"""Build a minimal mock adapter for send() testing."""
import threading
from unittest.mock import MagicMock, AsyncMock
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
from plugin.adapter import RocketChatAdapter, RocketChatREST
self.adapter = RocketChatAdapter.__new__(RocketChatAdapter)
self.adapter.config = MagicMock()
self.adapter.config.extra = {}
self.adapter.platform = "rocketchat"
self.adapter.base_url = "https://rocket.example.com"
self.adapter.user = "testbot"
self.adapter.password = "testpass"
self.adapter.rest = MagicMock(spec=RocketChatREST)
self.adapter.rest.auth_token = "fake-token"
self.adapter.rest.user_id = "fake-user-id"
self.adapter.rest.post_message = MagicMock(return_value="msg_12345")
self.adapter.ddp = None
self.adapter._auth_token = None
self.adapter._user_id = None
self.adapter._rooms = []
self.adapter._subscribed_rooms = set()
self.adapter._listen_task = None
self.adapter._status_timer = None
self.adapter._last_activity = 0.0
self.adapter._shutdown_event = threading.Event()
self.adapter._room_info = {}
self.adapter._pending_clarifies = {}
self.adapter._user_rooms = {}
self.adapter._rooms_with_pending_questions = set()
self.adapter._excluded_room_ids = set()
self.adapter._last_server_activity = 0.0
self.adapter._health_check_timer = None
self.adapter._last_ddp_ping_ok = False
self.adapter._running = False
self.adapter._pending_move_requests = {}
self.adapter._session_room_preferences = {}
self.adapter._recent_auto_routes = {}
self.adapter._explicit_switch_sticky = {}
self.adapter._clarify_state = {}
self.adapter._pending_clarify_dispatch = {}
self.adapter._onboarding_state = {}
self.adapter._room_map_summary = ""
self.adapter._post_message_with_retry = AsyncMock(return_value=True)
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
self.adapter._replace_slash_with_double_colon = MagicMock(
side_effect=lambda x: x
)
self.adapter._conversation_history = None # not needed for routing tests
self.adapter._multiroom_context = None
self.adapter.archivar = None
# Import module-level state
from plugin.adapter import (
_CURRENT_ORIGIN_ROOM,
_THEMATIC_TARGET_ROOM,
_room_context,
_room_context_lock,
_RED_FLAG_PENDING,
)
self._CURRENT_ORIGIN_ROOM = _CURRENT_ORIGIN_ROOM
self._THEMATIC_TARGET_ROOM = _THEMATIC_TARGET_ROOM
self._room_context = _room_context
self._room_context_lock = _room_context_lock
self._RED_FLAG_PENDING = _RED_FLAG_PENDING
def tearDown(self):
"""Clean up module-level state between tests."""
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._RED_FLAG_PENDING.set({})
with self._room_context_lock:
self._room_context.clear()
# ── Test 6: send() mit leerer ContextVar fällt auf _room_context zurück ──
def test_send_with_empty_contextvar_falls_back_to_room_context(self):
"""ContextVar leer, _room_context hat origin_room → send verwendet _room_context.
Szenario: Stream-Retry erzeugt neuen asyncio-Task. _CURRENT_ORIGIN_ROOM
ist leer (nicht vererbt). _room_context (global dict) hat aber noch
den origin_room aus _process_incoming. send() soll diesen Fallback nutzen.
"""
chat_id = "user:alice"
correct_room = "room_correct_123"
# ContextVars sind LEER (simuliert Stream-Retry in neuem Task)
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
# _room_context hat den korrekten Raum (wurde in _process_incoming gesetzt)
with self._room_context_lock:
self._room_context[chat_id] = {"origin_room": correct_room}
# _user_rooms ist LEER (kein Fallback über user_map)
self.adapter._user_rooms = {}
# _find_fallback_room_for_user gibt None zurück (kein weiterer Fallback)
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
# Verify: send() hat _post_message_with_retry mit dem korrekten Raum aufgerufen
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, correct_room,
f"send() sollte _room_context Fallback nutzen: {correct_room}, "
f"bekam aber: {real_room_id}"
)
# ── Test 7: Stream-Retry simuliert ContextVar-Reset ─────────────────
def test_stream_retry_simulates_fresh_contextvar(self):
"""Simuliere ContextVar-Reset (leer), _room_context hat Wert,
_user_rooms falsch → Korrektes Routing über _room_context.
Szenario: User ist in mehreren Räumen. _user_rooms hat den
FALSCHEN Raum als letzten Eintrag. ContextVar ist leer (Reset).
_room_context hat den KORREKTEN Raum. send() muss _room_context
priorisieren, nicht _user_rooms[-1].
"""
chat_id = "user:bob"
correct_room = "room_dm_bob"
wrong_room = "room_general"
# ContextVars sind LEER (simuliert Stream-Retry in neuem Task)
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
# _room_context hat den korrekten Raum
with self._room_context_lock:
self._room_context[chat_id] = {"origin_room": correct_room}
# _user_rooms hat den FALSCHEN Raum als letzten Eintrag
self.adapter._user_rooms = {
chat_id: [wrong_room, "room_other"]
}
# _find_fallback_room_for_user gibt None zurück
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
# Verify: send() hat _post_message_with_retry mit dem KORREKTEN Raum aufgerufen
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, correct_room,
f"send() sollte _room_context ({correct_room}) priorisieren, "
f"nicht _user_rooms[-1] ({wrong_room}). Bekam: {real_room_id}"
)
# ── Test 8: send_clarify mit leerer ContextVar → _room_context Fallback ──
def test_send_clarify_with_empty_contextvar_falls_back_to_room_context(self):
"""send_clarify() mit leerer ContextVar → _room_context Fallback.
Deckt die Inkonsistenz ab: send_clarify() hatte _THEMATIC_TARGET_ROOM
VOR _room_context geprüft (falsch). Nach dem Fix prüft send_clarify()
_CURRENT_ORIGIN_ROOM → _room_context → _THEMATIC_TARGET_ROOM,
exakt wie send().
"""
chat_id = "user:alice"
correct_room = "room_clarify_123"
thematic_room = "room_thematic_456"
# ContextVars sind LEER (simuliert Stream-Retry in neuem Task)
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set(thematic_room) # Archivar hat thematischen Zielraum
# _room_context hat den korrekten Raum (wurde in _process_incoming gesetzt)
with self._room_context_lock:
self._room_context[chat_id] = {"origin_room": correct_room}
# _user_rooms ist LEER
self.adapter._user_rooms = {}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send_clarify(
chat_id=chat_id,
question="Test question?",
choices=["Yes", "No"],
clarify_id="clarify_001",
session_key="session_001",
)
)
# Verify: send_clarify() hat _post_message_with_retry mit dem
# _room_context Fallback aufgerufen, NICHT mit _THEMATIC_TARGET_ROOM.
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, correct_room,
f"send_clarify() sollte _room_context ({correct_room}) priorisieren, "
f"nicht _THEMATIC_TARGET_ROOM ({thematic_room}). Bekam: {real_room_id}"
)
# ── Test 9: Concurrency — 10 parallele Tasks, konsistente Werte ─────
def test_concurrency_parallel_set_and_read(self):
"""10 parallele Tasks: 5 set + 5 read, alle sehen konsistenten Wert.
Stresstest für _set_room_context_origin() und _room_context_lock.
Keine Race-Condition: alle Reader sehen den zuletzt geschriebenen Wert.
"""
chat_id = "user:concurrent"
base_room = "room_concurrent"
async def _run():
results = []
async def setter(room_suffix: str):
"""Setze _room_context auf einen bestimmten Raum."""
room = f"{base_room}_{room_suffix}"
from plugin.adapter import _set_room_context_origin
_set_room_context_origin(chat_id, room)
results.append(("set", room_suffix, room))
async def reader(expected_suffix: str):
"""Lies _room_context und prüfe Konsistenz."""
from plugin.adapter import _room_context, _room_context_lock
with _room_context_lock:
ctx = _room_context.get(chat_id, {})
origin = ctx.get("origin_room", "")
results.append(("read", expected_suffix, origin))
# 5 Setter + 5 Reader parallel starten
tasks = []
for i in range(5):
tasks.append(asyncio.create_task(setter(f"s{i}")))
for i in range(5):
tasks.append(asyncio.create_task(reader(f"s{i}")))
await asyncio.gather(*tasks)
return results
results = asyncio.run(_run())
# Alle Setter haben ihren Wert gesetzt
setters = [r for r in results if r[0] == "set"]
self.assertEqual(len(setters), 5, "Alle 5 Setter sollten durchlaufen")
# Alle Reader haben einen nicht-leeren Wert gesehen
readers = [r for r in results if r[0] == "read"]
self.assertEqual(len(readers), 5, "Alle 5 Reader sollten durchlaufen")
for _, _, origin in readers:
self.assertTrue(
origin.startswith(base_room),
f"Reader sollte einen Raum mit Präfix {base_room} sehen, "
f"bekam: {origin}"
)
# ── Test 10: Stale-Entry — _room_context gewinnt gegen _user_rooms ──
def test_stale_entry_room_context_wins_over_user_rooms(self):
"""_room_context hat Raum X, _user_rooms hat Raum Y, ContextVar leer
→ _room_context gewinnt (Doku-Test).
Szenario: User war zuletzt in Raum Y (_user_rooms[-1]), aber die
aktuelle Frage kam aus Raum X (_room_context). ContextVar ist leer
(Stream-Retry). send() muss _room_context priorisieren.
"""
chat_id = "user:stale"
room_context_room = "room_X_correct"
user_rooms_room = "room_Y_wrong"
# ContextVars sind LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
# _room_context hat Raum X (korrekt)
with self._room_context_lock:
self._room_context[chat_id] = {"origin_room": room_context_room}
# _user_rooms hat Raum Y (falsch, veraltet)
self.adapter._user_rooms = {
chat_id: [user_rooms_room]
}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
# Verify: send() hat _room_context (Raum X) verwendet, nicht _user_rooms (Raum Y)
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, room_context_room,
f"send() sollte _room_context ({room_context_room}) priorisieren, "
f"nicht _user_rooms[-1] ({user_rooms_room}). Bekam: {real_room_id}"
)
# ═══════════════════════════════════════════════════════════════════════════════
# P1: Cross-Contamination-Fix — Task-Token + TTL-Sweep
# ═══════════════════════════════════════════════════════════════════════════════
class TestRoomContextCrossContamination(unittest.TestCase):
"""Tests für Task-Token-Validierung und TTL-Sweep (P1 Cross-Contamination-Fix)."""
def setUp(self):
"""Build a minimal mock adapter for send() testing."""
import threading
from unittest.mock import MagicMock, AsyncMock
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
from plugin.adapter import RocketChatAdapter, RocketChatREST
self.adapter = RocketChatAdapter.__new__(RocketChatAdapter)
self.adapter.config = MagicMock()
self.adapter.config.extra = {}
self.adapter.platform = "rocketchat"
self.adapter.base_url = "https://rocket.example.com"
self.adapter.user = "testbot"
self.adapter.password = "testpass"
self.adapter.rest = MagicMock(spec=RocketChatREST)
self.adapter.rest.auth_token = "fake-token"
self.adapter.rest.user_id = "fake-user-id"
self.adapter.rest.post_message = MagicMock(return_value="msg_12345")
self.adapter.ddp = None
self.adapter._auth_token = None
self.adapter._user_id = None
self.adapter._rooms = []
self.adapter._subscribed_rooms = set()
self.adapter._listen_task = None
self.adapter._status_timer = None
self.adapter._last_activity = 0.0
self.adapter._shutdown_event = threading.Event()
self.adapter._room_info = {}
self.adapter._pending_clarifies = {}
self.adapter._user_rooms = {}
self.adapter._rooms_with_pending_questions = set()
self.adapter._excluded_room_ids = set()
self.adapter._last_server_activity = 0.0
self.adapter._health_check_timer = None
self.adapter._last_ddp_ping_ok = False
self.adapter._running = False
self.adapter._pending_move_requests = {}
self.adapter._session_room_preferences = {}
self.adapter._recent_auto_routes = {}
self.adapter._explicit_switch_sticky = {}
self.adapter._clarify_state = {}
self.adapter._pending_clarify_dispatch = {}
self.adapter._onboarding_state = {}
self.adapter._room_map_summary = ""
self.adapter._post_message_with_retry = AsyncMock(return_value=True)
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
self.adapter._replace_slash_with_double_colon = MagicMock(
side_effect=lambda x: x
)
self.adapter._conversation_history = None
self.adapter._multiroom_context = None
self.adapter.archivar = None
# Import module-level state
from plugin.adapter import (
_CURRENT_ORIGIN_ROOM,
_THEMATIC_TARGET_ROOM,
_CURRENT_TASK_TOKEN,
_room_context,
_room_context_lock,
_RED_FLAG_PENDING,
_set_room_context_origin,
_get_room_context_origin,
_ROOM_CONTEXT_TTL_SECONDS,
)
self._CURRENT_ORIGIN_ROOM = _CURRENT_ORIGIN_ROOM
self._THEMATIC_TARGET_ROOM = _THEMATIC_TARGET_ROOM
self._CURRENT_TASK_TOKEN = _CURRENT_TASK_TOKEN
self._room_context = _room_context
self._room_context_lock = _room_context_lock
self._RED_FLAG_PENDING = _RED_FLAG_PENDING
self._set_room_context_origin = _set_room_context_origin
self._get_room_context_origin = _get_room_context_origin
self._ROOM_CONTEXT_TTL_SECONDS = _ROOM_CONTEXT_TTL_SECONDS
def tearDown(self):
"""Clean up module-level state between tests."""
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
self._RED_FLAG_PENDING.set({})
with self._room_context_lock:
self._room_context.clear()
# ── Test 11: _set_room_context_origin generiert Token + Timestamp ──
def test_set_room_context_origin_generates_token_and_timestamp(self):
"""_set_room_context_origin setzt task_token (UUID4) und timestamp (ISO)."""
chat_id = "user:alice"
room_id = "room_test_123"
token = self._set_room_context_origin(chat_id, room_id)
# Token ist ein gültiger UUID4-String
self.assertIsInstance(token, str)
self.assertEqual(len(token), 36) # UUID4: 8-4-4-4-12
self.assertEqual(token.count("-"), 4)
# _room_context hat den Eintrag mit allen Feldern
with self._room_context_lock:
ctx = self._room_context.get(chat_id, {})
self.assertEqual(ctx["origin_room"], room_id)
self.assertEqual(ctx["task_token"], token)
self.assertIn("timestamp", ctx)
# Timestamp ist ISO-Format
self.assertIn("T", ctx["timestamp"])
# _CURRENT_TASK_TOKEN wurde gesetzt
self.assertEqual(self._CURRENT_TASK_TOKEN.get(), token)
# ── Test 12: _get_room_context_origin mit Token-Match ──
def test_get_room_context_origin_token_match(self):
"""Token-Match → _get_room_context_origin gibt origin_room zurück."""
chat_id = "user:alice"
room_id = "room_match_123"
token = self._set_room_context_origin(chat_id, room_id)
# _CURRENT_TASK_TOKEN ist bereits durch _set_room_context_origin gesetzt
result = self._get_room_context_origin(chat_id)
self.assertEqual(result, room_id)
# ── Test 13: _get_room_context_origin mit Token-Mismatch (Cross-Contamination) ──
def test_get_room_context_origin_token_mismatch(self):
"""Token-Mismatch → _get_room_context_origin gibt '' zurück (Cross-Contamination)."""
chat_id = "user:alice"
room_id = "room_a_123"
# Dispatch A setzt _room_context
token_a = self._set_room_context_origin(chat_id, room_id)
# Dispatch B überschreibt _room_context (gleicher chat_id, anderer Raum!)
# Simuliere: _CURRENT_TASK_TOKEN wird auf Token B gesetzt
self._CURRENT_TASK_TOKEN.set("different-token-not-matching")
with self._room_context_lock:
self._room_context[chat_id] = {
"origin_room": "room_b_456",
"task_token": "different-token-not-matching",
"timestamp": "2026-01-01T00:00:00+00:00",
}
# Jetzt: _CURRENT_TASK_TOKEN = "different-token-not-matching"
# _room_context[chat_id].task_token = "different-token-not-matching"
# → Match! Das ist korrekt für Dispatch B.
# ABER: Wenn Dispatch A's send() läuft, hat es token_a in _CURRENT_TASK_TOKEN
# (via copy_context). Simuliere das:
self._CURRENT_TASK_TOKEN.set(token_a)
# Jetzt: _CURRENT_TASK_TOKEN = token_a (von Dispatch A)
# _room_context[chat_id].task_token = "different-token-not-matching" (von Dispatch B)
# → MISMATCH! Cross-Contamination erkannt.
result = self._get_room_context_origin(chat_id)
self.assertEqual(
result, "",
"Token-Mismatch muss '' zurückgeben — Cross-Contamination erkannt"
)
# ── Test 14: Cross-Contamination: Dispatch A in Raum X, Dispatch B in Raum Y ──
def test_cross_contamination_two_dispatches_different_rooms(self):
"""Zwei Dispatches mit verschiedenen Task-Tokens → send() erkennt Cross-Contamination.
Szenario: Andreas ist gleichzeitig in 2 Räumen aktiv.
Dispatch A: Raum X (Protonbridge)
Dispatch B: Raum Y (Rocketchat-Plugin)
send() für Dispatch A erkennt Token-Mismatch → ignoriert _room_context,
fällt durch zu _user_rooms (nächste Priorität).
"""
chat_id = "user:andreas"
room_x = "room_protonbridge"
room_y = "room_rocketchat_plugin"
fallback_room = "room_fallback_general"
# ── Dispatch A: Protonbridge ──
token_a = self._set_room_context_origin(chat_id, room_x)
# ── Dispatch B: Rocketchat-Plugin (überschreibt _room_context) ──
token_b = self._set_room_context_origin(chat_id, room_y)
# _room_context[chat_id] = {origin_room: room_y, task_token: token_b, ...}
# ── send() für Dispatch A ──
# ContextVars sind LEER (Stream-Retry in neuem Task)
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
# _CURRENT_TASK_TOKEN auf token_a setzen (wie im copy_context von Dispatch A)
self._CURRENT_TASK_TOKEN.set(token_a)
# _user_rooms hat einen Fallback-Raum (nächste Priorität nach _room_context)
self.adapter._user_rooms = {chat_id: [fallback_room]}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response for Dispatch A")
)
# Verify: send() hat Cross-Contamination erkannt (_room_context ignoriert)
# und ist auf _user_rooms zurückgefallen (nächste Priorität).
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, fallback_room,
f"Cross-Contamination erkannt → send() muss _room_context ignorieren "
f"und auf _user_rooms ({fallback_room}) zurückfallen. "
f"Bekam: {real_room_id}"
)
# ── Test 15: Stream-Retry (gleicher Task, gleiches Token) ──
def test_stream_retry_same_task_same_token(self):
"""Stream-Retry: gleicher Task, gleiches Token → send() verwendet _room_context.
Szenario: ContextVar ist leer (neuer asyncio-Task), aber _CURRENT_TASK_TOKEN
wurde via copy_context() eingefroren und matcht den _room_context-Eintrag.
"""
chat_id = "user:alice"
room_id = "room_stream_retry_123"
# _set_room_context_origin setzt Token + _CURRENT_TASK_TOKEN
token = self._set_room_context_origin(chat_id, room_id)
# Simuliere Stream-Retry: ContextVars sind LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
# _CURRENT_TASK_TOKEN ist noch gesetzt (via copy_context eingefroren)
# → Token-Match!
self.adapter._user_rooms = {}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, room_id,
f"Stream-Retry mit Token-Match muss _room_context verwenden. "
f"Erwartet: {room_id}, bekam: {real_room_id}"
)
# ── Test 16: Stream-Retry ohne Token (TTL gültig) ──
def test_stream_retry_no_token_ttl_valid(self):
"""Stream-Retry ohne Token (_CURRENT_TASK_TOKEN leer) → TTL-Check gültig.
Szenario: _CURRENT_TASK_TOKEN ist leer (nicht via copy_context eingefroren),
aber der _room_context-Eintrag ist frisch (< 30 Min) → TTL-Check erlaubt Verwendung.
"""
chat_id = "user:alice"
room_id = "room_ttl_valid_123"
# Setze _room_context mit Token (wie _set_room_context_origin)
self._set_room_context_origin(chat_id, room_id)
# Simuliere Stream-Retry: ContextVars LEER, Token LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("") # Token verloren (nicht via copy_context)
self.adapter._user_rooms = {}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, room_id,
f"Stream-Retry ohne Token, TTL gültig → muss _room_context verwenden. "
f"Erwartet: {room_id}, bekam: {real_room_id}"
)
# ── Test 17: TTL abgelaufen → Fallback auf nächste Priorität ──
def test_ttl_expired_falls_through_to_next_priority(self):
"""TTL abgelaufen → send() ignoriert _room_context, fällt durch zu _user_rooms.
Szenario: _room_context-Eintrag ist älter als 30 Min, ContextVar leer,
Token leer. send() muss den Eintrag ignorieren und auf _user_rooms zurückfallen.
"""
chat_id = "user:alice"
stale_room = "room_stale_old"
user_rooms_room = "room_user_rooms_fallback"
# Setze _room_context mit altem Timestamp (31 Min alt)
old_time = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(
seconds=self._ROOM_CONTEXT_TTL_SECONDS + 60
)
with self._room_context_lock:
self._room_context[chat_id] = {
"origin_room": stale_room,
"task_token": "old-token",
"timestamp": old_time.isoformat(),
}
# ContextVars LEER, Token LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
# _user_rooms hat einen Fallback-Raum
self.adapter._user_rooms = {chat_id: [user_rooms_room]}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, user_rooms_room,
f"TTL abgelaufen → send() muss _room_context ({stale_room}) ignorieren "
f"und auf _user_rooms ({user_rooms_room}) zurückfallen. "
f"Bekam: {real_room_id}"
)
# ── Test 18: _get_room_context_origin direkt — TTL abgelaufen ──
def test_get_room_context_origin_ttl_expired(self):
"""_get_room_context_origin direkt: TTL abgelaufen → '' zurück."""
chat_id = "user:alice"
room_id = "room_expired_123"
# Setze _room_context mit altem Timestamp
old_time = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(
seconds=self._ROOM_CONTEXT_TTL_SECONDS + 60
)
with self._room_context_lock:
self._room_context[chat_id] = {
"origin_room": room_id,
"task_token": "old-token",
"timestamp": old_time.isoformat(),
}
# Kein Token im ContextVar
self._CURRENT_TASK_TOKEN.set("")
result = self._get_room_context_origin(chat_id)
self.assertEqual(
result, "",
"TTL abgelaufen → _get_room_context_origin muss '' zurückgeben"
)
# ── Test 19: _get_room_context_origin direkt — TTL gültig ──
def test_get_room_context_origin_ttl_valid(self):
"""_get_room_context_origin direkt: TTL gültig → origin_room zurück."""
chat_id = "user:alice"
room_id = "room_ttl_ok_123"
# Setze _room_context mit frischem Timestamp
self._set_room_context_origin(chat_id, room_id)
# Kein Token im ContextVar (simuliert Stream-Retry ohne copy_context)
self._CURRENT_TASK_TOKEN.set("")
result = self._get_room_context_origin(chat_id)
self.assertEqual(
result, room_id,
"TTL gültig → _get_room_context_origin muss origin_room zurückgeben"
)
# ── Test 20: Backward-Kompatibilität — alter Eintrag ohne timestamp/task_token ──
def test_backward_compat_old_entry_no_timestamp(self):
"""Alter _room_context-Eintrag ohne timestamp/task_token → trotzdem verwenden.
Backward-Kompatibilität: Einträge die vor diesem Fix geschrieben wurden
haben kein task_token und keinen timestamp. Diese werden trotzdem verwendet.
"""
chat_id = "user:alice"
room_id = "room_old_format"
# Alter Eintrag: nur origin_room, kein task_token, kein timestamp
with self._room_context_lock:
self._room_context[chat_id] = {"origin_room": room_id}
# ContextVars LEER, Token LEER
self._CURRENT_ORIGIN_ROOM.set("")
self._THEMATIC_TARGET_ROOM.set("")
self._CURRENT_TASK_TOKEN.set("")
self.adapter._user_rooms = {}
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
result = asyncio.run(
self.adapter.send(chat_id=chat_id, content="Test response")
)
self.adapter._post_message_with_retry.assert_called_once()
call_args = self.adapter._post_message_with_retry.call_args
real_room_id = call_args[0][0]
self.assertEqual(
real_room_id, room_id,
f"Backward-Kompatibilität: alter Eintrag ohne Token/Timestamp "
f"muss trotzdem verwendet werden. Erwartet: {room_id}, bekam: {real_room_id}"
)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+1
View File
@@ -157,6 +157,7 @@ def _build_mock_adapter(room_map_path: str):
adapter._recent_auto_routes = {} adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {} adapter._explicit_switch_sticky = {}
adapter._clarify_state = {} adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {} # FIX 2 (P0): ISSUE 3
adapter._onboarding_state = {} adapter._onboarding_state = {}
adapter._room_map_summary = "" adapter._room_map_summary = ""
+1
View File
@@ -256,6 +256,7 @@ def _build_mock_adapter(room_map_path: str):
adapter._recent_auto_routes = {} adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {} adapter._explicit_switch_sticky = {}
adapter._clarify_state = {} adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {} # FIX 2 (P0): ISSUE 3
adapter._onboarding_state = {} adapter._onboarding_state = {}
adapter._room_map_summary = "" adapter._room_map_summary = ""
+1
View File
@@ -157,6 +157,7 @@ def _build_mock_adapter(room_map_path: str):
adapter._recent_auto_routes = {} adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {} adapter._explicit_switch_sticky = {}
adapter._clarify_state = {} adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {} # FIX 2 (P0): ISSUE 3
adapter._onboarding_state = {} adapter._onboarding_state = {}
adapter._room_map_summary = "" adapter._room_map_summary = ""
+529
View File
@@ -0,0 +1,529 @@
"""
Themenring Phase A — In-Memory Ringmatrix für menschenähnliche Kommunikation.
Herzstück der Multi-Room-Kommunikation: Andreas arbeitet gleichzeitig an
mehreren Themen in verschiedenen Räumen. Der Themenring speichert pro Raum
eine deque von TopicEntry-NamedTuples und erlaubt lock-free Reads via
Copy-on-Write-Snapshot (Reads greifen auf einen zwischengespeicherten
Deep-Copy zu, der nur nach Writes invalidiert und beim nächsten Read
neu aufgebaut wird — dadurch nie inkonsistent, aber nicht zwingend aktuell).
Architektur:
- Single-Reader-Multi-Writer Pattern: _lock schützt Schreibzugriffe,
_read_snapshot erlaubt lock-free Reads via copy-on-write.
- GC-Strategie: Beim Insert werden max_per_room und global_max geprüft,
älteste ephemeral-Einträge werden zuerst entfernt.
- Periodischer TTL-Sweep: Alle 5 Minuten werden abgelaufene Einträge entfernt.
Integration:
- _process_incoming() füllt den Ring NACH Archivar-Klassifikation (T1).
- send() liest den Ring (Prio 1) VOR _room_context-Fallback.
"""
from __future__ import annotations
import copy
import logging
import threading
import time
from collections import deque
from datetime import datetime, timezone
from typing import Dict, List, NamedTuple, Optional
from .config import (
TOPIC_RING_GLOBAL_MAX,
TOPIC_RING_MAX_PER_ROOM,
TOPIC_RING_PRUNE_INTERVAL,
TOPIC_RING_TTL_EPHEMERAL,
TOPIC_RING_TTL_PERSISTENT,
TOPIC_RING_TTL_SESSION,
)
logger = logging.getLogger(__name__)
# ── TopicEntry NamedTuple ────────────────────────────────────────────────────
class TopicEntry(NamedTuple):
"""Ein einzelner Eintrag im Themenring.
Attributes:
topic: Das extrahierte Thema (z.B. "RC-Plugin Deployment", "LAN-Doku Update").
room_id: Die Rocket.Chat Raum-ID, in der das Thema aktiv ist.
origin_room: Der Ursprungsraum, aus dem die Nachricht kam.
thematic_target: Der thematische Zielraum (aus Archivar-Klassifikation).
timestamp: ISO-8601-Zeitstempel der Erstellung.
ttl: 'ephemeral' (1h), 'session' (24h) oder 'persistent' (unendlich).
user_id: Der Benutzer, der die Nachricht gesendet hat (z.B. "user:andreas").
source: 'archivar' (aus Klassifikation), 'message' (aus Nachrichtentext),
oder 'manual' (manuell gesetzt).
"""
topic: str
room_id: str
origin_room: str
thematic_target: str
timestamp: str
ttl: str # 'ephemeral' | 'session' | 'persistent'
user_id: str
source: str # 'archivar' | 'message' | 'manual'
# ── TTL-Mapping ───────────────────────────────────────────────────────────────
_TTL_SECONDS: Dict[str, float] = {
"ephemeral": TOPIC_RING_TTL_EPHEMERAL,
"session": TOPIC_RING_TTL_SESSION,
"persistent": TOPIC_RING_TTL_PERSISTENT,
}
def _is_expired(entry: TopicEntry, now_ts: Optional[float] = None) -> bool:
"""Prüft, ob ein TopicEntry TTL-abgelaufen ist.
Args:
entry: Der zu prüfende Eintrag.
now_ts: Aktueller Unix-Timestamp (für Testbarkeit).
Returns:
True wenn der Eintrag abgelaufen ist.
"""
ttl_seconds = _TTL_SECONDS.get(entry.ttl, TOPIC_RING_TTL_EPHEMERAL)
if ttl_seconds == float("inf"):
return False
if now_ts is None:
now_ts = time.time()
try:
created = datetime.fromisoformat(entry.timestamp)
created_ts = created.timestamp()
except (ValueError, TypeError):
return True # unparseable timestamp → als expired behandeln
return (now_ts - created_ts) > ttl_seconds
# ── Topic-Extraktion ──────────────────────────────────────────────────────────
def extract_topic_from_message(text: str, max_len: int = 80, min_len: int = 8) -> str:
"""Extrahiert ein Topic aus einem Nachrichtentext.
Für nicht-Archivar-Nachrichten: erste sinnvolle Phrase aus dem Text.
Filtert Zeilenumbrüche, überflüssige Whitespaces und kürzt auf max_len.
Args:
text: Der Nachrichtentext.
max_len: Maximale Länge des extrahierten Topics.
min_len: Minimale Länge — kürzere Texte werden verworfen.
Returns:
Extrahiertes Topic oder leerer String wenn zu kurz.
"""
if not text:
return ""
# Erste Zeile, Zeilenumbrüche ersetzen
first_line = text.split("\n")[0].strip()
# Auf max_len kürzen, aber an Wortgrenze
if len(first_line) > max_len:
# An letztem Leerzeichen vor max_len abschneiden
truncated = first_line[:max_len]
last_space = truncated.rfind(" ")
if last_space > min_len:
first_line = truncated[:last_space]
else:
first_line = truncated
# Mindestlänge prüfen
if len(first_line) < min_len:
return ""
return first_line
def extract_topic_from_archivar_decision(
decision_target_room: str,
decision_category: str = "",
room_name: str = "",
) -> str:
"""Extrahiert ein Topic aus einer Archivar-Routing-Entscheidung.
Bei Archivar decision=butler/stay/alarm → topic = target room name
oder klassifizierter Intent.
Args:
decision_target_room: Zielraum-ID aus der RoutingDecision.
decision_category: Kategorie (direct_question, work_order, etc.).
room_name: Anzeigename des Zielraums.
Returns:
Extrahiertes Topic oder leerer String.
"""
if room_name:
return room_name.lstrip("#")
if decision_category:
return f"Archivar: {decision_category}"
return ""
# ── TopicRing Klasse ──────────────────────────────────────────────────────────
class TopicRing:
"""In-Memory Ringmatrix für Multi-Topic-Kommunikation.
Single-Reader-Multi-Writer Pattern:
- _lock schützt _rings + _dirty bei Schreibzugriffen.
- _read_snapshot erlaubt lock-free Reads via copy-on-write.
- Beim Write: with _lock: mutate, _dirty=True, _read_snapshot=None.
- Beim Read: snap=_read_snapshot; if None: with _lock: deepcopy, set snapshot.
Usage::
ring = TopicRing()
ring.add(entry)
active = ring.get_active_topic_for_chat("user:andreas")
"""
def __init__(self) -> None:
self._rings: Dict[str, deque[TopicEntry]] = {}
self._lock = threading.Lock()
self._read_snapshot: Optional[Dict[str, deque[TopicEntry]]] = None
self._dirty: bool = False
self._last_prune: float = time.time()
self._total_entries: int = 0
# ── Snapshot-Helfer ──────────────────────────────────────────────────
def _get_snapshot(self) -> Dict[str, deque[TopicEntry]]:
"""Liefert einen lock-free lesbaren Snapshot der Ring-Daten.
Snapshot spiegelt den Stand zum Zeitpunkt der letzten Schreib-Invalidation.
Lock-free Reads sind konsistent zu diesem Zeitpunkt, NICHT zwingend aktuell.
Erst beim nächsten Write wird der Snapshot invalidiert und beim nächsten
Read neu aufgebaut.
Returns:
Deep-Copy der _rings-Datenstruktur.
"""
snap = self._read_snapshot
if snap is not None:
return snap
with self._lock:
snap = copy.deepcopy(self._rings)
self._read_snapshot = snap
self._dirty = False
return snap
def _invalidate_snapshot(self) -> None:
"""Invalidiert den Read-Snapshot nach einem Schreibzugriff.
Setzt _read_snapshot auf None und _dirty auf True. Der nächste
Read-Aufruf von _get_snapshot() baut dann einen neuen Snapshot
via Deep-Copy auf. Dadurch sind Reads immer konsistent zum Stand
des letzten Writes — nicht zwingend aktuell, aber nie inkonsistent.
"""
self._read_snapshot = None
self._dirty = True
# ── GC / Pruning ─────────────────────────────────────────────────────
def _prune_expired(self, now_ts: Optional[float] = None) -> int:
"""Entfernt alle TTL-abgelaufenen Einträge aus allen Räumen.
Args:
now_ts: Aktueller Unix-Timestamp (für Testbarkeit).
Returns:
Anzahl der entfernten Einträge.
"""
if now_ts is None:
now_ts = time.time()
removed = 0
with self._lock:
for room_id in list(self._rings.keys()):
dq = self._rings[room_id]
new_dq = deque(
entry for entry in dq if not _is_expired(entry, now_ts)
)
removed += len(dq) - len(new_dq)
if new_dq:
self._rings[room_id] = new_dq
else:
del self._rings[room_id]
self._total_entries -= removed
self._invalidate_snapshot()
if removed:
logger.debug(
"TopicRing: Pruned %d expired entries, %d remaining",
removed, self._total_entries,
)
return removed
def _gc_global(self) -> int:
"""Entfernt älteste ephemeral-Einträge wenn global_max überschritten.
Returns:
Anzahl der entfernten Einträge.
"""
removed = 0
while self._total_entries > TOPIC_RING_GLOBAL_MAX:
# Finde den ältesten ephemeral-Eintrag über alle Räume
oldest_ephemeral: Optional[tuple[str, TopicEntry]] = None
oldest_ts = float("inf")
for room_id, dq in list(self._rings.items()):
for entry in dq:
if entry.ttl == "ephemeral":
try:
ts = datetime.fromisoformat(entry.timestamp).timestamp()
except (ValueError, TypeError):
ts = 0
if ts < oldest_ts:
oldest_ts = ts
oldest_ephemeral = (room_id, entry)
if oldest_ephemeral is None:
# Keine ephemeral-Einträge mehr → ältesten session-Eintrag nehmen
for room_id, dq in list(self._rings.items()):
for entry in dq:
if entry.ttl == "session":
try:
ts = datetime.fromisoformat(entry.timestamp).timestamp()
except (ValueError, TypeError):
ts = 0
if ts < oldest_ts:
oldest_ts = ts
oldest_ephemeral = (room_id, entry)
if oldest_ephemeral is None:
break # Nichts mehr zu entfernen
room_id, entry = oldest_ephemeral
dq = self._rings[room_id]
try:
dq.remove(entry)
except ValueError:
pass # Race: bereits entfernt
if not dq:
del self._rings[room_id]
self._total_entries -= 1
removed += 1
return removed
def _gc_room(self, room_id: str) -> int:
"""Entfernt ältesten Eintrag eines Raums wenn max_per_room überschritten.
Args:
room_id: Die Raum-ID.
Returns:
Anzahl der entfernten Einträge (0 oder 1).
"""
dq = self._rings.get(room_id)
if dq is None or len(dq) <= TOPIC_RING_MAX_PER_ROOM:
return 0
# Ältesten Eintrag entfernen (links = älteste)
dq.popleft()
self._total_entries -= 1
if not dq:
del self._rings[room_id]
return 1
def _maybe_prune(self) -> None:
"""Periodischer TTL-Sweep (alle PRUNE_INTERVAL Sekunden)."""
now = time.time()
if now - self._last_prune >= TOPIC_RING_PRUNE_INTERVAL:
self._prune_expired(now_ts=now)
self._last_prune = now
# ── Public API ────────────────────────────────────────────────────────
def add(self, entry: TopicEntry) -> None:
"""Fügt einen TopicEntry in den Ring ein.
Führt GC durch:
1. Periodischer TTL-Sweep (alle 5 Min).
2. max_per_room-Prüfung → ältesten Eintrag des Raums entfernen.
3. global_max-Prüfung → älteste ephemeral-Einträge entfernen.
Args:
entry: Der einzufügende TopicEntry.
"""
with self._lock:
self._maybe_prune()
if entry.room_id not in self._rings:
self._rings[entry.room_id] = deque()
self._rings[entry.room_id].append(entry)
self._total_entries += 1
# GC: max_per_room
self._gc_room(entry.room_id)
# GC: global_max
self._gc_global()
self._invalidate_snapshot()
logger.debug(
"TopicRing: Added topic='%s' room=%s ttl=%s (total=%d)",
entry.topic[:40], entry.room_id[:8], entry.ttl, self._total_entries,
)
def get_recent(self, room_id: str, n: int = 5) -> List[TopicEntry]:
"""Liefert die n neuesten Topic-Einträge für einen Raum.
Args:
room_id: Die Raum-ID.
n: Anzahl der zurückzugebenden Einträge.
Returns:
Liste der neuesten TopicEntry-Objekte (neueste zuerst).
"""
snap = self._get_snapshot()
dq = snap.get(room_id, deque())
# Neueste zuerst (rechts = neueste)
return list(reversed(list(dq)))[:n]
def get_active_topic(self, room_id: str) -> Optional[TopicEntry]:
"""Liefert den aktuell aktiven Topic für einen Raum.
Der aktive Topic ist der neueste nicht-abgelaufene Eintrag.
Args:
room_id: Die Raum-ID.
Returns:
Den aktiven TopicEntry oder None.
"""
snap = self._get_snapshot()
dq = snap.get(room_id, deque())
if not dq:
return None
# Neuesten Eintrag nehmen (rechts)
entry = dq[-1]
if _is_expired(entry):
return None
return entry
def get_active_topic_for_chat(self, chat_id: str) -> Optional[str]:
"""Liefert den origin_room für den aktiven Topic eines Chats.
Wird von send() als Prio 1 verwendet: Wenn der Themenring einen
aktiven Topic für diesen chat_id hat → verwende dessen origin_room.
Args:
chat_id: Der virtuelle Chat-ID (z.B. "user:andreas").
Returns:
origin_room des aktiven Topics oder None.
"""
snap = self._get_snapshot()
# Suche in allen Räumen nach Einträgen für diesen user_id
best_entry: Optional[TopicEntry] = None
best_ts = 0.0
for room_id, dq in snap.items():
for entry in dq:
if entry.user_id == chat_id and not _is_expired(entry):
try:
ts = datetime.fromisoformat(entry.timestamp).timestamp()
except (ValueError, TypeError):
ts = 0
if ts > best_ts:
best_ts = ts
best_entry = entry
if best_entry is None:
return None
# Priorität: thematic_target (wenn gesetzt) > origin_room
if best_entry.thematic_target:
return best_entry.thematic_target
return best_entry.origin_room
def clear(self, room_id: Optional[str] = None) -> int:
"""Leert den Ring für einen Raum oder alle Räume.
Args:
room_id: Raum-ID zum Leeren, oder None für alle Räume.
Returns:
Anzahl der entfernten Einträge.
"""
with self._lock:
if room_id is None:
removed = self._total_entries
self._rings.clear()
self._total_entries = 0
else:
dq = self._rings.pop(room_id, deque())
removed = len(dq)
self._total_entries -= removed
self._invalidate_snapshot()
return removed
def move_gc(self, from_room: str, to_room: str) -> int:
"""Verschiebt alle Einträge von einem Raum in einen anderen.
Nützlich wenn ein Raum umbenannt oder zusammengeführt wird.
Args:
from_room: Quell-Raum-ID.
to_room: Ziel-Raum-ID.
Returns:
Anzahl der verschobenen Einträge.
"""
with self._lock:
dq = self._rings.pop(from_room, deque())
if not dq:
return 0
if to_room not in self._rings:
self._rings[to_room] = deque()
# Einträge mit aktualisierter room_id neu erstellen
moved = 0
for entry in dq:
new_entry = TopicEntry(
topic=entry.topic,
room_id=to_room,
origin_room=entry.origin_room,
thematic_target=entry.thematic_target,
timestamp=entry.timestamp,
ttl=entry.ttl,
user_id=entry.user_id,
source=entry.source,
)
self._rings[to_room].append(new_entry)
moved += 1
self._invalidate_snapshot()
return moved
@property
def total_entries(self) -> int:
"""Gesamtanzahl der Einträge über alle Räume."""
return self._total_entries
@property
def room_count(self) -> int:
"""Anzahl der Räume mit Einträgen."""
snap = self._get_snapshot()
return len(snap)
def stats(self) -> Dict[str, int]:
"""Liefert Statistiken über den Ring-Zustand.
Returns:
Dict mit total_entries, room_count, und counts pro TTL-Typ.
"""
snap = self._get_snapshot()
ephemeral = 0
session = 0
persistent = 0
for dq in snap.values():
for entry in dq:
if entry.ttl == "ephemeral":
ephemeral += 1
elif entry.ttl == "session":
session += 1
elif entry.ttl == "persistent":
persistent += 1
return {
"total_entries": self._total_entries,
"room_count": len(snap),
"ephemeral": ephemeral,
"session": session,
"persistent": persistent,
}
# ── Modul-Singleton ───────────────────────────────────────────────────────────
# Globale Instanz — wird von adapter.py importiert und verwendet.
# Tests können eigene Instanzen erstellen.
topic_ring = TopicRing()
+1 -1
View File
@@ -1,4 +1,4 @@
name: rocketchat-platform name: rocketchat
label: Rocket.Chat label: Rocket.Chat
kind: platform kind: platform
version: 1.0.0 version: 1.0.0
+2 -2
View File
@@ -20,8 +20,8 @@ import urllib.parse
# Inlined from tools.registry — avoids import conflict with the plugin's # Inlined from tools.registry — avoids import conflict with the plugin's
# own tools.py module (which shadows the core tools/ package when the # own rc_tools.py module (which used to shadow the core tools/ package when
# plugin directory is on sys.path). # the plugin directory is on sys.path).
def tool_error(message, **extra) -> str: def tool_error(message, **extra) -> str:
result = {"error": str(message)} result = {"error": str(message)}
if extra: if extra:
+60 -2
View File
@@ -413,7 +413,7 @@ class TestPulseControllerPauseInAsyncMode:
# Setze cancel_pending # Setze cancel_pending
pc.cancel_pending() pc.cancel_pending()
assert pc._cancel_pending is True assert pc._cancel_pending_event.is_set()
# _pulse_tick sollte übersprungen werden # _pulse_tick sollte übersprungen werden
pc._pulse_tick() pc._pulse_tick()
@@ -421,7 +421,7 @@ class TestPulseControllerPauseInAsyncMode:
# set_status sollte NICHT aufgerufen worden sein # set_status sollte NICHT aufgerufen worden sein
mock_ddp.set_status.assert_not_called() mock_ddp.set_status.assert_not_called()
# cancel_pending sollte zurückgesetzt sein # cancel_pending sollte zurückgesetzt sein
assert pc._cancel_pending is False assert not pc._cancel_pending_event.is_set()
# ═══════════════════════════════════════════════════════════════════════════ # ═══════════════════════════════════════════════════════════════════════════
@@ -481,3 +481,61 @@ class TestLegacyTimerSetStatusRemainsSync:
adapter.ddp.set_status("away") adapter.ddp.set_status("away")
mock_ddp.set_status.assert_called_with("away") mock_ddp.set_status.assert_called_with("away")
# ═══════════════════════════════════════════════════════════════════════════
# Test 11: B1 — disconnect clears pending Futures with DDPNotConnected
# ═══════════════════════════════════════════════════════════════════════════
class TestDisconnectClearsPendingFutures:
"""B1: disconnect() löst alle pending Futures mit DDPNotConnected auf."""
def test_disconnect_clears_pending_futures(self):
"""Engine erstellt, set_status_async aufrufen, disconnect() → DDPNotConnected."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock()
async def _run():
# Starte set_status_async — registriert einen Future
task = asyncio.create_task(client.set_status_async("online", timeout=5.0))
await asyncio.sleep(0.05)
# Verifiziere: Future ist registriert
with client._result_lock:
assert len(client._pending_results) == 1
# Disconnect — muss den Future mit DDPNotConnected auflösen
client.disconnect()
# Der Task sollte jetzt DDPNotConnected werfen
with pytest.raises(DDPNotConnected) as exc_info:
await task
assert "connection closed" in str(exc_info.value).lower()
# _pending_results muss leer sein
with client._result_lock:
assert len(client._pending_results) == 0
asyncio.run(_run())
def test_reader_loop_exit_clears_pending_futures(self):
"""Simuliere reader-loop exit: _cancel_pending_results wird aufgerufen."""
client = _make_ddp_client(connected=True)
client._send_json = MagicMock()
# Registriere einen pending Future manuell
future = concurrent.futures.Future()
with client._result_lock:
client._pending_results["st9999999999_1"] = future
# Simuliere reader-loop exit (wie in _reader_loop nach while-Schleife)
client._cancel_pending_results()
# Future muss DDPNotConnected haben
assert future.done()
with pytest.raises(DDPNotConnected):
future.result()
# Store muss leer sein
with client._result_lock:
assert len(client._pending_results) == 0
+117 -6
View File
@@ -139,12 +139,13 @@ class TestUpdateOnlyServiceRestart:
"""Gateway-Dienst muss nach dem Update neu gestartet werden.""" """Gateway-Dienst muss nach dem Update neu gestartet werden."""
def test_systemctl_restart_present(self): def test_systemctl_restart_present(self):
"""systemctl --user restart hermes-gateway ist im --update-only Block.""" """restart_gateway (oder systemctl restart) ist im --update-only Block."""
content = _read_install_sh() content = _read_install_sh()
update_section = _extract_update_only_section(content) update_section = _extract_update_only_section(content)
assert "systemctl --user restart hermes-gateway" in update_section, ( # restart_gateway ist die Funktion, die systemctl --user restart kapselt
f"systemctl restart fehlt im --update-only Block:\n{update_section}" assert "restart_gateway" in update_section, (
f"restart_gateway fehlt im --update-only Block:\n{update_section}"
) )
def test_no_restart_flag_respected(self): def test_no_restart_flag_respected(self):
@@ -158,15 +159,15 @@ class TestUpdateOnlyServiceRestart:
) )
def test_restart_after_deploy(self): def test_restart_after_deploy(self):
"""systemctl restart kommt NACH deploy_plugin.""" """restart_gateway kommt NACH deploy_plugin."""
content = _read_install_sh() content = _read_install_sh()
update_section = _extract_update_only_section(content) update_section = _extract_update_only_section(content)
deploy_pos = update_section.find("deploy_plugin") deploy_pos = update_section.find("deploy_plugin")
restart_pos = update_section.find("systemctl --user restart hermes-gateway") restart_pos = update_section.find("restart_gateway")
assert restart_pos > deploy_pos, ( assert restart_pos > deploy_pos, (
f"restart ({restart_pos}) muss NACH deploy_plugin ({deploy_pos}) kommen" f"restart_gateway ({restart_pos}) muss NACH deploy_plugin ({deploy_pos}) kommen"
) )
@@ -361,3 +362,113 @@ class TestDeployPluginCacheCleanup:
assert "rm -rf" in func_body, ( assert "rm -rf" in func_body, (
f"deploy_plugin() nutzt kein rm -rf für __pycache__:\n{func_body[:500]}" f"deploy_plugin() nutzt kein rm -rf für __pycache__:\n{func_body[:500]}"
) )
# ═══════════════════════════════════════════════════════════════════════════
# Test 8: tools.py Cleanup (V8.6: rename tools.py → rc_tools.py)
# ═══════════════════════════════════════════════════════════════════════════
class TestToolsPyCleanup:
"""Alte tools.py muss in deploy_plugin() und --update-only gelöscht werden."""
def test_deploy_plugin_removes_old_tools_py(self):
"""deploy_plugin() löscht alte tools.py."""
content = _read_install_sh()
match = re.search(
r'deploy_plugin\(\)\s*\{.*?(?=\n\}\n\n#)',
content,
re.DOTALL,
)
assert match, "deploy_plugin()-Funktion nicht gefunden"
func_body = match.group(0)
assert "tools.py" in func_body, (
f"deploy_plugin() enthält keine tools.py-Bereinigung:\n{func_body[:500]}"
)
assert "rc_tools.py" in func_body, (
f"deploy_plugin() erwähnt rc_tools.py nicht:\n{func_body[:500]}"
)
def test_update_only_removes_old_tools_py(self):
"""--update-only Block löscht alte tools.py."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
assert "tools.py" in update_section, (
f"--update-only Block enthält keine tools.py-Bereinigung:\n{update_section}"
)
assert "rc_tools.py" in update_section, (
f"--update-only Block erwähnt rc_tools.py nicht:\n{update_section}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 9: Stale ~/.hermes/plugins/rocketchat/ Cleanup (V8.6)
# ═══════════════════════════════════════════════════════════════════════════
class TestStalePluginDirCleanup:
"""--update-only muss den alten falschen Pfad ~/.hermes/plugins/rocketchat/ bereinigen."""
def test_update_only_removes_stale_hermes_plugins_dir(self):
"""--update-only Block löscht ~/.hermes/plugins/rocketchat/."""
content = _read_install_sh()
update_section = _extract_update_only_section(content)
assert ".hermes/plugins/rocketchat" in update_section, (
f"--update-only Block bereinigt nicht ~/.hermes/plugins/rocketchat/:\n{update_section}"
)
assert "rm -rf" in update_section, (
f"--update-only Block nutzt kein rm -rf für stale Pfad:\n{update_section}"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 10: Kein hardcoded python3.13 (V8.6: dynamischer site-packages-Pfad)
# ═══════════════════════════════════════════════════════════════════════════
class TestNoHardcodedPythonVersion:
"""install.sh darf keinen hardcoded python3.13-Pfad enthalten."""
def test_no_hardcoded_python3_13_in_site_packages_path(self):
"""Kein 'python3.13/site-packages' als hartcodierter Pfad (außer Fallback/Dry-Run)."""
content = _read_install_sh()
# python3.13 darf nur in Kommentaren, Fallback-Strings, Dry-Run-Platzhaltern
# oder apt-Install vorkommen. Aber NICHT als hartcodierter site-packages-Pfad.
lines_with_python3_13 = [
line for line in content.split("\n")
if "python3.13" in line
]
for line in lines_with_python3_13:
if "site-packages" in line:
# Erlaubt: Fallback nach find_site_packages, Dry-Run-Platzhalter, Kommentare
ok = (
"find_site_packages" in line
or "||" in line
or "#" in line.strip()[:1]
or "<PIPX_VENV>" in line # Dry-Run-Platzhalter
)
assert ok, (
f"Hardcoded python3.13/site-packages ohne Fallback:\n {line.strip()}"
)
def test_find_site_packages_used_for_dropin(self):
"""systemd drop-in nutzt find_site_packages (nicht hardcoded python3.13)."""
content = _read_install_sh()
# Der drop-in-Block muss find_site_packages aufrufen
match = re.search(
r'install_gateway_service\(\).*?(?=\n\}\n\n#)',
content,
re.DOTALL,
)
assert match, "install_gateway_service()-Funktion nicht gefunden"
func_body = match.group(0)
assert "find_site_packages" in func_body, (
f"install_gateway_service() nutzt nicht find_site_packages:\n{func_body[:500]}"
)
+210
View File
@@ -0,0 +1,210 @@
"""
P0: Test that _process_incoming() does not crash with UnboundLocalError.
Root cause: local `from datetime import datetime` inside _process_incoming()
shadowed the module-level `import datetime`. Python's scoping rules treat
`datetime` as a local variable for the ENTIRE function, so any use of
`datetime.datetime.now()` BEFORE the local import raises UnboundLocalError.
This test verifies that _process_incoming() can be called with a minimal
mock message without hitting the UnboundLocalError.
"""
from __future__ import annotations
import asyncio
import os
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
def _build_minimal_adapter():
"""Build a RocketChatAdapter with minimal mocks for _process_incoming."""
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = "/tmp/test_p0_datetime_room_map.json"
os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/test_p0_datetime_state.json"
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
from plugin.adapter import RocketChatAdapter, RocketChatREST
from plugin.archivar.conversation_history import ConversationHistory
from plugin.archivar.multiroom_context import MultiRoomContextRing
from plugin.archivar.adapter_integration import ArchivarMessageHandler
from plugin.archivar.room_map import RoomMap
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter.config = MagicMock()
adapter.config.extra = {}
adapter.platform = "rocketchat"
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
adapter.user = os.getenv("ROCKETCHAT_USER", "")
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
adapter.rest = RocketChatREST(adapter.base_url)
adapter.ddp = None
adapter._auth_token = None
adapter._user_id = None
adapter._rooms = []
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = threading.Event()
adapter._room_info = {}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
adapter._conversation_history = ConversationHistory(max_size=10)
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
adapter.archivar = ArchivarMessageHandler(
send_callback=lambda *a, **kw: None,
button_send_callback=lambda *a, **kw: None,
conversation_history=adapter._conversation_history,
)
# Create a minimal room-map.json
tmpdir = tempfile.mkdtemp()
room_map_path = Path(tmpdir) / "room-map.json"
import json
room_map_data = {
"version": 5,
"rooms": {
"room_test": {
"name": "#Test-Room",
"theme": "Test Room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
},
"excluded_rooms": [],
"butler_mode": "cognitive",
"fact_store_path": str(Path(tmpdir) / "docs"),
}
room_map_path.write_text(json.dumps(room_map_data))
adapter.archivar._room_map = RoomMap.load(room_map_path)
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {}
adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {}
adapter._onboarding_state = {}
adapter._room_map_summary = ""
# Mock the REST client
mock_rest = MagicMock(spec=RocketChatREST)
mock_rest.auth_token = "fake-token"
mock_rest.user_id = "fake-user-id"
mock_rest.post_message = MagicMock(return_value="msg_12345")
mock_rest.get_rooms = MagicMock(return_value=[
{"id": "room_test", "name": "Test-Room", "type": "c"},
])
adapter.rest = mock_rest
adapter._room_info = {
"room_test": {"name": "Test-Room", "type": "c"},
}
# Mock _dispatch_agent and handle_message
adapter._dispatch_agent = AsyncMock()
adapter.handle_message = AsyncMock()
# Initialize Archivar
asyncio.run(adapter.archivar.initialize())
# Mock gateway types
import plugin.adapter as _adapter_mod
_adapter_mod.MessageType = type('MessageType', (), {
'TEXT': 'text', 'BUTTON_CLICK': 'button_click',
})
_adapter_mod.MessageEvent = type('MessageEvent', (), {
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
})
_adapter_mod.SessionSource = type('SessionSource', (), {
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
})
_adapter_mod.Platform = str
_adapter_mod.PlatformConfig = type('PlatformConfig', (), {
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
})
return adapter
class TestP0DatetimeUnboundLocalError(unittest.TestCase):
"""P0: _process_incoming() must not crash with UnboundLocalError.
The bug: local `from datetime import datetime` inside _process_incoming()
shadowed the module-level `import datetime`. Python treats `datetime` as
a local variable for the ENTIRE function scope, so any use of
`datetime.datetime.now()` BEFORE the local import raises UnboundLocalError.
This test calls _process_incoming() with a minimal mock message and
verifies no UnboundLocalError is raised.
"""
@classmethod
def setUpClass(cls):
cls.adapter = _build_minimal_adapter()
def test_process_incoming_no_unbound_local_error(self):
"""_process_incoming() should not raise UnboundLocalError for datetime."""
msg_obj = {
"_id": "msg_test_001",
"rid": "room_test",
"msg": "Hallo, das ist eine Test-Nachricht",
"u": {"username": "andreas", "_id": "user_andreas"},
}
# This should NOT raise UnboundLocalError
try:
asyncio.run(self.adapter._process_incoming(msg_obj))
except UnboundLocalError as e:
self.fail(
f"_process_incoming() raised UnboundLocalError: {e}\n"
"Root cause: local 'from datetime import datetime' shadows "
"module-level 'import datetime'."
)
def test_process_incoming_with_button_response_no_unbound_local_error(self):
"""Button response path should also not raise UnboundLocalError."""
msg_obj = {
"_id": "msg_btn_001",
"rid": "room_test",
"msg": "FAKT::1",
"u": {"username": "andreas", "_id": "user_andreas"},
}
try:
asyncio.run(self.adapter._process_incoming(msg_obj))
except UnboundLocalError as e:
self.fail(
f"_process_incoming() raised UnboundLocalError on button path: {e}"
)
def test_datetime_module_still_accessible(self):
"""Verify that datetime.datetime.now() works (module-level import intact)."""
import datetime
result = datetime.datetime.now(datetime.timezone.utc)
self.assertIsNotNone(result)
# Verify it's a datetime object, not a module
self.assertTrue(hasattr(result, 'isoformat'))
if __name__ == "__main__":
unittest.main()
+312
View File
@@ -0,0 +1,312 @@
"""
P0 Integration-Test: Onboarding-Button-Klick setzt Raum-Theme korrekt.
ROOT CAUSE: button_builder.py setzte msg = prefix (nur 'ONBOARD:<rid>'),
ohne '::' Suffix. _process_onboarding_response erwartet '::' als Trigger
fuer Button-Klick-Handler. Ohne '::' -> Fallthrough zu Text-Antwort-Handler
-> Theme wird mit Room-ID als Literal ueberschrieben (stille Korruption).
Dieser Test verifiziert:
1. ONBOARD:<rid>::select_<rid> wird als Button-Klick erkannt
2. _handle_onboarding_button_click wird aufgerufen (nicht interview answer)
3. build_button_attachments produziert korrekte msg-Payloads
4. Backward-compat: 2-Tupel ohne suffix -> msg = prefix
"""
from __future__ import annotations
import asyncio
import sys
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
# ═══════════════════════════════════════════════════════════════════════════
# Helpers
# ═══════════════════════════════════════════════════════════════════════════
def _make_mock_adapter():
"""Erzeugt einen minimalen Mock-Adapter mit Onboarding-State."""
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
# Grundlegende Attribute
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = MagicMock()
adapter._room_info = {}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {}
adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {} # FIX 2 (P0): ISSUE 3
adapter._room_map_summary = ""
# Mock REST
mock_rest = MagicMock()
mock_rest.auth_token = "fake-token"
mock_rest.user_id = "fake-user-id"
mock_rest.post_message = MagicMock(return_value="msg_12345")
adapter.rest = mock_rest
# Mock Archivar
mock_archivar = MagicMock()
mock_archivar._room_map = MagicMock()
mock_archivar._stats = {"onboarding_active": True}
mock_archivar._state = MagicMock()
adapter.archivar = mock_archivar
# Mock Post-Message
adapter._post_message_with_retry = AsyncMock(return_value=True)
# Mock _ask_onboarding_question (damit kein echter Rocket.Chat-Call)
adapter._ask_onboarding_question = AsyncMock()
# Mock _onboarding_next_room
adapter._onboarding_next_room = AsyncMock()
return adapter
# ═══════════════════════════════════════════════════════════════════════════
# Tests: Dispatch-Pfad
# ═══════════════════════════════════════════════════════════════════════════
class TestOnboardingButtonClickDispatch:
"""P0: ONBOARD:<rid>::select_<rid> wird als Button-Klick erkannt."""
def test_button_click_with_suffix_starts_interview(self):
"""ONBOARD:<rid>::select_<rid> -> _handle_onboarding_button_click
-> Interview wird gestartet (current_room_index=0, current_question=1)."""
adapter = _make_mock_adapter()
test_rid = "room_test_123"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#Testraum"},
],
"current_room_index": -1,
"current_question": 0,
"collected_data": {},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick mit :: Suffix (der Fix)
button_text = f"ONBOARD:{test_rid}::select_{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
state = adapter._onboarding_state
assert state["current_room_index"] == 0, (
f"current_room_index sollte 0 sein (Interview gestartet), "
f"ist aber {state['current_room_index']}"
)
assert state["current_question"] == 1, (
f"current_question sollte 1 sein (Frage 1: Theme), "
f"ist aber {state['current_question']}"
)
assert test_rid in state["collected_data"], (
f"collected_data sollte Eintrag fuer {test_rid} enthalten"
)
adapter._ask_onboarding_question.assert_called_once()
def test_button_click_without_suffix_is_silent_noop(self):
"""ONBOARD:<rid> ohne :: -> Fallthrough zu interview answer
-> current_q=0 -> early return (stiller No-Op, kein Interview)."""
adapter = _make_mock_adapter()
test_rid = "room_test_456"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#Bugraum"},
],
"current_room_index": -1,
"current_question": 0,
"collected_data": {},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick OHNE :: Suffix (alter Bug)
button_text = f"ONBOARD:{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
state = adapter._onboarding_state
# Kein Interview gestartet — stiller No-Op
assert state["current_room_index"] == -1, (
f"Ohne :: sollte kein Interview gestartet werden, "
f"current_room_index ist {state['current_room_index']}"
)
assert state["current_question"] == 0
# _ask_onboarding_question wurde NICHT aufgerufen
adapter._ask_onboarding_question.assert_not_called()
def test_button_click_without_suffix_corrupts_theme_during_interview(self):
"""Der eigentliche Bug: Wenn Interview laeuft (current_q=1),
wird ONBOARD:<rid> ohne :: als Theme-Text interpretiert
-> Theme = 'ONBOARD:<rid>' (stille Korruption)."""
adapter = _make_mock_adapter()
test_rid = "room_test_789"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#Korrumpiert"},
],
"current_room_index": 0,
"current_question": 1, # Frage 1: Theme
"collected_data": {
test_rid: {"theme": "", "keywords_100": [], "keywords_context": [], "catch_all": False},
},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick OHNE :: Suffix (alter Bug)
button_text = f"ONBOARD:{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
# BUG REPRODUZIERT: Theme wurde mit Room-ID als Literal ueberschrieben
state = adapter._onboarding_state
theme = state["collected_data"][test_rid]["theme"]
assert theme == f"ONBOARD:{test_rid}", (
f"BUG REPRODUZIERT: Theme wurde mit '{theme}' ueberschrieben "
f"(sollte NICHT die Room-ID als Literal enthalten)"
)
def test_button_click_with_suffix_does_not_corrupt_theme(self):
"""Mit :: Suffix: Button-Klick wird korrekt erkannt,
Theme bleibt unberuehrt (wird nicht mit Room-ID ueberschrieben)."""
adapter = _make_mock_adapter()
test_rid = "room_test_fixed"
adapter._onboarding_state = {
"missing_rooms": [
{"room_id": test_rid, "name": "#FixTest"},
],
"current_room_index": -1,
"current_question": 0,
"collected_data": {},
"operator_room_id": "dm_operator",
"skipped_rooms": [],
}
# Simuliere Button-Klick MIT :: Suffix (der Fix)
button_text = f"ONBOARD:{test_rid}::select_{test_rid}"
asyncio.run(adapter._process_onboarding_response(button_text, "dm_operator"))
state = adapter._onboarding_state
data = state["collected_data"].get(test_rid, {})
theme = data.get("theme", "")
assert theme == "", (
f"Theme sollte leer sein (''), ist aber '{theme}' — "
f"Room-ID wurde faelschlich als Theme gesetzt"
)
# ═══════════════════════════════════════════════════════════════════════════
# Tests: button_builder Payload
# ═══════════════════════════════════════════════════════════════════════════
class TestButtonBuilderPayload:
"""P0: build_button_attachments produziert korrekte msg-Payloads."""
def test_num_button_with_suffix_produces_double_colon(self):
"""3-Tupel (label, prefix, suffix) -> msg = 'prefix::suffix'."""
from plugin.archivar.button_builder import build_button_attachments
test_rid = "room_bb_test"
num_buttons = [
("Testraum", f"ONBOARD:{test_rid}", f"select_{test_rid}"),
]
attachments = build_button_attachments(
num_buttons, [], color="#1d74f5",
)
num_action = attachments[0]["actions"][0]
assert num_action["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}", (
f"num_button msg sollte 'ONBOARD:{test_rid}::select_{test_rid}' sein, "
f"ist aber '{num_action['msg']}'"
)
def test_special_button_without_suffix_uses_prefix_only(self):
"""3-Tupel (label, prefix, style) ohne suffix -> msg = prefix (backward-compat)."""
from plugin.archivar.button_builder import build_button_attachments
special_buttons = [
("⏭️ Überspringen", "ONBOARD", "default"),
]
attachments = build_button_attachments(
[], special_buttons, color="#1d74f5",
)
special_action = attachments[0]["actions"][0]
assert special_action["msg"] == "ONBOARD", (
f"special_button msg sollte 'ONBOARD' sein (backward-compat), "
f"ist aber '{special_action['msg']}'"
)
def test_two_tuple_backward_compat(self):
"""2-Tupel (label, prefix) ohne suffix -> msg = prefix (backward-compat)."""
from plugin.archivar.button_builder import build_button_attachments
num_buttons = [
("ReviewRaum", "REVIEW_ROOM_EDIT::rid123::edit"),
]
attachments = build_button_attachments(
num_buttons, [], color="#1d74f5",
)
num_action = attachments[0]["actions"][0]
assert num_action["msg"] == "REVIEW_ROOM_EDIT::rid123::edit", (
f"2-Tupel msg sollte unveraendert 'REVIEW_ROOM_EDIT::rid123::edit' sein, "
f"ist aber '{num_action['msg']}'"
)
def test_mixed_buttons(self):
"""Gemischt: num_buttons mit suffix, special_buttons ohne suffix."""
from plugin.archivar.button_builder import build_button_attachments
test_rid = "room_mixed"
num_buttons = [
("Raum A", f"ONBOARD:{test_rid}", f"select_{test_rid}"),
("Raum B", f"ONBOARD:other_rid", f"select_other_rid"),
]
special_buttons = [
("⏭️ Skip", "ONBOARD", "default"),
("⏰ Später", "ONBOARD", "default"),
]
attachments = build_button_attachments(
num_buttons, special_buttons, color="#1d74f5",
)
# Erstes Attachment: num_buttons
assert attachments[0]["actions"][0]["msg"] == f"ONBOARD:{test_rid}::select_{test_rid}"
assert attachments[0]["actions"][1]["msg"] == "ONBOARD:other_rid::select_other_rid"
# Zweites Attachment: special_buttons
assert attachments[1]["actions"][0]["msg"] == "ONBOARD"
assert attachments[1]["actions"][1]["msg"] == "ONBOARD"
+458
View File
@@ -0,0 +1,458 @@
"""
P1-Nacharbeit: Tests für Issue 5 — Widerspruchs-Routine (Undo/Rückhol-Logik).
Testet die Widerspruchs-Erkennung aus adapter.py _process_incoming()
(Zeilen 2510-2637):
- Keyword-Erkennung: 'passt hier nicht', 'gehört nicht hier', etc.
- Satzkontext-Whitelist: Wortgrenzen + Satzanfang/!-Check
- Zeitfenster: Auto-Route 10 Min, confirm_move 30 Min
- Lookup: direkter (auto-route) und inverser (confirm_move) Lookup
in _recent_auto_routes
"""
from __future__ import annotations
import re
import sys
import time
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from plugin.adapter import RocketChatAdapter
# ═══════════════════════════════════════════════════════════════════════════
# Hilfsfunktionen: Widerspruchs-Logik aus adapter.py extrahiert
# ═══════════════════════════════════════════════════════════════════════════
# Die Keywords aus adapter.py Z. 2515-2519
_WIDERSPRUCH_KEYWORDS = [
'halt', 'bleib hier', 'gehört hier her',
'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback',
'passt hier nicht', 'gehört nicht hier', 'falsch', 'doch nicht',
]
def _widerspruch_matches_sentence_context(kw: str, txt: str) -> bool:
"""Replikation der inline-Funktion aus adapter.py Z. 2522-2544.
Check if keyword matches with word boundaries AND is at sentence
start or in a sentence with an exclamation mark.
"""
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
pos = m.start()
# Search backwards for sentence start
sentence_start = 0
for i in range(pos - 1, -1, -1):
if txt[i] in '.!?\n':
sentence_start = i + 1
break
# Search forwards for sentence end
sentence_end = len(txt)
for i in range(pos, len(txt)):
if txt[i] in '.!?\n':
sentence_end = i
break
sentence = txt[sentence_start:sentence_end].strip()
# Whitelist: keyword at sentence start OR '!' in same sentence
if sentence.startswith(kw) or '!' in sentence:
return True
return False
def _is_widerspruch(text: str) -> bool:
"""Replikation der Widerspruchs-Erkennung aus adapter.py Z. 2546-2549."""
text_lower = text.lower()
return any(
_widerspruch_matches_sentence_context(kw, text_lower)
for kw in _WIDERSPRUCH_KEYWORDS
)
def _make_mock_adapter():
"""Erzeugt einen minimalen Mock-Adapter für Widerspruchs-Tests."""
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter._recent_auto_routes = {}
adapter._room_info = {}
adapter._session_room_preferences = {}
adapter.rest = MagicMock()
adapter.rest.delete_message = MagicMock(return_value=True)
adapter.rest.update_message = MagicMock(return_value=True)
return adapter
# ═══════════════════════════════════════════════════════════════════════════
# Test 3+4: Keyword-Erkennung
# ═══════════════════════════════════════════════════════════════════════════
class TestWiderspruchKeywordRecognition:
"""Tests für die Keyword-Erkennung der Widerspruchs-Routine."""
def test_keyword_passt_hier_nicht_recognized(self):
"""User sagt 'passt hier nicht' → Keyword erkannt, Widerspruch ausgelöst."""
# Keyword muss am Satzanfang stehen oder ! im Satz haben
# (Satzkontext-Whitelist aus adapter.py)
text = "Passt hier nicht! Das muss zurück in den anderen Raum"
assert _is_widerspruch(text), (
f"'passt hier nicht' sollte als Widerspruch erkannt werden in: '{text}'"
)
def test_keyword_gehoert_nicht_hier_recognized(self):
"""User sagt 'gehört nicht hier' → Keyword erkannt."""
text = "Gehört nicht hier! Die Nachricht ist falsch einsortiert"
assert _is_widerspruch(text), (
f"'gehört nicht hier' sollte als Widerspruch erkannt werden in: '{text}'"
)
def test_keyword_falscher_raum_recognized(self):
"""User sagt 'falscher raum' → Keyword erkannt."""
text = "Falscher Raum! Das Thema gehört woanders hin"
assert _is_widerspruch(text), (
f"'falscher raum' sollte als Widerspruch erkannt werden in: '{text}'"
)
def test_keyword_zurueck_recognized(self):
"""User sagt 'zurück' → Keyword erkannt."""
text = "Zurück! Das war ein Versehen"
assert _is_widerspruch(text), (
f"'zurück' sollte als Widerspruch erkannt werden in: '{text}'"
)
def test_keyword_rollback_recognized(self):
"""User sagt 'rollback' → Keyword erkannt."""
text = "Rollback bitte — das gehört in den anderen Raum"
assert _is_widerspruch(text), (
f"'rollback' sollte als Widerspruch erkannt werden in: '{text}'"
)
def test_keyword_stop_recognized(self):
"""User sagt 'stop' → Keyword erkannt."""
text = "Stop! Das ist der falsche Raum"
assert _is_widerspruch(text), (
f"'stop' sollte als Widerspruch erkannt werden in: '{text}'"
)
def test_normal_message_not_widerspruch(self):
"""Normale Nachricht ohne Widerspruch-Keywords → kein Widerspruch."""
text = "Kannst du mir bitte den Status vom Deployment zeigen?"
assert not _is_widerspruch(text), (
f"Normale Nachricht sollte KEIN Widerspruch sein: '{text}'"
)
def test_keyword_without_sentence_context_not_triggered(self):
"""Keyword 'nein' ohne Satzkontext (kein Satzanfang, kein !) → kein Widerspruch."""
# 'nein' ist mitten im Satz ohne ! → sollte nicht triggern
text = "Ich sage nein zu diesem Vorschlag aber das ist ok"
# 'nein' ist nicht am Satzanfang und kein ! im Satz → kein Widerspruch
assert not _is_widerspruch(text), (
f"'nein' ohne Satzkontext sollte KEIN Widerspruch sein: '{text}'"
)
def test_keyword_with_exclamation_triggers(self):
"""Keyword 'falsch' am Satzanfang mit ! → Widerspruch.
Der Satzkontext-Check in adapter.py prüft sentence.startswith(kw)
ODER '!' in sentence. Da der sentence-Slice Delimiter exkludiert,
greift primär der Satzanfang-Check. '!' als Satzende ist nie im
sentence enthalten.
"""
text = "Falsch! Das muss zurück"
assert _is_widerspruch(text), (
f"'falsch' am Satzanfang mit ! sollte Widerspruch sein: '{text}'"
)
def test_keyword_at_sentence_start_triggers(self):
"""Keyword 'stop' am Satzanfang → Widerspruch."""
text = "Stop. Das gehört hier nicht her."
assert _is_widerspruch(text), (
f"'stop' am Satzanfang sollte Widerspruch sein: '{text}'"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 1+2: confirm_move Widerspruch (30-Min-Fenster)
# ═══════════════════════════════════════════════════════════════════════════
class TestConfirmMoveWiderspruch:
"""Tests für confirm_move Widerspruchs-Routine (30-Min-Fenster)."""
def test_confirm_move_widerspruch_within_30min(self):
"""confirm_move wurde geklickt, innerhalb 30 Min sagt User
'passt hier nicht' im Zielraum → Widerspruchs-Routine triggert."""
adapter = _make_mock_adapter()
origin_room = "room_origin_123"
target_room = "room_target_456"
# Simuliere: confirm_move wurde vor 5 Min geklickt
adapter._recent_auto_routes[origin_room] = {
"origin_room": origin_room,
"target_room": target_room,
"topic": "deployment",
"timestamp": time.time() - 300, # 5 Minuten her
"origin_message_id": "msg_orig_1",
"target_message_id": "msg_target_1",
"source": "confirm",
}
# User schreibt im Zielraum: "passt hier nicht"
text = "Passt hier nicht! Das gehört zurück"
assert _is_widerspruch(text), "Text sollte als Widerspruch erkannt werden"
# Simuliere inversen Lookup (wie in adapter.py Z. 2559-2567)
route_info = None
route_source = None
room_id = target_room # User ist im Zielraum
# Direkter Lookup
if room_id in adapter._recent_auto_routes:
route_info = adapter._recent_auto_routes[room_id]
route_source = route_info.get("source", "auto")
else:
# Inverser Lookup für confirm_move
for origin_rid, entry in list(adapter._recent_auto_routes.items()):
if (entry.get("target_room") == room_id
and entry.get("source") == "confirm"):
route_info = entry
route_source = "confirm"
break
assert route_info is not None, (
"Inverser Lookup sollte confirm_move-Route finden"
)
assert route_source == "confirm"
# Zeitfenster-Check: confirm_move = 1800s (30 Min)
elapsed = time.time() - route_info["timestamp"]
max_window = 1800 if route_source == "confirm" else 600
assert elapsed <= max_window, (
f"5 Min sollten innerhalb des 30-Min-Fensters liegen "
f"(elapsed={elapsed:.0f}s, max={max_window}s)"
)
def test_confirm_move_widerspruch_after_30min(self):
"""Nach 30 Min → Widerspruchs-Routine triggert NICHT
(Fenster abgelaufen)."""
adapter = _make_mock_adapter()
origin_room = "room_origin_123"
target_room = "room_target_456"
# Simuliere: confirm_move wurde vor 35 Min geklickt
adapter._recent_auto_routes[origin_room] = {
"origin_room": origin_room,
"target_room": target_room,
"topic": "deployment",
"timestamp": time.time() - 2100, # 35 Minuten her
"origin_message_id": "msg_orig_1",
"target_message_id": "msg_target_1",
"source": "confirm",
}
# Inverser Lookup
room_id = target_room
route_info = None
route_source = None
for origin_rid, entry in list(adapter._recent_auto_routes.items()):
if (entry.get("target_room") == room_id
and entry.get("source") == "confirm"):
route_info = entry
route_source = "confirm"
break
assert route_info is not None, "Inverser Lookup sollte Route finden"
assert route_source == "confirm"
# Zeitfenster-Check
elapsed = time.time() - route_info["timestamp"]
max_window = 1800 # 30 Min für confirm_move
assert elapsed > max_window, (
f"35 Min sollten AUSSERHALB des 30-Min-Fensters liegen "
f"(elapsed={elapsed:.0f}s, max={max_window}s)"
)
# ═══════════════════════════════════════════════════════════════════════════
# Test 5+6: Auto-Route Widerspruch (10-Min-Fenster)
# ═══════════════════════════════════════════════════════════════════════════
class TestAutoRouteWiderspruch:
"""Tests für Auto-Route Widerspruchs-Routine (10-Min-Fenster)."""
def test_auto_route_widerspruch_within_10min(self):
"""Auto-Route Widerspruch innerhalb 10 Min → triggert."""
adapter = _make_mock_adapter()
origin_room = "room_origin_789"
target_room = "room_target_012"
# Simuliere: Auto-Route wurde vor 3 Min ausgelöst
adapter._recent_auto_routes[origin_room] = {
"origin_room": origin_room,
"target_room": target_room,
"topic": "archivar",
"timestamp": time.time() - 180, # 3 Minuten her
"origin_message_id": "msg_orig_2",
"target_message_id": "msg_target_2",
"source": "auto",
}
# User schreibt im Ursprungsraum: "stop, falscher raum!"
text = "Stop! Falscher Raum — das gehört hier her"
assert _is_widerspruch(text), "Text sollte als Widerspruch erkannt werden"
# Direkter Lookup (auto-route: room_id == origin_room)
room_id = origin_room
route_info = None
route_source = None
if room_id in adapter._recent_auto_routes:
route_info = adapter._recent_auto_routes[room_id]
route_source = route_info.get("source", "auto")
assert route_info is not None, "Direkter Lookup sollte Auto-Route finden"
assert route_source == "auto"
# Zeitfenster-Check: auto-route = 600s (10 Min)
elapsed = time.time() - route_info["timestamp"]
max_window = 600
assert elapsed <= max_window, (
f"3 Min sollten innerhalb des 10-Min-Fensters liegen "
f"(elapsed={elapsed:.0f}s, max={max_window}s)"
)
def test_auto_route_widerspruch_after_10min(self):
"""Auto-Route Widerspruch nach 10 Min → triggert NICHT."""
adapter = _make_mock_adapter()
origin_room = "room_origin_789"
target_room = "room_target_012"
# Simuliere: Auto-Route wurde vor 15 Min ausgelöst
adapter._recent_auto_routes[origin_room] = {
"origin_room": origin_room,
"target_room": target_room,
"topic": "archivar",
"timestamp": time.time() - 900, # 15 Minuten her
"origin_message_id": "msg_orig_2",
"target_message_id": "msg_target_2",
"source": "auto",
}
# Direkter Lookup
room_id = origin_room
route_info = None
route_source = None
if room_id in adapter._recent_auto_routes:
route_info = adapter._recent_auto_routes[room_id]
route_source = route_info.get("source", "auto")
assert route_info is not None, "Direkter Lookup sollte Route finden"
assert route_source == "auto"
# Zeitfenster-Check
elapsed = time.time() - route_info["timestamp"]
max_window = 600 # 10 Min für auto-route
assert elapsed > max_window, (
f"15 Min sollten AUSSERHALB des 10-Min-Fensters liegen "
f"(elapsed={elapsed:.0f}s, max={max_window}s)"
)
# ═══════════════════════════════════════════════════════════════════════════
# Integration: Inverser Lookup für confirm_move
# ═══════════════════════════════════════════════════════════════════════════
class TestWiderspruchLookup:
"""Tests für den _recent_auto_routes Lookup (direkt + invers)."""
def test_direct_lookup_finds_auto_route(self):
"""Direkter Lookup: room_id == origin_room → findet Auto-Route."""
adapter = _make_mock_adapter()
origin_room = "room_abc"
adapter._recent_auto_routes[origin_room] = {
"origin_room": origin_room,
"target_room": "room_xyz",
"source": "auto",
"timestamp": time.time() - 60,
}
# Direkter Lookup
assert origin_room in adapter._recent_auto_routes
route_info = adapter._recent_auto_routes[origin_room]
assert route_info["source"] == "auto"
def test_inverse_lookup_finds_confirm_move(self):
"""Inverser Lookup: room_id == target_room → findet confirm_move."""
adapter = _make_mock_adapter()
origin_room = "room_origin"
target_room = "room_target"
adapter._recent_auto_routes[origin_room] = {
"origin_room": origin_room,
"target_room": target_room,
"source": "confirm",
"timestamp": time.time() - 120,
}
# room_id ist der Zielraum (User ist im Zielraum)
room_id = target_room
# Direkter Lookup schlägt fehl (room_id ist target, nicht origin)
assert room_id not in adapter._recent_auto_routes
# Inverser Lookup
route_info = None
for origin_rid, entry in list(adapter._recent_auto_routes.items()):
if (entry.get("target_room") == room_id
and entry.get("source") == "confirm"):
route_info = entry
break
assert route_info is not None, (
f"Inverser Lookup sollte confirm_move-Route finden "
f"(target_room={target_room})"
)
assert route_info["source"] == "confirm"
assert route_info["origin_room"] == origin_room
def test_inverse_lookup_ignores_auto_routes(self):
"""Inverser Lookup ignoriert Auto-Routes (nur source='confirm')."""
adapter = _make_mock_adapter()
origin_room = "room_origin"
target_room = "room_target"
# Auto-Route (source='auto') — sollte NICHT per inversem Lookup gefunden werden
adapter._recent_auto_routes[origin_room] = {
"origin_room": origin_room,
"target_room": target_room,
"source": "auto",
"timestamp": time.time() - 60,
}
room_id = target_room
route_info = None
for origin_rid, entry in list(adapter._recent_auto_routes.items()):
if (entry.get("target_room") == room_id
and entry.get("source") == "confirm"):
route_info = entry
break
assert route_info is None, (
"Inverser Lookup sollte Auto-Routes IGNORIEREN "
"(nur source='confirm' wird gesucht)"
)