Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d3cb91478 | |||
| 3a66743256 |
@@ -1,58 +0,0 @@
|
||||
# Contributing to Hermes Rocket.Chat Plugin
|
||||
|
||||
## Commit-Message-Convention
|
||||
|
||||
Alle Commits folgen dem Conventional-Commits-Format mit einem
|
||||
**Production-Impact-Footer**.
|
||||
|
||||
### Format
|
||||
|
||||
```
|
||||
<type>(<scope>): <kurze Beschreibung>
|
||||
|
||||
<ausführliche Beschreibung>
|
||||
|
||||
Production-Impact: <none|low|medium|high|critical>
|
||||
```
|
||||
|
||||
### Types
|
||||
|
||||
- `feat`: Neue Funktionalität
|
||||
- `fix`: Bugfix
|
||||
- `docs`: Dokumentation
|
||||
- `refactor`: Code-Umbau ohne Funktionsänderung
|
||||
- `test`: Tests
|
||||
- `chore`: Build/Tooling
|
||||
|
||||
### Scopes
|
||||
|
||||
- `adapter`: Gateway-Adapter (REST, DDP, WebSocket)
|
||||
- `presence`: PresenceEngine, PulseController, DetectionTimer
|
||||
- `archivar`: Archivar-Logik (Routing, Room-Map, History)
|
||||
- `gateway`: Gateway-Integration
|
||||
|
||||
### Production-Impact-Footer
|
||||
|
||||
Jeder Commit MUSS einen `Production-Impact`-Footer haben:
|
||||
|
||||
| Level | Bedeutung |
|
||||
|----------|-----------|
|
||||
| `none` | Kein Einfluss auf Produktion (Doku, Tests, Chores) |
|
||||
| `low` | Kosmetische Änderung, kein Verhaltenswechsel |
|
||||
| `medium` | Verhaltensänderung mit geringem Risiko |
|
||||
| `high` | Signifikante Verhaltensänderung (Circuit-Breaker, Rate-Limiting) |
|
||||
| `critical` | Hotfix für Produktionsausfall |
|
||||
|
||||
### Beispiele
|
||||
|
||||
```
|
||||
feat(adapter): http_timeout als konfigurierbarer Parameter
|
||||
|
||||
Production-Impact: none
|
||||
```
|
||||
|
||||
```
|
||||
fix(P1): users.setStatus 429 Circuit-Breaker — verhindert Gateway-Hang
|
||||
|
||||
Production-Impact: HIGH — verhindert Gateway-Hang durch 429-Endlosschleife
|
||||
```
|
||||
@@ -1,396 +0,0 @@
|
||||
# Presence-Engine v9: Schachuhr-Architektur
|
||||
|
||||
Autor: Rainer (Architektur-Review)
|
||||
Datum: 2026-08-03
|
||||
Status: ARCHITEKTUR-VORSCHLAG — nicht implementiert
|
||||
Auftraggeber: Andreas / Bernd
|
||||
|
||||
================================================================================
|
||||
TL;DR — DAS NEUE MODELL IN EINEM ABSATZ
|
||||
================================================================================
|
||||
|
||||
Wir schmeissen alle vier Timer raus und ersetzen sie durch eine
|
||||
ereignisgesteuerte Schachuhr: Status steht auf ONLINE wenn niemand arbeitet,
|
||||
auf BUSY/BESCHAEFTIGT ab dem ersten Hook-Eintreffen, und wieder auf ONLINE
|
||||
wenn der letzte Hook schliesst. Quellen der Hooks sind ausschliesslich die
|
||||
bereits existierenden Hermes-Core-Hooks pre_gateway_dispatch,
|
||||
pre_llm_call, post_llm_call, subagent_start, subagent_stop — keine eigenen
|
||||
Timer, keine pgrep-Hacks, keine gateway_state.json-Polls. Die REST-API
|
||||
users.setStatus wird direkt (synchron, ein Call pro Transition) angesprochen,
|
||||
DDP setDefaultStatus verschwindet komplett. Konkurrierende Counter, Locks
|
||||
und Coalescing-Logik werden obsolet.
|
||||
|
||||
================================================================================
|
||||
1. BEFUND: WAS HEUTE FALSCH LAEUFT
|
||||
================================================================================
|
||||
|
||||
1.1 Faktenlage (verifiziert im Hermes-Core, ~/.hermes/profiles/don/.../hermes_cli)
|
||||
|
||||
a) Hermes-Core hat BEREITS alle Hooks die wir brauchen (plugins.py Z.135-215):
|
||||
- pre_gateway_dispatch (gateway/run.py Z.9996) — Schachuhr-START Hauptagent
|
||||
- pre_llm_call (plugins.py Z.144) — feinere Hauptagent-Erkennung
|
||||
- post_llm_call (plugins.py Z.145) — letztes Tool fertig
|
||||
- subagent_start (plugins.py Z.164) — Schachuhr-START delegate_task
|
||||
- subagent_stop (plugins.py Z.165) — Schachuhr-ENDE delegate_task
|
||||
- on_session_start/end (plugins.py Z.160-161) — Schachuhr CLI-Sessions
|
||||
Miguels fruehere Aussage "Plugins koennen Core-Hooks nicht abonnieren"
|
||||
ist VERALTET. plugins.py Z.1158 expose_t `register_hook(hook_name, cb)`,
|
||||
und der Core ruft invoke_hook() an exakt den richtigen Stellen.
|
||||
|
||||
b) pre_gateway_dispatch in gateway/run.py Z.9996 feuert:
|
||||
- NACH internal-event-Guard (Bot-eigene Events werden gefiltert)
|
||||
- VOR auth/pairing (eingehende User-Nachricht ist authentifiziert)
|
||||
- BEKOMMT das MessageEvent + GatewayRunner + session_store
|
||||
Das ist der semantisch korrekte "Schachuhr-START" fuer Szenario A.
|
||||
|
||||
c) presence_engine.py Z.683, 702, 1280, 1347 nutzt BEREITS REST
|
||||
users.setStatus. DDP setDefaultStatus ist nur noch fuer Away-Mode
|
||||
im Spiel (Z.847 _await_timeout=4.0s fuer DDP). Andreas' Frage
|
||||
"IST REST die bessere API" ist FAKTISCH BEANTWORTET: ja, und wir
|
||||
setzen es schon ein.
|
||||
|
||||
d) gateway_state.json enthaelt active_agents (gateway.py Z.5371) — wird
|
||||
aber NUR fuer Status-Anzeige beim Shutdown genutzt, nicht als
|
||||
Echtzeit-Quelle. Polling dieser Datei ist ein Hack.
|
||||
|
||||
1.2 Aktuelle Timer-Inventur (presence_engine.py V8.x)
|
||||
|
||||
Timer 1: PulseController (Z.810) — toggled online/away alle 1.5s
|
||||
Timer 2: DetectionTimer (Z.1387) — pollt gateway_state.json alle 10s
|
||||
Timer 3: Coalesce-Timer (Z.648) — sammelt Status-Wechsel, 2s
|
||||
Timer 4: Honeymoon-Timer (Z.344) — erzwingt min 1s busy-sichtbar
|
||||
|
||||
Plus 2 Locks (_busy_honeymoon_lock, _mode_lock, Z.156-170) und
|
||||
Counter-Semantik (_active_tasks, _background_count, _busy_counter).
|
||||
|
||||
Gesamtbild: vier Timer die sich gegenseitig neutralisieren.
|
||||
|
||||
1.3 Warum das nicht zuverlaessig funktioniert
|
||||
|
||||
Race 1: mark_busy_started() setzt Counter, PulseController toggled sofort
|
||||
auf away, dann Honeymoon-Timer zwingt zurueck auf busy. Drei
|
||||
Status-Wechsel innerhalb 1.5s — RC sieht "busy" fuer 200ms, dann
|
||||
"away" — exakt das was Pulse eigentlich verhindern soll.
|
||||
|
||||
Race 2: DetectionTimer (10s) liest gateway_state.json, stellt fest dass
|
||||
ein Background-Task laeuft, ruft set_pulse_target("busy") auf.
|
||||
Aber PulseController hat schon "away" gepulst. Wieder 1-2
|
||||
Status-Wechsel mehr als noetig.
|
||||
|
||||
Race 3: Coalesce-Timer (2s) sammelt mehrere set_pulse_target-Calls
|
||||
innerhalb 2s, sendet dann den letzten. Aber PulseController
|
||||
sendet dazwischen. Wer "gewinnt" ist nicht-deterministisch.
|
||||
|
||||
Race 4: 429-Circuit-Breaker (P-010) ist eine SYMPTOM-Bekämpfung. Die
|
||||
Ursache ist: zu viele Calls. Weniger Calls → kein 429.
|
||||
|
||||
1.4 Vier Timer, zwei Locks, ein Counter-Set — wofuer?
|
||||
|
||||
Pulse: simuliert Aktivitaet, weil echte Hook-Erkennung fehlt.
|
||||
Detection: pollt eine Datei, weil Pulse es nicht weiss.
|
||||
Coalesce: verhindert 429, weil Pulse zu oft sendet.
|
||||
Honeymoon: verhindert Status-Flackern, weil Coalesce + Pulse gegeneinander arbeiten.
|
||||
|
||||
→ alle vier Timer kompensieren einander. Keiner ist aus eigener Berechtigung
|
||||
noetig. Sie sind alle Symptom-Behandlung desselben Architekturproblems:
|
||||
"Wir wissen nicht WANN der Agent arbeitet, also raten wir mit Timern."
|
||||
|
||||
================================================================================
|
||||
2. BEWERTUNG: ANDREAS' BEOBACHTUNGEN
|
||||
================================================================================
|
||||
|
||||
Alle drei Beobachtungen von Andreas sind korrekt und jeder Befund oben
|
||||
stuetzt sie:
|
||||
|
||||
(1) Hauptagent im Gateway — kein PID. BESTAETIGT (gateway.py).
|
||||
(2) delegate_task-Subagenten = asyncio-Tasks. BESTAETIGT — ABER: der
|
||||
Core emittiert subagent_start/stop-Hooks, die wir bisher nicht
|
||||
abonniert haben. Die Luecke war WISSEN, nicht ARCHITEKTUR.
|
||||
(3) Schachuhr-Prinzip. BESTAETIGT — exakt das was
|
||||
pre_gateway_dispatch + subagent_start/stop liefern.
|
||||
|
||||
Zusaetzlicher Befund (positiv):
|
||||
|
||||
(4) REST users.setStatus ist BEREITS die genutzte API. Andreas' Frage
|
||||
ist nicht "sollen wir wechseln", sondern "wir sind schon dort".
|
||||
DDP-Komplexitaet kann weg.
|
||||
|
||||
================================================================================
|
||||
3. EMPFEHLUNG: SCHACHUHR-ARCHITEKTUR V9
|
||||
================================================================================
|
||||
|
||||
3.1 Invarianten (was gilt IMMER)
|
||||
|
||||
I1: Status ist ONLINE wenn der Busy-Counter 0 ist, BUSY sonst.
|
||||
I2: Busy-Counter ist die Summe aus:
|
||||
- Hauptagent-Counter (1 wenn pre_gateway_dispatch gefeuert hat
|
||||
und post_llm_call noch nicht, 0 sonst)
|
||||
- delegate_task-Counter (N wenn N subagent_start ohne
|
||||
subagent_stop)
|
||||
- hermes chat --profile-Counter (via on_session_start/end)
|
||||
- Background-Terminal-Counter (terminal(background=true) Hook —
|
||||
derzeit nicht als Core-Hook, siehe 3.4)
|
||||
I3: Jede Transition ONLINE→BUSY oder BUSY→ONLINE erzeugt GENAU EINEN
|
||||
REST-Call. Keine Pulse, keine Coalesce, keine Debounce.
|
||||
I4: REST-Calls sind asynchron (Thread oder asyncio.create_task), aber
|
||||
niemals parallel. Reihenfolge ist garantiert via asyncio.Lock.
|
||||
I5: Bei REST-Fehler (nicht 429): ein Retry nach 2s, dann放弃.
|
||||
Bei 429: Backoff 5s, kein Retry, Counter bleibt inkrementiert
|
||||
(naechster sauberer Hook behebt es). RC-Status bleibt auf dem
|
||||
letzten bekannten Wert — das ist akzeptabel, weil RC sowieso
|
||||
serverseitig auf "offline" nach 60s faellt.
|
||||
|
||||
3.2 Hook-Verdrahtung (EINE Tabelle, keine Ausnahmen)
|
||||
|
||||
+-------------------+---------------------+--------------------+
|
||||
| Hook | Aktion | Counter-Name |
|
||||
+-------------------+---------------------+--------------------+
|
||||
| pre_gateway_dispatch | counter += 1 | main_agent |
|
||||
| post_llm_call | counter -= 1 | main_agent |
|
||||
| subagent_start | counter += 1 | delegate_subagent |
|
||||
| subagent_stop | counter -= 1 | delegate_subagent |
|
||||
| on_session_start | counter += 1 | chat_profile |
|
||||
| on_session_end | counter -= 1 | chat_profile |
|
||||
+-------------------+---------------------+--------------------+
|
||||
|
||||
Hook-Callbacks leben im presence_engine-Modul und werden via
|
||||
plugin_manager.register_hook() in adapter.py registriert (das ist
|
||||
die offizielle Plugin-API, plugins.py Z.1158).
|
||||
|
||||
3.3 State-Maschine (Pseudocode-Beschreibung, keine Implementierung)
|
||||
|
||||
Zustand: status ∈ {ONLINE, BUSY}
|
||||
Daten: counters: dict[str, int] = {main_agent: 0, delegate_subagent: 0,
|
||||
chat_profile: 0, background_term: 0}
|
||||
Mutex: transition_lock (asyncio.Lock oder threading.Lock)
|
||||
|
||||
Auf jeden Hook-Callback:
|
||||
1. lock acquire
|
||||
2. counter[hook_name] += 1 (oder -= 1)
|
||||
3. total = sum(counter.values())
|
||||
4. if total > 0 and status == ONLINE:
|
||||
status = BUSY
|
||||
schedule_transition("busy", "...") # siehe 3.5
|
||||
5. elif total == 0 and status == BUSY:
|
||||
status = ONLINE
|
||||
schedule_transition("online")
|
||||
6. lock release
|
||||
7. return # Hook-Callback ist fire-and-forget; Status-Effekt ist async
|
||||
|
||||
schedule_transition() macht:
|
||||
- wenn schon eine Transition pending ist: ueberschreiben (last-wins)
|
||||
- asyncio.create_task(_send_rest_status(status, message))
|
||||
- KEIN Timer, KEIN Debounce — der naechste Hook ersetzt ggf. die Task
|
||||
|
||||
Warum last-wins statt Coalesce-Timer: Wenn pre_gateway_dispatch
|
||||
(counter=1) und 50ms spaeter pre_llm_call desselben Turns feuert,
|
||||
ist beides BUSY — der erste REST-Call ist noetig, der zweite ist
|
||||
redundant. Mit last-wins schlucken wir Redundanz OHNE Timer.
|
||||
|
||||
3.4 Background-Terminal-Counter (offene Frage)
|
||||
|
||||
terminal(background=true) hat heute keinen Core-Hook. Workarounds:
|
||||
(a) Gateway liest subagent_status.json — wir wissen dass das fragil
|
||||
ist (P-006, P-007).
|
||||
(b) Wir parken das Feature: v9 erkennt NUR Hauptagent + delegate_task +
|
||||
chat_profile. Background-Terminal bleibt auf "ONLINE bis Antwort
|
||||
kommt" — das ist ein akzeptabler Default, weil Background-Terminal
|
||||
in der Praxis sofort antwortet ("started in background, PID xxx").
|
||||
(c) Langfristig: Hermes-Core-PR der post_terminal_background +
|
||||
post_terminal_complete als neue Hooks hinzufuegt. Siehe 5.2.
|
||||
|
||||
Empfehlung: (b) fuer v9, (c) als Core-PR-Anfrage.
|
||||
|
||||
3.5 Status-Message-Inhalt (rein, ohne Logik)
|
||||
|
||||
ONLINE: "online"
|
||||
BUSY: "beschaeftigt — {counter_typ}" wenn nur ein Typ aktiv
|
||||
"beschaeftigt — {n_typen} Aufgaben" wenn mehrere Typen
|
||||
|
||||
Beispiel: "beschaeftigt — delegiere Subagent" oder
|
||||
"beschaeftigt — 2 Aufgaben".
|
||||
|
||||
Status-Message wird NUR bei Transition berechnet, nicht zyklisch.
|
||||
|
||||
3.6 REST-API-Wahl
|
||||
|
||||
Endpoint: POST /api/v1/users.setStatus
|
||||
Body: {"status": "online"|"busy"|"away", "message": "..."}
|
||||
Header: X-Auth-Token + X-User-Id
|
||||
Async: via asyncio.create_task (NICHT threading.Timer)
|
||||
Retry: 1x bei Netzfehler, 0x bei 4xx (ausser 429)
|
||||
Backoff: bei 429: skip, kein retry. Status bleibt wie er ist.
|
||||
|
||||
DDP setDefaultStatus: KOMPLETT ENTFERNEN. away-Mode ist obsolete
|
||||
weil Pulse wegfaellt (kein Notwendigkeit mehr fuer zyklisches away-
|
||||
toggling wenn die Schachuhr die Realitaet abbildet).
|
||||
|
||||
3.7 Warum das zuverlaessig ist (Andreas' Anforderung)
|
||||
|
||||
- Jeder Hook-Counter-Stand entspricht 1:1 der Realitaet.
|
||||
- Keine Timer die raten, keine Dateien die gepollt werden.
|
||||
- Race-Conditions: counters werden unter Lock mutiert, Reihenfolge
|
||||
ist garantiert. Die einzige externe Asynchronitaet (REST-Call)
|
||||
ist last-wins, was bei Status-Transitionen nie zu inkonsistentem
|
||||
RC-Status fuehrt (UEBER-GANG BUSY→BUSY ist No-Op nach Coalesce-
|
||||
Veroeffentlichung).
|
||||
- 429 wird zur Nicht-Sache, weil Calls nur bei echten Transitionen
|
||||
passieren. Bei 100 User-Nachrichten/h sind das ~100 Calls/h statt
|
||||
~2400 Calls/h (Puls 1.5s * 2 Status).
|
||||
|
||||
================================================================================
|
||||
4. KONKRETE MIGRATION: V8.x → V9
|
||||
================================================================================
|
||||
|
||||
4.1 Was verschwindet (komplett)
|
||||
|
||||
- PulseController (presence_engine.py Z.810-1384) — 575 Zeilen
|
||||
- DetectionTimer (presence_engine.py Z.1387-...) — Polling-Logik
|
||||
- Coalesce-Timer (presence_engine.py Z.646-650)
|
||||
- Honeymoon-Timer (presence_engine.py Z.344-346)
|
||||
- _busy_honeymoon_lock, _mode_lock — nur EIN Lock bleibt (transition_lock)
|
||||
- _busy_counter, _active_tasks, _background_count — durch counters-dict
|
||||
- away-Mode (DDP setDefaultStatus) — komplett
|
||||
- gateway_state.json-Polling — komplett (bleibt nur fuer Diagnose)
|
||||
|
||||
Geschätzte Reduktion: 1754 → ~400 Zeilen. Vier Timer → null Timer.
|
||||
Zwei Locks → ein Lock. Drei Counter-Variablen → ein Dict.
|
||||
|
||||
4.2 Was neu entsteht (klein)
|
||||
|
||||
- Hook-Registrierung in adapter.py: 6 register_hook-Calls, ~30 Zeilen.
|
||||
- Counter-Dict + State-Maschine in presence_engine.py: ~100 Zeilen.
|
||||
- schedule_transition() Helper: ~30 Zeilen.
|
||||
- Tests: 6 Hook-Trigger-Tests + 4 Counter-Tests + 3 Race-Tests.
|
||||
|
||||
4.3 Was bleibt
|
||||
|
||||
- REST-Call-Wrapper (an asyncio.create_task angepasst, statt threading).
|
||||
- Telemetrie (Counter, Erfolg, 429-Rate).
|
||||
- Config-Knobs (Coalesce → ENTFALLEN, Pulse → ENTFALLEN, Honeymoon →
|
||||
ENTFALLEN). Bleibt: enabled, away-grace-Sekunden (siehe 4.4).
|
||||
|
||||
4.4 Neuer Config-Knob: away-grace
|
||||
|
||||
Wir brauchen EINE Sache noch: wenn alle Counter 0 sind, nicht sofort
|
||||
auf ONLINE, sondern 2s warten (RC-Konvention: man sieht 2s "online",
|
||||
dann springt es auf online — kein Flackern).
|
||||
|
||||
Implementierung: schedule_transition("online") startet EINEN asyncio-
|
||||
Task, der nach 2s den REST-Call macht. Wenn in diesen 2s ein neuer
|
||||
Hook feuert (counter > 0), wird der Task gecancelt.
|
||||
|
||||
Ein Timer, einer einziger, mit klarer Semantik. Nicht vier.
|
||||
|
||||
================================================================================
|
||||
5. CORE-HOOK-FORSCHUNG: WAS BRAUCHEN WIR NOCH?
|
||||
================================================================================
|
||||
|
||||
5.1 Was bereits da ist (verifiziert)
|
||||
|
||||
| Hook | Core-Stelle | Reichweite |
|
||||
|----------------------|----------------------------|--------------------|
|
||||
| pre_gateway_dispatch | gateway/run.py Z.9996 | Hauptagent (RC/TG) |
|
||||
| pre_llm_call | plugins.py invoke_hook | Hauptagent |
|
||||
| post_llm_call | plugins.py invoke_hook | Hauptagent |
|
||||
| subagent_start | plugins.py VALID_HOOKS | delegate_task |
|
||||
| subagent_stop | plugins.py VALID_HOOKS | delegate_task |
|
||||
| on_session_start | plugins.py VALID_HOOKS | hermes chat -p |
|
||||
| on_session_end | plugins.py VALID_HOOKS | hermes chat -p |
|
||||
| pre_tool_call | plugins.py Z.2145 | Jeder Tool-Call |
|
||||
| post_tool_call | plugins.py Z.2145 | Jeder Tool-Call |
|
||||
|
||||
Bewertung: AUSREICHEND fuer Szenarien A, B, C.
|
||||
|
||||
5.2 Was fehlt (Background-Terminal)
|
||||
|
||||
terminal(background=true) und terminal(background)-Abschluss haben
|
||||
keinen Hook. Workaround: wir nutzen pre_tool_call/post_tool_call
|
||||
und erkennen am Arg ob es background=true ist.
|
||||
|
||||
Vorteil: kein neuer Core-Hook noetig, funktioniert ab heute.
|
||||
Nachteil: pre_tool_call feuert bei JEDEM Tool (nicht nur terminal),
|
||||
wir muessen tool_name=="terminal" UND args.background==true pruefen.
|
||||
|
||||
Langfristig: Core-PR der post_background_terminal +
|
||||
on_terminal_complete als saubere Hooks einfuehrt. Aufwand fuer
|
||||
Core-Team: ~30 Zeilen. Siehe 5.3 fuer PR-Skizze.
|
||||
|
||||
5.3 PR-Skizze fuer Hermes-Core (zur Diskussion, nicht implementiert)
|
||||
|
||||
Vorschlag: zwei neue Hooks in VALID_HOOKS (plugins.py):
|
||||
- "post_background_terminal": feuert wenn terminal(background=true)
|
||||
gestartet wurde. Kwargs: pid, command, session_id.
|
||||
- "on_terminal_complete": feuert wenn Hintergrund-Task endet
|
||||
(erfolg, fehler, timeout). Kwargs: pid, exit_code, session_id.
|
||||
|
||||
Begruendung im PR-Text: "Präsenz-Engines brauchen saubere
|
||||
Schachuhr-Signale fuer Hintergrund-Tasks, ohne Polling oder PID-Hacks.
|
||||
Aktuelle Loesungen im Plugin-Umfeld (subagent_status.json,
|
||||
pgrep) sind fragil. Hook-basierter Ansatz folgt dem Pattern der
|
||||
existierenden subagent_start/stop-Hooks."
|
||||
|
||||
Aufwand: minimal, klar im Scope, konkretes Use-Case (unser Plugin).
|
||||
|
||||
================================================================================
|
||||
6. KONKURRENZ-VERMEIDUNG: WARUM WIR NUR EINEN TIMER BRAUCHEN
|
||||
================================================================================
|
||||
|
||||
Timer 1 (alt: Pulse): weg — Schachuhr ersetzt
|
||||
Timer 2 (alt: Detection): weg — Hooks ersetzen
|
||||
Timer 3 (alt: Coalesce): weg — last-wins in schedule_transition
|
||||
Timer 4 (alt: Honeymoon): weg — kein Coalesce-Flackern mehr
|
||||
Timer 5 (neu: away-grace): EINE Async-Task pro ONLINE-Transition,
|
||||
wird bei naechstem BUSY-Hook gecancelt.
|
||||
|
||||
Verbleibende Konkurrenz: keine. away-grace-Task und ein gleichzeitiger
|
||||
Hook-Callback teilen sich transition_lock; der Callback gewinnt
|
||||
(synchroner Mutex), cancelt den Task, setzt Status auf BUSY.
|
||||
Keine Race weil alles unter einem Lock.
|
||||
|
||||
================================================================================
|
||||
7. ZUSAMMENFASSUNG: VORHER / NACHHER
|
||||
================================================================================
|
||||
|
||||
VORHER (V8.x):
|
||||
- 4 Timer + 2 Locks + 3 Counter
|
||||
- Polling gateway_state.json alle 10s
|
||||
- pgrep / SubagentTracker fuer externe Subagenten
|
||||
- DDP-Pulse + REST-Hybrid (Away/Online ueber DDP, Busy/Heartbeat ueber REST)
|
||||
- Honeymoon-Schutz gegen eigenes Flackern
|
||||
- 429-Circuit-Breaker noetig (P-010)
|
||||
- 1754 Zeilen
|
||||
|
||||
NACHHER (V9):
|
||||
- 1 Async-Task (away-grace, max 2s)
|
||||
- 1 Lock (transition_lock)
|
||||
- 1 Counter-Dict
|
||||
- 6 Hook-Callbacks
|
||||
- REST-only, ein Call pro Transition
|
||||
- Kein 429-Symptom mehr (zu wenige Calls)
|
||||
- ~400 Zeilen
|
||||
- Zuverlaessigkeit: 1:1-Mapping Counter→Realitaet, keine Schaetzung
|
||||
|
||||
Architektur-Prinzip: "Wisse wann du arbeitest" statt "rate wann du
|
||||
wahrscheinlich arbeitest".
|
||||
|
||||
================================================================================
|
||||
8. OFFENE PUNKTE FUER ANDREAS / BERND
|
||||
================================================================================
|
||||
|
||||
O-1: Background-Terminal via pre_tool_call-Filter — ok als Workaround
|
||||
fuer v9, oder doch Core-PR abwarten?
|
||||
O-2: Soll away-grace konfigurierbar sein (default 2s), oder hartcodiert?
|
||||
O-3: Was passiert wenn der Gateway-Prozess stirbt waehrend counter > 0?
|
||||
→ Status bleibt auf BUSY bis RC serverseitig auf offline faellt
|
||||
(60s). Akzeptabel, oder brauchen wir heartbeat?
|
||||
O-4: subagent_start-Kwargs: kennt der Core den "Grund" (explizit vs.
|
||||
Hintergrund)? Falls ja, koennten wir differenzieren: explizite
|
||||
Subagenten → BUSY, Cron-Subagenten → stillschweigend.
|
||||
O-5: Wenn die Core-Hook-Forschung stimmt: koennen wir den alten
|
||||
PulseController + DetectionTimer SOFORT entsorgen oder erst
|
||||
nach einem Validierungs-Release (V8.x-Compat)?
|
||||
|
||||
================================================================================
|
||||
ENDE — Architektur-Vorschlag, kein Code
|
||||
================================================================================
|
||||
@@ -1,543 +0,0 @@
|
||||
# Presence-Engine V10 — Mediator Layer (Architektur-Entwurf)
|
||||
|
||||
**Status:** Entwurf (noch NICHT implementiert)
|
||||
**Autor:** Rainer (Architektur-Review)
|
||||
**Datum:** 2026-08-05
|
||||
**Bezug:** V9.2.3 (presence_engine.py) → V10.0
|
||||
**Trigger:** P-010 (DDP/REST 429 Rate-Limiting), V9.2 Pulse-Pattern
|
||||
**Architektur-Vorgabe:** Andreas (Phase-Konzept)
|
||||
|
||||
---
|
||||
|
||||
## 0. Management Summary
|
||||
|
||||
Die V9-Engine feuert einen REST-`users.setStatus`-Call bei **jeder Counter-Änderung** und
|
||||
vertraut auf ein Caching-Last-Wins, um redundante Calls zu vermeiden. Bei aktivem Pulsing
|
||||
(Rot↔Gelb oder Grün↔Gelb in V9.2) ist Caching wirkungslos — die Status-Werte wechseln
|
||||
absichtlich, also löst jeder Toggle einen Call aus. Resultat: 429-Sturm (P-010),
|
||||
mit einem Workaround-Circuit-Breaker, der das Symptom kaschiert, die Ursache aber nicht
|
||||
behebt.
|
||||
|
||||
**V10-Lösung:** Eine **Mediator-Schicht** zwischen Counter-Logik und REST-Sender
|
||||
trennt zwei Verantwortlichkeiten, die heute vermischt sind:
|
||||
|
||||
1. **Counter-Logik (innen):** Mutiert Zähler, bestimmt die *interne Phase* (einer von 4).
|
||||
2. **Mediator (Mitte):** Reagiert nur auf **Phasen-Übergänge**, nicht auf Counter-Deltas.
|
||||
Steuert das *interne Pulsieren* über einen eigenen Timer. Schickt REST-Calls.
|
||||
3. **REST-Sender (außen):** Unverändert, fire-and-forget Daemon-Thread.
|
||||
|
||||
Konsequenz: 3 nacheinander startende Subagenten erzeugen **einen** REST-Call
|
||||
(Übergang in Phase ROT↔GELB), nicht drei. Das Pulsieren GRÜN↔GELB / ROT↔GELB läuft
|
||||
**lokal in der Mediator-Schicht** über einen Timer — Rocket.Chat sieht nur den einen
|
||||
Phasen-Übergang und die nachfolgenden statischen States.
|
||||
|
||||
---
|
||||
|
||||
## 1. Phasen-Konzept (Andreas-Spezifikation)
|
||||
|
||||
Vier sichtbare Phasen. Jede Phase ist ein **benannter Zustand** mit eigener
|
||||
REST-Status-Bedeutung und eigenem Puls-Verhalten.
|
||||
|
||||
| Phase | Sichtbarer Status | Puls-Verhalten | REST-Calls |
|
||||
|---|---|---|---|
|
||||
| **P1 GREEN_STATIC** | `online` | statisch (kein Puls) | 1× beim Eintritt |
|
||||
| **P2 RED_STATIC** | `busy` | statisch (kein Puls) | 1× beim Eintritt |
|
||||
| **P3 GREEN_PULSE** | `online` ↔ `away` (Timer) | Mediator pulst lokal | 1× beim Eintritt in P3 |
|
||||
| **P4 RED_PULSE** | `busy` ↔ `away` (Timer) | Mediator pulst lokal | 1× beim Eintritt in P4 |
|
||||
|
||||
**Phasen-Übergang (einzige Quelle für REST-Calls):**
|
||||
|
||||
| Von → Nach | Trigger |
|
||||
|---|---|
|
||||
| beliebig → P1 | `sum(counters) == 0` UND letzte Phase war nicht P1 |
|
||||
| beliebig → P2 | `main_agent > 0` UND `delegate_subagent == 0` UND `chat_profile == 0` UND `background_term == 0` |
|
||||
| beliebig → P3 | `subagent_active` UND `main_agent == 0` |
|
||||
| beliebig → P4 | `subagent_active` UND `main_agent > 0` |
|
||||
|
||||
`subagent_active := delegate_subagent > 0 OR chat_profile > 0 OR background_term > 0`
|
||||
|
||||
P3/P4 sind "pulsierend", aber das Pulsieren selbst ist **kein Phasen-Übergang** — die
|
||||
Mediator-Schicht toggelt intern die REST-Status-Werte `online` ↔ `away` (P3) oder
|
||||
`busy` ↔ `away` (P4) über ihren Timer, **ohne** Phasen-Übergang, **ohne** Counter-Delta.
|
||||
|
||||
---
|
||||
|
||||
## 2. Architektur-Schichten
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Core-Hook-Callbacks (V9-API, unverändert) │
|
||||
│ on_pre_gateway_dispatch, on_subagent_start, ... │
|
||||
└────────────────────────────┬────────────────────────────────────┘
|
||||
│ _apply_counter_delta(name, ±1)
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Schicht 1: Counter + Phase-Resolver (neu in V10) │
|
||||
│ - mutiert counter-dict unter transition_lock │
|
||||
│ - berechnet neue Phase aus Counter-Snapshot │
|
||||
│ - emittiert NUR bei Phasen-Übergang ein Phase-Event │
|
||||
│ - KEIN direkter REST-Call, KEIN Timer, KEIN Pulsing │
|
||||
└────────────────────────────┬────────────────────────────────────┘
|
||||
│ phase_transition_event (old, new)
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Schicht 2: Mediator (NEU — Kernstück V10) │
|
||||
│ - empfängt Phase-Transition-Events │
|
||||
│ - hält aktuelle Phase + Puls-Timer │
|
||||
│ - beim Eintritt in P3/P4: startet Puls-Timer │
|
||||
│ - beim Verlassen von P3/P4: stoppt Puls-Timer │
|
||||
│ - emittiert NUR Phasen-Übergang als REST-Auftrag │
|
||||
│ - 429-Backoff: setzt globalen REST-Cooldown (Safety-Net) │
|
||||
│ - Caching: gleicher Status + Message → skip (aus V9 übernommen)│
|
||||
└────────────────────────────┬────────────────────────────────────┘
|
||||
│ rest_status_request (status, message)
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Schicht 3: REST-Sender (aus V9, fast unverändert) │
|
||||
│ - fire-and-forget Daemon-Thread │
|
||||
│ - urllib.request POST /api/v1/users.setStatus │
|
||||
│ - bei 429: setzt Mediator-Backoff-Flag (Rückkanal) │
|
||||
│ - bei sonstigem Fehler: 1 Retry nach 2s │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Drei Verantwortlichkeiten, drei Schichten, eine Richtung.** Keine Schicht kennt
|
||||
die Implementierungs-Details der anderen.
|
||||
|
||||
---
|
||||
|
||||
## 3. Datenmodell
|
||||
|
||||
### 3.1 Phase-Enum (neu)
|
||||
|
||||
```text
|
||||
Phase = Enum("Phase", [
|
||||
"GREEN_STATIC", # P1
|
||||
"RED_STATIC", # P2
|
||||
"GREEN_PULSE", # P3
|
||||
"RED_PULSE", # P4
|
||||
])
|
||||
```
|
||||
|
||||
Interner Repräsentant. Phasen sind **keine** Rocket.Chat-Status-Strings — die
|
||||
Übersetzung Phase → RC-Status passiert erst im Mediator.
|
||||
|
||||
### 3.2 Phase-Resolver (neu, pure Funktion)
|
||||
|
||||
```text
|
||||
def resolve_phase(counters: Dict[str, int]) -> Phase
|
||||
```
|
||||
|
||||
Achtung: Wortlaut-Beschreibung, kein Code. Logik:
|
||||
|
||||
- Wenn `sum(counters) == 0`: `GREEN_STATIC`
|
||||
- Wenn `main_agent > 0` und `subagent_active == False`: `RED_STATIC`
|
||||
- Wenn `subagent_active == True` und `main_agent == 0`: `GREEN_PULSE`
|
||||
- Wenn `subagent_active == True` und `main_agent > 0`: `RED_PULSE`
|
||||
|
||||
Priorität: P1 (alle 0) > P2 (nur main) > P3/P4 (subagent aktiv). Identisch zur
|
||||
V9-GELB-Logik, nur als 4-Phasen-Vokabular statt 3-Status-Vokabular.
|
||||
|
||||
### 3.3 Counter-Resolver (unverändert aus V9)
|
||||
|
||||
Das `counters`-Dict bleibt exakt wie in V9: 4 Zähler (main_agent, delegate_subagent,
|
||||
chat_profile, background_term), Mutationen unter `_transition_lock`.
|
||||
|
||||
### 3.4 Mediator-State (neu)
|
||||
|
||||
```text
|
||||
- current_phase: Phase
|
||||
- last_sent_phase: Optional[Phase] (für Caching)
|
||||
- last_sent_message: str
|
||||
- pulse_timer: Optional[threading.Timer] (für P3/P4)
|
||||
- pulse_toggle: bool (welche Seite des Pulses gerade "aktiv" ist)
|
||||
- rest_cooldown_until: float (monotonische Zeit; 429-Safety-Net)
|
||||
- telemetry_pulse_ticks: int
|
||||
- telemetry_phase_transitions: int
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Phasen-Übergang vs. Counter-Delta
|
||||
|
||||
### 4.1 Aktuelles Verhalten (V9, problematisch)
|
||||
|
||||
In V9 löst **jede** Counter-Änderung `_apply_counter_delta` aus. Diese ruft
|
||||
`_determine_status` auf und prüft `if self._status != new_status`. Das ist ein
|
||||
3-State-Vergleich. Bei aktiver Subagent-Phase (V9 nennt es "AWAY/GELB") ist
|
||||
`self._status = "AWAY"`. Sobald `main_agent` von 0 auf 1 wechselt, ändert sich der
|
||||
**interne 3-State-Status nicht** (bleibt AWAY), aber `_determine_status` liefert
|
||||
immer noch `away` (Subagent-Vorrang). Der Caching-Check in `_schedule_transition`
|
||||
überspringt den REST-Call, weil Status+Message identisch sind.
|
||||
|
||||
**Aber:** In V9.2 wurde zusätzlich ein **Pulsing-Layer** (V8.x PulseController-Rest)
|
||||
reaktiviert, der zwischen ROT↔GELB toggelt. Dieser Toggle ist **kein** Status-Wechsel
|
||||
im 3-State-Modell, sondern ein bewusst anderer Status. Also löst jeder Puls-Tick
|
||||
einen REST-Call aus → 429.
|
||||
|
||||
### 4.2 V10: Phasen-Modell löst das Pulsing-Problem strukturell
|
||||
|
||||
In V10 ist die Phase-Granularität **feiner** als der sichtbare RC-Status. Eine
|
||||
Phase-Transition kann zu *einem* REST-Call führen, aber das interne Pulsing innerhalb
|
||||
von P3/P4 ist **kein** Phasen-Übergang. Beispiel:
|
||||
|
||||
1. `main_agent = 0`, `delegate_subagent = 0` → P1 (GREEN_STATIC)
|
||||
2. `on_subagent_start()` → Counter ändert sich, Phase wechselt P1 → P3
|
||||
→ Mediator: **1 REST-Call** (z.B. `online` als Start, dann sofort `away`)
|
||||
3. `on_subagent_start()` (2. Subagent) → Counter ändert sich, **Phase bleibt P3**
|
||||
→ Mediator: **0 REST-Calls** (kein Phasen-Übergang)
|
||||
4. `on_subagent_start()` (3. Subagent) → dito → 0 REST-Calls
|
||||
5. `on_subagent_stop()` (alle 3) → Counter fällt, Phase bleibt P3 solange ≥1 aktiv
|
||||
6. Letzter `on_subagent_stop()` → Phase wechselt P3 → P1
|
||||
→ Mediator: **1 REST-Call** (`online`)
|
||||
|
||||
**Resultat: 2 REST-Calls für 3 Starts + 3 Stops, unabhängig von der Anzahl der
|
||||
Subagenten.** In V9.2 wären das 6+ Calls (jeder Counter-Delta = 1 Puls-Tick).
|
||||
|
||||
---
|
||||
|
||||
## 5. Mediator: Puls-Timer
|
||||
|
||||
### 5.1 Puls-Intervall
|
||||
|
||||
Aus V9.2-Pattern: 3 Sekunden Takt (away-pulse). V10 übernimmt:
|
||||
|
||||
- `PULSE_INTERVAL_S: float = 3.0` (Mediator-Konstante, neu)
|
||||
- Puls toggelt zwischen den zwei sichtbaren RC-Status-Werten der Phase:
|
||||
- P3: `online` ↔ `away` (GRÜN ↔ GELB)
|
||||
- P4: `busy` ↔ `away` (ROT ↔ GELB)
|
||||
|
||||
### 5.2 Timer-Lebenszyklus
|
||||
|
||||
```text
|
||||
Phasen-Übergang nach P3 oder P4:
|
||||
1. Mediator stoppt alten Puls-Timer (falls vorhanden)
|
||||
2. Mediator sendet Initial-REST-Call (Startseite des Pulses)
|
||||
3. Mediator startet neuen Puls-Timer
|
||||
4. Timer-Callback: REST-Call mit togglender Status-Seite
|
||||
5. Timer reschedulet sich selbst (periodischer Timer)
|
||||
|
||||
Phasen-Übergang weg von P3/P4 (z.B. P3 → P1):
|
||||
1. Mediator stoppt Puls-Timer
|
||||
2. Mediator sendet Final-REST-Call (Zielstatus der neuen Phase)
|
||||
```
|
||||
|
||||
### 5.3 REST-Cooldown-Bug-Vermeidung (kritisch)
|
||||
|
||||
Der Puls-Timer darf **keinen** REST-Call absetzen, solange der Mediator einen
|
||||
`rest_cooldown_until > now()` hat. Sonst kollidiert das Pulsing mit dem 429-Backoff
|
||||
und produziert sofort den nächsten 429. Lösung:
|
||||
|
||||
```text
|
||||
im Timer-Callback:
|
||||
wenn rest_cooldown_until > now():
|
||||
log "pulse-tick suppressed (cooldown)"
|
||||
reschedule Timer (kein Sendeversuch)
|
||||
return
|
||||
sonst:
|
||||
REST-Call senden
|
||||
```
|
||||
|
||||
### 5.4 Race: Counter-Delta während Puls-Timer-Callback
|
||||
|
||||
Wenn der Puls-Timer gerade einen REST-Call absetzt (Daemon-Thread) und parallel
|
||||
ein Hook eine Phasen-Transition auslöst, könnten zwei REST-Calls gleichzeitig
|
||||
unterwegs sein. Schutz:
|
||||
|
||||
- `transition_lock` serialisiert Counter-Mutationen und damit Phasen-Resolver
|
||||
- Mediator hat **eigenen** `mediator_lock` für Phase + Timer-Mutationen
|
||||
- Phasen-Transition ruft Mediator unter beiden Locks auf
|
||||
- REST-Sender läuft in eigenem Daemon-Thread, ist vom Lock unabhängig
|
||||
- Caching im Mediator (last_sent_phase + last_sent_message) verhindert dass
|
||||
Phasen-Übergang + Puls-Tick denselben Status gleichzeitig senden
|
||||
|
||||
---
|
||||
|
||||
## 6. 429-Notfall-Pause (Safety-Net)
|
||||
|
||||
### 6.1 Wo greift der Backoff ein?
|
||||
|
||||
Der V9-Code kennt `BACKOFF_429_S = 5.0`, **verwendet es aber nicht** (toter Code,
|
||||
siehe Pitfall-Befund). V10 macht daraus einen echten Mediator-Mechanismus:
|
||||
|
||||
```text
|
||||
REST-Sender (Schicht 3) bei 429-Antwort:
|
||||
1. setze mediator.rest_cooldown_until = now() + REST_BACKOFF_429_S
|
||||
2. telemetry_rest_429 += 1
|
||||
3. KEIN retry (V9-Verhalten beibehalten — P-010-Prävention)
|
||||
4. KEIN Aufgeben — der nächste Phasen-Übergang oder Puls-Tick sendet erneut
|
||||
```
|
||||
|
||||
**Wichtig: Der Backoff ist ein Pausen-Schild, kein Stop.** Die Engine bleibt
|
||||
funktional; nur die REST-Sender-Komponente schweigt kurz.
|
||||
|
||||
### 6.2 Was passiert während des Cooldowns?
|
||||
|
||||
| Aktion | Verhalten während Cooldown |
|
||||
|---|---|
|
||||
| Phasen-Übergang | Phase wird umgeschaltet, Timer ge-startet/-gestoppt — aber REST-Call wird **unterdrückt** (geloggt) |
|
||||
| Puls-Tick (P3/P4) | Tick wird **unterdrückt** (geloggt), Timer reschedulet sich |
|
||||
| Counter-Delta ohne Phasen-Übergang | keine Auswirkung (Counter wird mutiert, kein Sendeversuch) |
|
||||
| Counter-Delta mit Phasen-Übergang | Phase wechselt intern, Caching-Check verhindert Doppel-Sendeversuch nach Cooldown-Ende |
|
||||
| Cooldown endet | Mediator sendet **einen** Reconciliation-Call (aktueller Phase-Status), um Drift zu beheben |
|
||||
|
||||
### 6.3 Reconciliation nach Cooldown-Ende (neu, V10-spezifisch)
|
||||
|
||||
Problem: Während 5s Cooldown können mehrere Phasen-Übergänge + Puls-Ticks
|
||||
unterdrückt worden sein. Nach Cooldown-Ende ist der **tatsächliche** RC-Status
|
||||
möglicherweise veraltet (z.B. Phase wechselte P3 → P1, aber RC weiß es nicht).
|
||||
|
||||
Lösung: Reconciliation-Timer (threading.Timer, 1-shot, läuft bei Cooldown-Ende).
|
||||
Sendet genau einen REST-Call mit dem aktuellen Phase-Status. Idempotent: Wenn
|
||||
die Phase sich in der Zwischenzeit nicht geändert hat, macht Caching den Call
|
||||
überflüssig.
|
||||
|
||||
### 6.4 Warum diese Architektur das 429-Problem *strukturell* löst
|
||||
|
||||
V9 produziert N REST-Calls pro N Counter-Deltas. Bei Subagent-Bursts ist N
|
||||
groß. Caching reduziert die *sichtbaren* Calls, aber das Pulsing umgeht Caching
|
||||
(absichtliche Status-Wechsel).
|
||||
|
||||
V10 produziert:
|
||||
- **1 Call pro Phasen-Übergang** (typisch: 2-4 pro Subagent-Lebenszyklus)
|
||||
- **Puls-Calls nur in P3/P4, im 3s-Takt** (statt Counter-Delta-getrieben)
|
||||
- **0 Calls bei Counter-Delta innerhalb derselben Phase**
|
||||
|
||||
Erwartete Reduktion: Faktor 5-10× weniger REST-Calls bei typischen Workloads.
|
||||
429-Cooldown wird **selten** greifen — das Safety-Net bleibt, ist aber Notfall
|
||||
statt Dauerzustand.
|
||||
|
||||
---
|
||||
|
||||
## 7. Was bleibt, was wird neu, was wird entfernt
|
||||
|
||||
### 7.1 Bleibt (unverändert aus V9)
|
||||
|
||||
- **Counter-Dict** mit 4 Zählern (main_agent, delegate_subagent, chat_profile, background_term)
|
||||
- **`_transition_lock: threading.Lock`** — serialisiert Counter-Mutationen
|
||||
- **6 Hook-Callbacks:** `on_pre_gateway_dispatch`, `on_post_llm_call`, `on_subagent_start`,
|
||||
`on_subagent_stop`, `on_session_start`, `on_session_end` (Z.175-197)
|
||||
- **2 Tool-Filter-Hooks:** `on_pre_tool_call`, `on_post_tool_call` (Z.199-215)
|
||||
- **REST-Sender-Logik:** `_rest_set_status` (Z.418-503), fire-and-forget Daemon-Thread
|
||||
- **Retry-Logik** bei Nicht-429-Fehlern: 1 Retry nach `RETRY_DELAY_S = 2.0`
|
||||
- **away-grace-Timer** für ONLINE-Transition (wird in V10 von Mediator verwaltet,
|
||||
nicht von Counter-Logik)
|
||||
- **Telemetrie-Felder** `rest_calls`, `rest_success`, `rest_429`, `rest_errors`
|
||||
- **Caching-Logik** (`_last_sent_status` / `_last_sent_message`) — wandert in den
|
||||
Mediator um, gleiche Semantik
|
||||
- **`disable()` / `enable()`** Funktionalität
|
||||
- **Sync-Hooks-Constraint** (V9.0.1 P-024) — Hooks bleiben synchron, da `invoke_hook()`
|
||||
im Core synchron ruft
|
||||
- **Pre-Tool-Call-Filter** auf `terminal(background=true)` (Workaround O-1)
|
||||
- **Counter-Negativ-Klemme** (`if new_value < 0: new_value = 0`)
|
||||
|
||||
### 7.2 Wird neu
|
||||
|
||||
- **`Phase` Enum** (P1-P4) — siehe §3.1
|
||||
- **`resolve_phase(counters)` pure Funktion** — siehe §3.2
|
||||
- **`Mediator` Komponente** (oder `_Mediator` private Klasse innerhalb PresenceEngine):
|
||||
- hält aktuelle Phase, Puls-Timer, Cooldown-State
|
||||
- `on_phase_transition(old, new)` Methode
|
||||
- `start_pulse()` / `stop_pulse()` Methoden
|
||||
- `request_rest_status(status, message)` mit Cooldown-Suppression
|
||||
- `reconcile_after_cooldown()` 1-shot-Timer
|
||||
- **`PULSE_INTERVAL_S: float = 3.0`** Mediator-Konstante
|
||||
- **`REST_BACKOFF_429_S: float = 5.0`** aktiv genutzt (aus V9 toter Code)
|
||||
- **Telemetrie-Felder:**
|
||||
- `phase_transitions: int`
|
||||
- `pulse_ticks: int`
|
||||
- `pulse_ticks_suppressed: int` (Cooldown)
|
||||
- `phase_transitions_suppressed: int` (Cooldown)
|
||||
- **3-Schicht-Trennung** in der Code-Struktur (Methoden-Sektionen klar getrennt)
|
||||
|
||||
### 7.3 Wird entfernt
|
||||
|
||||
- **V9-GELB-Logik-Vokabular in `_apply_counter_delta`** (Z.250-303): Die
|
||||
`if total == 0 / elif rc_status == "away" / else` Logik wird ersetzt durch
|
||||
`_apply_counter_delta → resolve_phase → on_phase_transition`. Die Status-Strings
|
||||
`ONLINE`/`BUSY`/`AWAY` als interner Repräsentant werden ersetzt durch `Phase`-Enum.
|
||||
Externe API (`get_status() → "ONLINE"|"BUSY"|"AWAY"`) bleibt für Tests/Kompatibilität
|
||||
via Mapping-Funktion erhalten.
|
||||
- **`_build_busy_message()`** (Z.305-326): Die ad-hoc Message-Konstruktion wandert
|
||||
in den Mediator. Im neuen Modell baut der Mediator pro Phase eine Standard-Message.
|
||||
- **`BACKOFF_429_S` als toter Code** (V9 Z.74): wird aktiviert, nicht entfernt
|
||||
- **Cache-Logik in `_schedule_transition`** (Z.345-349): wandert in Mediator
|
||||
- **`_last_sent_status` / `_last_sent_message`** als Engine-Felder (Z.115-116):
|
||||
werden zu Mediator-Feldern
|
||||
|
||||
### 7.4 Wird modifiziert
|
||||
|
||||
- **`_apply_counter_delta()`** (V9 Z.250-303) wird zu einem reinen Counter-Mutator +
|
||||
Phase-Resolver. KEINE direkten REST-Schedule-Calls mehr. Aufruf:
|
||||
`self._mediator.on_phase_transition(old_phase, new_phase)` bei Übergang.
|
||||
- **`_schedule_transition()` / `_send_transition()`** (V9 Z.330-377) werden zu
|
||||
Mediator-Methoden (`_mediator._send_rest_status()`). REST-Sender-Funktion
|
||||
(`_rest_set_status`) bleibt, wird vom Mediator aufgerufen.
|
||||
- **`_schedule_away_grace()` / `_cancel_away_grace()` / `_on_away_grace_expired()`**
|
||||
(V9 Z.381-414): Funktionalität bleibt, aber der away-grace wird zur
|
||||
Mediator-Verantwortung. Timer-Mechanik identisch.
|
||||
- **`get_status()`** Rückgabewerte bleiben `"ONLINE"|"BUSY"|"AWAY"` für
|
||||
Test-Kompatibilität. Mapping: P1→ONLINE, P2→BUSY, P3→ONLINE (visible side
|
||||
wechselt, aber interner Phase-Name bleibt), P4→BUSY (dito).
|
||||
- **Doku-Kommentar** im Modul-Header (V9 Z.1-20): komplett ersetzt durch
|
||||
V10-Architektur-Beschreibung.
|
||||
|
||||
---
|
||||
|
||||
## 8. Invarianten (V10)
|
||||
|
||||
| ID | Invariante | Test-Klasse (mapping aus V9) |
|
||||
|---|---|---|
|
||||
| I1 | `resolve_phase(counters)` ist deterministisch + pure | (neu: `TestPhaseResolver`) |
|
||||
| I2 | Phasen-Übergang erzeugt **maximal einen** REST-Call | `TestCounterTransition` (adaptiert) |
|
||||
| I3 | Counter-Delta ohne Phasen-Übergang erzeugt **0** REST-Calls | `TestCounterSum` + `TestMultipleSubagents` (adaptiert) |
|
||||
| I4 | Pulsing erfolgt nur in P3/P4, max. 1 Call pro `PULSE_INTERVAL_S` | (neu: `TestPulseTimer`) |
|
||||
| I5 | 429 setzt `rest_cooldown_until = now() + REST_BACKOFF_429_S` | `TestHttp429Handling` (adaptiert + erweitert) |
|
||||
| I6 | Während Cooldown: keine REST-Calls, Reconciliation nach Cooldown-Ende | (neu: `TestCooldownSuppression`, `TestReconcileAfterCooldown`) |
|
||||
| I7 | `disable()` cancelt away-grace UND stoppt Puls-Timer | `TestEnableDisable`, `TestShutdown` (adaptiert) |
|
||||
| I8 | Thread-Sicherheit: `transition_lock` + `mediator_lock` | `TestRaceParallelHooks` (adaptiert) |
|
||||
| I9 | Caching überspringt identische (Phase, Message) — gilt auch Puls-Ticks | `TestCaching` (neu/adaptiert) |
|
||||
| I10 | Reconciliation nach Cooldown: max. 1 Call, idempotent | (neu: `TestReconcileIdempotent`) |
|
||||
|
||||
---
|
||||
|
||||
## 9. Test-Konsequenzen (Konzept, keine Implementierung)
|
||||
|
||||
### 9.1 Tests die bleiben (ggf. minimal angepasst)
|
||||
|
||||
- `TestHookPreGatewayDispatch` / `TestHookPostLlmCall` / `TestHookSubagent*` /
|
||||
`TestHookSession*` / `TestHookBackgroundTerminal` (Z.59-209): unveraendert
|
||||
— Hooks rufen weiterhin `_apply_counter_delta` auf, das Verhalten ist nach
|
||||
außen identisch.
|
||||
- `TestCounterIncrement` / `TestCounterDecrement` / `TestCounterSum` (Z.211-276):
|
||||
testet Counter-Dict — bleibt.
|
||||
- `TestRaceParallelHooks` (Z.315-347): Thread-Sicherheit — bleibt relevant.
|
||||
|
||||
### 9.2 Tests die adaptiert werden müssen
|
||||
|
||||
- `TestCounterTransition` (Z.281-313): "BUSY"/"ONLINE" durch Phase-Enum +
|
||||
Mapping ersetzen. away-grace-Verhalten jetzt via Mediator.
|
||||
- `TestRaceLastWins` (Z.349-366): "last wins" jetzt auf Phase-Ebene, nicht
|
||||
Status-Ebene. Caching-Semantik unverändert, aber Schlüssel = Phase.
|
||||
- `TestHttp429Handling` (Z.458-516): testet jetzt zusätzlich
|
||||
`rest_cooldown_until` Setzung + Reconciliation-Verhalten.
|
||||
- `TestEnableDisable` / `TestShutdown` (Z.424-456): müssen auch `pulse_timer`
|
||||
canceln.
|
||||
|
||||
### 9.3 Tests die neu hinzukommen (V10-spezifisch)
|
||||
|
||||
- `TestPhaseResolver`: 4-5 Tests für `resolve_phase()` pure-Funktion (alle 16
|
||||
Counter-Kombinationen abdecken, nicht alle 2^4 = 16 nötig — Boundary-Cases reichen)
|
||||
- `TestPhaseTransitionRestCall`: Beweis dass N Counter-Deltas in derselben
|
||||
Phase nur 1-2 REST-Calls auslösen (nicht N)
|
||||
- `TestPulseTimerLifecycle`: P3/P4-Eintritt startet Timer, P3/P4-Austritt
|
||||
stoppt Timer, Takt = 3s ± Jitter
|
||||
- `TestCooldownSuppression`: Puls-Tick während Cooldown → kein Call, geloggt
|
||||
- `TestReconcileAfterCooldown`: nach 5s Cooldown genau 1 Call mit aktueller Phase
|
||||
- `TestReconcileIdempotent`: Reconciliation-Call wenn Phase identisch zu
|
||||
last_sent → Caching skip
|
||||
- `TestMediatorPhaseMapping`: Phase → sichtbarer Status String korrekt
|
||||
(P1→ONLINE, P2→BUSY, P3/P4→ONLINE/BUSY je nach Puls-Toggle)
|
||||
- `TestRestBackoffActivation`: nach 429 wird `REST_BACKOFF_429_S` aktiv (V9
|
||||
hatte das als toten Code, jetzt wird's geprüft)
|
||||
|
||||
### 9.4 Tests die sterben (V8.x-Reste)
|
||||
|
||||
- `@pytest.mark.skip` Klassen (Z.654-940): `TestPulseController*`,
|
||||
`TestDetectionTimer*`, `TestHoneymoonBusy*`, `TestHeartbeat*`,
|
||||
`TestPluginState*` — alle bereits in V9 als skipped markiert. In V10
|
||||
endgültig entfernen, da V10.x die Konzepte sauber ersetzt.
|
||||
|
||||
---
|
||||
|
||||
## 10. Konfigurations-Mapping (V9 → V10)
|
||||
|
||||
| V9-Konstante | V10-Zuordnung | Bemerkung |
|
||||
|---|---|---|
|
||||
| `AWAY_GRACE_DEFAULT_S: 2.0` | `MEDIATOR_AWAY_GRACE_S: 2.0` | bleibt, wandert zu Mediator |
|
||||
| `REST_TIMEOUT_S: 10.0` | unverändert | REST-Sender-Schicht |
|
||||
| `RETRY_DELAY_S: 2.0` | unverändert | REST-Sender-Schicht |
|
||||
| `BACKOFF_429_S: 5.0` | `REST_BACKOFF_429_S: 5.0` (Mediator) | war tot, jetzt aktiv |
|
||||
| (neu) | `PULSE_INTERVAL_S: 3.0` (Mediator) | war V8.x PulseController-Konstante |
|
||||
| (neu) | `COOLDOWN_RECONCILE_DELAY_S: 0.1` (Mediator) | Reconciliation-Timer-Verzögerung |
|
||||
| (neu) | `MEDIATOR_LOCK: threading.Lock` | schützt Mediator-State |
|
||||
|
||||
---
|
||||
|
||||
## 11. Risiken & offene Fragen
|
||||
|
||||
### 11.1 Sync-vs-Async-Frage (P-024-Familie)
|
||||
|
||||
Der Mediator läuft vollständig synchron im Threading-Modell, kompatibel zu V9.
|
||||
**Aber:** Wenn der Core irgendwann auf async-Hooks umgestellt wird (P-024-Langfrist),
|
||||
muss der Mediator nachziehen. Empfehlung: Mediator-API so gestalten, dass die
|
||||
async-Migration nur den Inner Loop (`on_phase_transition`) betrifft, nicht die
|
||||
äußere Struktur.
|
||||
|
||||
### 11.2 Reconciliation-Ordering
|
||||
|
||||
Was passiert, wenn während des Cooldowns Phase P3 → P1 wechselt UND ein
|
||||
Puls-Tick auf der neuen Phase läuft? Reconciliation-Order:
|
||||
1. Cooldown endet → Reconciliation-Timer feuert
|
||||
2. Reconciliation sendet aktuellen Phase-Status (P1 → online)
|
||||
3. Wenn Phase sich in Zwischenzeit geändert hat: Reconciliation verwendet
|
||||
**aktuelle** Phase, nicht die zur Cooldown-Start-Zeit
|
||||
4. Caching prüft ob Phase-Status identisch zu `last_sent` (sollte nie sein,
|
||||
da Cooldown alle Calls unterdrückt hat — aber defensive programming)
|
||||
|
||||
### 11.3 Doppel-Cooldown-Race
|
||||
|
||||
Zwei 429-Antworten in 10ms setzen `rest_cooldown_until` zweimal. Kein Problem
|
||||
(Idempotenz), aber Logging sollte beide Vorfälle zeigen. Telemetrie zählt
|
||||
jeden 429-Call separat, `cooldown_set_count` als neues Feld sinnvoll.
|
||||
|
||||
### 11.4 Pulse-Phase-Transition-Konflikt
|
||||
|
||||
Puls-Timer läuft in P3 (GRÜN↔GELB). Plötzlich Counter-Delta: main_agent = 1.
|
||||
Phase wechselt P3 → P4. Während dieses Übergangs läuft gerade ein Puls-Tick
|
||||
im Daemon-Thread. Lösung:
|
||||
- `mediator_lock` schützt Phase-Mutation
|
||||
- `on_phase_transition()` lockt Mediator, stoppt alten Timer, startet neuen
|
||||
- REST-Sender läuft zwar parallel, aber Caching auf Phase-Ebene verhindert
|
||||
widersprüchliche Calls (alter Status aus P3 + neuer Status aus P4 → Caching
|
||||
hilft nicht, aber Phase-Transition setzt `last_sent_phase` als atomischen
|
||||
Schritt)
|
||||
|
||||
### 11.5 Multi-Backend-Konsistenz
|
||||
|
||||
Falls später DDP und REST parallel genutzt werden (V8.x hatte das): V10
|
||||
definiert nur den REST-Pfad. DDP-Integration ist **out of scope** für V10
|
||||
und sollte in einem separaten Architektur-Auftrag behandelt werden.
|
||||
|
||||
---
|
||||
|
||||
## 12. Pitfall-Verweise (P-IDs)
|
||||
|
||||
| P-ID | Bezug in V10 |
|
||||
|---|---|
|
||||
| **P-010** (DDP/REST 429) | strukturell adressiert: Phasen-Übergang-only + Mediator-Cooldown. Safety-Net bleibt für RC-Quellen-429. |
|
||||
| **P-024** (async hooks) | Mediator bleibt sync, da Core aktuell sync ist. API so gestalten, dass async-Migration nur den Inner Loop betrifft. |
|
||||
| **P-028** (Booster Fuzzy) | nicht relevant für Presence-Engine. Kein Bezug. |
|
||||
| **(NEU)** `BACKOFF_429_S` toter Code in V9 Z.74 | in V10 aktiviert, nicht entfernt. Empfehlung: V10-Migration dokumentiert das. |
|
||||
| **(NEU)** V8.x PulseController-Reste in Tests (Z.654-940) | bereits `@pytest.mark.skip`. V10 räumt endgültig auf — siehe §9.4. |
|
||||
| **(NEU)** away-grace-Verantwortung wandert von Counter-Logik zu Mediator | semantische Verschiebung — Tests müssen `_schedule_away_grace` als Mediator-Aufruf verstehen, nicht als Engine-Aufruf |
|
||||
|
||||
---
|
||||
|
||||
## 13. Nächste Schritte
|
||||
|
||||
1. **Review-Gate:** Bernd + Andreas reviewen diesen Entwurf
|
||||
2. **V10-Spec-Datei** erstellen mit vollständiger Klassen-Signatur (verbale
|
||||
Beschreibung, kein Code — das ist Implementierungs-Aufgabe)
|
||||
3. **Migrations-Plan** V9 → V10: Welche Schritte in welcher Reihenfolge, wie
|
||||
lange läuft V9 parallel
|
||||
4. **Test-Strategie:** Neue Tests zuerst (TDD), dann V10-Implementation,
|
||||
dann V9-Altests anpassen, dann V8.x-Skips entfernen
|
||||
5. **Pre-Prod-Verifikation** auf .45 (MyTestBot) — siehe HANDLUNGSMANIFEST §4.2
|
||||
6. **Pitfalls-Sammlung updaten:** P-030 (V10-Phasen-Übergang-Semantik) + P-031
|
||||
(Mediator-Threading-Modell) als neue Einträge
|
||||
|
||||
---
|
||||
|
||||
*Ende des Architektur-Entwurfs. Code-Implementation ist explizit nicht Teil
|
||||
dieses Auftrags und muss separat beauftragt werden.*
|
||||
@@ -1,76 +0,0 @@
|
||||
# V10 Implementierungs-Auftrag für Miguel
|
||||
|
||||
## Architektur-Entwurf (verbindlich)
|
||||
Lese: `~/projekte/Hermes_rocket.chat_Plugin/docs/architecture/presence-mediator-layer-v10.md`
|
||||
Diese Datei enthält ALLE Details: 4 Phasen, 3-Schicht-Architektur, Mediator, Puls-Timer, 429-Cooldown, Reconciliation, Invarianten I1-I10, Test-Strategie.
|
||||
|
||||
## Aktueller Code
|
||||
`~/.hermes/plugins/platforms/rocketchat/archivar/presence_engine.py` (V9.2.3, ca. 500 Zeilen)
|
||||
|
||||
## TDD-Reihenfolge (Tests zuerst)
|
||||
|
||||
### 1. Phase-Enum + resolve_phase
|
||||
- Phase-Enum (P1-P4) erstellen
|
||||
- resolve_phase(counters) pure Funktion
|
||||
- Tests: TestPhaseResolver
|
||||
|
||||
### 2. Mediator-Komponente
|
||||
- current_phase, pulse_timer, rest_cooldown_until, mediator_lock
|
||||
- on_phase_transition(old, new) — startet/stoppt Puls-Timer, sendet REST
|
||||
- start_pulse() / stop_pulse() — 3s Takt, toggelnd
|
||||
- request_rest_status(status, message) — mit Cooldown-Suppression
|
||||
- reconcile_after_cooldown() — 1-shot Timer nach Cooldown-Ende
|
||||
- Tests: TestPulseTimerLifecycle, TestCooldownSuppression, TestReconcileAfterCooldown, TestReconcileIdempotent, TestMediatorPhaseMapping
|
||||
|
||||
### 3. V9-Adaptation
|
||||
- _apply_counter_delta → ruft resolve_phase + mediator.on_phase_transition
|
||||
- _schedule_transition / _send_transition → wandern in Mediator
|
||||
- _schedule_away_grace / _cancel_away_grace → Mediator-Verantwortung
|
||||
- get_status() bleibt ONLINE|BUSY|AWAY (Mapping: P1=ONLINE, P2=BUSY, P3=ONLINE, P4=BUSY)
|
||||
- get_visible_status() NEU: liefert Puls-Toggle
|
||||
- Tests adaptieren: TestCounterTransition, TestRaceLastWins, TestHttp429Handling, TestEnableDisable, TestShutdown
|
||||
|
||||
### 4. Cleanup
|
||||
- V8.x skipped Tests endgueltig entfernen
|
||||
- BACKOFF_429_S toten Code aktivieren (als REST_BACKOFF_429_S im Mediator)
|
||||
- TestPresenceCachingSkipsRedundant (pass-Bodies) fuellen
|
||||
- Tests: TestRestBackoffActivation
|
||||
|
||||
## Invarianten (alle muessen erfuellt sein)
|
||||
- I1: resolve_phase deterministisch + pure
|
||||
- I2: Phasen-Uebergang erzeugt maximal 1 REST-Call
|
||||
- I3: Counter-Delta ohne Phasen-Uebergang erzeugt 0 REST-Calls
|
||||
- I4: Pulsing nur in P3/P4, max 1 Call pro PULSE_INTERVAL_S (3s)
|
||||
- I5: 429 setzt rest_cooldown_until = now() + 5s
|
||||
- I6: Waehrend Cooldown keine REST-Calls, Reconciliation nach Ende
|
||||
- I7: disable() cancelt away-grace UND stoppt Puls-Timer
|
||||
- I8: Thread-Sicherheit: transition_lock + mediator_lock
|
||||
- I9: Caching ueberspringt identische (Phase, Message)
|
||||
- I10: Reconciliation max 1 Call, idempotent
|
||||
|
||||
## Konstanten
|
||||
- PULSE_INTERVAL_S = 3.0 (Mediator)
|
||||
- REST_BACKOFF_429_S = 5.0 (Mediator, war toter Code in V9)
|
||||
- AWAY_GRACE_DEFAULT_S = 2.0 (bleibt, wandert zu Mediator)
|
||||
- REST_TIMEOUT_S = 10.0 (bleibt, REST-Sender)
|
||||
- RETRY_DELAY_S = 2.0 (bleibt, REST-Sender)
|
||||
|
||||
## Wichtig
|
||||
- Alle Hooks bleiben SYNCHRON (P-024)
|
||||
- Counter-Dict bleibt unveraendert (4 Zaehler)
|
||||
- 6 Core-Hooks + 2 Tool-Filter-Hooks bleiben unveraendert
|
||||
- REST-Sender (fire-and-forget Daemon-Thread) bleibt unveraendert
|
||||
- Kein async/await — threading.Lock + threading.Timer
|
||||
|
||||
## Quality Gates
|
||||
- F1: Syntax-Check
|
||||
- F2: Alle Tests gruen (pytest tests/test_presence_engine.py -v)
|
||||
- F3: Architektur — 3-Schicht-Trennung sauber
|
||||
- F4: Pitfall-Check
|
||||
- F7: Neuer Pitfall?
|
||||
|
||||
## Pitfall-Verweis
|
||||
/data/Wissensdatenbank/0299 Projektdokumentationen/Pitfalls & Lessons Learned.md
|
||||
|
||||
Flagge neue Pitfalls im Rueckkehr-Report.
|
||||
Commit mit klarer Message (V10.0.0). KEIN Push.
|
||||
@@ -1,675 +0,0 @@
|
||||
# F6 R27: Quick-Reply Dedup + Same-Raum-UX-Text
|
||||
|
||||
> Plan für Miguel — Implementation auf Branch `fix/f6-r27-quick-reply-dedup`
|
||||
> Stand: HEAD 5c22391 auf .45 (P5 V9.x live) und lokal
|
||||
|
||||
**Goal:** Quick-Reply aus dem OutboundGate wird pro aktivem Stream genau EINMAL
|
||||
gesendet (statt 3× bei parallelen `_dispatch_agent`-Tasks) und der Text ist im
|
||||
Same-Raum-Fall nicht mehr zirkulär.
|
||||
|
||||
**Architecture:**
|
||||
- `_TurnHandle` bekommt ein Flag `quick_reply_sent: bool` (Gate-interne Wahrheit).
|
||||
- OutboundGate exponiert zwei Public-Methoden `mark_quick_reply_sent()` und
|
||||
`quick_reply_already_sent()` (Race-frei via `_lock`).
|
||||
- adapter.py bekommt einen Helper `_maybe_send_quick_reply(...)` der den Flag
|
||||
atomar prüft + setzt; beide Aufrufer (`send()` Z.6629-6648, `send_clarify()`
|
||||
Z.7085-7099) rufen nur noch den Helper.
|
||||
- UX-Text-Auswahl passiert kontextabhängig im Helper: gleicher Trigger-Raum
|
||||
wie aktiver Raum → kompakter Text, ohne Raum-Referenz.
|
||||
|
||||
**Tech Stack:** Python 3.13, asyncio, pytest, pytest-asyncio (in venv).
|
||||
|
||||
---
|
||||
|
||||
## Phase A — outbound_gate.py erweitern
|
||||
|
||||
**File:** `plugin/archivar/outbound_gate.py`
|
||||
|
||||
### Task A1: Flag an `_TurnHandle` anhängen
|
||||
|
||||
**Step 1 — Lesen:** `_TurnHandle` liegt in outbound_gate.py Z.44-60.
|
||||
|
||||
**Step 2 — Edit:** Füge ein Feld `quick_reply_sent: bool = False` an den
|
||||
Dataclass an. HINTER `chat_id: str = ""` (Z.60). Neuer Eintrag:
|
||||
|
||||
```
|
||||
quick_reply_sent: bool = False
|
||||
```
|
||||
|
||||
Begründung: Dataclass-Felder mit Default MÜSSEN nach feldern ohne Default
|
||||
kommen — `chat_id` hat schon `= ""`, also passt die Reihenfolge direkt danach.
|
||||
|
||||
**Step 3 — Verifizieren:**
|
||||
|
||||
```bash
|
||||
cd /home/bernd/projekte/Hermes_rocket.chat_Plugin
|
||||
./venv/bin/python -c "from plugin.archivar.outbound_gate import _TurnHandle; \
|
||||
h = _TurnHandle(task_token='t', started_at=0.0, real_room_id='r'); \
|
||||
assert h.quick_reply_sent is False; print('OK')"
|
||||
```
|
||||
|
||||
Erwartet: `OK`
|
||||
|
||||
**Step 4 — Commit:**
|
||||
|
||||
```bash
|
||||
git add plugin/archivar/outbound_gate.py
|
||||
git commit -m "feat(outbound_gate): quick_reply_sent flag on _TurnHandle"
|
||||
```
|
||||
|
||||
### Task A2: Public-Methoden `mark_quick_reply_sent` + `quick_reply_already_sent`
|
||||
|
||||
**Step 1 — Lesen:** `try_acquire` endet in outbound_gate.py bei Z.228.
|
||||
Die neuen Methoden kommen direkt darunter (zwischen `try_acquire` und
|
||||
`release`, Z.229).
|
||||
|
||||
**Step 2 — Edit:** Zwei neue Methoden auf `OutboundGate` einfügen.
|
||||
|
||||
```
|
||||
async def mark_quick_reply_sent(self, room_id: str) -> bool:
|
||||
"""Markiert den aktuellen Turn für room_id als Quick-Reply-gesendet.
|
||||
|
||||
Wird vom adapter-Helper _maybe_send_quick_reply aufgerufen NACHDEM
|
||||
die Nachricht erfolgreich gepostet wurde. Setzt das Flag am
|
||||
_TurnHandle atomar unter dem _lock.
|
||||
|
||||
Idempotent: zweiter Aufruf ist No-Op (gibt False zurück).
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID (Gate-Key).
|
||||
|
||||
Returns:
|
||||
True wenn das Flag gesetzt wurde, False wenn der Raum nicht
|
||||
(mehr) in _in_flight ist oder das Flag schon gesetzt war.
|
||||
"""
|
||||
async with self._lock:
|
||||
handle = self._in_flight.get(room_id)
|
||||
if handle is None:
|
||||
return False
|
||||
if handle.quick_reply_sent:
|
||||
return False
|
||||
handle.quick_reply_sent = True
|
||||
return True
|
||||
|
||||
|
||||
def quick_reply_already_sent(self, room_id: str) -> bool:
|
||||
"""Prüft (lock-frei) ob für room_id bereits eine Quick-Reply gesendet wurde.
|
||||
|
||||
Lock-frei weil es nur ein Boolean-Read ist — falls parallel ein
|
||||
mark_quick_reply_sent läuft, bekommen wir entweder den alten oder
|
||||
den neuen Wert; beides ist semantisch korrekt (entweder senden
|
||||
wir noch oder nicht mehr).
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID (Gate-Key).
|
||||
|
||||
Returns:
|
||||
True wenn bereits eine Quick-Reply gesendet wurde.
|
||||
"""
|
||||
handle = self._in_flight.get(room_id)
|
||||
return bool(handle and handle.quick_reply_sent)
|
||||
```
|
||||
|
||||
**Step 3 — Verifizieren (Smoke ohne Tests):**
|
||||
|
||||
```bash
|
||||
./venv/bin/python -c "
|
||||
import asyncio
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
|
||||
async def main():
|
||||
g = OutboundGate()
|
||||
d = await g.try_acquire('room_a', 'tok_a')
|
||||
assert d.allow
|
||||
assert g.quick_reply_already_sent('room_a') is False
|
||||
ok = await g.mark_quick_reply_sent('room_a')
|
||||
assert ok is True
|
||||
assert g.quick_reply_already_sent('room_a') is True
|
||||
# idempotent
|
||||
ok2 = await g.mark_quick_reply_sent('room_a')
|
||||
assert ok2 is False
|
||||
print('OK')
|
||||
asyncio.run(main())
|
||||
"
|
||||
```
|
||||
|
||||
Erwartet: `OK`
|
||||
|
||||
**Step 4 — Commit:**
|
||||
|
||||
```bash
|
||||
git add plugin/archivar/outbound_gate.py
|
||||
git commit -m "feat(outbound_gate): mark_quick_reply_sent + quick_reply_already_sent"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase B — Gate-Tests rot schreiben (TDD red)
|
||||
|
||||
**File:** `plugin/archivar/tests/test_outbound_gate.py`
|
||||
|
||||
### Task B1: 3 neue Unit-Tests
|
||||
|
||||
**Step 1 — Lesen:** Datei hat 282 Zeilen, endet mit
|
||||
`test_outbound_gate_stats_defaults` (Z.270-282). Neue Tests werden
|
||||
**vor** der Helper-Implementation ROT sein (expected) und nach A2 GRÜN.
|
||||
|
||||
**Step 2 — Edit:** Drei neue Tests am Ende der Datei anhängen
|
||||
(NACH `test_outbound_gate_stats_defaults`).
|
||||
|
||||
Test 1 — `test_outbound_gate_quick_reply_flag_default_false`:
|
||||
|
||||
```python
|
||||
@pytest.mark.outbound_gate
|
||||
@pytest.mark.asyncio
|
||||
async def test_outbound_gate_quick_reply_flag_default_false():
|
||||
"""6.1: Frisch erworbener Slot hat quick_reply_sent=False per Default.
|
||||
|
||||
Regression-Schutz: das Flag darf den Default _TurnHandle nicht
|
||||
brechen. try_acquire legt den Handle an — das Flag muss initial
|
||||
False sein, sonst ist die Dedup-Logik tot.
|
||||
"""
|
||||
gate = OutboundGate()
|
||||
decision = await gate.try_acquire("room_a", "tok_a")
|
||||
assert decision.allow
|
||||
assert gate.quick_reply_already_sent("room_a") is False
|
||||
gate.release("room_a", "tok_a")
|
||||
```
|
||||
|
||||
Test 2 — `test_outbound_gate_mark_quick_reply_sent_idempotent`:
|
||||
|
||||
```python
|
||||
@pytest.mark.outbound_gate
|
||||
@pytest.mark.asyncio
|
||||
async def test_outbound_gate_mark_quick_reply_sent_idempotent():
|
||||
"""6.2: mark_quick_reply_sent ist idempotent.
|
||||
|
||||
Erster Aufruf setzt das Flag (True), zweiter Aufruf ist No-Op
|
||||
(gibt False zurück, ändert aber nichts am Flag-Zustand).
|
||||
quick_reply_already_sent bleibt True.
|
||||
"""
|
||||
gate = OutboundGate()
|
||||
await gate.try_acquire("room_a", "tok_a")
|
||||
first = await gate.mark_quick_reply_sent("room_a")
|
||||
assert first is True
|
||||
second = await gate.mark_quick_reply_sent("room_a")
|
||||
assert second is False
|
||||
assert gate.quick_reply_already_sent("room_a") is True
|
||||
gate.release("room_a", "tok_a")
|
||||
```
|
||||
|
||||
Test 3 — `test_outbound_gate_mark_quick_reply_no_such_room`:
|
||||
|
||||
```python
|
||||
@pytest.mark.outbound_gate
|
||||
@pytest.mark.asyncio
|
||||
async def test_outbound_gate_mark_quick_reply_no_such_room():
|
||||
"""6.3: mark_quick_reply_sent auf unbekanntem Raum gibt False zurück.
|
||||
|
||||
Race-Schutz: wenn der Stream release() zwischen wait_until_clear
|
||||
und mark_quick_reply_sent aufgerufen hat, ist der Handle weg.
|
||||
Kein Crash, False zurück.
|
||||
"""
|
||||
gate = OutboundGate()
|
||||
# Kein try_acquire vorher
|
||||
result = await gate.mark_quick_reply_sent("nonexistent")
|
||||
assert result is False
|
||||
assert gate.quick_reply_already_sent("nonexistent") is False
|
||||
```
|
||||
|
||||
**Step 3 — Tests ROT laufen lassen:**
|
||||
|
||||
```bash
|
||||
cd /home/bernd/projekte/Hermes_rocket.chat_Plugin
|
||||
./venv/bin/python -m pytest plugin/archivar/tests/test_outbound_gate.py -v --tb=short 2>&1 | tail -25
|
||||
```
|
||||
|
||||
Erwartet: 7 PASSED, 3 FAILED (AttributeError: OutboundGate has no attribute
|
||||
`mark_quick_reply_sent` / `quick_reply_already_sent`). Das ist ROT — gut.
|
||||
|
||||
**Step 4 — Tests GRÜN machen:** A2 ist schon implementiert, also:
|
||||
|
||||
```bash
|
||||
./venv/bin/python -m pytest plugin/archivar/tests/test_outbound_gate.py -v --tb=short 2>&1 | tail -15
|
||||
```
|
||||
|
||||
Erwartet: 10 PASSED.
|
||||
|
||||
**Step 5 — Commit:**
|
||||
|
||||
```bash
|
||||
git add plugin/archivar/tests/test_outbound_gate.py
|
||||
git commit -m "test(outbound_gate): 3 tests for quick_reply_sent flag + idempotency"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase C — adapter.py: Dedup-Helper + UX-Text-Logik
|
||||
|
||||
**File:** `plugin/adapter.py`
|
||||
|
||||
### Task C1: Helper `_maybe_send_quick_reply` einfügen
|
||||
|
||||
**Step 1 — Lokalisieren:** Beide Quick-Reply-Blöcke sind in `send()`
|
||||
(Z.6629-6648) und `send_clarify()` (Z.7085-7099) textidentisch (Doppelung).
|
||||
Der Helper ersetzt BEIDE Blöcke.
|
||||
|
||||
**Step 2 — Edit:** Neuen Helper direkt VOR `send()` einfügen, also vor der
|
||||
`async def send(self, ...):` Definition. Suche die Zeile mit
|
||||
`async def send(self, chat_id: str, content: str,` und füge DAVOR ein:
|
||||
|
||||
```python
|
||||
async def _maybe_send_quick_reply(
|
||||
self,
|
||||
gate_room_id: str,
|
||||
trigger_room_id: str,
|
||||
) -> bool:
|
||||
"""Sendet eine Quick-Reply (Gate-blockiert) — maximal EINMAL pro aktivem Stream.
|
||||
|
||||
BUG-FIX F6 R27: Ohne Dedup feuerten send() und send_clarify() beide
|
||||
unabhängig ihren Quick-Reply-Block, und bei parallelen _dispatch_agent-
|
||||
Tasks (3. Trigger) kam es zu Mehrfach-Sends. Dieses Helper ist die
|
||||
einzige Stelle die `await self._post_message_unlocked(...)` mit dem
|
||||
Quick-Reply-Text aufruft; der Flag-Check lebt im OutboundGate.
|
||||
|
||||
BUG-FIX F6 R27 (UX): Wenn der Trigger-Raum == aktiver Raum ist, wird
|
||||
der Text OHNE Raum-Referenz gesendet ('Ich bin gerade beschäftigt — ...').
|
||||
Sonst MIT Raum-Referenz (bisheriger Text). Begründung: zirkulärer
|
||||
Text ('ich antworte gerade in #hier') wirkt mechanisch.
|
||||
|
||||
Args:
|
||||
gate_room_id: Raum-ID unter dem das Gate den Eintrag hat
|
||||
(real_room_id aus _TurnHandle, = _gate_room_id in den Call-Sites).
|
||||
trigger_room_id: Raum in den der User gerade schreibt (an den die
|
||||
Quick-Reply geht). Für Same-Raum-Vergleich.
|
||||
|
||||
Returns:
|
||||
True wenn eine Quick-Reply gesendet wurde, False wenn bereits
|
||||
eine gesendet wurde (Dedup-Treffer) oder Gate fehlt.
|
||||
"""
|
||||
gate = getattr(self, '_outbound_gate', None)
|
||||
if gate is None:
|
||||
return False
|
||||
if gate.quick_reply_already_sent(gate_room_id):
|
||||
logger.debug(
|
||||
"[rocketchat] F6 R27: Quick-Reply dedup hit for room=%s — skip",
|
||||
gate_room_id[:8],
|
||||
)
|
||||
return False
|
||||
|
||||
active_room = gate.active_room_id
|
||||
active_name = ""
|
||||
if active_room and active_room in self._room_info:
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
|
||||
same_room = (active_room is not None and active_room == trigger_room_id)
|
||||
if same_room:
|
||||
# BUG 2 (F6 R27): Trigger-Raum == aktiver Raum → kompakter Text,
|
||||
# OHNE Raum-Referenz. Wir sagen NICHT 'ich antworte gerade hier'
|
||||
# (zirkulär), sondern 'ich bin gerade beschäftigt'.
|
||||
quick_reply_text = (
|
||||
"Ich bin gerade beschäftigt — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
elif active_name:
|
||||
# Cross-Raum: bisheriger Text mit Raum-Referenz.
|
||||
quick_reply_text = (
|
||||
f"Ich antworte gerade in #{active_name} — "
|
||||
f"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
else:
|
||||
# Cross-Raum aber Name unbekannt (z.B. DM-Raum ohne Eintrag in _room_info).
|
||||
quick_reply_text = (
|
||||
"Ich antworte gerade in einem anderen Raum — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
|
||||
await self._post_message_unlocked(trigger_room_id, quick_reply_text)
|
||||
gate.stats.quick_reply += 1
|
||||
await gate.mark_quick_reply_sent(gate_room_id)
|
||||
logger.info(
|
||||
"[rocketchat] F6 R27: Quick-Reply sent to room=%s (same_room=%s blocked_by=%s)",
|
||||
trigger_room_id[:8], same_room, active_name,
|
||||
)
|
||||
return True
|
||||
```
|
||||
|
||||
Begründung Same-Raum-Vergleich: `active_room` ist der Raum, in dem der
|
||||
Gate-Eintrag liegt (= der Raum in dem der Agent gerade sendet). `trigger_room_id`
|
||||
ist der Raum in den der User gerade schreibt. Wenn beide gleich sind, ist der
|
||||
User im SELBEN Raum in dem der Agent arbeitet — klassischer Same-Raum-Trigger
|
||||
(Stream-Retry-Mismatch via `same_room_different_token`).
|
||||
|
||||
### Task C2: Quick-Reply-Block in `send()` durch Helper ersetzen
|
||||
|
||||
**File:** `plugin/adapter.py` Z.6629-6648 (alter Code)
|
||||
|
||||
**Alter Code (Z.6629-6648):**
|
||||
|
||||
```python
|
||||
if not decision.allow:
|
||||
# Quick-Reply: anderer Raum blockiert immer noch
|
||||
active_room = self._outbound_gate.active_room_id
|
||||
active_name = ""
|
||||
if active_room and active_room in self._room_info:
|
||||
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||
quick_reply_text = (
|
||||
f"Ich antworte gerade in #{active_name} — "
|
||||
f"einen Moment bitte, ich bin gleich bei dir."
|
||||
) if active_name else (
|
||||
"Ich antworte gerade in einem anderen Raum — "
|
||||
"einen Moment bitte, ich bin gleich bei dir."
|
||||
)
|
||||
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||
self._outbound_gate.stats.quick_reply += 1
|
||||
logger.info(
|
||||
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
|
||||
_gate_room_id[:8], active_name,
|
||||
)
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
```
|
||||
|
||||
**Neuer Code (5 Zeilen):**
|
||||
|
||||
```python
|
||||
if not decision.allow:
|
||||
# F6 R27: Dedup via _maybe_send_quick_reply — nur 1x pro Stream.
|
||||
if await self._maybe_send_quick_reply(_gate_room_id, _gate_room_id):
|
||||
return SendResult(success=True, message_id="quick_reply")
|
||||
# Bereits gesendet (paralleler Task) — return ohne Erfolg-Flag.
|
||||
return SendResult(success=True, message_id="quick_reply_dedup")
|
||||
```
|
||||
|
||||
Begründung: `trigger_room_id == _gate_room_id` (Same-Raum-Vergleichs-Input
|
||||
ist hier der Gate-Raum selbst, weil in `send()` der Trigger-Raum = der Raum
|
||||
ist in den geschrieben werden soll = der Gate-Raum). Der Helper erkennt
|
||||
same_room=True selbst.
|
||||
|
||||
### Task C3: Quick-Reply-Block in `send_clarify()` durch Helper ersetzen
|
||||
|
||||
**File:** `plugin/adapter.py` Z.7085-7099 (alter Code)
|
||||
|
||||
**Alter Code (Z.7085-7099):** identisch zu C2 alter Code, anderer Docstring-Kommentar.
|
||||
|
||||
**Neuer Code:** identisch zu C2 neuer Code (Copy-Paste der 5 Zeilen).
|
||||
|
||||
**Step 1 — Verifizieren (komplette Suite):**
|
||||
|
||||
```bash
|
||||
cd /home/bernd/projekte/Hermes_rocket.chat_Plugin
|
||||
./venv/bin/python -m pytest plugin/archivar/tests/test_outbound_gate.py -v 2>&1 | tail -15
|
||||
```
|
||||
|
||||
Erwartet: 10/10 PASSED.
|
||||
|
||||
**Step 2 — Commit:**
|
||||
|
||||
```bash
|
||||
git add plugin/adapter.py
|
||||
git commit -m "fix(adapter): F6 R27 — dedup quick-reply via helper + same-room UX text"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase D — Integration-Test
|
||||
|
||||
**File:** `plugin/archivar/tests/test_outbound_gate.py` (am Ende anhängen)
|
||||
|
||||
### Task D1: Parallel-Tasks-Dedup-Test
|
||||
|
||||
**Test (NEU):**
|
||||
|
||||
```python
|
||||
@pytest.mark.outbound_gate
|
||||
@pytest.mark.asyncio
|
||||
async def test_outbound_gate_parallel_acquires_only_one_quick_reply():
|
||||
"""6.4: 3 parallele 'Tasks' die alle blockiert werden → nur 1 Quick-Reply-Logik.
|
||||
|
||||
Reproduziert das Bug-Szenario: drei paralleler _dispatch_agent-Tasks
|
||||
rufen try_acquire für drei verschiedene Token auf denselben blockierten
|
||||
Raum auf. Alle drei bekommen 'allow=False'. Bei Bug waren das 3 Quick-
|
||||
Replies; mit Fix wird das quick_reply_sent-Flag nur beim ersten
|
||||
Setz-Versuch True, die anderen 2 sehen das Flag und returnen sofort.
|
||||
|
||||
Test simuliert das auf Gate-Ebene: drei sequentielle
|
||||
mark_quick_reply_sent-Aufrufe → nur der erste gibt True zurück.
|
||||
Der Adapter-_maybe_send_quick_reply-Smoke wird im adapter-Test (Phase D2)
|
||||
separat geprüft.
|
||||
"""
|
||||
gate = OutboundGate(default_timeout_s=0.1, max_entry_age_s=60.0)
|
||||
room_a = "room_a"
|
||||
room_b = "room_b"
|
||||
|
||||
# Raum A akquiriert (blockt B)
|
||||
d_a = await gate.try_acquire(room_a, "tok_a")
|
||||
assert d_a.allow
|
||||
|
||||
# 3 parallele Tasks versuchen Raum B → alle blockiert
|
||||
decisions = await asyncio.gather(
|
||||
gate.try_acquire(room_b, "tok_b1"),
|
||||
gate.try_acquire(room_b, "tok_b2"),
|
||||
gate.try_acquire(room_b, "tok_b3"),
|
||||
)
|
||||
assert all(not d.allow for d in decisions)
|
||||
assert all(d.reason == "different_room_busy" for d in decisions)
|
||||
|
||||
# 3 sequentielle mark_quick_reply_sent für room_a (= blockierender Raum)
|
||||
r1 = await gate.mark_quick_reply_sent(room_a)
|
||||
r2 = await gate.mark_quick_reply_sent(room_a)
|
||||
r3 = await gate.mark_quick_reply_sent(room_a)
|
||||
assert r1 is True
|
||||
assert r2 is False
|
||||
assert r3 is False
|
||||
assert gate.stats.quick_reply == 0 # Counter wird im Helper, nicht im Gate gesetzt
|
||||
|
||||
# Cleanup
|
||||
gate.release(room_a, "tok_a")
|
||||
```
|
||||
|
||||
**Step 1 — Test laufen:**
|
||||
|
||||
```bash
|
||||
cd /home/bernd/projekte/Hermes_rocket.chat_Plugin
|
||||
./venv/bin/python -m pytest plugin/archivar/tests/test_outbound_gate.py::test_outbound_gate_parallel_acquires_only_one_quick_reply -v
|
||||
```
|
||||
|
||||
Erwartet: PASSED.
|
||||
|
||||
### Task D2: Adapter-Smoke für `_maybe_send_quick_reply`
|
||||
|
||||
**File:** `tests/test_adapter.py` (Haupt-Testverzeichnis, NICHT archivar/tests)
|
||||
oder NEU `plugin/archivar/tests/test_quick_reply_dedup.py` — Miguel wählt.
|
||||
|
||||
**Empfehlung:** Neue Datei `plugin/archivar/tests/test_quick_reply_dedup.py`
|
||||
weil:
|
||||
- Keep archivar-Tests zusammen
|
||||
- Adapter-Tests dort sind mock-heavy, smoke ist hier einfacher
|
||||
|
||||
**Test-Skizze (NEU in test_quick_reply_dedup.py):**
|
||||
|
||||
```python
|
||||
"""F6 R27: Adapter-Helper _maybe_send_quick_reply — Dedup + Same-Raum-UX-Text."""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_maybe_send_quick_reply_dedups_within_same_stream():
|
||||
"""Helper sendet beim 2. Aufruf NICHT erneut (Dedup)."""
|
||||
adapter = MagicMock()
|
||||
adapter._room_info = {"room_b": {"name": "andreas"}}
|
||||
gate = OutboundGate()
|
||||
adapter._outbound_gate = gate
|
||||
adapter._post_message_unlocked = AsyncMock()
|
||||
|
||||
# Raum A blockt
|
||||
await gate.try_acquire("room_a", "tok_a")
|
||||
decision = await gate.try_acquire("room_b", "tok_b")
|
||||
assert not decision.allow
|
||||
|
||||
# Helper am Adapter aufrufen
|
||||
from plugin.adapter import RocketChatAdapter # noqa: F401
|
||||
|
||||
# Direkter Helper-Aufruf: wir holen ihn aus der Klasse
|
||||
helper = getattr(RocketChatAdapter, "_maybe_send_quick_reply")
|
||||
r1 = await helper(adapter, "room_a", "room_b")
|
||||
r2 = await helper(adapter, "room_a", "room_b")
|
||||
assert r1 is True
|
||||
assert r2 is False
|
||||
assert adapter._post_message_unlocked.await_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_maybe_send_quick_reply_same_room_omits_room_reference():
|
||||
"""Same-Raum-Trigger: Quick-Reply OHNE Raum-Referenz."""
|
||||
adapter = MagicMock()
|
||||
adapter._room_info = {"room_a": {"name": "andreas"}}
|
||||
gate = OutboundGate()
|
||||
adapter._outbound_gate = gate
|
||||
adapter._post_message_unlocked = AsyncMock()
|
||||
|
||||
# Raum A akquiriert mit Token-A, ein 2. Task versucht denselben Raum mit Token-B
|
||||
# → same_room_different_token → blockiert OHNE blocking_room_id → direkter Quick-Reply-Pfad
|
||||
await gate.try_acquire("room_a", "tok_a")
|
||||
decision = await gate.try_acquire("room_a", "tok_b")
|
||||
assert not decision.allow
|
||||
assert decision.reason == "same_room_different_token"
|
||||
|
||||
from plugin.adapter import RocketChatAdapter # noqa: F401
|
||||
helper = getattr(RocketChatAdapter, "_maybe_send_quick_reply")
|
||||
sent = await helper(adapter, "room_a", "room_a")
|
||||
assert sent is True
|
||||
text = adapter._post_message_unlocked.await_args.args[1]
|
||||
# Same-Raum-Text: KEIN '#andreas' im String
|
||||
assert "#" not in text
|
||||
assert "beschäftigt" in text
|
||||
```
|
||||
|
||||
**Falls `RocketChatAdapter` einen teuren Import hat** (z.B. requests), dann
|
||||
lokale Hilfs-Klasse anlegen — siehe Plan-Ende "Hinweise".
|
||||
|
||||
**Step 1 — Test laufen:**
|
||||
|
||||
```bash
|
||||
cd /home/bernd/projekte/Hermes_rocket.chat_Plugin
|
||||
./venv/bin/python -m pytest plugin/archivar/tests/test_quick_reply_dedup.py -v
|
||||
```
|
||||
|
||||
Erwartet: 2 PASSED.
|
||||
|
||||
**Step 2 — Commit:**
|
||||
|
||||
```bash
|
||||
git add plugin/archivar/tests/test_outbound_gate.py
|
||||
git add plugin/archivar/tests/test_quick_reply_dedup.py
|
||||
git commit -m "test: F6 R27 parallel-tasks dedup + same-room UX smoke"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase E — Smoke auf .45
|
||||
|
||||
**Server:** `192.168.180.45`, Pfad `~/.hermes/plugins/platforms/rocketchat/`
|
||||
|
||||
### Task E1: Pull + Tests
|
||||
|
||||
```bash
|
||||
ssh bernd@192.168.180.45
|
||||
cd ~/.hermes/plugins/platforms/rocketchat
|
||||
git pull origin fix/f6-r27-quick-reply-dedup
|
||||
source venv/bin/activate # oder direkt venv/bin/python
|
||||
./venv/bin/python -m pytest plugin/archivar/tests/test_outbound_gate.py \
|
||||
plugin/archivar/tests/test_quick_reply_dedup.py -v
|
||||
```
|
||||
|
||||
Erwartet: 12/12 PASSED (10 alte + 1 aus D1 + 2 aus D2 — bzw. 11/11 wenn D1
|
||||
in test_outbound_gate.py ist und D2 separat).
|
||||
|
||||
### Task E2: Live-Plugin-Restart
|
||||
|
||||
```bash
|
||||
# Service stoppen, neu starten, 10s warten, Log prüfen
|
||||
sudo systemctl restart hermes-rocketchat-plugin # oder: install.sh re-run
|
||||
sleep 10
|
||||
journalctl -u hermes-rocketchat-plugin --since "1 minute ago" | grep -E "F6 R27|quick_reply|outbound_gate" | tail -20
|
||||
```
|
||||
|
||||
Erwartet: keine Exceptions, ggf. Startup-Log mit OutboundGate-Init.
|
||||
|
||||
### Task E3: Manueller Smoke-Test (Rocket.Chat)
|
||||
|
||||
Vorbedingung: zwei Browser-Tabs offen mit unterschiedlichen Räumen (z.B. #andreas und #test).
|
||||
|
||||
1. In #andreas: `!ping 30` oder ähnlich (long-running command der das Gate blockiert)
|
||||
2. Während der Agent in #andreas beschäftigt ist, in #test schreiben
|
||||
3. **Erwartet (BUG 1):** Genau EINE Quick-Reply in #test (nicht 3)
|
||||
4. **Erwartet (BUG 2 — alt):** Text "Ich antworte gerade in #andreas ..."
|
||||
5. **Erwartet (BUG 2 — neu):** Text "Ich bin gerade beschäftigt — einen Moment bitte, ich bin gleich bei dir." (kein '#andreas')
|
||||
|
||||
Same-Raum-Test (für BUG 2):
|
||||
|
||||
1. In #andreas: `!ping 30`
|
||||
2. Während der Agent im #andreas beschäftigt ist, NOCHMAL in #andreas schreiben
|
||||
3. **Erwartet:** Quick-Reply OHNE '#andreas' im Text
|
||||
|
||||
Bei Misserfolg: Log-Capture + sofort Rollback mit `git revert HEAD~3..HEAD`.
|
||||
|
||||
---
|
||||
|
||||
## Quality Gate F1-F6
|
||||
|
||||
Nach Phase E, vor dem Push nach `main`:
|
||||
|
||||
| Gate | Kriterium | Command |
|
||||
|------|-----------|---------|
|
||||
| **F1** | Security: keine Secrets, kein shell-injection | `git diff HEAD~5 HEAD \| grep -iE "(api_key\|secret\|password\|token).*=.*['\"][^'\"]{6,}['\"]"` (leer) |
|
||||
| **F2** | Vollständige Suite grün | `./venv/bin/python -m pytest --tb=no -q 2>&1 \| tail -3` — keine NEW failures vs. Baseline 37 pre-existing |
|
||||
| **F3** | Outbound-Gate-Suite grün | `./venv/bin/python -m pytest plugin/archivar/tests/test_outbound_gate.py plugin/archivar/tests/test_quick_reply_dedup.py -v` — 12/12 |
|
||||
| **F4** | Keine Code-Block-Verschmutzung im Diff | `git diff HEAD~5 HEAD -- plugin/ \| wc -l` — Diff-Größe plausibel (<300 Zeilen für 3 Commits) |
|
||||
| **F5** | Live-Smoke auf .45 | Phase E Tasks E1-E3 dokumentiert bestanden |
|
||||
| **F6** | Commit-Messages präzise (feat/fix/test) | `git log HEAD~5..HEAD --oneline` — Convention-konform |
|
||||
|
||||
Bei F2: Baseline ist **37 pre-existing failed** (von F6 R26). NEUE Failures
|
||||
gegenüber diesem Stand → Blocker. Total sollte 1331+ passed sein (war 1313
|
||||
in R24, ~1330-1340 nach R27).
|
||||
|
||||
Bei F5-Fail: `git revert HEAD~3..HEAD` auf .45, dann Issue/Rainer-Re-Review.
|
||||
|
||||
---
|
||||
|
||||
## Hinweise für Miguel
|
||||
|
||||
1. **Branch-Name:** `fix/f6-r27-quick-reply-dedup` (PR gegen main)
|
||||
2. **Reihenfolge:** A1 → A2 → B1 (rot) → B1 (grün durch A2) → C1 → C2 → C3 → D1 → D2 → E
|
||||
3. **Falls `RocketChatAdapter` Import zu teuer:** in `test_quick_reply_dedup.py`
|
||||
die MagicMock-Klasse selbst mit der Helper-Methode ausstatten (kopier den
|
||||
Helper-Code in eine lokale Test-Helper-Klasse `_StubAdapter`).
|
||||
4. **Falls `active_room_id` None ist** (Gate leer): Helper gibt False zurück,
|
||||
KEIN Quick-Reply — das ist OK weil dann auch `decision.allow` True gewesen
|
||||
wäre (Gate-Clear-Path). Defense-in-depth.
|
||||
5. **NICHT den `wait_until_clear`-Loop antippen** — der Fix lebt NUR im
|
||||
Quick-Reply-POST, nicht im Warten.
|
||||
|
||||
---
|
||||
|
||||
## Commit-Übersicht (erwartet)
|
||||
|
||||
```
|
||||
feat(outbound_gate): quick_reply_sent flag on _TurnHandle
|
||||
feat(outbound_gate): mark_quick_reply_sent + quick_reply_already_sent
|
||||
test(outbound_gate): 3 tests for quick_reply_sent flag + idempotency
|
||||
fix(adapter): F6 R27 — dedup quick-reply via helper + same-room UX text
|
||||
test: F6 R27 parallel-tasks dedup + same-room UX smoke
|
||||
```
|
||||
|
||||
5 Commits, ~80-100 Zeilen Diff (A1: 1, A2: 35, B1: 60, C1: 60, C2+C3: -30+10,
|
||||
D1+D2: 80).
|
||||
+75
-205
@@ -48,7 +48,6 @@ SKIP_OLLAMA_MODELS=false
|
||||
NO_RESTART=false
|
||||
FRESH_ONBOARDING=false
|
||||
MIGRATE_ONLY=false
|
||||
MIGRATE_TO_VENV=false
|
||||
|
||||
# Farben (nur wenn Terminal)
|
||||
if [ -t 1 ]; then
|
||||
@@ -262,13 +261,17 @@ install_system_deps() {
|
||||
fi
|
||||
fi
|
||||
|
||||
# B1: Python 3.13 ist empfohlen, aber nicht zwingend (>= 3.11 reicht).
|
||||
# .101 läuft real mit Python 3.11 — kein Hard-Fail mehr.
|
||||
if command -v python3.13 >/dev/null 2>&1; then
|
||||
ok "Python 3.13 verfügbar: $(python3.13 --version 2>/dev/null)"
|
||||
else
|
||||
warn "Python 3.13 nicht installiert — empfohlen, aber nicht zwingend (>= 3.11 reicht)"
|
||||
# B1: Python 3.13 für pipx erzwingen (pipx-Python-Version-Drift verhindern)
|
||||
if ! command -v python3.13 >/dev/null 2>&1; then
|
||||
log "Python 3.13 nicht gefunden — installiere via apt..."
|
||||
if ! $DRY_RUN; then
|
||||
sudo apt-get install -y -qq python3.13 python3.13-venv python3.13-dev >/dev/null \
|
||||
|| die "python3.13 Installation fehlgeschlagen"
|
||||
else
|
||||
printf '%s[dry]%s apt install python3.13 python3.13-venv python3.13-dev\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
fi
|
||||
ok "Python 3.13 verfügbar: $(python3.13 --version 2>/dev/null || echo 'dry-run')"
|
||||
|
||||
log "Prüfe / installiere apt-Pakete (python3-pip, pipx, git, curl)..."
|
||||
if ! $DRY_RUN; then
|
||||
@@ -300,62 +303,81 @@ install_system_deps() {
|
||||
install_hermes_agent() {
|
||||
banner "2. Hermes Agent"
|
||||
|
||||
local venv
|
||||
local hermes_venv="$HOME/.hermes/hermes-agent/venv"
|
||||
|
||||
# ── P1: User-Space-venv als First-Class-Install-Modus ──
|
||||
# Prüfe zuerst ob ~/.hermes/hermes-agent/venv/ existiert und nutzbar ist.
|
||||
if [ -d "$hermes_venv" ] && [ -x "$hermes_venv/bin/python" ]; then
|
||||
log "User-Space-venv gefunden: $hermes_venv (First-Class)"
|
||||
venv="$hermes_venv"
|
||||
elif venv="$(find_pipx_venv 2>/dev/null)" && [ -n "$venv" ]; then
|
||||
# Bestehende pipx-Installation — als Fallback nutzen, nicht migrieren
|
||||
log "pipx-venv gefunden: $venv (Fallback — bestehende Installation)"
|
||||
else
|
||||
# ── Neuinstallation: User-Space-venv erstellen (First-Class) ──
|
||||
log "Kein venv gefunden — erstelle User-Space-venv unter $hermes_venv..."
|
||||
if ! $DRY_RUN; then
|
||||
python3 -m venv "$hermes_venv" \
|
||||
|| die "python3 -m venv $hermes_venv fehlgeschlagen"
|
||||
"$hermes_venv/bin/python" -m pip install --quiet --upgrade pip \
|
||||
|| warn "pip upgrade im User-Space-venv fehlgeschlagen"
|
||||
"$hermes_venv/bin/python" -m pip install --quiet hermes-agent \
|
||||
|| die "hermes-agent Installation im User-Space-venv fehlgeschlagen"
|
||||
# Symlink nach ~/.local/bin/hermes
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
ln -sf "$hermes_venv/bin/hermes" "$HOME/.local/bin/hermes"
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
venv="$hermes_venv"
|
||||
else
|
||||
printf '%s[dry]%s python3 -m venv %s && %s/bin/python -m pip install hermes-agent && ln -sf %s/bin/hermes ~/.local/bin/hermes\n' \
|
||||
"$C_YELLOW" "$C_RESET" "$hermes_venv" "$hermes_venv" "$hermes_venv"
|
||||
venv="$hermes_venv"
|
||||
# P11: pipx-Bootstrap — auf frischem Debian 13 ist pipx nicht vorinstalliert.
|
||||
# Guard analog zum ollama-Install-Block in install_system_deps().
|
||||
if ! command -v pipx >/dev/null 2>&1; then
|
||||
if $SKIP_SYSTEM_DEPS; then
|
||||
die "pipx fehlt, aber SKIP_SYSTEM_DEPS=1 — pipx manuell installieren: sudo apt-get install -y pipx"
|
||||
fi
|
||||
log "pipx nicht gefunden — installiere via apt..."
|
||||
if ! $DRY_RUN; then
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq pipx >/dev/null \
|
||||
|| die "pipx-Installation via apt fehlgeschlagen"
|
||||
else
|
||||
printf '%s[dry]%s sudo apt-get install -y pipx\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
fi
|
||||
ok "pipx verfügbar: $(pipx --version 2>/dev/null || echo 'dry-run')"
|
||||
|
||||
local venv
|
||||
if venv="$(find_pipx_venv 2>/dev/null)" && [ -n "$venv" ]; then
|
||||
# B1: Prüfe ob pipx-venv tatsächlich Python 3.13 nutzt
|
||||
local venv_py_ver
|
||||
venv_py_ver="$("$venv/bin/python" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null || echo "0.0")"
|
||||
if [ "$venv_py_ver" != "3.13" ]; then
|
||||
warn "pipx-venv nutzt Python $venv_py_ver statt 3.13 — Neuinstallation mit python3.13"
|
||||
if ! $DRY_RUN; then
|
||||
pipx uninstall hermes-agent 2>/dev/null || true
|
||||
pipx install --python python3.13 hermes-agent \
|
||||
|| die "pipx install --python python3.13 hermes-agent fehlgeschlagen"
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
venv="$(find_pipx_venv 2>/dev/null)" \
|
||||
|| die "pipx-venv nach Neuinstallation nicht gefunden"
|
||||
else
|
||||
printf '%s[dry]%s pipx uninstall hermes-agent && pipx install --python python3.13 hermes-agent\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
else
|
||||
log "Hermes Agent bereits in pipx-venv (Python 3.13): $venv"
|
||||
fi
|
||||
else
|
||||
log "pipx install hermes-agent --python python3.13..."
|
||||
if ! $DRY_RUN; then
|
||||
pipx install --python python3.13 hermes-agent \
|
||||
|| die "pipx install --python python3.13 hermes-agent fehlgeschlagen"
|
||||
# PATH für diese Session refreshen
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
venv="$(find_pipx_venv 2>/dev/null)" \
|
||||
|| die "pipx-venv nach Installation nicht gefunden"
|
||||
else
|
||||
printf '%s[dry]%s pipx install --python python3.13 hermes-agent\n' "$C_YELLOW" "$C_RESET"
|
||||
venv="$HOME/.local/share/pipx/venvs/hermes-agent"
|
||||
fi
|
||||
ok "User-Space-venv erstellt: $hermes_venv"
|
||||
fi
|
||||
|
||||
# Im Dry-Run simulierten venv-Pfad setzen
|
||||
# Im Dry-Run simulierten venv-Pfad setzen, damit nachfolgende Ausgaben schön sind
|
||||
if $DRY_RUN && [ -z "${venv:-}" ]; then
|
||||
venv="$hermes_venv"
|
||||
venv="$HOME/.local/share/pipx/venvs/hermes-agent"
|
||||
fi
|
||||
|
||||
PIPX_VENV="$venv"
|
||||
VENV_PY="$venv/bin/python"
|
||||
|
||||
# P1 — KRITISCH: snowballstemmer in venv injecten
|
||||
log "Injecte snowballstemmer in venv (P1)..."
|
||||
# P1 — KRITISCH: snowballstemmer in pipx-venv injecten
|
||||
log "Injecte snowballstemmer in pipx-venv (P1)..."
|
||||
if ! $DRY_RUN; then
|
||||
"$VENV_PY" -m pip install --quiet snowballstemmer>=3.0.0
|
||||
# Verifikation
|
||||
if ! "$VENV_PY" -c 'import snowballstemmer' 2>/dev/null; then
|
||||
die "snowballstemmer im venv nicht importierbar — P1-Regression!"
|
||||
die "snowballstemmer im pipx-venv nicht importierbar — P1-Regression!"
|
||||
fi
|
||||
else
|
||||
printf '%s[dry]%s %s -m pip install snowballstemmer\n' "$C_YELLOW" "$C_RESET" "$VENV_PY"
|
||||
fi
|
||||
ok "snowballstemmer in venv"
|
||||
ok "snowballstemmer in pipx-venv"
|
||||
|
||||
# requirements.txt aus dem Plugin-Repo in den venv installieren
|
||||
# requirements.txt aus dem Plugin-Repo in die pipx-venv installieren
|
||||
local script_dir
|
||||
script_dir="$(cd "$(dirname "$0")" && pwd)"
|
||||
local req="$script_dir/requirements.txt"
|
||||
@@ -434,14 +456,6 @@ deploy_plugin() {
|
||||
log "Alte tools.py gelöscht (ersetzt durch rc_tools.py)"
|
||||
fi
|
||||
|
||||
# V9.2: Commit-Hash in version.py setzen
|
||||
if [ -f "$dst/archivar/version.py" ]; then
|
||||
local commit_hash
|
||||
commit_hash="$(cd "$script_dir" && git rev-parse --short HEAD 2>/dev/null || echo "unknown")"
|
||||
sed -i 's/__commit__ = .*/__commit__ = "'"$commit_hash"'"/' "$dst/archivar/version.py"
|
||||
log "version.py: __commit__ = $commit_hash"
|
||||
fi
|
||||
|
||||
# plugin.yaml am richtigen Ort? Datei liegt in plugin/plugin.yaml
|
||||
# → kopiert als $dst/plugin.yaml. Korrekt.
|
||||
local count
|
||||
@@ -473,7 +487,7 @@ deploy_plugin() {
|
||||
if [ -d "$src/archivar" ]; then
|
||||
local site_packages
|
||||
site_packages="$(find_site_packages "$PIPX_VENV")"
|
||||
[ -n "$site_packages" ] || site_packages="$(ls -d "$PIPX_VENV/lib/python3."*"/site-packages" 2>/dev/null | head -1)"
|
||||
[ -n "$site_packages" ] || site_packages="$PIPX_VENV/lib/python3.13/site-packages"
|
||||
local archivar_link="$site_packages/archivar"
|
||||
log "Archivar-Symlink: $archivar_link -> $dst/archivar"
|
||||
if ! $DRY_RUN; then
|
||||
@@ -547,7 +561,7 @@ migrate_to_userspace() {
|
||||
if venv="$(find_pipx_venv 2>/dev/null)" && [ -n "$venv" ]; then
|
||||
local site_packages
|
||||
site_packages="$(find_site_packages "$venv")"
|
||||
[ -n "$site_packages" ] || site_packages="$(ls -d "$venv/lib/python3."*"/site-packages" 2>/dev/null | head -1)"
|
||||
[ -n "$site_packages" ] || site_packages="$venv/lib/python3.13/site-packages"
|
||||
local archivar_link="$site_packages/archivar"
|
||||
log "Archivar-Symlink: $archivar_link -> $user_dst/archivar"
|
||||
ln -sfn "$user_dst/archivar" "$archivar_link"
|
||||
@@ -560,77 +574,6 @@ migrate_to_userspace() {
|
||||
ok "Migration abgeschlossen: Bundled → User-Space"
|
||||
}
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# 3c. Migration: pipx → User-Space-venv (P3)
|
||||
# Aufruf: install.sh --migrate-to-venv
|
||||
# Explizit, NICHT automatisch — bestehende pipx-Installationen bleiben
|
||||
# ohne dieses Flag unangetastet.
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
migrate_to_venv() {
|
||||
banner "Migration: pipx → User-Space-venv (P3)"
|
||||
|
||||
local hermes_venv="$HOME/.hermes/hermes-agent/venv"
|
||||
local pipx_venv
|
||||
|
||||
# Prüfe ob pipx-venv existiert
|
||||
pipx_venv="$(find_pipx_venv 2>/dev/null)" || true
|
||||
if [ -z "$pipx_venv" ]; then
|
||||
warn "Kein pipx-venv gefunden — nichts zu migrieren"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Prüfe ob es WIRKLICH ein pipx-venv ist (nicht schon User-Space)
|
||||
case "$pipx_venv" in
|
||||
"$hermes_venv")
|
||||
ok "Bereits User-Space-venv: $hermes_venv — Migration übersprungen"
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
log "pipx-venv gefunden: $pipx_venv"
|
||||
log "Ziel User-Space-venv: $hermes_venv"
|
||||
|
||||
if $DRY_RUN; then
|
||||
printf '%s[dry]%s python3 -m venv %s\\n' "$C_YELLOW" "$C_RESET" "$hermes_venv"
|
||||
printf '%s[dry]%s %s/bin/python -m pip install hermes-agent\\n' "$C_YELLOW" "$C_RESET" "$hermes_venv"
|
||||
printf '%s[dry]%s ln -sf %s/bin/hermes ~/.local/bin/hermes\\n' "$C_YELLOW" "$C_RESET" "$hermes_venv"
|
||||
printf '%s[dry]%s pipx uninstall hermes-agent\\n' "$C_YELLOW" "$C_RESET"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# a) User-Space-venv neu aufbauen
|
||||
log "Erstelle User-Space-venv unter $hermes_venv..."
|
||||
python3 -m venv "$hermes_venv" \
|
||||
|| die "python3 -m venv $hermes_venv fehlgeschlagen"
|
||||
"$hermes_venv/bin/python" -m pip install --quiet --upgrade pip \
|
||||
|| warn "pip upgrade im User-Space-venv fehlgeschlagen"
|
||||
|
||||
# b) hermes-agent im User-Space-venv installieren
|
||||
log "Installiere hermes-agent im User-Space-venv..."
|
||||
"$hermes_venv/bin/python" -m pip install --quiet hermes-agent \
|
||||
|| die "hermes-agent Installation im User-Space-venv fehlgeschlagen"
|
||||
|
||||
# c) Symlink umhängen: ~/.local/bin/hermes → User-Space-venv
|
||||
log "Hänge Symlink um: ~/.local/bin/hermes → $hermes_venv/bin/hermes"
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
ln -sf "$hermes_venv/bin/hermes" "$HOME/.local/bin/hermes"
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
|
||||
# d) pipx-venv unmounten
|
||||
log "Unmounte pipx-venv (pipx uninstall hermes-agent)..."
|
||||
pipx uninstall hermes-agent 2>/dev/null || warn "pipx uninstall fehlgeschlagen — manuell prüfen"
|
||||
|
||||
ok "Migration abgeschlossen: pipx → User-Space-venv"
|
||||
echo ""
|
||||
echo " ┌─────────────────────────────────────────────────────────────┐"
|
||||
echo " │ WICHTIG: Gateway neustarten! │"
|
||||
echo " │ │"
|
||||
echo " │ systemctl --user restart hermes-gateway │"
|
||||
echo " │ systemctl --user status hermes-gateway │"
|
||||
echo " └─────────────────────────────────────────────────────────────┘"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# 4. config.yaml generieren (aus env-Variablen)
|
||||
# P2: auxiliary darf NICHT openrouter/Nous versuchen (payment errors)
|
||||
@@ -673,11 +616,6 @@ model:
|
||||
providers:
|
||||
ollama-cloud: {}
|
||||
|
||||
# Toolset-Registrierung: hermes-rocketchat muss nach venv-Neuaufbau
|
||||
# in config.yaml stehen, sonst ist der Bot stumm (keine Tools/Senden).
|
||||
toolsets:
|
||||
- rocketchat
|
||||
|
||||
# P2: auxiliary-Provider explizit auf ollama-cloud setzen.
|
||||
# Verhindert Auto-Discovery-Chain (openrouter/Nous → payment errors + Timeout).
|
||||
auxiliary:
|
||||
@@ -777,46 +715,6 @@ YAML
|
||||
fi
|
||||
}
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# 4b. Toolset-Registrierung sicherstellen (idempotent)
|
||||
# Nach venv-Neuaufbau (pipx install) fehlt das rocketchat-Toolset in
|
||||
# config.yaml → Bot ist stumm (keine Tools/Senden). Diese Funktion
|
||||
# stellt sicher, dass 'rocketchat' unter toolsets: registriert ist.
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
ensure_toolset() {
|
||||
local config="$HOME/.hermes/config.yaml"
|
||||
[ -f "$config" ] || { warn "config.yaml nicht gefunden — Toolset-Registrierung übersprungen"; return 0; }
|
||||
|
||||
# Idempotenz: Nur handeln wenn rocketchat NICHT bereits registriert ist
|
||||
if grep -q '^ - rocketchat$' "$config" 2>/dev/null; then
|
||||
log "Toolset 'rocketchat' bereits in config.yaml registriert"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "Registriere 'rocketchat' Toolset in config.yaml..."
|
||||
if $DRY_RUN; then
|
||||
printf '%s[dry]%s Füge rocketchat zu toolsets: in %s hinzu\\n' "$C_YELLOW" "$C_RESET" "$config"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Prüfe ob toolsets:-Sektion existiert
|
||||
if grep -q '^toolsets:' "$config" 2>/dev/null; then
|
||||
# toolsets: existiert — füge rocketchat als neuen Eintrag ein
|
||||
# Suche die Zeile 'toolsets:' und füge danach ' - rocketchat' ein
|
||||
sed -i '/^toolsets:/a\ - rocketchat' "$config"
|
||||
else
|
||||
# Keine toolsets:-Sektion — füge sie nach providers: ein
|
||||
sed -i '/^providers:/a\\ntoolsets:\n - rocketchat' "$config"
|
||||
fi
|
||||
|
||||
# Verifikation
|
||||
if grep -q '^ - rocketchat$' "$config" 2>/dev/null; then
|
||||
ok "Toolset 'rocketchat' in config.yaml registriert"
|
||||
else
|
||||
err "FAIL: Toolset 'rocketchat' konnte nicht in config.yaml registriert werden"
|
||||
fi
|
||||
}
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# 5. .env generieren (aus env-Variablen)
|
||||
# P4: .env NICHT zwischen Maschinen kopieren (Identitätskonflikt)
|
||||
@@ -1158,18 +1056,13 @@ verify_installation() {
|
||||
return 0
|
||||
fi
|
||||
|
||||
# B1: Python-Version im venv prüfen (>= 3.11 reicht, 3.13 empfohlen)
|
||||
# B1: pipx-venv Python-Version MUSS 3.13 sein
|
||||
local venv_py_ver
|
||||
venv_py_ver="$("$VENV_PY" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")' 2>/dev/null || echo "0.0")"
|
||||
local venv_major="${venv_py_ver%%.*}"
|
||||
local venv_minor="${venv_py_ver#*.}"
|
||||
if [ "$venv_major" -ge "$PYTHON_MIN_MAJOR" ] && [ "$venv_minor" -ge "$PYTHON_MIN_MINOR" ]; then
|
||||
ok "venv Python $venv_py_ver (>= $PYTHON_MIN_MAJOR.$PYTHON_MIN_MINOR)"
|
||||
if [ "$venv_py_ver" != "3.13" ]; then
|
||||
warn "Python $venv_py_ver statt 3.13 — 3.13 ist empfohlen, aber nicht zwingend"
|
||||
fi
|
||||
if [ "$venv_py_ver" = "3.13" ]; then
|
||||
ok "pipx-venv Python $venv_py_ver (B1: 3.13 erzwungen)"
|
||||
else
|
||||
err "FAIL: venv Python $venv_py_ver zu alt — brauche >= $PYTHON_MIN_MAJOR.$PYTHON_MIN_MINOR"; fail=1
|
||||
err "FAIL: pipx-venv Python $venv_py_ver statt 3.13 (B1)"; fail=1
|
||||
fi
|
||||
|
||||
# P1: snowballstemmer in pipx-venv
|
||||
@@ -1343,7 +1236,6 @@ OPTIONEN:
|
||||
--force Bestehende Dateien überschreiben (SOUL.md etc.)
|
||||
--fresh-onboarding room-map.json + archivar_state.json löschen (frisches Onboarding)
|
||||
--migrate Migration: Bundled → User-Space (Variante B)
|
||||
--migrate-to-venv Migration: pipx → User-Space-venv (P3, explizit)
|
||||
--skip-system-deps apt-Install überspringen (für Container/CI)
|
||||
--skip-ollama-models ollama pull überspringen
|
||||
|
||||
@@ -1395,7 +1287,6 @@ while [ $# -gt 0 ]; do
|
||||
--no-restart) NO_RESTART=true; shift ;;
|
||||
--fresh-onboarding) FRESH_ONBOARDING=true; shift ;;
|
||||
--migrate) MIGRATE_ONLY=true; shift ;;
|
||||
--migrate-to-venv) MIGRATE_TO_VENV=true; shift ;;
|
||||
--*) err "Unbekannte Option: $1"; print_help; exit 1 ;;
|
||||
*) err "Unbekanntes Argument: $1"; exit 1 ;;
|
||||
esac
|
||||
@@ -1568,15 +1459,6 @@ if $MIGRATE_ONLY; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if $MIGRATE_TO_VENV; then
|
||||
# P3: Migration von pipx → User-Space-venv (explizit, nicht automatisch).
|
||||
# Führt nur die Migration aus, kein Deployment, keine Konfiguration.
|
||||
banner "Migration-Only (pipx → User-Space-venv)"
|
||||
read_env
|
||||
migrate_to_venv
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if $UPDATE_ONLY; then
|
||||
# V8.6: Update-Only — Plugin-Code aktualisieren (git pull) + deployen
|
||||
# + __pycache__-Cleanup + Service-Restart + Post-Deploy-Verifikation.
|
||||
@@ -1598,12 +1480,8 @@ if $UPDATE_ONLY; then
|
||||
|
||||
read_env
|
||||
# Hermes-venv finden
|
||||
PIPX_VENV="$(find_pipx_venv 2>/dev/null)" || {
|
||||
warn "pipx-venv nicht gefunden — falle zurück auf Vollinstallation"
|
||||
install_hermes_agent
|
||||
PIPX_VENV="$(find_pipx_venv 2>/dev/null)" \
|
||||
|| die "pipx-venv nach install_hermes_agent immer noch nicht gefunden"
|
||||
}
|
||||
PIPX_VENV="$(find_pipx_venv 2>/dev/null)" \
|
||||
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
||||
VENV_PY="$PIPX_VENV/bin/python"
|
||||
|
||||
# Ziel-Pfad: User-Space (Variante B)
|
||||
@@ -1623,11 +1501,6 @@ if $UPDATE_ONLY; then
|
||||
# ── Schritt 2: Plugin deployen ──
|
||||
deploy_plugin
|
||||
|
||||
# ── Schritt 2b: Toolset-Registrierung nach venv-Neuaufbau ──
|
||||
# Wenn install_hermes_agent() den venv neu gebaut hat, fehlt das
|
||||
# rocketchat-Toolset in config.yaml → Bot wäre stumm.
|
||||
ensure_toolset
|
||||
|
||||
# ── Schritt 3: __pycache__ NACH dem Kopieren NOCHMAL löschen ──
|
||||
log "Lösche __pycache__ im Ziel NACH Deployment..."
|
||||
if ! $DRY_RUN; then
|
||||
@@ -1791,9 +1664,6 @@ deploy_plugin
|
||||
# 4. config.yaml
|
||||
write_config_yaml
|
||||
|
||||
# 4b. Toolset-Registrierung sicherstellen (idempotent)
|
||||
ensure_toolset
|
||||
|
||||
# 5. .env
|
||||
write_env_file
|
||||
|
||||
|
||||
@@ -17,18 +17,6 @@ sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── V9: Modul-Level-Adapter-Referenz für Hook-Callbacks ──────────────────
|
||||
# F1.1: Statt privater ctx._adapter/ctx._platforms nutzen die Hook-Callbacks
|
||||
# diese offizielle Modul-Referenz. Sie wird in RocketChatAdapter.connect()
|
||||
# gesetzt und in disconnect() auf None zurückgesetzt.
|
||||
_active_adapter = None # RocketChatAdapter instance, set in connect()
|
||||
|
||||
# ── V9: Hook-Registrierungs-Flag (Idempotenz) ────────────────────────────
|
||||
_hooks_registered = False
|
||||
|
||||
# ── V9: PluginContext-Referenz (für deferred Hook-Registrierung) ─────────
|
||||
_plugin_ctx = None # PluginContext, set in register()
|
||||
|
||||
# ── Interaction Templates (source of truth — zero yaml dependency) ──
|
||||
_TEMPLATE_MAP = {
|
||||
"yes_no": {
|
||||
@@ -120,9 +108,6 @@ def is_connected(config) -> bool:
|
||||
|
||||
def register(ctx):
|
||||
"""Plugin entry point — called by the Hermes plugin system at startup."""
|
||||
global _plugin_ctx
|
||||
_plugin_ctx = ctx # F1.2: Store for deferred hook registration in connect()
|
||||
|
||||
_MULTIROOM = os.getenv("MULTIROOM_AGENT", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||
|
||||
from .adapter import RocketChatAdapter # lazy import avoids circular deps
|
||||
@@ -152,135 +137,3 @@ def register(ctx):
|
||||
)
|
||||
|
||||
register_tools(ctx)
|
||||
|
||||
# ── V9: PresenceEngine — Hook-Registrierung (deferred) ────────────────
|
||||
# Die 8 Hooks (6 Core + 2 Tool-Filter) werden NICHT hier in register()
|
||||
# registriert, sondern erst in RocketChatAdapter.connect().
|
||||
#
|
||||
# Grund (F1.2 — Lifecycle): In register() existiert der Adapter noch
|
||||
# nicht — register_platform() erzeugt nur eine Factory. Die Hooks
|
||||
# brauchen aber Zugriff auf den instanziierten Adapter (via
|
||||
# _presence_engine). connect() ist die korrekte Lifecycle-Phase:
|
||||
# Der Adapter ist vollständig initialisiert, REST-Login erfolgt,
|
||||
# PresenceEngine ist gebunden, und der asyncio-Loop läuft.
|
||||
#
|
||||
# Hook-Mapping (V10.0.2 — P-032 Fix, siehe docs/architecture/2026-08-03-presence-engine-schachuhr.md):
|
||||
# pre_gateway_dispatch → main_agent += 1 (ROT Start)
|
||||
# post_llm_call → main_agent -= 1 (ROT Ende, Clamp bei 0)
|
||||
# subagent_start → delegate_subagent += 1 (GELB Start)
|
||||
# subagent_stop → delegate_subagent -= 1 (GELB Ende)
|
||||
# on_session_start → chat_profile += 1 (GELB Start, echter Session-Start)
|
||||
# on_session_end → NO-OP (feuert PRO TURN, nicht pro Session)
|
||||
# on_session_finalize → chat_profile -= 1 (GELB Ende, echtes Session-Ende)
|
||||
# on_session_reset → alle Counter auf 0 (/reset)
|
||||
# pre_tool_call → background_term += 1 (wenn terminal bg=true)
|
||||
# post_tool_call → background_term -= 1 (wenn terminal bg=true)
|
||||
#
|
||||
# Die Callbacks nutzen adapter._active_adapter (Modul-Level-Referenz,
|
||||
# gesetzt in connect()) statt privater ctx-Attribute (F1.1 — offizielle API).
|
||||
#
|
||||
# _register_presence_hooks() wird von RocketChatAdapter.connect()
|
||||
# aufgerufen. Idempotent: doppelte Aufrufe (z.B. Reconnect) sind No-Ops.
|
||||
|
||||
|
||||
def _register_presence_hooks() -> None:
|
||||
"""Registriere 10 Presence-Hooks via ctx.register_hook().
|
||||
|
||||
Wird von RocketChatAdapter.connect() aufgerufen, sobald der Adapter
|
||||
vollständig initialisiert ist (REST-Login, PresenceEngine, asyncio-Loop).
|
||||
|
||||
Idempotent: doppelte Aufrufe (z.B. Reconnect) sind No-Ops.
|
||||
"""
|
||||
global _hooks_registered
|
||||
if _hooks_registered:
|
||||
return
|
||||
|
||||
ctx = _plugin_ctx
|
||||
if ctx is None:
|
||||
logger.warning("[presence-v9] Kein PluginContext — Hook-Registrierung übersprungen")
|
||||
return
|
||||
|
||||
try:
|
||||
# ── Wrapper: Holt die PresenceEngine via _active_adapter ──────────
|
||||
# V9.0.1: SYNCHRON — invoke_hook() im Core ruft Callbacks via
|
||||
# ret = cb(**kwargs) auf. Async-Callbacks würden als Coroutine-Objekt
|
||||
# zurückgegeben aber nie awaited → Hook-Code wird NIE ausgeführt.
|
||||
def _get_engine_and_call(method_name: str, **kwargs):
|
||||
"""Hole PresenceEngine aus dem aktiven Adapter und rufe Methode auf.
|
||||
|
||||
Nutzt die Modul-Level-Referenz _active_adapter (F1.1: offizielle
|
||||
API statt privater ctx._adapter/ctx._platforms).
|
||||
|
||||
V9.0.1: Synchron — invoke_hook() erwartet sync-Callbacks.
|
||||
"""
|
||||
try:
|
||||
adapter = _active_adapter
|
||||
if adapter is None:
|
||||
return
|
||||
engine = getattr(adapter, '_presence_engine', None)
|
||||
if engine is None or not engine.is_enabled():
|
||||
return
|
||||
method = getattr(engine, method_name, None)
|
||||
if method is not None:
|
||||
method(**kwargs)
|
||||
except Exception as e:
|
||||
logger.debug("[presence-v9] Hook %s fehlgeschlagen: %s", method_name, e)
|
||||
|
||||
# ── 6 Core-Hooks (V9.0.1: synchron) ──────────────────────────────
|
||||
def _on_pre_gateway_dispatch(**kwargs):
|
||||
_get_engine_and_call("on_pre_gateway_dispatch", **kwargs)
|
||||
|
||||
def _on_post_llm_call(**kwargs):
|
||||
_get_engine_and_call("on_post_llm_call", **kwargs)
|
||||
|
||||
def _on_subagent_start(**kwargs):
|
||||
_get_engine_and_call("on_subagent_start", **kwargs)
|
||||
|
||||
def _on_subagent_stop(**kwargs):
|
||||
_get_engine_and_call("on_subagent_stop", **kwargs)
|
||||
|
||||
def _on_session_start(**kwargs):
|
||||
_get_engine_and_call("on_session_start", **kwargs)
|
||||
|
||||
def _on_session_end(**kwargs):
|
||||
# P-032: on_session_end feuert PRO TURN — No-Op in der Engine.
|
||||
# chat_profile-Dekrement erfolgt via on_session_finalize/on_session_reset.
|
||||
_get_engine_and_call("on_session_end", **kwargs)
|
||||
|
||||
def _on_session_finalize(**kwargs):
|
||||
_get_engine_and_call("on_session_finalize", **kwargs)
|
||||
|
||||
def _on_session_reset(**kwargs):
|
||||
_get_engine_and_call("on_session_reset", **kwargs)
|
||||
|
||||
# ── 2 Tool-Filter-Hooks (O-1: Background-Terminal-Workaround) ─────
|
||||
def _on_pre_tool_call(**kwargs):
|
||||
_get_engine_and_call("on_pre_tool_call", **kwargs)
|
||||
|
||||
def _on_post_tool_call(**kwargs):
|
||||
_get_engine_and_call("on_post_tool_call", **kwargs)
|
||||
|
||||
# ── Registrierung via offizielle API ──────────────────────────────
|
||||
ctx.register_hook("pre_gateway_dispatch", _on_pre_gateway_dispatch)
|
||||
ctx.register_hook("post_llm_call", _on_post_llm_call)
|
||||
ctx.register_hook("subagent_start", _on_subagent_start)
|
||||
ctx.register_hook("subagent_stop", _on_subagent_stop)
|
||||
ctx.register_hook("on_session_start", _on_session_start)
|
||||
ctx.register_hook("on_session_end", _on_session_end)
|
||||
ctx.register_hook("on_session_finalize", _on_session_finalize)
|
||||
ctx.register_hook("on_session_reset", _on_session_reset)
|
||||
ctx.register_hook("pre_tool_call", _on_pre_tool_call)
|
||||
ctx.register_hook("post_tool_call", _on_post_tool_call)
|
||||
|
||||
_hooks_registered = True
|
||||
logger.info(
|
||||
"[presence-v10] 10 Hooks registriert: "
|
||||
"pre_gateway_dispatch, post_llm_call, subagent_start, subagent_stop, "
|
||||
"on_session_start, on_session_end, on_session_finalize, on_session_reset, "
|
||||
"pre_tool_call, post_tool_call"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"[presence-v9] Hook-Registrierung fehlgeschlagen: %s — "
|
||||
"PresenceEngine läuft ohne Hooks (graceful degradation)", e
|
||||
)
|
||||
|
||||
+133
-367
@@ -51,13 +51,6 @@ _CURRENT_TASK_TOKEN: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||||
"_rocketchat_task_token", default=""
|
||||
)
|
||||
|
||||
# B3: ContextVar für die aktuelle Session-ID — wird in _dispatch_agent gesetzt,
|
||||
# in send() und send_clarify() für release() verwendet.
|
||||
# _CURRENT_TASK_TOKEN bleibt bestehen. _CURRENT_SESSION_ID ist ZUSÄTZLICH.
|
||||
_CURRENT_SESSION_ID: contextvars.ContextVar[str] = contextvars.ContextVar(
|
||||
"_rocketchat_session_id", default=""
|
||||
)
|
||||
|
||||
|
||||
def _set_room_context_origin(chat_id: str, room_id: str) -> str:
|
||||
"""Atomar _room_context[chat_id]["origin_room"] = room_id setzen.
|
||||
@@ -266,22 +259,20 @@ def _sanitize_file_path_component(value: str) -> str:
|
||||
|
||||
|
||||
class RocketChatREST:
|
||||
def __init__(self, base_url: str, http_timeout: float = 30.0):
|
||||
def __init__(self, base_url: str):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.http_timeout = http_timeout
|
||||
self.auth_token: Optional[str] = None
|
||||
self.user_id: Optional[str] = None
|
||||
|
||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None, timeout: Optional[float] = None):
|
||||
def _request(self, method: str, endpoint: str, headers: Optional[dict] = None, data: Optional[dict] = None):
|
||||
url = f"{self.base_url}{endpoint}"
|
||||
req_headers = dict(headers) if headers else {}
|
||||
body = json.dumps(data).encode("utf-8") if data else None
|
||||
if body:
|
||||
req_headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=body, headers=req_headers, method=method)
|
||||
_timeout = timeout if timeout is not None else self.http_timeout
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=_timeout) as resp:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 429:
|
||||
@@ -436,97 +427,6 @@ class RocketChatREST:
|
||||
}, data=payload)
|
||||
return bool(r and r.get("success"))
|
||||
|
||||
def upload_file(self, room_id: str, file_path: str, message: str = "", description: str = "") -> dict:
|
||||
"""Upload a file to a Rocket.Chat room using multipart/form-data.
|
||||
|
||||
Two-step flow:
|
||||
1. POST /api/v1/rooms.media/{room_id} (multipart/form-data)
|
||||
2. POST /api/v1/chat.postMessage with title_link + type=file attachment
|
||||
|
||||
Returns:
|
||||
dict with ``success`` (bool), ``upload`` (rooms.media response),
|
||||
and ``post_message`` (chat.postMessage response) on success.
|
||||
dict with ``success=False`` and ``error`` on failure.
|
||||
"""
|
||||
import mimetypes
|
||||
if not self.auth_token:
|
||||
return {"success": False, "error": "Not authenticated"}
|
||||
if not os.path.exists(file_path):
|
||||
return {"success": False, "error": f"File not found: {file_path}"}
|
||||
content_type, _ = mimetypes.guess_type(file_path)
|
||||
if content_type is None:
|
||||
content_type = "application/octet-stream"
|
||||
boundary = "----HermesAgentUploadBoundary"
|
||||
body_parts: list = []
|
||||
with open(file_path, "rb") as f:
|
||||
file_data = f.read()
|
||||
filename = os.path.basename(file_path)
|
||||
# Add file field
|
||||
body_parts.append(f"--{boundary}\r\n".encode())
|
||||
body_parts.append(
|
||||
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'.encode()
|
||||
)
|
||||
body_parts.append(f"Content-Type: {content_type}\r\n\r\n".encode())
|
||||
body_parts.append(file_data)
|
||||
body_parts.append(b"\r\n")
|
||||
if message:
|
||||
body_parts.append(f"--{boundary}\r\n".encode())
|
||||
body_parts.append(b'Content-Disposition: form-data; name="msg"\r\n\r\n')
|
||||
body_parts.append(message.encode())
|
||||
body_parts.append(b"\r\n")
|
||||
if description:
|
||||
body_parts.append(f"--{boundary}\r\n".encode())
|
||||
body_parts.append(b'Content-Disposition: form-data; name="description"\r\n\r\n')
|
||||
body_parts.append(description.encode())
|
||||
body_parts.append(b"\r\n")
|
||||
body_parts.append(f"--{boundary}--\r\n".encode())
|
||||
body = b"".join(body_parts)
|
||||
url = f"{self.base_url}/api/v1/rooms.media/{room_id}"
|
||||
headers: dict = {
|
||||
"X-Auth-Token": self.auth_token,
|
||||
"X-User-Id": self.user_id,
|
||||
"Content-Type": f"multipart/form-data; boundary={boundary}",
|
||||
}
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
upload_result = json.loads(resp.read().decode("utf-8"))
|
||||
if not upload_result.get("success"):
|
||||
return upload_result
|
||||
# Step 2: Post message with the uploaded file as attachment
|
||||
file_info = upload_result.get("file") or {}
|
||||
file_id = file_info.get("_id")
|
||||
if file_id:
|
||||
attachment: dict = {
|
||||
"title": filename,
|
||||
"title_link": f"/file-upload/{file_id}/{filename}",
|
||||
"title_link_download": True,
|
||||
"type": "file",
|
||||
}
|
||||
if description:
|
||||
attachment["description"] = description
|
||||
post_result = self.post_message(
|
||||
room_id=room_id,
|
||||
text=message or "",
|
||||
attachments=[attachment],
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"upload": upload_result,
|
||||
"post_message": post_result,
|
||||
}
|
||||
return upload_result
|
||||
except urllib.error.HTTPError as exc:
|
||||
msg = f"Upload HTTP {exc.code}"
|
||||
try:
|
||||
detail = json.loads(exc.read().decode("utf-8"))
|
||||
msg += f": {detail}"
|
||||
except Exception:
|
||||
pass
|
||||
return {"success": False, "error": msg}
|
||||
except Exception as exc:
|
||||
return {"success": False, "error": str(exc)}
|
||||
|
||||
|
||||
class DDPTimeout(Exception):
|
||||
"""Raised when a DDP method call times out waiting for a result message."""
|
||||
@@ -1277,7 +1177,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._multiroom_context = None
|
||||
# P5 V9.x: OutboundGate — Parallel-Stream-Schutz
|
||||
from archivar.outbound_gate import OutboundGate, GateDecision
|
||||
self._outbound_gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=10.0) # B+: 10s statt 60s
|
||||
self._outbound_gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
|
||||
if self.archivar is not None:
|
||||
self.archivar.bind_outbound_gate(self._outbound_gate)
|
||||
# User-Flow C: Move-Requests
|
||||
@@ -1310,33 +1210,37 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._inline_commands = InlineCommandRegistry()
|
||||
self._register_inline_commands()
|
||||
|
||||
# V9: PresenceEngine — Schachuhr-Architektur (Hook-basiert)
|
||||
# V8.6: PresenceEngine — Aktivitäts-Indikator
|
||||
try:
|
||||
from archivar.presence_engine import PresenceEngine
|
||||
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||
_away_grace_s = float(os.getenv("ROCKETCHAT_PRESENCE_AWAY_GRACE_S", "2.0"))
|
||||
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
||||
_pulse_interval = float(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "1.5"))
|
||||
self._presence_engine = PresenceEngine(
|
||||
rest=self.rest,
|
||||
enabled=_presence_enabled,
|
||||
away_grace_s=_away_grace_s,
|
||||
use_ddp=True,
|
||||
adapter=self,
|
||||
coalesce_ms=_coalesce_ms,
|
||||
pulse_interval=_pulse_interval,
|
||||
)
|
||||
# V9: Kein PulseController, kein DDP, kein DetectionTimer mehr.
|
||||
# Hook-Registrierung erfolgt in plugin/__init__.py via ctx.register_hook().
|
||||
# P0-1: PulseController mit REST und DDP verdrahten
|
||||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||
if self.ddp:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
# P2-2: PresenceEngine an ArchivarMessageHandler weiterreichen
|
||||
if self.archivar is not None:
|
||||
self.archivar.set_presence_engine(self._presence_engine)
|
||||
logger.info(
|
||||
"[rocketchat] V9: PresenceEngine initialisiert (enabled=%s, away_grace=%.1fs)",
|
||||
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s, pulse_interval=%.1fs)",
|
||||
_presence_enabled,
|
||||
_away_grace_s,
|
||||
_coalesce_ms,
|
||||
_pulse_interval,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] V9: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
self._presence_engine = None # Graceful degradation
|
||||
self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift
|
||||
|
||||
def _build_room_map_summary(self) -> str:
|
||||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||||
@@ -1374,14 +1278,31 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
def _on_ddp_connected(self) -> None:
|
||||
"""Callback when DDP connection is established.
|
||||
|
||||
Sets initial online status via DDP.
|
||||
V9: Kein PulseController, kein DetectionTimer mehr.
|
||||
Sets initial online status and binds DDP to PulseController
|
||||
if PresenceEngine is active (EC-1: on_connected_cb race).
|
||||
|
||||
P1b: Starts DetectionTimer after DDP connection is established
|
||||
to prevent race condition with gateway_state.json.
|
||||
"""
|
||||
if self.ddp:
|
||||
# B3: Bewusst sync — first status after connect does not need
|
||||
# await-confirmation.
|
||||
# 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.
|
||||
self.ddp.set_status("online")
|
||||
# V9: PresenceEngine braucht keine DDP-Bindung mehr (REST-only).
|
||||
# V8.6: PulseController DDP-Bindung nach Connect (EC-1)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
try:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e)
|
||||
# P1b: DetectionTimer erst nach DDP-Connect starten
|
||||
try:
|
||||
self._presence_engine.start_detection()
|
||||
logger.debug("[rocketchat] P1b: DetectionTimer gestartet (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] P1b: DetectionTimer start failed: %s", e)
|
||||
|
||||
def _on_ddp_room_event(self, event: dict) -> None:
|
||||
"""A1b: Callback für DDP rooms-changed Events.
|
||||
@@ -1784,36 +1705,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._rooms = self.rest.get_rooms()
|
||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||
|
||||
# V9: Bind asyncio loop to DDP (PresenceEngine braucht keinen Loop mehr — sync Hooks)
|
||||
# P1-2 O-2: Bind asyncio loop to DDPClient and PulseController
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
self.ddp.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] V9: DDP loop-bound: yes (loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||
"(loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
except RuntimeError:
|
||||
# No running event loop (e.g., in tests) — graceful degradation
|
||||
logger.info(
|
||||
"[rocketchat] V9: DDP loop-bound: no "
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||
"(no running event loop)"
|
||||
)
|
||||
|
||||
# ── V9: Register Presence Hooks (F1.1 + F1.2) ──────────────────
|
||||
# Hooks werden erst hier registriert, nicht in register().
|
||||
# Grund: Der Adapter ist jetzt vollständig initialisiert (REST-Login,
|
||||
# PresenceEngine, asyncio-Loop). Die Hook-Callbacks nutzen die
|
||||
# Modul-Level-Referenz _active_adapter (offizielle API, F1.1).
|
||||
try:
|
||||
import sys as _sys; _plugin_module = _sys.modules.get(__name__.rsplit(".", 1)[0])
|
||||
_plugin_module._active_adapter = self
|
||||
_plugin_module._register_presence_hooks()
|
||||
logger.info("[rocketchat] V9: Presence-Hooks registriert via connect()")
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"[rocketchat] V9: Presence-Hook-Registrierung fehlgeschlagen: %s", e
|
||||
)
|
||||
|
||||
# A1b: Subscribe to stream-notify-room for rooms-changed events
|
||||
if self.ddp.connected:
|
||||
room_events_sub = self.ddp.subscribe_room_events()
|
||||
@@ -2082,18 +1991,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.user = resolved.lower()
|
||||
logger.info("[rocketchat] Resolved self.user from login (reconnect): %s", self.user)
|
||||
|
||||
# V9: Re-bind asyncio loop to DDP (PresenceEngine braucht keinen Loop mehr — sync Hooks)
|
||||
# P1-2 O-2: Re-bind asyncio loop to new DDPClient and PulseController
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
self.ddp.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] V9: DDP loop-bound: yes "
|
||||
"(reconnect, loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||
"(reconnect, loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
except RuntimeError:
|
||||
logger.info(
|
||||
"[rocketchat] V9: DDP loop-bound: no "
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||
"(reconnect, no running event loop)"
|
||||
)
|
||||
|
||||
@@ -2149,11 +2060,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
def _schedule_idle_timer(self) -> None:
|
||||
"""Schedule idle timer to mark bot as away when inactive.
|
||||
|
||||
V9: Deaktiviert wenn PresenceEngine aktiv ist.
|
||||
Die PresenceEngine übernimmt das Status-Management via Hooks.
|
||||
V8.6: Deaktiviert wenn PresenceEngine aktiv ist (ROCKETCHAT_PRESENCE_ENABLED=true).
|
||||
Der alte _set_away-Timer kann eine DDP-Subscription-Endlosschleife auslösen
|
||||
(Rainer-Warnung). Die PresenceEngine übernimmt das Status-Management.
|
||||
"""
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
logger.debug("[rocketchat] V9: _schedule_idle_timer skipped — PresenceEngine active")
|
||||
logger.debug("[rocketchat] V8.6: _schedule_idle_timer skipped — PresenceEngine active")
|
||||
return
|
||||
if self._status_timer:
|
||||
self._status_timer.cancel()
|
||||
@@ -2293,12 +2205,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
virtual_chat_id = f"user:{username}"
|
||||
_set_room_context_origin(virtual_chat_id, room_id)
|
||||
|
||||
# ── V9: PresenceEngine — Hooks übernehmen das Status-Management ──
|
||||
# Kein mark_busy_started(), kein increment_background_tasks() mehr.
|
||||
# pre_gateway_dispatch/post_llm_call Hooks steuern die Schachuhr.
|
||||
# ── V8.6 P1a: PresenceEngine — mark_busy_started (Honeymoon-Timer) ──
|
||||
# Graceful degradation: wenn _presence_engine nicht existiert
|
||||
# (z.B. in Tests die __new__ statt __init__ verwenden), skip.
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
logger.debug("[presence-v9] Dispatch beginnt — Hooks steuern Counter")
|
||||
self._presence_engine.mark_busy_started(room_name=room_name)
|
||||
# B12: Background-Tasks zählen — Heartbeat-Message aktivieren
|
||||
self._presence_engine.increment_background_tasks()
|
||||
logger.info("[presence] mark_busy_started (room=%s)", room_name)
|
||||
|
||||
try:
|
||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||
@@ -2577,8 +2492,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# als thematische Frage klassifiziert und ins Catch-All kopiert.
|
||||
if room_id in self._pending_move_requests:
|
||||
move_req = self._pending_move_requests.pop(room_id)
|
||||
# ── V9: PresenceEngine — Move-Request beantwortet ──
|
||||
# V9: Kein clear_move_request mehr (Hooks steuern Status).
|
||||
# ── V8.6: PresenceEngine — Move-Request beantwortet → clear ──
|
||||
if _has_presence:
|
||||
self._presence_engine.clear_move_request(room_id)
|
||||
choice = text.strip()
|
||||
|
||||
# Neues Format: MOVE_REQ:<room_id>::<choice> (native Buttons)
|
||||
@@ -3327,9 +3243,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
'username': username,
|
||||
'message_id': msg_id,
|
||||
}
|
||||
# ── V9: PresenceEngine — Move-Request pending ──
|
||||
# V9: Hooks steuern Status, kein manuelles update_presence mehr.
|
||||
# ── V8.6: PresenceEngine — Move-Request pending → away ──
|
||||
target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
|
||||
if _has_presence:
|
||||
self._presence_engine.set_move_request_pending(room_id, target_name)
|
||||
self._presence_engine.update_presence()
|
||||
# Lernsystem: Keywords für Feedback-Loop speichern
|
||||
if hasattr(decision, 'matched_keywords') and decision.matched_keywords:
|
||||
self.archivar._routed_messages[msg_id] = {
|
||||
@@ -3588,8 +3506,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||
# handle_message() erzeugt intern asyncio.create_task (Drain-Task).
|
||||
# Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen.
|
||||
# V9: Agent wurde dispatched (für OutboundGate-Tracking)
|
||||
self._agent_dispatched_this_turn = True
|
||||
self._agent_dispatch_task = asyncio.create_task(
|
||||
ctx.run(self.handle_message, event)
|
||||
)
|
||||
@@ -3630,13 +3546,16 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
except Exception as e2:
|
||||
logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2)
|
||||
finally:
|
||||
# ── V9: PresenceEngine — Hooks steuern das Status-Management ──
|
||||
# Kein Busy-Done-Debounce mehr. post_llm_call Hook dekrementiert
|
||||
# den main_agent-Counter automatisch wenn der LLM-Call endet.
|
||||
# ── V8.6 P1a: PresenceEngine — mark_busy_done (Honeymoon-Timer) ──
|
||||
# try/finally garantiert decrement auch bei Exceptions/Errors.
|
||||
if _has_presence:
|
||||
logger.debug("[presence-v9] Turn complete — Hooks steuern Counter")
|
||||
|
||||
# ── P5 V9.x: OutboundGate — release ──
|
||||
self._presence_engine.mark_busy_done()
|
||||
# B12: Background-Tasks decrement — Heartbeat-Message aktualisieren
|
||||
self._presence_engine.decrement_background_tasks()
|
||||
# P1-2: current_room zurücksetzen nach Verarbeitung
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] mark_busy_done (turn complete)")
|
||||
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||
# W2: release in try/except BaseException im finally-Block.
|
||||
try:
|
||||
_gate_room_id = f"user:{username}"
|
||||
@@ -3806,7 +3725,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
is_natural_help_request,
|
||||
build_help_text,
|
||||
)
|
||||
from archivar.version import get_version_string
|
||||
|
||||
stripped = text.strip()
|
||||
|
||||
@@ -3825,7 +3743,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
help_text = build_help_text(
|
||||
self._inline_commands,
|
||||
room_map_summary=self._room_map_summary,
|
||||
plugin_version=get_version_string(),
|
||||
)
|
||||
unknown_msg = (
|
||||
f"Unbekannter Befehl `::{command}`. "
|
||||
@@ -3847,7 +3764,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
help_text = build_help_text(
|
||||
self._inline_commands,
|
||||
room_map_summary=self._room_map_summary,
|
||||
plugin_version=get_version_string(),
|
||||
)
|
||||
unknown_msg = (
|
||||
f"Unbekannter Befehl `::{cmd_question}`. "
|
||||
@@ -3861,7 +3777,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
help_text = build_help_text(
|
||||
self._inline_commands,
|
||||
room_map_summary=self._room_map_summary,
|
||||
plugin_version=get_version_string(),
|
||||
)
|
||||
await self._post_message_with_retry(room_id, help_text)
|
||||
return True
|
||||
@@ -3941,28 +3856,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
async def _cmd_hilfe(self, room_id: str, args: str) -> str:
|
||||
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
|
||||
from archivar.inline_commands import build_help_text
|
||||
from archivar.version import get_version_string
|
||||
|
||||
# V9: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
presence_enabled = None
|
||||
current_status = "online"
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = self._presence_engine.get_status()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
|
||||
return build_help_text(
|
||||
self._inline_commands,
|
||||
room_map_summary=self._room_map_summary,
|
||||
presence_enabled=presence_enabled,
|
||||
current_status=current_status,
|
||||
plugin_version=get_version_string(),
|
||||
)
|
||||
|
||||
async def _cmd_status(self, room_id: str, args: str) -> str:
|
||||
"""::status — Zeigt den aktuellen Plugin-Status."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
from archivar.version import get_version_string
|
||||
|
||||
room_count = 0
|
||||
archivar_active = False
|
||||
@@ -3977,15 +3889,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
|
||||
onboarding_active = self.archivar._stats.get("onboarding_active", False)
|
||||
|
||||
# V9: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
presence_enabled = None
|
||||
current_status = "online"
|
||||
pulse_active = False
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = self._presence_engine.get_status()
|
||||
pulse_active = self._presence_engine.is_pulse_active()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
pulse_active = self._presence_engine._pulse_controller.is_running()
|
||||
|
||||
return build_status_text(
|
||||
room_count=room_count,
|
||||
@@ -3996,7 +3908,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
presence_enabled=presence_enabled,
|
||||
current_status=current_status,
|
||||
pulse_active=pulse_active,
|
||||
plugin_version=get_version_string(),
|
||||
)
|
||||
|
||||
async def _cmd_reset(self, room_id: str, args: str) -> str:
|
||||
@@ -4356,33 +4267,46 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
if subcmd in ("on", "an", "ein", "enable", "start"):
|
||||
self._presence_engine.enable()
|
||||
# V9: Kein PulseController mehr — enable() reicht
|
||||
logger.info("[rocketchat] V9: ::setstatus on — PresenceEngine aktiviert")
|
||||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy)."
|
||||
# P0-3: ::setstatus on → PulseController aktivieren
|
||||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||
if self.ddp:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
# B1: PulseController sofort starten — kein Warten auf DetectionTimer (10s)
|
||||
try:
|
||||
self._presence_engine._pulse_controller.start()
|
||||
except Exception as e:
|
||||
logger.warning("[rocketchat] ::setstatus on: PulseController.start() failed: %s", e)
|
||||
logger.info("[rocketchat] V8.6: ::setstatus on — PresenceEngine aktiviert")
|
||||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy/away)."
|
||||
|
||||
elif subcmd in ("off", "aus", "disable", "stop"):
|
||||
self._presence_engine.disable()
|
||||
# V9: Kein PulseController mehr — disable() reicht
|
||||
logger.info("[rocketchat] V9: ::setstatus off — PresenceEngine deaktiviert")
|
||||
# P0-3: ::setstatus off → PulseController stoppen
|
||||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||
self._presence_engine._pulse_controller.stop()
|
||||
logger.info("[rocketchat] V8.6: ::setstatus off — PresenceEngine deaktiviert")
|
||||
return "🔴 **Aktivitäts-Indikator: AUS**\n\nDer Bot-Status bleibt auf 'online'. Keine automatischen Status-Wechsel."
|
||||
|
||||
else:
|
||||
# status
|
||||
enabled = self._presence_engine.is_enabled()
|
||||
counters = self._presence_engine.get_counters()
|
||||
telemetry = self._presence_engine.get_telemetry()
|
||||
active = self._presence_engine._active_tasks
|
||||
bg = self._presence_engine._background_tasks
|
||||
onboarding = self._presence_engine._onboarding_active
|
||||
error = self._presence_engine._error_state
|
||||
|
||||
lines = [
|
||||
"📊 **Aktivitäts-Indikator Status**",
|
||||
"",
|
||||
f"Status: {'🟢 Aktiviert' if enabled else '🔴 Deaktiviert'}",
|
||||
f"Counter: {counters}",
|
||||
f"State: {self._presence_engine.get_status()}",
|
||||
f"REST-Calls: {telemetry['rest_calls']} "
|
||||
f"(Erfolg: {telemetry['rest_success']}, "
|
||||
f"429: {telemetry['rest_429']}, "
|
||||
f"Fehler: {telemetry['rest_errors']})",
|
||||
f"Aktive Tasks: {active}",
|
||||
f"Background Tasks: {bg}",
|
||||
]
|
||||
if onboarding:
|
||||
lines.append("Onboarding: 🔄 Läuft")
|
||||
if error:
|
||||
lines.append(f"Fehler: ⚠️ {error}")
|
||||
if not enabled:
|
||||
lines.append("", "💡 `::setstatus on` zum Aktivieren")
|
||||
|
||||
@@ -4708,10 +4632,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"""
|
||||
return MessageType.COMMAND if is_button_response else MessageType.TEXT
|
||||
|
||||
# ── V9: Busy-Done-Debounce ENTFERNT ─────────────────────────────────
|
||||
# V9: Hooks (post_llm_call) steuern den main_agent-Counter automatisch.
|
||||
# Kein manuelles mark_busy_done(), kein Debounce-Timer mehr.
|
||||
|
||||
async def _dispatch_agent(
|
||||
self,
|
||||
text: str,
|
||||
@@ -4783,11 +4703,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# _CURRENT_TASK_TOKEN. copy_context() friert es ein, sodass send()
|
||||
# später den Token-Match validieren kann.
|
||||
_set_room_context_origin(virtual_chat_id, room_id)
|
||||
# ── B3: Session-ID für OutboundGate owner_session_id ──
|
||||
# _CURRENT_SESSION_ID wird via copy_context() eingefroren,
|
||||
# sodass send()/send_clarify() sie für release() nutzen können.
|
||||
# Fallback: uuid4().hex wenn Core keine session_id übergibt.
|
||||
_CURRENT_SESSION_ID.set(uuid.uuid4().hex)
|
||||
# ── V8.1 P1: ContextVar-Snapshot für Drain-Task ──────────
|
||||
ctx = contextvars.copy_context()
|
||||
# V8.1 P1 diagnostic: log dispatch context
|
||||
@@ -4801,8 +4716,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_target[:8] if _target else "",
|
||||
)
|
||||
# P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort.
|
||||
# V9: Agent wurde dispatched (für OutboundGate-Tracking)
|
||||
self._agent_dispatched_this_turn = True
|
||||
self._agent_dispatch_task = asyncio.create_task(
|
||||
ctx.run(self.handle_message, event)
|
||||
)
|
||||
@@ -5130,9 +5043,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = True
|
||||
# ── V9: PresenceEngine — Onboarding start ──
|
||||
# V9: Hooks steuern Status, kein manuelles set_onboarding_active mehr.
|
||||
# ── V8.6: PresenceEngine — Onboarding start → away ──
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.set_onboarding_active(True)
|
||||
self._presence_engine.update_presence()
|
||||
|
||||
# Bug 3 fix: Robuster Zugriff auf _build_custom_buttons
|
||||
_build = self._get_build_custom_buttons()
|
||||
@@ -5747,7 +5662,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = self._presence_engine.get_status()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
help_text = build_help_text(self._inline_commands, room_map_summary=self._room_map_summary,
|
||||
presence_enabled=presence_enabled, current_status=current_status)
|
||||
await self._post_message_with_retry(operator_room_id, help_text)
|
||||
@@ -6451,8 +6366,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
self._onboarding_state = {}
|
||||
# ── V9: PresenceEngine — Onboarding end ──
|
||||
# V9: Hooks steuern Status, kein manuelles update_presence mehr.
|
||||
# ── V8.6: PresenceEngine — Onboarding end → online ──
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.set_onboarding_active(False)
|
||||
self._presence_engine.update_presence()
|
||||
# F8: State Machine — AWAITING_TEST → ACTIVE
|
||||
if hasattr(self, '_onboarding_sm'):
|
||||
self._onboarding_sm.advance_test()
|
||||
@@ -6598,15 +6516,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return text
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
# ── V9: Clear active adapter reference (F1.1) ──
|
||||
try:
|
||||
import sys as _sys; _plugin_module = _sys.modules.get(__name__.rsplit(".", 1)[0])
|
||||
if _plugin_module._active_adapter is self:
|
||||
_plugin_module._active_adapter = None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── V9: Kein Busy-Done-Debounce mehr ──
|
||||
# ── P1b: Gate-Sweep-Task sauber beenden ──
|
||||
if hasattr(self, '_gate_sweep_task') and self._gate_sweep_task is not None:
|
||||
self._gate_sweep_task.cancel()
|
||||
@@ -6750,8 +6659,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_gate_acquired = False # P1a: track whether WE created the gate entry
|
||||
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
from archivar.outbound_gate import GateDecision
|
||||
_session_id = _CURRENT_SESSION_ID.get() # B3: Session-ID für release()-Fallback
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
if not decision.allow:
|
||||
# Blockiert — warte bis zu 30s (A4: blocking_room_id)
|
||||
blocking_room = decision.blocking_room_id
|
||||
@@ -6761,7 +6669,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
blocking_room_id=blocking_room, timeout_s=30.0
|
||||
)
|
||||
# Retry acquire nach wait
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
except asyncio.TimeoutError:
|
||||
decision = GateDecision(allow=False, reason="timeout")
|
||||
|
||||
@@ -6840,27 +6748,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# B2: allow_proactive_user_map Opt-In
|
||||
# Priority 2 (_user_rooms[-1]) und _find_fallback_room_for_user
|
||||
# werden NUR genutzt wenn allow_proactive_user_map=True in der
|
||||
# Plugin-Config (config.yaml) oder metadata['allow_proactive']=True.
|
||||
_allow_proactive = (
|
||||
self.config.extra.get("allow_proactive_user_map", False)
|
||||
or (metadata or {}).get("allow_proactive", False)
|
||||
)
|
||||
if not _allow_proactive:
|
||||
logger.error(
|
||||
"[rocketchat] No resolved room for %s — "
|
||||
"provide explicit room_id or enable allow_proactive_user_map",
|
||||
chat_id,
|
||||
)
|
||||
return SendResult(
|
||||
success=False,
|
||||
error=(
|
||||
f"No resolved room for {chat_id} — "
|
||||
"provide explicit room_id or enable allow_proactive_user_map"
|
||||
),
|
||||
)
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
@@ -7023,7 +6910,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
||||
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
||||
# würde den Agenten vorzeitig auf "online" setzen.
|
||||
# V9: Kein Busy-Done-Debounce mehr — Hooks steuern Status
|
||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||
|
||||
finally:
|
||||
@@ -7096,7 +6982,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
success = await self._post_message_with_retry(room_id, chunk_text)
|
||||
if success:
|
||||
last_msg_id = str(int(time.time() * 1000))
|
||||
# V9: Kein Busy-Done-Debounce mehr — Hooks steuern Status
|
||||
# Small delay between chunks to preserve order
|
||||
if i < total:
|
||||
await asyncio.sleep(0.5)
|
||||
@@ -7226,8 +7111,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
_gate_acquired = False # P1a: track whether WE created the gate entry
|
||||
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
from archivar.outbound_gate import GateDecision
|
||||
_session_id = _CURRENT_SESSION_ID.get() # B3: Session-ID für release()-Fallback
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
if not decision.allow:
|
||||
blocking_room = decision.blocking_room_id
|
||||
if blocking_room:
|
||||
@@ -7235,7 +7119,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self._outbound_gate.wait_until_clear(
|
||||
blocking_room_id=blocking_room, timeout_s=30.0
|
||||
)
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token, owner_session_id=_session_id)
|
||||
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||
except asyncio.TimeoutError:
|
||||
decision = GateDecision(allow=False, reason="timeout")
|
||||
if not decision.allow:
|
||||
@@ -7306,27 +7190,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# B2: allow_proactive_user_map Opt-In
|
||||
# Priority 2 (_user_rooms[-1]) und _find_fallback_room_for_user
|
||||
# werden NUR genutzt wenn allow_proactive_user_map=True in der
|
||||
# Plugin-Config (config.yaml) oder metadata['allow_proactive']=True.
|
||||
_allow_proactive = (
|
||||
self.config.extra.get("allow_proactive_user_map", False)
|
||||
or (metadata or {}).get("allow_proactive", False)
|
||||
)
|
||||
if not _allow_proactive:
|
||||
logger.error(
|
||||
"[rocketchat] send_clarify: No resolved room for %s — "
|
||||
"provide explicit room_id or enable allow_proactive_user_map",
|
||||
chat_id,
|
||||
)
|
||||
return SendResult(
|
||||
success=False,
|
||||
error=(
|
||||
f"No resolved room for {chat_id} — "
|
||||
"provide explicit room_id or enable allow_proactive_user_map"
|
||||
),
|
||||
)
|
||||
# Priority 2: proactive message — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
@@ -7413,103 +7276,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
||||
pass
|
||||
|
||||
async def send_document(
|
||||
self,
|
||||
chat_id: str,
|
||||
file_path: str,
|
||||
caption: Optional[str] = None,
|
||||
file_name: Optional[str] = None,
|
||||
reply_to: Optional[str] = None,
|
||||
metadata: Optional[Dict[str, Any]] = None,
|
||||
**kwargs,
|
||||
) -> SendResult:
|
||||
"""Send a document/file natively via Rocket.Chat REST API.
|
||||
|
||||
Uses the rooms.media → chat.postMessage 2-step flow to upload
|
||||
and attach a file. Falls back to the base-class text notice on
|
||||
any failure.
|
||||
"""
|
||||
if not self.rest.auth_token:
|
||||
logger.warning("[rocketchat] send_document: not authenticated, falling back to base")
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to, metadata=metadata, **kwargs,
|
||||
)
|
||||
|
||||
# ── Resolve real room_id (same logic as send()) ──────────────
|
||||
real_room_id = chat_id
|
||||
if chat_id.startswith("user:"):
|
||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||
if origin:
|
||||
current_token = _CURRENT_TASK_TOKEN.get()
|
||||
ctx_entry = _room_context.get(chat_id, {})
|
||||
stored_token = ctx_entry.get("task_token", "")
|
||||
if current_token and stored_token and current_token != stored_token:
|
||||
origin = ""
|
||||
if origin:
|
||||
real_room_id = origin
|
||||
else:
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
else:
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
else:
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1]
|
||||
else:
|
||||
logger.warning(
|
||||
"[rocketchat] send_document: no resolved room for %s, "
|
||||
"falling back to base",
|
||||
chat_id,
|
||||
)
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to,
|
||||
metadata=metadata, **kwargs,
|
||||
)
|
||||
|
||||
# ── Upload via rooms.media → chat.postMessage ────────────────
|
||||
display_name = file_name or os.path.basename(file_path)
|
||||
message_text = caption or ""
|
||||
try:
|
||||
result = self.rest.upload_file(
|
||||
room_id=real_room_id,
|
||||
file_path=file_path,
|
||||
message=message_text,
|
||||
description=display_name,
|
||||
)
|
||||
if result.get("success"):
|
||||
logger.info(
|
||||
"[rocketchat] send_document: uploaded %s to room %s",
|
||||
display_name, real_room_id[:8],
|
||||
)
|
||||
return SendResult(success=True, message_id=result.get("post_message"))
|
||||
else:
|
||||
error = result.get("error", "unknown upload error")
|
||||
logger.warning(
|
||||
"[rocketchat] send_document: upload failed for %s: %s — "
|
||||
"falling back to base",
|
||||
display_name, error,
|
||||
)
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to, metadata=metadata, **kwargs,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"[rocketchat] send_document: exception uploading %s: %s — "
|
||||
"falling back to base",
|
||||
display_name, exc,
|
||||
)
|
||||
return await super().send_document(
|
||||
chat_id=chat_id, file_path=file_path, caption=caption,
|
||||
file_name=file_name, reply_to=reply_to, metadata=metadata, **kwargs,
|
||||
)
|
||||
|
||||
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
|
||||
info = self._room_info.get(chat_id, {})
|
||||
return {"name": info.get("name", chat_id), "type": "group" if info.get("type") in ("c", "p") else "dm"}
|
||||
@@ -7591,12 +7357,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"""P5 V9.x W2: Periodischer Sweep stale Gate-Einträge.
|
||||
|
||||
Läuft als asyncio.create_task (nicht threading.Timer).
|
||||
B+: Sweept alle 5s (war 30s) — entfernt Einträge die älter als
|
||||
max_entry_age_s (10s, war 60s) sind.
|
||||
Sweept alle 30s — entfernt Einträge die älter als
|
||||
max_entry_age_s (60s) sind.
|
||||
"""
|
||||
while self._running and not self._shutdown_event.is_set():
|
||||
try:
|
||||
await asyncio.sleep(5.0) # B+: 5s statt 30s
|
||||
await asyncio.sleep(30.0)
|
||||
if hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||
swept = self._outbound_gate._sweep_stale_entries()
|
||||
if swept > 0:
|
||||
|
||||
@@ -638,15 +638,6 @@ class ArchivarMessageHandler:
|
||||
Returns:
|
||||
True wenn der Button erfolgreich gesendet wurde, False bei Fehler.
|
||||
"""
|
||||
# P-040: Defensiver Check — wenn origin==target, kein Button
|
||||
if decision.move_request_target_id == room_id:
|
||||
logger.warning(
|
||||
"P-040: Move-Request origin==target (%s) — skip button",
|
||||
room_id[:8],
|
||||
)
|
||||
self._stats['move_request_self_skipped'] = self._stats.get('move_request_self_skipped', 0) + 1
|
||||
return False
|
||||
|
||||
try:
|
||||
target_name = decision.move_request_target_name or "Zielraum"
|
||||
template = MOVE_REQUEST_TEMPLATE
|
||||
|
||||
+41
-84
@@ -7,12 +7,6 @@ Verfeinert FAISS-Suchergebnisse durch Keyword-Analyse:
|
||||
- Mehrdeutige Keywords sind neutral
|
||||
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords (+0.05 Boost)
|
||||
|
||||
P-028 Mitigation (2026-08-05):
|
||||
- keywords_100 werden mit match_keyword_exact gematcht (kein Fuzzy/Stemming,
|
||||
nur hyphen-insensitiv) → verhindert False Positives wie 'homelab' ↔ 'homelabor'
|
||||
- keywords_context werden mit match_keyword gematcht (mit Fuzzy/Stemming,
|
||||
da Context-Keywords weniger präzise sein sollen)
|
||||
|
||||
Usage::
|
||||
|
||||
from .room_map import RoomMap
|
||||
@@ -33,20 +27,14 @@ import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, List, Set, Tuple
|
||||
|
||||
from .keyword_matcher import match_keyword, match_keyword_exact
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class KeywordBooster:
|
||||
"""Keyword-basierter Score-Booster für RoomIndexManager.search()-Ergebnisse.
|
||||
|
||||
Baut aus einer geladenen RoomMap zwei Mappings:
|
||||
- _kw100_to_rooms: keyword → set of room_ids (aus keywords_100)
|
||||
- _kwctx_to_rooms: keyword → set of room_ids (aus keywords_context)
|
||||
|
||||
keywords_100 werden mit match_keyword_exact gematcht (P-028),
|
||||
keywords_context mit match_keyword (Fuzzy/Stemming).
|
||||
Baut aus einer geladenen RoomMap ein Mapping: keyword → set of room_ids.
|
||||
Wendet dann Boosts auf FAISS-Scores an basierend auf Keyword-Eindeutigkeit.
|
||||
"""
|
||||
|
||||
def __init__(self, room_map) -> None:
|
||||
@@ -56,45 +44,34 @@ class KeywordBooster:
|
||||
room_map: Eine ``RoomMap``-Instanz (aus ``room_map.py``).
|
||||
"""
|
||||
self._room_map = room_map
|
||||
self._kw100_to_rooms: Dict[str, Set[str]] = {}
|
||||
self._kwctx_to_rooms: Dict[str, Set[str]] = {}
|
||||
self._keyword_to_rooms: Dict[str, Set[str]] = {}
|
||||
self._build_mapping()
|
||||
|
||||
# ── Mapping ───────────────────────────────────────────────────────
|
||||
|
||||
def _build_mapping(self) -> None:
|
||||
"""Baut kw100 → set(room_ids) und kwctx → set(room_ids) getrennt auf."""
|
||||
self._kw100_to_rooms.clear()
|
||||
self._kwctx_to_rooms.clear()
|
||||
"""Baut keyword → set(room_ids) aus allen keywords_100 + keywords_context."""
|
||||
self._keyword_to_rooms.clear()
|
||||
|
||||
for room_id, entry in self._room_map.rooms.items():
|
||||
if entry.catch_all:
|
||||
continue # Catch-All nimmt nicht an Keyword-Boosts teil
|
||||
|
||||
# keywords_100 → _kw100_to_rooms
|
||||
for kw in entry.keywords_100:
|
||||
all_keywords: List[str] = []
|
||||
all_keywords.extend(entry.keywords_100)
|
||||
all_keywords.extend(entry.keywords_context)
|
||||
|
||||
for kw in all_keywords:
|
||||
kw_lower = kw.lower().strip()
|
||||
if not kw_lower:
|
||||
continue
|
||||
if kw_lower not in self._kw100_to_rooms:
|
||||
self._kw100_to_rooms[kw_lower] = set()
|
||||
self._kw100_to_rooms[kw_lower].add(room_id)
|
||||
if kw_lower not in self._keyword_to_rooms:
|
||||
self._keyword_to_rooms[kw_lower] = set()
|
||||
self._keyword_to_rooms[kw_lower].add(room_id)
|
||||
|
||||
# keywords_context → _kwctx_to_rooms
|
||||
for kw in entry.keywords_context:
|
||||
kw_lower = kw.lower().strip()
|
||||
if not kw_lower:
|
||||
continue
|
||||
if kw_lower not in self._kwctx_to_rooms:
|
||||
self._kwctx_to_rooms[kw_lower] = set()
|
||||
self._kwctx_to_rooms[kw_lower].add(room_id)
|
||||
|
||||
total_kw = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
||||
logger.debug(
|
||||
"KeywordBooster mapping built: %d kw100 + %d kwctx = %d total across %d rooms",
|
||||
len(self._kw100_to_rooms),
|
||||
len(self._kwctx_to_rooms),
|
||||
total_kw,
|
||||
"KeywordBooster mapping built: %d keywords across %d rooms",
|
||||
len(self._keyword_to_rooms),
|
||||
len(self._room_map.rooms),
|
||||
)
|
||||
|
||||
@@ -122,33 +99,22 @@ class KeywordBooster:
|
||||
# ── Score-Dict aufbauen ──────────────────────────────────
|
||||
score_dict: Dict[str, float] = {room_id: score for room_id, score in scores}
|
||||
|
||||
# ── Keywords im Text finden (P-028: getrennte Matcher) ────
|
||||
# keywords_100: match_keyword_exact (kein Fuzzy, hyphen-insensitiv)
|
||||
matched_kw100: List[str] = [
|
||||
kw for kw in self._kw100_to_rooms if match_keyword_exact(kw, text)
|
||||
# ── Keywords im Text finden ───────────────────────────────
|
||||
text_lower = text.lower()
|
||||
matched_keywords: List[str] = [
|
||||
kw for kw in self._keyword_to_rooms if kw in text_lower
|
||||
]
|
||||
# keywords_context: match_keyword (mit Fuzzy/Stemming)
|
||||
matched_kwctx: List[str] = [
|
||||
kw for kw in self._kwctx_to_rooms if match_keyword(kw, text)
|
||||
]
|
||||
|
||||
matched_keywords = matched_kw100 + matched_kwctx
|
||||
|
||||
if not matched_keywords:
|
||||
# Keine Keywords → Scores unverändert zurück
|
||||
return sorted(scores, key=lambda x: x[1], reverse=True)
|
||||
|
||||
# ── V8.2 A3: Matches für Demotion-Tracking aufzeichnen ──────
|
||||
self._record_matches(text, matched_kw100)
|
||||
self._record_matches(text_lower, matched_keywords)
|
||||
|
||||
# ── Boost-Phase: +0.10 für eindeutige Keywords ────────────
|
||||
# Vereinigtes Mapping für Boost-Lookup
|
||||
all_kw_to_rooms: Dict[str, Set[str]] = {}
|
||||
all_kw_to_rooms.update(self._kw100_to_rooms)
|
||||
all_kw_to_rooms.update(self._kwctx_to_rooms)
|
||||
|
||||
for kw in matched_keywords:
|
||||
rooms = all_kw_to_rooms[kw]
|
||||
rooms = self._keyword_to_rooms[kw]
|
||||
if len(rooms) == 1:
|
||||
unique_room = next(iter(rooms))
|
||||
if unique_room in score_dict:
|
||||
@@ -163,7 +129,7 @@ class KeywordBooster:
|
||||
# Zähle eindeutige Keywords pro Raum und gib Bonus für hohe Anzahl
|
||||
unique_counts_per_room: Dict[str, int] = {}
|
||||
for kw in matched_keywords:
|
||||
rooms = all_kw_to_rooms[kw]
|
||||
rooms = self._keyword_to_rooms[kw]
|
||||
if len(rooms) == 1:
|
||||
unique_room = next(iter(rooms))
|
||||
if unique_room in score_dict:
|
||||
@@ -184,7 +150,7 @@ class KeywordBooster:
|
||||
# ── Nach Boost sortieren ──────────────────────────────────
|
||||
boosted = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
|
||||
|
||||
# ── Konfliktlösung: Top-2 Diff < 0.05 ────────────────────
|
||||
# ── Konfliktlösung: Top-2 Diff < 0.03 ────────────────────
|
||||
if len(boosted) >= 2:
|
||||
top1_room, top1_score = boosted[0]
|
||||
top2_room, top2_score = boosted[1]
|
||||
@@ -192,8 +158,8 @@ class KeywordBooster:
|
||||
|
||||
if diff < 0.05:
|
||||
# Zähle eindeutige Keyword-Treffer für beide Räume
|
||||
unique_count_1 = self._count_unique_matches(text, top1_room)
|
||||
unique_count_2 = self._count_unique_matches(text, top2_room)
|
||||
unique_count_1 = self._count_unique_matches(text_lower, top1_room)
|
||||
unique_count_2 = self._count_unique_matches(text_lower, top2_room)
|
||||
|
||||
if unique_count_1 > unique_count_2:
|
||||
score_dict[top1_room] += 0.05
|
||||
@@ -218,49 +184,40 @@ class KeywordBooster:
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────
|
||||
|
||||
def _count_unique_matches(self, text: str, room_id: str) -> int:
|
||||
def _count_unique_matches(self, text_lower: str, room_id: str) -> int:
|
||||
"""Zählt wie viele eindeutige Keywords (nur in diesem Raum) im Text vorkommen.
|
||||
|
||||
Prüft beide Mappings (kw100 + kwctx) mit den jeweiligen Matchern.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext (RAW, Normalisierung passiert intern).
|
||||
text_lower: Der Text in lowercase.
|
||||
room_id: Die zu prüfende Raum-ID.
|
||||
|
||||
Returns:
|
||||
Anzahl der eindeutigen Keyword-Treffer für diesen Raum.
|
||||
"""
|
||||
count = 0
|
||||
|
||||
# keywords_100: match_keyword_exact
|
||||
for kw, rooms in self._kw100_to_rooms.items():
|
||||
if len(rooms) == 1 and room_id in rooms and match_keyword_exact(kw, text):
|
||||
for kw, rooms in self._keyword_to_rooms.items():
|
||||
if len(rooms) == 1 and room_id in rooms and kw in text_lower:
|
||||
count += 1
|
||||
|
||||
# keywords_context: match_keyword
|
||||
for kw, rooms in self._kwctx_to_rooms.items():
|
||||
if len(rooms) == 1 and room_id in rooms and match_keyword(kw, text):
|
||||
count += 1
|
||||
|
||||
return count
|
||||
|
||||
# ── V8.2 A3: 90-Tage-Demotion ─────────────────────────────────────
|
||||
|
||||
def _record_matches(self, text: str, matched_kw100: List[str]) -> None:
|
||||
"""Zeichnet last_matched-Timestamps für alle getroffenen kw100-Keywords.
|
||||
def _record_matches(self, text_lower: str, matched_keywords: List[str]) -> None:
|
||||
"""Zeichnet last_matched-Timestamps für alle getroffenen Keywords.
|
||||
|
||||
Wird nach jedem boost()-Aufruf aufgerufen, um die RoomMap-Tracking-Felder
|
||||
aktuell zu halten. Nur Keywords in keywords_100 werden getrackt
|
||||
(Demotion betrifft nur 100%-Keywords).
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext (RAW, Normalisierung passiert intern).
|
||||
matched_kw100: Liste der via match_keyword_exact gefundenen kw100-Keywords.
|
||||
text_lower: Der Text in lowercase.
|
||||
matched_keywords: Liste der im Text gefundenen Keywords.
|
||||
"""
|
||||
now = datetime.now().isoformat()
|
||||
for kw in matched_kw100:
|
||||
rooms = self._kw100_to_rooms.get(kw, set())
|
||||
for kw in matched_keywords:
|
||||
rooms = self._keyword_to_rooms.get(kw, set())
|
||||
for room_id in rooms:
|
||||
# Nur keywords_100 tracken (Demotion betrifft nur 100%-Keywords)
|
||||
entry = self._room_map.get_room_by_id(room_id)
|
||||
if entry is None:
|
||||
continue
|
||||
@@ -296,9 +253,9 @@ class KeywordBooster:
|
||||
def cleanup_orphaned_rooms(self, valid_room_ids: set) -> int:
|
||||
"""M13: Bereinigt das Keyword-Mapping für gelöschte Räume.
|
||||
|
||||
Baut die internen ``_kw100_to_rooms``- und ``_kwctx_to_rooms``-Mappings
|
||||
komplett neu aus der aktuellen RoomMap. Da die RoomMap bereits durch M13
|
||||
bereinigt wurde, enthalten die neuen Mappings nur noch gültige Räume.
|
||||
Baut das interne ``_keyword_to_rooms``-Mapping komplett neu aus
|
||||
der aktuellen RoomMap. Da die RoomMap bereits durch M13 bereinigt
|
||||
wurde, enthält das neue Mapping nur noch gültige Räume.
|
||||
|
||||
Args:
|
||||
valid_room_ids: Set von Raum-IDs, die behalten werden sollen
|
||||
@@ -308,9 +265,9 @@ class KeywordBooster:
|
||||
Returns:
|
||||
Anzahl der Keywords im neuen Mapping (0 wenn keine Räume übrig).
|
||||
"""
|
||||
before = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
||||
before = len(self._keyword_to_rooms)
|
||||
self._build_mapping()
|
||||
after = len(self._kw100_to_rooms) + len(self._kwctx_to_rooms)
|
||||
after = len(self._keyword_to_rooms)
|
||||
if before != after:
|
||||
logger.info(
|
||||
"KeywordBooster GC: mapping rebuilt — %d → %d keywords "
|
||||
|
||||
@@ -216,7 +216,6 @@ def build_help_text(
|
||||
room_map_summary: str = "",
|
||||
presence_enabled: Optional[bool] = None,
|
||||
current_status: str = "online",
|
||||
plugin_version: str = "",
|
||||
) -> str:
|
||||
"""Baut die Hilfeseite mit ::-Befehlen und natürlichen Sprach-Befehlen.
|
||||
|
||||
@@ -225,7 +224,6 @@ def build_help_text(
|
||||
room_map_summary: Optionale Raum-Map-Übersicht für den Status-Teil.
|
||||
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht verfügbar).
|
||||
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
||||
plugin_version: Plugin-Version (z.B. "9.2 (1d31d2c)").
|
||||
|
||||
Returns:
|
||||
Formatierte Hilfeseite als Markdown-String.
|
||||
@@ -233,18 +231,10 @@ def build_help_text(
|
||||
lines = [
|
||||
"## 🤖 Rocket.Chat Plugin — Hilfe",
|
||||
"",
|
||||
"Diese Befehle erkennst du am `::` am Satzanfang:",
|
||||
"",
|
||||
]
|
||||
|
||||
# V9.2: Plugin-Version anzeigen
|
||||
if plugin_version:
|
||||
lines.append(f"**Plugin-Version:** {plugin_version}")
|
||||
lines.append("")
|
||||
|
||||
lines.append(
|
||||
"Diese Befehle erkennst du am `::` am Satzanfang:"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# ── Sektion 0: Core-Befehle (Hermes Core, immer verfügbar) ────────
|
||||
lines.append("### ⚙️ Core-Befehle")
|
||||
lines.append("")
|
||||
@@ -396,7 +386,6 @@ def build_status_text(
|
||||
presence_enabled: Optional[bool] = None,
|
||||
current_status: str = "online",
|
||||
pulse_active: bool = False,
|
||||
plugin_version: str = "",
|
||||
) -> str:
|
||||
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
|
||||
|
||||
@@ -409,7 +398,6 @@ def build_status_text(
|
||||
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht anzeigen).
|
||||
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
||||
pulse_active: Ob der PulseController gerade pulsiert.
|
||||
plugin_version: Plugin-Version (z.B. "9.2 (1d31d2c)").
|
||||
|
||||
Returns:
|
||||
Formatierte Status-Seite.
|
||||
@@ -423,19 +411,11 @@ def build_status_text(
|
||||
lines = [
|
||||
"## 📊 Plugin-Status",
|
||||
"",
|
||||
]
|
||||
|
||||
# V9.2: Plugin-Version anzeigen
|
||||
if plugin_version:
|
||||
lines.append(f"**Plugin-Version:** {plugin_version}")
|
||||
lines.append("")
|
||||
|
||||
lines.extend([
|
||||
f"- **Räume in Map:** {room_count}",
|
||||
f"- **Archivar:** {'✅ Aktiv' if archivar_active else '❌ Inaktiv'}",
|
||||
f"- **Butler-Modus:** {butler_labels.get(butler_mode, butler_mode)}",
|
||||
f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}",
|
||||
])
|
||||
]
|
||||
|
||||
# P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt)
|
||||
if presence_enabled is not None:
|
||||
|
||||
@@ -51,8 +51,6 @@ class _TurnHandle:
|
||||
real_room_id: Rocket.Chat Raum-ID.
|
||||
task: asyncio.Task Referenz (für Cancel/Diagnose).
|
||||
chat_id: Virtuelle Chat-ID (z.B. "user:alice").
|
||||
owner_session_id: Session-ID (aus _CURRENT_SESSION_ID) für
|
||||
release()-Fallback bei Token-Mismatch (B1).
|
||||
"""
|
||||
|
||||
task_token: str
|
||||
@@ -61,7 +59,6 @@ class _TurnHandle:
|
||||
task: Optional[asyncio.Task] = None
|
||||
chat_id: str = ""
|
||||
quick_reply_sent: bool = False
|
||||
owner_session_id: str = "" # B1: Session-ID für release()-Fallback
|
||||
|
||||
|
||||
# ── GateStats: 9 Counter für Monitoring ───────────────────────────────────
|
||||
@@ -126,13 +123,13 @@ class OutboundGate:
|
||||
def __init__(
|
||||
self,
|
||||
default_timeout_s: float = 30.0,
|
||||
max_entry_age_s: float = 10.0, # B+: 10s statt 60s
|
||||
max_entry_age_s: float = 60.0,
|
||||
):
|
||||
"""Initialisiert das OutboundGate.
|
||||
|
||||
Args:
|
||||
default_timeout_s: Default-Timeout für wait_until_clear (30s).
|
||||
max_entry_age_s: Maximales Alter eines Eintrags bevor er als stale gilt (10s, B+).
|
||||
max_entry_age_s: Maximales Alter eines Eintrags bevor er als stale gilt (60s).
|
||||
"""
|
||||
self._in_flight: Dict[str, _TurnHandle] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
@@ -153,7 +150,7 @@ class OutboundGate:
|
||||
return next(iter(self._in_flight))
|
||||
return None
|
||||
|
||||
async def try_acquire(self, room_id: str, task_token: str, owner_session_id: str = "") -> GateDecision:
|
||||
async def try_acquire(self, room_id: str, task_token: str) -> GateDecision:
|
||||
"""Versucht den Gate-Slot für einen Raum zu akquirieren.
|
||||
|
||||
ASYNC — verwendet asyncio.Lock für Thread-Safety.
|
||||
@@ -169,8 +166,6 @@ class OutboundGate:
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
task_token: UUID4 Task-Token (aus _CURRENT_TASK_TOKEN).
|
||||
owner_session_id: Session-ID (aus _CURRENT_SESSION_ID) für
|
||||
release()-Fallback bei Token-Mismatch (B1).
|
||||
|
||||
Returns:
|
||||
GateDecision mit allow, reason, blocking_room_id.
|
||||
@@ -223,7 +218,6 @@ class OutboundGate:
|
||||
task_token=task_token,
|
||||
started_at=time.monotonic(),
|
||||
real_room_id=room_id,
|
||||
owner_session_id=owner_session_id, # B1: Session-ID für release()-Fallback
|
||||
)
|
||||
self._in_flight[room_id] = handle
|
||||
self.stats.acquired_total += 1
|
||||
@@ -276,17 +270,13 @@ class OutboundGate:
|
||||
|
||||
Idempotent: kein Fehler wenn der Raum nicht in _in_flight ist.
|
||||
Token-Check: nur releasen wenn der Token matched.
|
||||
B1: Session-ID-Fallback — wenn task_token leer ist (Stream-Retry
|
||||
in anderem asyncio-Task), aber der Eintrag eine owner_session_id
|
||||
hat, wird trotzdem released.
|
||||
|
||||
Setzt alle wartenden Events für diesen Raum (_waiters[room_id])
|
||||
damit blockierte Streams ihren wait_until_clear auflösen können.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
task_token: UUID4 Task-Token (muss mit _in_flight übereinstimmen,
|
||||
oder leer mit owner_session_id-Fallback).
|
||||
task_token: UUID4 Task-Token (muss mit _in_flight übereinstimmen).
|
||||
"""
|
||||
if room_id not in self._in_flight:
|
||||
logger.debug(
|
||||
@@ -297,22 +287,12 @@ class OutboundGate:
|
||||
|
||||
existing = self._in_flight[room_id]
|
||||
if existing.task_token != task_token:
|
||||
# B1: Session-ID-Fallback — task_token ist leer (Stream-Retry
|
||||
# in anderem asyncio-Task), aber owner_session_id existiert.
|
||||
if not task_token and existing.owner_session_id:
|
||||
logger.info(
|
||||
"[outbound_gate] Release via session-id fallback: "
|
||||
"room=%s token empty, session=%s",
|
||||
room_id[:8], existing.owner_session_id[:8],
|
||||
)
|
||||
# Fall through to release
|
||||
else:
|
||||
logger.warning(
|
||||
"[outbound_gate] Release token mismatch: "
|
||||
"room=%s expected=%s got=%s — skipping",
|
||||
room_id[:8], existing.task_token[:8], task_token[:8],
|
||||
)
|
||||
return
|
||||
logger.warning(
|
||||
"[outbound_gate] Release token mismatch: "
|
||||
"room=%s expected=%s got=%s — skipping",
|
||||
room_id[:8], existing.task_token[:8], task_token[:8],
|
||||
)
|
||||
return
|
||||
|
||||
del self._in_flight[room_id]
|
||||
self.stats.released_total += 1
|
||||
|
||||
+1138
-1190
File diff suppressed because it is too large
Load Diff
+5
-110
@@ -278,89 +278,6 @@ class RoomMap:
|
||||
"""
|
||||
self._fact_store_created_at = timestamp
|
||||
|
||||
# ── Tiebreak Helpers ──────────────────────────────────────────────
|
||||
|
||||
def _get_matched_keywords(self, room: RoomEntry, text: str, keyword_type: str) -> list[str]:
|
||||
"""Return the list of keywords that matched *text* for *room*.
|
||||
|
||||
Args:
|
||||
room: The room to check.
|
||||
text: The message text.
|
||||
keyword_type: ``"100"`` for keywords_100 (morphological matching)
|
||||
or ``"context"`` for keywords_context (exact matching).
|
||||
|
||||
Returns:
|
||||
List of matching keyword strings.
|
||||
"""
|
||||
if keyword_type == "100":
|
||||
return [kw for kw in room.keywords_100 if match_keyword(kw, text)]
|
||||
else:
|
||||
return [kw for kw in room.keywords_context if match_keyword_exact(kw, text)]
|
||||
|
||||
def _keyword_room_count(self, keyword: str) -> int:
|
||||
"""Count how many rooms (excluding catch-all) contain *keyword*.
|
||||
|
||||
Searches both ``keywords_100`` and ``keywords_context`` across all
|
||||
non-catch-all rooms. Lower count = rarer keyword = better tiebreak.
|
||||
|
||||
Args:
|
||||
keyword: The keyword to count (case-sensitive, as stored).
|
||||
|
||||
Returns:
|
||||
Number of rooms that have this keyword.
|
||||
"""
|
||||
count = 0
|
||||
for room in self._rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
if keyword in room.keywords_100 or keyword in room.keywords_context:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
def _tiebreak_compare(
|
||||
self,
|
||||
room_a: RoomEntry,
|
||||
room_b: RoomEntry,
|
||||
matched_a: list[str],
|
||||
matched_b: list[str],
|
||||
) -> bool:
|
||||
"""Return True if *room_a* beats *room_b* in a score tie.
|
||||
|
||||
Tiebreak rules (Option B, Rainer 2026-08-06):
|
||||
1. Room whose rarest matched keyword has the lowest *room_count* wins.
|
||||
2. If still tied: room whose longest matched keyword is longer wins.
|
||||
3. If still tied: *room_b* stays (stable sort — first seen wins).
|
||||
|
||||
Args:
|
||||
room_a: Challenger room.
|
||||
room_b: Current best room.
|
||||
matched_a: Keywords that matched for room_a.
|
||||
matched_b: Keywords that matched for room_b.
|
||||
|
||||
Returns:
|
||||
True if room_a should replace room_b as the best match.
|
||||
"""
|
||||
# Rule 1: Rarest keyword (lowest room_count) wins
|
||||
rarity_a = min(
|
||||
(self._keyword_room_count(kw) for kw in matched_a),
|
||||
default=999,
|
||||
)
|
||||
rarity_b = min(
|
||||
(self._keyword_room_count(kw) for kw in matched_b),
|
||||
default=999,
|
||||
)
|
||||
if rarity_a != rarity_b:
|
||||
return rarity_a < rarity_b
|
||||
|
||||
# Rule 2: Longest matched keyword wins
|
||||
longest_a = max((len(kw) for kw in matched_a), default=0)
|
||||
longest_b = max((len(kw) for kw in matched_b), default=0)
|
||||
if longest_a != longest_b:
|
||||
return longest_a > longest_b
|
||||
|
||||
# Rule 3: Stable — keep current best
|
||||
return False
|
||||
|
||||
# ── Lookup Methods ────────────────────────────────────────────────
|
||||
|
||||
def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
|
||||
@@ -369,10 +286,6 @@ class RoomMap:
|
||||
Uses morphological matching (stemming, fuzzy) for 100%-keywords
|
||||
and exact matching for context keywords.
|
||||
|
||||
At equal scores, tiebreaking favours the room whose matched keyword
|
||||
is the rarest across the entire room map (lowest room_count), then
|
||||
the longest matched keyword (Option B, P-033 fix).
|
||||
|
||||
Args:
|
||||
text: The message text to classify.
|
||||
min_score: Minimum score required to return a room (default: 1).
|
||||
@@ -386,30 +299,21 @@ class RoomMap:
|
||||
is below the minimum threshold.
|
||||
"""
|
||||
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
|
||||
# Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen.
|
||||
# Bei Score-Tie: Tiebreak per Keyword-Rarität (P-033).
|
||||
# Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen
|
||||
# Catch-All-Räume werden in Stufe 1 NICHT berücksichtigt
|
||||
# (100%-Keywords auf Catch-All sind für Auto-Route gedacht, nicht für Keyword-Match)
|
||||
best_100_room: Optional[RoomEntry] = None
|
||||
best_100_score: int = 0
|
||||
best_100_matched: list[str] = []
|
||||
|
||||
for room in self._rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
|
||||
matched = self._get_matched_keywords(room, text, "100")
|
||||
score_100 = len(matched)
|
||||
|
||||
# Zähle 100%-Keyword-Treffer (morphologisches Matching)
|
||||
score_100 = sum(1 for kw in room.keywords_100 if match_keyword(kw, text))
|
||||
if score_100 > best_100_score:
|
||||
best_100_score = score_100
|
||||
best_100_room = room
|
||||
best_100_matched = matched
|
||||
elif score_100 == best_100_score and score_100 > 0:
|
||||
# P-033: Tiebreak per Keyword-Rarität
|
||||
if self._tiebreak_compare(room, best_100_room, matched, best_100_matched):
|
||||
best_100_room = room
|
||||
best_100_matched = matched
|
||||
|
||||
# Wenn mindestens ein 100%-Match existiert → sofort diesen Raum zurückgeben
|
||||
if best_100_room is not None and best_100_score > 0:
|
||||
@@ -431,24 +335,15 @@ class RoomMap:
|
||||
# V8.4.6: Catch-All-Räume sind in Stufe 3 als Butler-Ziele erlaubt.
|
||||
# Catch-All als Keyword-Match-Ziel war für 100%-Auto-Route blockiert (Stufe 1).
|
||||
# Für Kontext-Keywords (Stufe 3) sind Catch-All-Räume valide Butler-Ziele.
|
||||
# P-033: Tiebreak per Keyword-Rarität bei Score-Tie.
|
||||
best_room: Optional[RoomEntry] = None
|
||||
best_score: int = 0
|
||||
best_matched: list[str] = []
|
||||
|
||||
for room in self._rooms.values():
|
||||
matched = self._get_matched_keywords(room, text, "context")
|
||||
context_score = len(matched)
|
||||
|
||||
# Prüfe kontextabhängige Keywords (exaktes Matching)
|
||||
context_score = sum(1 for kw in room.keywords_context if match_keyword_exact(kw, text))
|
||||
if context_score > best_score:
|
||||
best_score = context_score
|
||||
best_room = room
|
||||
best_matched = matched
|
||||
elif context_score == best_score and context_score > 0:
|
||||
# P-033: Tiebreak per Keyword-Rarität
|
||||
if self._tiebreak_compare(room, best_room, matched, best_matched):
|
||||
best_room = room
|
||||
best_matched = matched
|
||||
|
||||
if best_room is not None and best_score >= min_score:
|
||||
return best_room
|
||||
|
||||
@@ -484,25 +484,8 @@ class BidirectionalRouter:
|
||||
# Kein 100%-Treffer → Catch-All (LLM antwortet im DM).
|
||||
# FAISS + weiche Keywords: in DMs NICHT ausführen.
|
||||
routing_telemetry.start_timer()
|
||||
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
||||
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=None)
|
||||
if matched_room is not None:
|
||||
# P-040: origin==target Check — wenn der gefundene Raum
|
||||
# der eigene DM-Raum ist, KEIN Move-Request (Nachricht
|
||||
# ist bereits im korrekten Raum).
|
||||
if matched_room.room_id == origin_room_id:
|
||||
logger.info(
|
||||
"P-040: DM-Match ist origin_room %s — skip Move-Request",
|
||||
origin_room_id[:8],
|
||||
)
|
||||
routing_counter.increment('dm_self_match_stay')
|
||||
logger.info("ROUTING DECISION: reason=dm_self_match_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
is_catch_all=True,
|
||||
stay_in_room=True,
|
||||
)
|
||||
is_100 = self._room_map.is_100_percent_match(text, matched_room)
|
||||
if is_100:
|
||||
# 100%-Keyword in DM → Butler (Move-Request vorschlagen)
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
"""
|
||||
P-039: Drift-Korrektur darf chat_profile NICHT auf 0 setzen.
|
||||
|
||||
Testet dass _drift_correction() nur delegate_subagent via pgrep prüft
|
||||
und chat_profile + background_term unverändert lässt (Hook-gesetzt).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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[2]))
|
||||
|
||||
|
||||
def _make_mock_rest():
|
||||
rest = MagicMock()
|
||||
rest.auth_token = "test-token"
|
||||
rest.user_id = "test-user"
|
||||
rest._request = MagicMock()
|
||||
return rest
|
||||
|
||||
|
||||
def _make_engine(rest=None, enabled=True, away_grace_s=0.1):
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
if rest is None:
|
||||
rest = _make_mock_rest()
|
||||
engine = PresenceEngine(rest=rest, enabled=enabled, away_grace_s=away_grace_s)
|
||||
return engine
|
||||
|
||||
|
||||
class TestP039DriftKeepsChatProfile:
|
||||
"""P-039: Drift-Korrektur setzt chat_profile NICHT auf 0."""
|
||||
|
||||
def test_drift_correction_keeps_chat_profile(self):
|
||||
"""Setup: chat_profile=1, delegate_subagent=0, pgrep findet 0.
|
||||
Erwartung: chat_profile bleibt 1 (NICHT 0)."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
rest = _make_mock_rest()
|
||||
engine = _make_engine(rest=rest)
|
||||
|
||||
# Setup: chat_profile=1 (via Hook gesetzt), delegate_subagent=0
|
||||
engine.counters["chat_profile"] = 1
|
||||
engine.counters["delegate_subagent"] = 0
|
||||
engine.counters["background_term"] = 0
|
||||
|
||||
# Mock pgrep: findet 0 delegierte Subagenten
|
||||
with patch.object(
|
||||
PresenceEngine, "_count_delegated_subagents", return_value=0
|
||||
):
|
||||
engine._drift_correction()
|
||||
|
||||
# P-039: chat_profile darf NICHT auf 0 gesetzt worden sein
|
||||
assert engine.counters["chat_profile"] == 1, (
|
||||
f"P-039 FAIL: chat_profile wurde auf {engine.counters['chat_profile']} "
|
||||
f"gesetzt, sollte aber 1 bleiben (Hook-gesetzt, nicht pgrep-detektierbar)"
|
||||
)
|
||||
assert engine.counters["background_term"] == 0, (
|
||||
f"background_term sollte 0 bleiben"
|
||||
)
|
||||
assert engine.counters["delegate_subagent"] == 0, (
|
||||
f"delegate_subagent sollte 0 bleiben (keine realen Subagenten)"
|
||||
)
|
||||
|
||||
def test_drift_correction_keeps_chat_profile_with_delegate_drift(self):
|
||||
"""Setup: chat_profile=1, delegate_subagent=2, pgrep findet 0.
|
||||
Erwartung: delegate_subagent wird auf 0 gesetzt, chat_profile bleibt 1."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
rest = _make_mock_rest()
|
||||
engine = _make_engine(rest=rest)
|
||||
|
||||
engine.counters["chat_profile"] = 1
|
||||
engine.counters["delegate_subagent"] = 2
|
||||
engine.counters["background_term"] = 0
|
||||
|
||||
with patch.object(
|
||||
PresenceEngine, "_count_delegated_subagents", return_value=0
|
||||
):
|
||||
engine._drift_correction()
|
||||
|
||||
# delegate_subagent wurde korrigiert (pgrep findet 0)
|
||||
assert engine.counters["delegate_subagent"] == 0, (
|
||||
f"delegate_subagent sollte auf 0 korrigiert werden"
|
||||
)
|
||||
# chat_profile bleibt unverändert (P-039)
|
||||
assert engine.counters["chat_profile"] == 1, (
|
||||
f"P-039 FAIL: chat_profile wurde auf {engine.counters['chat_profile']} "
|
||||
f"gesetzt, sollte aber 1 bleiben"
|
||||
)
|
||||
|
||||
def test_drift_correction_keeps_background_term(self):
|
||||
"""Setup: background_term=1, delegate_subagent=0, pgrep findet 0.
|
||||
Erwartung: background_term bleibt 1 (Hook-gesetzt)."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
rest = _make_mock_rest()
|
||||
engine = _make_engine(rest=rest)
|
||||
|
||||
engine.counters["chat_profile"] = 0
|
||||
engine.counters["delegate_subagent"] = 0
|
||||
engine.counters["background_term"] = 1
|
||||
|
||||
with patch.object(
|
||||
PresenceEngine, "_count_delegated_subagents", return_value=0
|
||||
):
|
||||
engine._drift_correction()
|
||||
|
||||
assert engine.counters["background_term"] == 1, (
|
||||
f"P-039 FAIL: background_term wurde auf {engine.counters['background_term']} "
|
||||
f"gesetzt, sollte aber 1 bleiben (Hook-gesetzt)"
|
||||
)
|
||||
@@ -1,46 +0,0 @@
|
||||
"""
|
||||
P-039: PULSE_INTERVAL_S muss 5.0 sein (nicht 3.0).
|
||||
|
||||
Testet dass die Mediator-Konstante auf 5.0s gesetzt ist
|
||||
(3.0s verursachte 429-Storms mit 2+ Agenten).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
|
||||
class TestP039PulseInterval5s:
|
||||
"""P-039: PULSE_INTERVAL_S = 5.0 (nicht 3.0)."""
|
||||
|
||||
def test_pulse_interval_is_5_seconds(self):
|
||||
"""PULSE_INTERVAL_S muss exakt 5.0 sein."""
|
||||
from plugin.archivar.presence_engine import _Mediator
|
||||
|
||||
assert _Mediator.PULSE_INTERVAL_S == 5.0, (
|
||||
f"P-039 FAIL: PULSE_INTERVAL_S = {_Mediator.PULSE_INTERVAL_S}, "
|
||||
f"sollte 5.0 sein (3.0s verursachte 429-Storms mit 2+ Agenten)"
|
||||
)
|
||||
|
||||
def test_pulse_interval_not_3_seconds(self):
|
||||
"""PULSE_INTERVAL_S darf NICHT 3.0 sein."""
|
||||
from plugin.archivar.presence_engine import _Mediator
|
||||
|
||||
assert _Mediator.PULSE_INTERVAL_S != 3.0, (
|
||||
f"P-039 FAIL: PULSE_INTERVAL_S ist immer noch 3.0 — "
|
||||
f"das verursacht 429-Storms!"
|
||||
)
|
||||
|
||||
def test_pulse_interval_reasonable_range(self):
|
||||
"""PULSE_INTERVAL_S sollte zwischen 5.0 und 10.0 liegen."""
|
||||
from plugin.archivar.presence_engine import _Mediator
|
||||
|
||||
assert 5.0 <= _Mediator.PULSE_INTERVAL_S <= 10.0, (
|
||||
f"P-039 FAIL: PULSE_INTERVAL_S = {_Mediator.PULSE_INTERVAL_S} "
|
||||
f"liegt außerhalb des empfohlenen Bereichs [5.0, 10.0]"
|
||||
)
|
||||
@@ -1,129 +0,0 @@
|
||||
"""
|
||||
P-040: DM-Move-Request mit origin==target → stay_in_room.
|
||||
|
||||
Testet dass der DM-Branch in router.py einen origin==target Check
|
||||
VOR is_100_percent_match durchführt und stay_in_room=True zurückgibt.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.router import BidirectionalRouter, RoutingDecision
|
||||
from plugin.archivar.room_map import RoomMap
|
||||
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
||||
from plugin.archivar.archivar_state import ArchivarState
|
||||
|
||||
|
||||
class MockEmbeddingClient(EmbeddingClient):
|
||||
def get_embedding(self, text: str) -> list | None:
|
||||
return [0.1] * 768
|
||||
|
||||
|
||||
def _make_room_map_with_self_match() -> RoomMap:
|
||||
"""Build a RoomMap where a DM room_id matches a room's keywords."""
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
map_path = Path(tmp.name) / "room-map.json"
|
||||
|
||||
test_data = {
|
||||
"version": 5,
|
||||
"rooms": {
|
||||
"room_bat": {
|
||||
"name": "#BAT-Team",
|
||||
"theme": "BAT Team Koordination",
|
||||
"description": "BAT Team Raum",
|
||||
"keywords_100": ["BAT", "bat-team", "batbot"],
|
||||
"keywords_context": ["team", "koordination"],
|
||||
"catch_all": False,
|
||||
},
|
||||
"room_catchall": {
|
||||
"name": "DM mit Andreas",
|
||||
"theme": "Catch-All für DMs",
|
||||
"description": "Catch-All für alle Themen ohne eigenen Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
with open(map_path, "w") as f:
|
||||
json.dump(test_data, f)
|
||||
|
||||
return RoomMap.load(map_path)
|
||||
|
||||
|
||||
def _make_router(room_map: RoomMap) -> BidirectionalRouter:
|
||||
classifier = IntentClassifier(
|
||||
embedding_client=MockEmbeddingClient(),
|
||||
llm_client=None,
|
||||
)
|
||||
state = ArchivarState(":memory:")
|
||||
state.load()
|
||||
router = BidirectionalRouter(room_map, classifier, state)
|
||||
router.set_subscribed_room_ids(list(room_map.rooms.keys()))
|
||||
return router
|
||||
|
||||
|
||||
class TestP040DMMoveRequestOriginTarget:
|
||||
"""P-040: origin==target im DM-Branch → stay_in_room, kein Move-Request."""
|
||||
|
||||
@pytest.fixture
|
||||
def router(self):
|
||||
room_map = _make_room_map_with_self_match()
|
||||
return _make_router(room_map)
|
||||
|
||||
def test_dm_self_match_stay_in_room(self, router):
|
||||
"""Setup: origin_room == room_bat, Text enthält 'BAT'.
|
||||
Erwartung: stay_in_room=True, move_request_sent=False, is_catch_all=True."""
|
||||
# Der DM-Raum hat die gleiche ID wie der BAT-Raum in der Map
|
||||
dm_room_id = "room_bat"
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"BAT-Status: Wie läuft der Sprint?",
|
||||
origin_room_id=dm_room_id,
|
||||
is_dm=True,
|
||||
))
|
||||
|
||||
assert decision is not None
|
||||
assert decision.stay_in_room is True, (
|
||||
f"P-040 FAIL: stay_in_room muss True sein (origin==target), "
|
||||
f"ist aber {decision.stay_in_room}"
|
||||
)
|
||||
assert decision.move_request_sent is False, (
|
||||
f"P-040 FAIL: move_request_sent muss False sein (origin==target), "
|
||||
f"ist aber {decision.move_request_sent}"
|
||||
)
|
||||
assert decision.is_catch_all is True, (
|
||||
f"P-040 FAIL: is_catch_all muss True sein (origin==target), "
|
||||
f"ist aber {decision.is_catch_all}"
|
||||
)
|
||||
assert decision.category == "direct_question", (
|
||||
f"Erwartet category='direct_question', bekam '{decision.category}'"
|
||||
)
|
||||
|
||||
def test_dm_different_room_still_routes(self, router):
|
||||
"""Setup: origin_room != room_bat, Text enthält 'BAT'.
|
||||
Erwartung: move_request_sent=True (normales Butler-Verhalten)."""
|
||||
dm_room_id = "6a56004b9eae0cd36b1aa16c" # anderer DM-Raum
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"BAT-Status: Wie läuft der Sprint?",
|
||||
origin_room_id=dm_room_id,
|
||||
is_dm=True,
|
||||
))
|
||||
|
||||
assert decision is not None
|
||||
assert decision.move_request_sent is True, (
|
||||
f"P-040 FAIL: move_request_sent muss True sein (anderer Raum), "
|
||||
f"ist aber {decision.move_request_sent}"
|
||||
)
|
||||
assert decision.stay_in_room is False
|
||||
@@ -1,100 +0,0 @@
|
||||
"""
|
||||
P-040: _send_move_request defensiver origin==target Check.
|
||||
|
||||
Testet dass _send_move_request() False zurückgibt und keinen Button
|
||||
sendet, wenn move_request_target_id == room_id (origin==target).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.archivar.router import RoutingDecision
|
||||
|
||||
|
||||
def _make_decision_with_target(target_id: str) -> RoutingDecision:
|
||||
"""Erzeuge eine RoutingDecision mit move_request_target_id."""
|
||||
return RoutingDecision(
|
||||
category="work_order",
|
||||
target_room=target_id,
|
||||
confidence=0.95,
|
||||
matched_room_name="#Test-Raum",
|
||||
source_room_notification="Test",
|
||||
matched_keywords=["test"],
|
||||
move_request_sent=True,
|
||||
move_request_target_name="#Test-Raum",
|
||||
move_request_target_id=target_id,
|
||||
)
|
||||
|
||||
|
||||
class TestP040MoveRequestSkipsSelf:
|
||||
"""P-040: _send_move_request skip bei origin==target."""
|
||||
|
||||
@pytest.fixture
|
||||
def handler(self):
|
||||
"""Erzeuge einen ArchivarMessageHandler mit gemockten Abhängigkeiten."""
|
||||
with patch(
|
||||
"plugin.archivar.adapter_integration.ArchivarMessageHandler._load_room_map",
|
||||
return_value=MagicMock(),
|
||||
), patch(
|
||||
"plugin.archivar.adapter_integration.ArchivarState",
|
||||
autospec=True,
|
||||
), patch(
|
||||
"plugin.archivar.adapter_integration.IntentClassifier",
|
||||
autospec=True,
|
||||
):
|
||||
from plugin.archivar.adapter_integration import ArchivarMessageHandler
|
||||
|
||||
handler = ArchivarMessageHandler(
|
||||
send_callback=AsyncMock(return_value=True),
|
||||
button_send_callback=AsyncMock(return_value=True),
|
||||
)
|
||||
handler._stats = {}
|
||||
return handler
|
||||
|
||||
def test_move_request_skips_when_origin_equals_target(self, handler):
|
||||
"""Setup: move_request_target_id == room_id.
|
||||
Erwartung: False, kein Button gesendet, _stats['move_request_self_skipped'] += 1."""
|
||||
room_id = "room_bat"
|
||||
decision = _make_decision_with_target(room_id)
|
||||
|
||||
result = asyncio.run(
|
||||
handler._send_move_request(room_id, "test text", decision)
|
||||
)
|
||||
|
||||
assert result is False, (
|
||||
f"P-040 FAIL: _send_move_request muss False zurückgeben bei origin==target, "
|
||||
f"gab aber {result}"
|
||||
)
|
||||
# Kein Button-Callback aufgerufen
|
||||
handler._button_send_callback.assert_not_called()
|
||||
handler._send_callback.assert_not_called()
|
||||
# Telemetrie
|
||||
assert handler._stats.get("move_request_self_skipped", 0) == 1, (
|
||||
f"P-040 FAIL: move_request_self_skipped sollte 1 sein, "
|
||||
f"ist {handler._stats.get('move_request_self_skipped', 0)}"
|
||||
)
|
||||
|
||||
def test_move_request_sends_when_origin_differs_from_target(self, handler):
|
||||
"""Setup: move_request_target_id != room_id.
|
||||
Erwartung: True, Button wird gesendet."""
|
||||
room_id = "room_other"
|
||||
decision = _make_decision_with_target("room_bat")
|
||||
|
||||
result = asyncio.run(
|
||||
handler._send_move_request(room_id, "test text", decision)
|
||||
)
|
||||
|
||||
assert result is True, (
|
||||
f"P-040 FAIL: _send_move_request muss True zurückgeben bei "
|
||||
f"unterschiedlichen Räumen, gab aber {result}"
|
||||
)
|
||||
# Button-Callback wurde aufgerufen
|
||||
handler._button_send_callback.assert_called_once()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -724,196 +724,3 @@ class TestRoomMapSaveRefuseGuard:
|
||||
assert map_path.exists(), "Datei sollte erstellt worden sein"
|
||||
finally:
|
||||
tmpdir.cleanup()
|
||||
|
||||
|
||||
# ── P-033: Tiebreak-Bug Regression Tests ───────────────────────────────────
|
||||
|
||||
|
||||
class TestP033Tiebreak:
|
||||
"""P-033: Tiebreak-Bug — bei Score-Tie gewinnt der semantisch passendere Raum.
|
||||
|
||||
Root Cause: room_map.py:314 verwendete strict ``>`` statt Tiebreak.
|
||||
Bei Score-Tie 1:1 entschied Dict-Insertion-Order, nicht Logik.
|
||||
Fix: Option B — Keyword-Rarität (room_count), dann längstes Keyword.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def room_map_p033(self) -> RoomMap:
|
||||
"""Room map simulating the P-033 scenario.
|
||||
|
||||
#LAN-Dokumentation and #Rocketchat-Plugin both match "Dokumentation"
|
||||
(one via keywords_100, one via keywords_context), but "rocketchat"
|
||||
is unique to Plugin — so Plugin should win the tiebreak.
|
||||
"""
|
||||
data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"r_lan": {
|
||||
"name": "#LAN-Dokumentation",
|
||||
"theme": "LAN und Netzwerk-Dokumentation",
|
||||
"keywords_100": ["dokumentation", "lan", "netzwerk"],
|
||||
"keywords_context": [],
|
||||
},
|
||||
"r_plugin": {
|
||||
"name": "#Rocketchat-Plugin",
|
||||
"theme": "Rocketchat Plugin Entwicklung",
|
||||
"keywords_100": ["rocketchat", "rc", "plugin"],
|
||||
"keywords_context": ["dokumentation"],
|
||||
},
|
||||
"r_admin": {
|
||||
"name": "DM Admin",
|
||||
"theme": "admin",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": "/tmp/test_docs",
|
||||
}
|
||||
json_str = json.dumps(data)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
return RoomMap.load(path)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_tiebreak_rocketchat_dokumentation_matches_plugin(self, room_map_p033):
|
||||
"""Text mit 'Rocketchat' + 'Dokumentation' muss #Rocketchat-Plugin matchen.
|
||||
|
||||
Beide Räume scoren 1:1 (LAN: dokumentation, Plugin: rocketchat).
|
||||
Tiebreak: 'rocketchat' ist seltener (nur in Plugin) als 'dokumentation'
|
||||
(in beiden Räumen) → Plugin gewinnt.
|
||||
"""
|
||||
result = room_map_p033.find_room_by_keywords(
|
||||
"Rocketchat Dokumentation Update"
|
||||
)
|
||||
assert result is not None, "Sollte einen Raum finden"
|
||||
assert result.name == "#Rocketchat-Plugin", (
|
||||
f"Tiebreak-Fehler: Erwartet #Rocketchat-Plugin, "
|
||||
f"bekam {result.name}. 'rocketchat' ist seltener als 'dokumentation'."
|
||||
)
|
||||
|
||||
def test_dokumentation_only_matches_lan(self, room_map_p033):
|
||||
"""Text mit nur 'Dokumentation' muss #LAN-Dokumentation matchen.
|
||||
|
||||
LAN-Doku hat 'dokumentation' als 100%-Keyword → Stufe 1 Match.
|
||||
Plugin hat 'dokumentation' nur als Kontext-Keyword → Stufe 3.
|
||||
Stufe 1 schlägt Stufe 3 → LAN gewinnt.
|
||||
"""
|
||||
result = room_map_p033.find_room_by_keywords("Dokumentation")
|
||||
assert result is not None, "Sollte einen Raum finden"
|
||||
assert result.name == "#LAN-Dokumentation", (
|
||||
f"Erwartet #LAN-Dokumentation (100%-Keyword), bekam {result.name}"
|
||||
)
|
||||
|
||||
def test_rocketchat_only_matches_plugin(self, room_map_p033):
|
||||
"""Text mit nur 'Rocketchat' muss #Rocketchat-Plugin matchen."""
|
||||
result = room_map_p033.find_room_by_keywords("Rocketchat")
|
||||
assert result is not None, "Sollte einen Raum finden"
|
||||
assert result.name == "#Rocketchat-Plugin", (
|
||||
f"Erwartet #Rocketchat-Plugin, bekam {result.name}"
|
||||
)
|
||||
|
||||
def test_tiebreak_rarity_wins_over_length(self, room_map_p033):
|
||||
"""Rarität (room_count) schlägt Keyword-Länge im Tiebreak.
|
||||
|
||||
Szenario: Zwei Räume mit gleichem Score, aber unterschiedlicher
|
||||
Keyword-Rarität. Der Raum mit dem selteneren Keyword gewinnt,
|
||||
auch wenn das Keyword kürzer ist.
|
||||
"""
|
||||
# Beide Räume matchen "dokumentation" (room_count=2) und
|
||||
# "rocketchat" (room_count=1). Plugin hat das seltenere Keyword.
|
||||
result = room_map_p033.find_room_by_keywords(
|
||||
"Rocketchat Dokumentation"
|
||||
)
|
||||
assert result is not None
|
||||
assert result.name == "#Rocketchat-Plugin", (
|
||||
f"Rarität sollte Länge schlagen: 'rocketchat' (count=1) "
|
||||
f"ist seltener als 'dokumentation' (count=2)"
|
||||
)
|
||||
|
||||
def test_tiebreak_stable_when_all_equal(self, room_map_p033):
|
||||
"""Wenn Rarität und Länge gleich sind → first-seen gewinnt (stabil)."""
|
||||
# Erstelle zwei Räume mit identischen Keywords
|
||||
data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"r_a": {
|
||||
"name": "#Raum-A",
|
||||
"theme": "Erster Raum",
|
||||
"keywords_100": ["shared"],
|
||||
"keywords_context": [],
|
||||
},
|
||||
"r_b": {
|
||||
"name": "#Raum-B",
|
||||
"theme": "Zweiter Raum",
|
||||
"keywords_100": ["shared"],
|
||||
"keywords_context": [],
|
||||
},
|
||||
"r_admin": {
|
||||
"name": "DM Admin",
|
||||
"theme": "admin",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": "/tmp/test_docs",
|
||||
}
|
||||
json_str = json.dumps(data)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
result = rm.find_room_by_keywords("shared keyword")
|
||||
assert result is not None
|
||||
# Bei identischen Keywords: first-seen gewinnt (stabil)
|
||||
assert result.name == "#Raum-A", (
|
||||
f"Stable sort: first-seen sollte gewinnen, bekam {result.name}"
|
||||
)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_tiebreak_length_wins_when_rarity_equal(self, room_map_p033):
|
||||
"""Wenn Rarität gleich, gewinnt das längste gematchte Keyword."""
|
||||
data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"r_short": {
|
||||
"name": "#Kurz",
|
||||
"theme": "Kurzes Keyword",
|
||||
"keywords_100": ["abc"],
|
||||
"keywords_context": [],
|
||||
},
|
||||
"r_long": {
|
||||
"name": "#Lang",
|
||||
"theme": "Langes Keyword",
|
||||
"keywords_100": ["abcdefghij"],
|
||||
"keywords_context": [],
|
||||
},
|
||||
"r_admin": {
|
||||
"name": "DM Admin",
|
||||
"theme": "admin",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": "/tmp/test_docs",
|
||||
}
|
||||
json_str = json.dumps(data)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
result = rm.find_room_by_keywords("abc abcdefghij")
|
||||
assert result is not None
|
||||
# Beide Keywords sind gleich selten (room_count=1),
|
||||
# aber "abcdefghij" ist länger → #Lang gewinnt
|
||||
assert result.name == "#Lang", (
|
||||
f"Längeres Keyword sollte bei gleicher Rarität gewinnen, "
|
||||
f"bekam {result.name}"
|
||||
)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
@@ -1,466 +0,0 @@
|
||||
"""
|
||||
P1 Fix: Session-Isolation — Tests für _CURRENT_SESSION_ID + OutboundGate owner_session_id.
|
||||
|
||||
B3: ContextVar _CURRENT_SESSION_ID Propagation
|
||||
B1: _TurnHandle.owner_session_id in OutboundGate
|
||||
B2: allow_proactive_user_map Opt-In
|
||||
B+: Sweep-Intervall + max_entry_age reduziert
|
||||
Integration: Concurrent-Session-Isolation
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextvars
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, AsyncMock
|
||||
|
||||
# Ensure the plugin package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# B3: _CURRENT_SESSION_ID ContextVar
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSessionIdPropagation(unittest.TestCase):
|
||||
"""Tests für _CURRENT_SESSION_ID ContextVar (B3)."""
|
||||
|
||||
def setUp(self):
|
||||
"""Importiere _CURRENT_SESSION_ID aus adapter.py."""
|
||||
from plugin.adapter import _CURRENT_SESSION_ID
|
||||
self._CURRENT_SESSION_ID = _CURRENT_SESSION_ID
|
||||
|
||||
def tearDown(self):
|
||||
"""Clean up ContextVar."""
|
||||
self._CURRENT_SESSION_ID.set("")
|
||||
|
||||
def test_session_id_propagation(self):
|
||||
"""_CURRENT_SESSION_ID wird gesetzt und kann gelesen werden."""
|
||||
session_id = "session-abc-123"
|
||||
self._CURRENT_SESSION_ID.set(session_id)
|
||||
self.assertEqual(self._CURRENT_SESSION_ID.get(), session_id)
|
||||
|
||||
def test_session_id_no_core_arg_fallback(self):
|
||||
"""Wenn Core keine session_id übergibt, wird uuid4().hex als Fallback generiert."""
|
||||
# Der Fallback wird in _dispatch_agent gesetzt — hier testen wir nur,
|
||||
# dass der Default-Wert ein leerer String ist (vor Setzung).
|
||||
self._CURRENT_SESSION_ID.set("")
|
||||
self.assertEqual(self._CURRENT_SESSION_ID.get(), "")
|
||||
|
||||
def test_session_id_default_is_empty_string(self):
|
||||
"""Default-Wert von _CURRENT_SESSION_ID ist ''."""
|
||||
# Neuer ContextVar ohne explizite Setzung
|
||||
cv = contextvars.ContextVar("_test_session_id", default="")
|
||||
self.assertEqual(cv.get(), "")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# B1: _TurnHandle.owner_session_id + release() Session-ID-Fallback
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestOutboundGateSessionId(unittest.TestCase):
|
||||
"""Tests für owner_session_id in OutboundGate (B1)."""
|
||||
|
||||
def setUp(self):
|
||||
from plugin.archivar.outbound_gate import OutboundGate, _TurnHandle
|
||||
self.OutboundGate = OutboundGate
|
||||
self._TurnHandle = _TurnHandle
|
||||
|
||||
def test_turn_handle_has_owner_session_id_field(self):
|
||||
"""_TurnHandle hat owner_session_id Feld mit Default ''."""
|
||||
handle = self._TurnHandle(
|
||||
task_token="token-1",
|
||||
started_at=12345.0,
|
||||
real_room_id="room-a",
|
||||
)
|
||||
self.assertEqual(handle.owner_session_id, "")
|
||||
|
||||
def test_try_acquire_records_owner_session_id(self):
|
||||
"""try_acquire speichert owner_session_id im _TurnHandle."""
|
||||
gate = self.OutboundGate()
|
||||
|
||||
async def _run():
|
||||
return await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
|
||||
|
||||
decision = asyncio.run(_run())
|
||||
self.assertTrue(decision.allow)
|
||||
self.assertEqual(decision.reason, "gate_clear")
|
||||
|
||||
# Verify: _TurnHandle hat owner_session_id
|
||||
handle = gate._in_flight["room-a"]
|
||||
self.assertEqual(handle.owner_session_id, "session-1")
|
||||
|
||||
def test_release_respects_owner_session_id(self):
|
||||
"""release() mit Token-Mismatch aber Session-ID-Match → release OK."""
|
||||
gate = self.OutboundGate()
|
||||
|
||||
async def _run():
|
||||
await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
# Release mit falschem Token, aber korrekter Session-ID
|
||||
# (Simuliert: Stream-Completion in anderem asyncio-Task,
|
||||
# _CURRENT_TASK_TOKEN ist leer, aber _CURRENT_SESSION_ID matcht)
|
||||
gate.release("room-a", "") # task_token="" (leer, wie bei Stream-Retry)
|
||||
|
||||
# Der Eintrag sollte entfernt worden sein (Session-ID-Match)
|
||||
self.assertNotIn("room-a", gate._in_flight)
|
||||
self.assertEqual(gate.stats.released_total, 1)
|
||||
|
||||
def test_release_token_mismatch_no_session_match_skips(self):
|
||||
"""release() mit Token-Mismatch UND Session-ID-Mismatch → skip."""
|
||||
gate = self.OutboundGate()
|
||||
|
||||
async def _run():
|
||||
await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
# Release mit falschem Token UND keiner Session-ID (default "")
|
||||
# → sollte skippen
|
||||
gate.release("room-a", "wrong-token")
|
||||
|
||||
# Der Eintrag sollte NICHT entfernt worden sein
|
||||
self.assertIn("room-a", gate._in_flight)
|
||||
self.assertEqual(gate.stats.released_total, 0)
|
||||
|
||||
def test_release_token_match_no_session_needed(self):
|
||||
"""release() mit korrektem Token → release OK (Session-ID nicht benötigt)."""
|
||||
gate = self.OutboundGate()
|
||||
|
||||
async def _run():
|
||||
await gate.try_acquire("room-a", "token-a", owner_session_id="session-1")
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
# Release mit korrektem Token
|
||||
gate.release("room-a", "token-a")
|
||||
|
||||
self.assertNotIn("room-a", gate._in_flight)
|
||||
self.assertEqual(gate.stats.released_total, 1)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# B2: allow_proactive_user_map Opt-In
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestAllowProactiveUserMap(unittest.TestCase):
|
||||
"""Tests für allow_proactive_user_map Opt-In (B2)."""
|
||||
|
||||
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
|
||||
|
||||
# OutboundGate mock
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
self.adapter._outbound_gate = OutboundGate()
|
||||
|
||||
# Import module-level state
|
||||
from plugin.adapter import (
|
||||
_CURRENT_ORIGIN_ROOM,
|
||||
_THEMATIC_TARGET_ROOM,
|
||||
_CURRENT_TASK_TOKEN,
|
||||
_CURRENT_SESSION_ID,
|
||||
_room_context,
|
||||
_room_context_lock,
|
||||
_RED_FLAG_PENDING,
|
||||
)
|
||||
self._CURRENT_ORIGIN_ROOM = _CURRENT_ORIGIN_ROOM
|
||||
self._THEMATIC_TARGET_ROOM = _THEMATIC_TARGET_ROOM
|
||||
self._CURRENT_TASK_TOKEN = _CURRENT_TASK_TOKEN
|
||||
self._CURRENT_SESSION_ID = _CURRENT_SESSION_ID
|
||||
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._CURRENT_TASK_TOKEN.set("")
|
||||
self._CURRENT_SESSION_ID.set("")
|
||||
self._RED_FLAG_PENDING.set({})
|
||||
with self._room_context_lock:
|
||||
self._room_context.clear()
|
||||
|
||||
def test_user_map_blocked_by_default(self):
|
||||
"""Ohne allow_proactive_user_map=True → Priority 2 (_user_rooms[-1]) wird NICHT genutzt."""
|
||||
chat_id = "user:alice"
|
||||
wrong_room = "room_wrong_general"
|
||||
|
||||
# ContextVars sind LEER (kein _CURRENT_ORIGIN_ROOM, kein _room_context)
|
||||
self._CURRENT_ORIGIN_ROOM.set("")
|
||||
self._THEMATIC_TARGET_ROOM.set("")
|
||||
self._CURRENT_TASK_TOKEN.set("")
|
||||
|
||||
# _user_rooms hat einen Raum (Priority 2)
|
||||
self.adapter._user_rooms = {chat_id: [wrong_room]}
|
||||
|
||||
# _find_fallback_room_for_user gibt None zurück
|
||||
self.adapter._find_fallback_room_for_user = MagicMock(return_value=None)
|
||||
|
||||
# Config: allow_proactive_user_map = False (default)
|
||||
self.adapter.config.extra = {}
|
||||
|
||||
result = asyncio.run(
|
||||
self.adapter.send(chat_id=chat_id, content="Test response")
|
||||
)
|
||||
|
||||
# Verify: send() hat einen Fehler zurückgegeben (kein Raum gefunden)
|
||||
# SendResult kann dict (Fallback) oder SendResult-Objekt sein
|
||||
_success = result.success if hasattr(result, 'success') else result.get('success', True)
|
||||
_error = result.error if hasattr(result, 'error') else result.get('error', '')
|
||||
self.assertFalse(_success)
|
||||
self.assertIn("No resolved room", _error)
|
||||
|
||||
def test_user_map_allowed_with_optin(self):
|
||||
"""Mit allow_proactive_user_map=True → Priority 2 (_user_rooms[-1]) wird genutzt."""
|
||||
chat_id = "user:alice"
|
||||
correct_room = "room_correct_dm"
|
||||
|
||||
# ContextVars sind LEER
|
||||
self._CURRENT_ORIGIN_ROOM.set("")
|
||||
self._THEMATIC_TARGET_ROOM.set("")
|
||||
self._CURRENT_TASK_TOKEN.set("")
|
||||
|
||||
# _user_rooms hat einen Raum
|
||||
self.adapter._user_rooms = {chat_id: [correct_room]}
|
||||
|
||||
# Config: allow_proactive_user_map = True
|
||||
self.adapter.config.extra = {"allow_proactive_user_map": True}
|
||||
|
||||
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)
|
||||
|
||||
def test_fallback_room_respects_optin(self):
|
||||
"""_find_fallback_room_for_user wird NUR genutzt wenn allow_proactive_user_map=True."""
|
||||
chat_id = "user:alice"
|
||||
fallback_room = "room_fallback_123"
|
||||
|
||||
# ContextVars sind LEER
|
||||
self._CURRENT_ORIGIN_ROOM.set("")
|
||||
self._THEMATIC_TARGET_ROOM.set("")
|
||||
self._CURRENT_TASK_TOKEN.set("")
|
||||
|
||||
# _user_rooms ist LEER (kein Priority 2)
|
||||
self.adapter._user_rooms = {}
|
||||
|
||||
# _find_fallback_room_for_user gibt einen Raum zurück
|
||||
self.adapter._find_fallback_room_for_user = MagicMock(return_value=fallback_room)
|
||||
|
||||
# Config: allow_proactive_user_map = False (default)
|
||||
self.adapter.config.extra = {}
|
||||
|
||||
result = asyncio.run(
|
||||
self.adapter.send(chat_id=chat_id, content="Test response")
|
||||
)
|
||||
|
||||
# Verify: send() hat einen Fehler zurückgegeben (Fallback nicht genutzt)
|
||||
_success = result.success if hasattr(result, 'success') else result.get('success', True)
|
||||
_error = result.error if hasattr(result, 'error') else result.get('error', '')
|
||||
self.assertFalse(_success)
|
||||
self.assertIn("No resolved room", _error)
|
||||
|
||||
def test_allow_proactive_metadata_override(self):
|
||||
"""metadata['allow_proactive'] = True überschreibt Config-Wert pro-Aufruf."""
|
||||
chat_id = "user:alice"
|
||||
correct_room = "room_proactive_override"
|
||||
|
||||
# ContextVars sind LEER
|
||||
self._CURRENT_ORIGIN_ROOM.set("")
|
||||
self._THEMATIC_TARGET_ROOM.set("")
|
||||
self._CURRENT_TASK_TOKEN.set("")
|
||||
|
||||
# _user_rooms hat einen Raum
|
||||
self.adapter._user_rooms = {chat_id: [correct_room]}
|
||||
|
||||
# Config: allow_proactive_user_map = False (default)
|
||||
self.adapter.config.extra = {}
|
||||
|
||||
# metadata['allow_proactive'] = True überschreibt
|
||||
result = asyncio.run(
|
||||
self.adapter.send(
|
||||
chat_id=chat_id,
|
||||
content="Test response",
|
||||
metadata={"allow_proactive": True},
|
||||
)
|
||||
)
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# B+: Sweep-Intervall + max_entry_age reduziert
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSweepIntervalReduced(unittest.TestCase):
|
||||
"""Tests für reduziertes Sweep-Intervall und max_entry_age (B+)."""
|
||||
|
||||
def test_max_entry_age_default_is_10s(self):
|
||||
"""OutboundGate default max_entry_age_s ist 10.0 (war 60.0)."""
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
gate = OutboundGate()
|
||||
self.assertEqual(gate.max_entry_age_s, 10.0)
|
||||
|
||||
def test_sweep_removes_stale_after_10s(self):
|
||||
"""Stale Einträge werden nach 10s entfernt (nicht erst nach 60s)."""
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
gate = OutboundGate(max_entry_age_s=0.05) # 50ms für schnellen Test
|
||||
|
||||
async def _run():
|
||||
await gate.try_acquire("room-a", "token-a")
|
||||
self.assertIn("room-a", gate._in_flight)
|
||||
await asyncio.sleep(0.1) # 100ms > 50ms TTL
|
||||
swept = gate._sweep_stale_entries()
|
||||
self.assertGreaterEqual(swept, 1)
|
||||
self.assertNotIn("room-a", gate._in_flight)
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# Integration: Concurrent-Session-Isolation
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSessionIdIsolatesConcurrentSessions(unittest.TestCase):
|
||||
"""Integrationstest: Zwei parallele Dispatches mit verschiedenen session_ids
|
||||
dürfen sich nicht gegenseitig die Gate-Slots streitig machen."""
|
||||
|
||||
def test_session_id_isolates_concurrent_sessions(self):
|
||||
"""Zwei Sessions mit verschiedenen session_ids können parallel senden."""
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
|
||||
gate = OutboundGate()
|
||||
|
||||
async def _run():
|
||||
# Session 1: Raum A, Token A, Session-ID "session-1"
|
||||
decision_1 = await gate.try_acquire(
|
||||
"room-a", "token-a", owner_session_id="session-1"
|
||||
)
|
||||
self.assertTrue(decision_1.allow)
|
||||
self.assertEqual(decision_1.reason, "gate_clear")
|
||||
|
||||
# Session 2: Raum B, Token B, Session-ID "session-2"
|
||||
# Sollte blockiert sein (anderer Raum busy)
|
||||
decision_2 = await gate.try_acquire(
|
||||
"room-b", "token-b", owner_session_id="session-2"
|
||||
)
|
||||
self.assertFalse(decision_2.allow)
|
||||
self.assertEqual(decision_2.reason, "different_room_busy")
|
||||
|
||||
# Session 1 released (Token ist leer wegen Stream-Retry in anderem Task)
|
||||
# ABER: owner_session_id matcht → release OK
|
||||
gate.release("room-a", "") # task_token="" (leer)
|
||||
|
||||
# Jetzt sollte Session 2 senden können
|
||||
decision_2_retry = await gate.try_acquire(
|
||||
"room-b", "token-b", owner_session_id="session-2"
|
||||
)
|
||||
self.assertTrue(decision_2_retry.allow)
|
||||
self.assertEqual(decision_2_retry.reason, "gate_clear")
|
||||
|
||||
# Cleanup
|
||||
gate.release("room-b", "token-b")
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
def test_same_session_multi_turn_allowed(self):
|
||||
"""Gleiche Session, gleicher Raum, gleicher Token → Multi-Turn allowed."""
|
||||
from plugin.archivar.outbound_gate import OutboundGate
|
||||
|
||||
gate = OutboundGate()
|
||||
|
||||
async def _run():
|
||||
# Erster Turn
|
||||
d1 = await gate.try_acquire(
|
||||
"room-a", "token-a", owner_session_id="session-1"
|
||||
)
|
||||
self.assertTrue(d1.allow)
|
||||
self.assertEqual(d1.reason, "gate_clear")
|
||||
|
||||
# Zweiter Turn (gleiche Session, gleicher Raum, gleicher Token)
|
||||
d2 = await gate.try_acquire(
|
||||
"room-a", "token-a", owner_session_id="session-1"
|
||||
)
|
||||
self.assertTrue(d2.allow)
|
||||
self.assertEqual(d2.reason, "same_room_same_token")
|
||||
|
||||
# Release
|
||||
gate.release("room-a", "token-a")
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,689 +0,0 @@
|
||||
"""
|
||||
V8.7: Subagent-Status — PresenceEngine Integrationstests (pgrep-basiert).
|
||||
|
||||
Testet:
|
||||
- mark_busy_done mit background_tasks > 0 (kein online-Übergang)
|
||||
- mark_busy_done mit background_tasks == 0 (Regression: online-Übergang)
|
||||
- _honeymoon_expired mit background_tasks > 0
|
||||
- DetectionTimer._pgrep_hermes_subagents() — /proc-basierte Erkennung
|
||||
- PulseController pulse_target="away" toggles
|
||||
- PulseController pulse_target="busy" message-pulses
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.skip(reason='V8.x removed in V9 Schachuhr-Architektur')
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# B4: Autouse fixture — engine.shutdown() nach jedem Test
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_ENGINE_REGISTRY: list = []
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _shutdown_presence_engines():
|
||||
"""Track all PresenceEngine instances and call shutdown() after each test."""
|
||||
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()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Helper: create a PresenceEngine with mocked REST
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_engine(**kwargs):
|
||||
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, **kwargs)
|
||||
return engine, mock_rest
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: mark_busy_done with bg_tasks > 0 does NOT transition to online
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestMarkBusyDoneWithBgTasks:
|
||||
"""Test 3: mark_busy_done mit background_tasks > 0 geht NICHT auf online."""
|
||||
|
||||
def test_busy_done_with_bg_tasks_stays_away_or_busy(self):
|
||||
"""Wenn background_tasks > 0, transitioniert mark_busy_done nicht auf online."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
# Simuliere: Hauptagent busy + Subagent läuft
|
||||
engine.mark_busy_started(room_name="testroom")
|
||||
engine.increment_background_tasks() # bg=1
|
||||
|
||||
# Honeymoon abwarten
|
||||
time.sleep(1.2)
|
||||
|
||||
# mark_busy_done — sollte NICHT auf online gehen weil bg=1
|
||||
engine.mark_busy_done()
|
||||
|
||||
# Flush coalesce
|
||||
time.sleep(0.3)
|
||||
|
||||
# Prüfe: letzter gesendeter Status ist NICHT "online"
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) > 0, "Expected at least one REST call"
|
||||
last_call = calls[-1]
|
||||
last_data = last_call[1].get("data", {})
|
||||
assert last_data.get("status") != "online", (
|
||||
f"Expected non-online status, got {last_data}"
|
||||
)
|
||||
|
||||
def test_busy_done_zero_bg_tasks_transitions_to_online(self):
|
||||
"""Regression: background_tasks == 0 → online (klassischer Pfad)."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
# Mock _pgrep_hermes_subagents → 0 (keine Subagenten)
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0):
|
||||
engine.mark_busy_started(room_name="testroom")
|
||||
# KEIN increment_background_tasks → bg=0
|
||||
|
||||
time.sleep(1.2)
|
||||
|
||||
engine.mark_busy_done()
|
||||
time.sleep(0.3)
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
last_call = calls[-1]
|
||||
last_data = last_call[1].get("data", {})
|
||||
assert last_data.get("status") == "online", (
|
||||
f"Expected online status, got {last_data}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: _honeymoon_expired with bg_tasks > 0
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestHoneymoonExpiredWithBgTasks:
|
||||
"""Test 5: _honeymoon_expired mit background_tasks > 0 geht nicht auf online."""
|
||||
|
||||
def test_honeymoon_expired_with_bg_tasks_does_not_transition(self):
|
||||
"""Honeymoon-Timer feuert, aber bg_tasks > 0 → kein online."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
engine.mark_busy_started(room_name="testroom")
|
||||
engine.increment_background_tasks() # bg=1
|
||||
|
||||
time.sleep(1.2)
|
||||
|
||||
engine._transition_from_busy()
|
||||
|
||||
time.sleep(0.3)
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
last_call = calls[-1]
|
||||
last_data = last_call[1].get("data", {})
|
||||
assert last_data.get("status") != "online", (
|
||||
f"Expected non-online status after honeymoon with bg_tasks, got {last_data}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: DetectionTimer._pgrep_hermes_subagents() — /proc-basierte Erkennung
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPgrepHermesSubagents:
|
||||
"""Test 6: _pgrep_hermes_subagents() erkennt hermes chat --profile Prozesse.
|
||||
|
||||
V8.8: argv-basierter Scanner — verhindert False-Positives auf
|
||||
Shell-Befehle die 'hermes'+'chat'+'--profile' als Text enthalten.
|
||||
"""
|
||||
|
||||
def test_pgrep_finds_hermes_binary_chat_profile(self):
|
||||
"""_pgrep_hermes_subagents() findet 'hermes chat --profile rainer'."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Mock /proc: ein echter hermes chat --profile Prozess
|
||||
mock_proc_entries = ["1", "2", str(own_pid), "99999", "12345"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == "12345":
|
||||
# argv: ["hermes", "chat", "--profile", "rainer"]
|
||||
return b"hermes\x00chat\x00--profile\x00rainer\x00"
|
||||
elif pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
else:
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
# Mock _read_gateway_pid → None (kein Gateway)
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
assert count == 1, f"Expected 1, got {count}"
|
||||
|
||||
def test_pgrep_finds_python_m_hermes_cli_chat_profile(self):
|
||||
"""_pgrep_hermes_subagents() findet 'python -m hermes_cli.main chat --profile miguel'."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == "12345":
|
||||
# argv: ["python", "-m", "hermes_cli.main", "chat", "--profile", "miguel"]
|
||||
return b"python\x00-m\x00hermes_cli.main\x00chat\x00--profile\x00miguel\x00"
|
||||
elif pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
assert count == 1, f"Expected 1, got {count}"
|
||||
|
||||
def test_pgrep_false_positive_bash_grep(self):
|
||||
"""V8.8: 'bash -c grep hermes.*chat.*--profile' → KEIN match (False-Positive)."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == "12345":
|
||||
# argv: ["bash", "-c", "grep hermes.*chat.*--profile /var/log/..."]
|
||||
return b"bash\x00-c\x00grep hermes.*chat.*--profile /var/log/syslog\x00"
|
||||
elif pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
assert count == 0, f"Expected 0 (false positive), got {count}"
|
||||
|
||||
def test_pgrep_false_positive_hermes_snap_path(self):
|
||||
"""V8.8: '/tmp/hermes-snap-xxx bash -c ...' → KEIN match (False-Positive)."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == "12345":
|
||||
# argv: ["/tmp/hermes-snap-xxx", "bash", "-c", "hermes chat --profile"]
|
||||
return b"/tmp/hermes-snap-abc123\x00bash\x00-c\x00hermes chat --profile rainer\x00"
|
||||
elif pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
assert count == 0, f"Expected 0 (false positive), got {count}"
|
||||
|
||||
def test_pgrep_false_positive_gateway_process(self):
|
||||
"""V8.8: Gateway 'python -m hermes_cli.main gateway run' → KEIN match."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == "12345":
|
||||
# argv: ["python", "-m", "hermes_cli.main", "gateway", "run"]
|
||||
return b"python\x00-m\x00hermes_cli.main\x00gateway\x00run\x00"
|
||||
elif pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
assert count == 0, f"Expected 0 (gateway, no chat), got {count}"
|
||||
|
||||
def test_pgrep_excludes_gateway_pid(self):
|
||||
"""V8.8: Gateway-PID aus gateway_state.json wird ausgeschlossen."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
gateway_pid = 12345
|
||||
mock_proc_entries = ["1", str(own_pid), str(gateway_pid)]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == str(gateway_pid):
|
||||
# Sieht aus wie hermes chat --profile, ist aber Gateway
|
||||
return b"hermes\x00chat\x00--profile\x00miguel\x00"
|
||||
elif pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=gateway_pid):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
assert count == 0, f"Expected 0 (gateway excluded), got {count}"
|
||||
|
||||
def test_pgrep_returns_zero_when_no_hermes_processes(self):
|
||||
"""_pgrep_hermes_subagents() → 0 wenn keine hermes-Prozesse."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
mock_proc_entries = ["1", "2", str(own_pid), "99999"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
assert count == 0, f"Expected 0, got {count}"
|
||||
|
||||
def test_pgrep_excludes_own_pid(self):
|
||||
"""_pgrep_hermes_subagents() schließt eigene PID aus."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
# Nur eigener Prozess (der wie hermes aussieht)
|
||||
mock_proc_entries = [str(own_pid)]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
# Eigener Prozess hat hermes chat --profile in cmdline
|
||||
return b"hermes\x00chat\x00--profile\x00miguel\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
# Eigene PID wird ausgeschlossen → 0
|
||||
assert count == 0, f"Expected 0 (own PID excluded), got {count}"
|
||||
|
||||
def test_pgrep_ignores_non_hermes_processes(self):
|
||||
"""_pgrep_hermes_subagents() ignoriert nicht-hermes Prozesse."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
mock_proc_entries = ["1", "2", str(own_pid), "55555", "66666"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == "55555":
|
||||
return b"hermes\x00serve\x00" # hermes binary aber kein chat
|
||||
elif pid_dir == "66666":
|
||||
return b"python\x00chat\x00--profile\x00" # chat+profile aber argv0=python ohne -m hermes_cli
|
||||
elif pid_dir == str(own_pid):
|
||||
return b"python\x00pytest\x00"
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
# Keiner der Prozesse hat hermes+chat+--profile → 0
|
||||
assert count == 0, f"Expected 0, got {count}"
|
||||
|
||||
def test_pgrep_handles_permission_errors(self):
|
||||
"""_pgrep_hermes_subagents() behandelt PermissionError graceful."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
mock_proc_entries = ["1", str(own_pid), "99999"]
|
||||
|
||||
def mock_cmdline_read(pid_dir):
|
||||
if pid_dir == "99999":
|
||||
raise PermissionError("Permission denied")
|
||||
return b"bash\x00"
|
||||
|
||||
with patch("os.listdir", return_value=mock_proc_entries):
|
||||
with patch("builtins.open") as mock_open:
|
||||
def open_side_effect(path, mode="r"):
|
||||
parts = path.split("/")
|
||||
if len(parts) >= 3 and parts[1] == "proc":
|
||||
pid_dir = parts[2]
|
||||
mock_file = MagicMock()
|
||||
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||
return mock_file
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
mock_open.side_effect = open_side_effect
|
||||
|
||||
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||
count = DetectionTimer._pgrep_hermes_subagents()
|
||||
# PermissionError → Prozess wird ignoriert, count=0
|
||||
assert count == 0, f"Expected 0, got {count}"
|
||||
|
||||
def test_detection_timer_check_uses_pgrep(self):
|
||||
"""DetectionTimer.check() nutzt _pgrep_hermes_subagents() als Quelle."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
)
|
||||
|
||||
# Mock: PID-Sentinel tot, gateway_state leer, plugin_state leer
|
||||
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
||||
with patch.object(timer, '_pgrep_hermes_subagents', return_value=2):
|
||||
result = timer.check()
|
||||
|
||||
# pgrep findet 2 Prozesse → True
|
||||
assert result is True, f"Expected True, got {result}"
|
||||
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
|
||||
def test_detection_timer_check_zero_pgrep(self):
|
||||
"""DetectionTimer.check() → False wenn pgrep 0 findet."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
gateway_path = f.name
|
||||
try:
|
||||
timer = DetectionTimer(
|
||||
gateway_state_path=gateway_path,
|
||||
detection_interval=10.0,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state_v8_7.json",
|
||||
)
|
||||
|
||||
with patch.object(timer, '_check_gateway_pid_alive', return_value=False), \
|
||||
patch.object(timer, '_pgrep_hermes_subagents', return_value=0):
|
||||
result = timer.check()
|
||||
|
||||
assert result is False, f"Expected False, got {result}"
|
||||
|
||||
finally:
|
||||
os.unlink(gateway_path)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: PulseController pulse_target="away" toggles
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerAwayMode:
|
||||
"""Test 7: PulseController mit pulse_target='away' toggled online↔away."""
|
||||
|
||||
def test_pulse_target_default_is_away(self):
|
||||
"""Default pulse_target ist 'away'."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
assert pc.get_pulse_target() == "away"
|
||||
|
||||
def test_set_pulse_target_away(self):
|
||||
"""set_pulse_target('away') funktioniert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
changed = pc.set_pulse_target("away")
|
||||
assert changed is False # already "away"
|
||||
assert pc.get_pulse_target() == "away"
|
||||
|
||||
def test_set_pulse_target_busy(self):
|
||||
"""set_pulse_target('busy') wechselt Modus."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
changed = pc.set_pulse_target("busy")
|
||||
assert changed is True
|
||||
assert pc.get_pulse_target() == "busy"
|
||||
|
||||
def test_set_pulse_target_invalid_raises(self):
|
||||
"""Ungültiger pulse_target wirft ValueError."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
with pytest.raises(ValueError):
|
||||
pc.set_pulse_target("invalid")
|
||||
|
||||
def test_pulse_target_mode_sentinel_prevents_race(self):
|
||||
"""Mode-Sentinel: parallele set_pulse_target-Aufrufe sind sicher."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
|
||||
errors = []
|
||||
|
||||
def toggle_mode():
|
||||
try:
|
||||
for _ in range(50):
|
||||
pc.set_pulse_target("away")
|
||||
pc.set_pulse_target("busy")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = [threading.Thread(target=toggle_mode) for _ in range(4)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert len(errors) == 0, f"Errors: {errors}"
|
||||
assert pc.get_pulse_target() in ("away", "busy")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 8: PulseController pulse_target="busy" message-pulses
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerBusyMode:
|
||||
"""Test 8: PulseController mit pulse_target='busy' hält busy-Status."""
|
||||
|
||||
def test_busy_mode_does_not_toggle_to_online(self):
|
||||
"""Im busy-Modus wird nicht auf online getoggled."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||
pc.set_pulse_target("busy")
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock()
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
pc.start()
|
||||
time.sleep(0.4)
|
||||
pc.stop()
|
||||
|
||||
assert pc.get_pulse_target() == "busy"
|
||||
|
||||
def test__update_presence_with_subagents_idle(self):
|
||||
"""_update_presence_with_subagents bei idle startet away-Pulse."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
assert engine._active_tasks == 0
|
||||
|
||||
engine._update_presence_with_subagents(3)
|
||||
|
||||
time.sleep(0.3)
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) > 0
|
||||
last_data = calls[-1][1].get("data", {})
|
||||
assert last_data.get("status") == "away"
|
||||
assert "3 Subagent" in last_data.get("message", "")
|
||||
|
||||
def test__update_presence_with_subagents_busy(self):
|
||||
"""_update_presence_with_subagents bei busy setzt busy+Message."""
|
||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||
|
||||
engine.increment_active_tasks()
|
||||
engine.set_current_room("testroom")
|
||||
|
||||
engine._update_presence_with_subagents(2)
|
||||
|
||||
time.sleep(0.3)
|
||||
|
||||
calls = mock_rest._request.call_args_list
|
||||
assert len(calls) > 0
|
||||
last_data = calls[-1][1].get("data", {})
|
||||
assert last_data.get("status") == "busy"
|
||||
assert "2 Subagent" in last_data.get("message", "")
|
||||
assert "testroom" in last_data.get("message", "")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test: _read_subagent_count (pgrep-basiert)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestReadSubagentCount:
|
||||
"""Test: _read_subagent_count() nutzt pgrep."""
|
||||
|
||||
def test_read_subagent_count_returns_zero_when_no_processes(self):
|
||||
"""Keine hermes-Prozesse → 0."""
|
||||
engine, _ = _make_engine()
|
||||
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=0):
|
||||
assert engine._read_subagent_count() == 0
|
||||
|
||||
def test_read_subagent_count_returns_count(self):
|
||||
"""2 hermes-Prozesse → 2."""
|
||||
engine, _ = _make_engine()
|
||||
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=2):
|
||||
assert engine._read_subagent_count() == 2
|
||||
|
||||
def test_read_subagent_count_handles_errors(self):
|
||||
"""Fehler in pgrep → 0 (graceful degradation)."""
|
||||
engine, _ = _make_engine()
|
||||
# _pgrep_hermes_subagents() fängt OSError intern → 0
|
||||
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=0):
|
||||
assert engine._read_subagent_count() == 0
|
||||
@@ -836,8 +836,6 @@ class TestRoomContextCrossContamination(unittest.TestCase):
|
||||
# _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)
|
||||
# B2: allow_proactive_user_map=True für _user_rooms-Fallback
|
||||
self.adapter.config.extra = {"allow_proactive_user_map": True}
|
||||
|
||||
result = asyncio.run(
|
||||
self.adapter.send(chat_id=chat_id, content="Test response for Dispatch A")
|
||||
@@ -958,8 +956,6 @@ class TestRoomContextCrossContamination(unittest.TestCase):
|
||||
# _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)
|
||||
# B2: allow_proactive_user_map=True für _user_rooms-Fallback
|
||||
self.adapter.config.extra = {"allow_proactive_user_map": True}
|
||||
|
||||
result = asyncio.run(
|
||||
self.adapter.send(chat_id=chat_id, content="Test response")
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
"""
|
||||
V10.0.2: Plugin-Version — zentrale Versionsnummer für ::status und ::hilfe.
|
||||
|
||||
Wird von install.sh beim Deployment aktualisiert:
|
||||
COMMIT=$(git rev-parse --short HEAD)
|
||||
sed -i "s/__commit__ = .*/__commit__ = \"$COMMIT\"/" version.py
|
||||
"""
|
||||
|
||||
__version__ = "10.0.2"
|
||||
__commit__ = "e7668f9" # wird von install.sh auf aktuellen Git-Hash gesetzt
|
||||
|
||||
|
||||
def get_version_string() -> str:
|
||||
"""Liefert den formatierten Versions-String für ::status und ::hilfe.
|
||||
|
||||
Returns:
|
||||
z.B. 'V10.0.2 (e7668f9)'
|
||||
"""
|
||||
return f"V{__version__} ({__commit__})"
|
||||
@@ -1,38 +0,0 @@
|
||||
"""
|
||||
Root conftest for rocketchat plugin tests.
|
||||
|
||||
Ensures the parent directory is on sys.path so that test files can use
|
||||
``from plugin.archivar.room_map import ...``.
|
||||
|
||||
In the Hermes plugin runtime, the module is loaded as a flat module named
|
||||
``rocketchat`` (P-022). In the git repo, the directory is named ``plugin``
|
||||
and the module is importable as ``plugin`` directly. This conftest handles
|
||||
both cases.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure the parent directory (containing the plugin package) is on sys.path
|
||||
_parent_dir = str(Path(__file__).resolve().parent)
|
||||
if _parent_dir not in sys.path:
|
||||
sys.path.insert(0, _parent_dir)
|
||||
|
||||
# In the Hermes runtime, the plugin is loaded as a flat module named
|
||||
# 'rocketchat', but test code imports from 'plugin.archivar.*'.
|
||||
# Register 'plugin' as an alias for 'rocketchat' when running inside
|
||||
# the Hermes plugin directory (not the git repo).
|
||||
import importlib
|
||||
|
||||
try:
|
||||
_rocketchat = importlib.import_module("rocketchat")
|
||||
sys.modules["plugin"] = _rocketchat
|
||||
# Register submodules
|
||||
import rocketchat.archivar # noqa: E402
|
||||
sys.modules["plugin.archivar"] = rocketchat.archivar
|
||||
import rocketchat.archivar.room_map # noqa: E402
|
||||
sys.modules["plugin.archivar.room_map"] = rocketchat.archivar.room_map
|
||||
import rocketchat.archivar.keyword_matcher # noqa: E402
|
||||
sys.modules["plugin.archivar.keyword_matcher"] = rocketchat.archivar.keyword_matcher
|
||||
except ImportError:
|
||||
# Running from git repo — 'plugin' is the real package name
|
||||
pass
|
||||
@@ -30,7 +30,7 @@ def main() -> int:
|
||||
]
|
||||
|
||||
print(f"FAISS+Booster Smoke-Test: {idx.size} Raeume, Version {idx._version}")
|
||||
print(f"Booster: {len(booster._kw100_to_rooms)} kw100 + {len(booster._kwctx_to_rooms)} kwctx Keywords, +0.10/unique")
|
||||
print(f"Booster: {len(booster._keyword_to_rooms)} Keywords, immer aktiv, +0.10/unique")
|
||||
print()
|
||||
|
||||
ok = 0
|
||||
|
||||
@@ -94,10 +94,10 @@ class RateLimiter:
|
||||
"""Simple token-bucket rate limiter.
|
||||
|
||||
Allows max_tokens calls per window_seconds. Thread-safe via lock.
|
||||
Default: 15 calls/minute (was 30 — RC triggers 429 aggressively).
|
||||
Default: 30 calls/minute (was 60 — RC triggers 429 at 3-4 calls in <10s).
|
||||
"""
|
||||
|
||||
def __init__(self, max_tokens: int = 15, window_seconds: float = 60.0):
|
||||
def __init__(self, max_tokens: int = 30, window_seconds: float = 60.0):
|
||||
self.max_tokens = max_tokens
|
||||
self.window_seconds = window_seconds
|
||||
self.tokens = float(max_tokens)
|
||||
@@ -138,7 +138,7 @@ _rate_limiter: RateLimiter | None = None
|
||||
def _get_rate_limiter() -> RateLimiter:
|
||||
global _rate_limiter
|
||||
if _rate_limiter is None:
|
||||
_rate_limiter = RateLimiter(max_tokens=15, window_seconds=60.0)
|
||||
_rate_limiter = RateLimiter(max_tokens=30, window_seconds=60.0)
|
||||
return _rate_limiter
|
||||
|
||||
|
||||
|
||||
@@ -24,13 +24,13 @@ from .rc_rest import RCRestClient
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Progressive backoff intervals in seconds (rate-limiter-friendly).
|
||||
# Default: 5s -> 8s -> 12s -> 20s (max 45s total).
|
||||
# Default: 2s -> 3s -> 5s -> 8s (max 18s total).
|
||||
# Callers can override the first interval via initial_interval.
|
||||
_DEFAULT_BACKOFF_INTERVALS = [5.0, 8.0, 12.0, 20.0]
|
||||
_MAX_TOTAL_WAIT = 45.0 # seconds
|
||||
_DEFAULT_BACKOFF_INTERVALS = [2.0, 3.0, 5.0, 8.0]
|
||||
_MAX_TOTAL_WAIT = 18.0 # seconds
|
||||
|
||||
# 429 exponential backoff: 5s -> 10s -> 20s -> 40s (max)
|
||||
_MAX_429_BACKOFF = 40.0
|
||||
# 429 exponential backoff: 3s -> 6s -> 12s -> 20s -> 30s (max)
|
||||
_MAX_429_BACKOFF = 30.0
|
||||
# After 5 consecutive 429s, abort with SKIP instead of retrying forever
|
||||
_MAX_CONSECUTIVE_429 = 5
|
||||
|
||||
@@ -89,7 +89,7 @@ def wait_for_bot_message(
|
||||
cached_messages: list = [] # Cursor caching: reuse fetched batch
|
||||
|
||||
# Build backoff intervals with caller's initial_interval
|
||||
backoff_intervals = [initial_interval, 8.0, 12.0, 20.0]
|
||||
backoff_intervals = [initial_interval, 3.0, 5.0, 8.0]
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
# Cursor caching: if we already have messages, scan them first
|
||||
@@ -137,8 +137,8 @@ def wait_for_bot_message(
|
||||
"aggressive. Consider increasing poll intervals or "
|
||||
"reducing concurrent test load."
|
||||
)
|
||||
# Exponential backoff on rate-limit errors: 5s -> 10s -> 20s -> 40s
|
||||
backoff = min(5.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
||||
# Exponential backoff on rate-limit errors: 3s -> 6s -> 12s -> 20s -> 30s
|
||||
backoff = min(3.0 * (2 ** (consecutive_429 - 1)), _MAX_429_BACKOFF)
|
||||
logger.warning(
|
||||
"Poll: HTTP 429 (consecutive=%d/%d) -- backing off %ds",
|
||||
consecutive_429, _MAX_CONSECUTIVE_429, backoff,
|
||||
@@ -170,12 +170,12 @@ def wait_for_bot_message(
|
||||
)
|
||||
return msg
|
||||
|
||||
# Progressive backoff: initial_interval -> 8s -> 12s -> 20s
|
||||
# Progressive backoff: initial_interval -> 3s -> 5s -> 8s
|
||||
if interval_idx < len(backoff_intervals):
|
||||
delay = backoff_intervals[interval_idx]
|
||||
interval_idx += 1
|
||||
else:
|
||||
delay = 20.0
|
||||
delay = 8.0
|
||||
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
|
||||
@@ -77,9 +77,9 @@ class RCRestClient:
|
||||
|
||||
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
||||
|
||||
# 429 retry with exponential backoff: 5s → 10s → 20s → 40s (max 4 retries)
|
||||
# Total possible wait: 75s — gives RC enough time to reset its rate-limit window.
|
||||
_429_BACKOFFS = [5.0, 10.0, 20.0, 40.0]
|
||||
# 429 retry with exponential backoff: 3s → 6s → 12s → 20s → 30s (max 5 retries)
|
||||
# Total possible wait: 71s — gives RC enough time to reset its rate-limit window.
|
||||
_429_BACKOFFS = [3.0, 6.0, 12.0, 20.0, 30.0]
|
||||
max_429_retries = len(_429_BACKOFFS)
|
||||
for attempt in range(max_429_retries + 1):
|
||||
# Rate-limit before every API call (protects post, history, delete, etc.)
|
||||
|
||||
@@ -73,99 +73,57 @@ def test_04_multi_room(
|
||||
posted_ids_main: list = []
|
||||
posted_ids_project: list = []
|
||||
|
||||
# ── Startup grace: 10s Pause für Bot-Startup und Rate-Limit-Reset ──
|
||||
logger.info("Test 04: 10s startup grace — letting rate-limit window reset")
|
||||
time.sleep(10.0)
|
||||
|
||||
# ── Step 1: /reset im Haupt-Testraum ────────────────────────────────
|
||||
_reset_id, _ = post_test_message(
|
||||
rc_client, test_room_id, "/reset",
|
||||
posted_ids_main, rate_limiter,
|
||||
# Step 1: Post keyword message in main test room (DM proxy)
|
||||
# Use a keyword_100 match from room-map.json — 'rocketchat' matches
|
||||
# #Rocketchat-Plugin with 100% keyword confidence → auto-route.
|
||||
keyword_text = (
|
||||
"rocketchat Multi-Room Test — Archivar sollte diese Nachricht "
|
||||
"automatisch in den Rocketchat-Plugin-Raum routen"
|
||||
)
|
||||
logger.info("Test 04: sent /reset to main room (msg %s)", _reset_id[:12])
|
||||
time.sleep(5.0)
|
||||
|
||||
# ── Step 2: Cursor holen ────────────────────────────────────────────
|
||||
main_cursor = get_latest_timestamp(rc_client, test_room_id, rate_limiter=rate_limiter)
|
||||
logger.info("Test 04: main room cursor = %s", main_cursor[:19])
|
||||
|
||||
# ── Step 3: Context-Keyword-Nachricht posten (Butler-Mode) ──────────
|
||||
# KEINE keywords_100-Wörter (kein 'rocketchat', 'ddp', 'websocket', 'rc',
|
||||
# 'adapter', 'install.sh', 'gateway-crash', 'core-dump', 'message-handler',
|
||||
# 'hermes-gateway', 'raummap').
|
||||
# NUR keywords_context-Wörter für #Rocketchat-Plugin:
|
||||
# "plugin", "deployment", "button", "sync", "archivar", "hermes"
|
||||
# → Butler-Mode: Bot sendet Move-Request-Buttons statt Auto-Route.
|
||||
keyword_text = (
|
||||
"plugin deployment archivar hermes gateway sync button — "
|
||||
"Multi-Room Butler Test: Archivar sollte Move-Request-Buttons senden"
|
||||
)
|
||||
msg_id, _ = post_test_message(
|
||||
rc_client, test_room_id, keyword_text,
|
||||
posted_ids_main, rate_limiter,
|
||||
)
|
||||
logger.info("Test 04: posted context-keyword message %s in main room", msg_id[:12])
|
||||
logger.info("Test 04: posted keyword message %s in main room", msg_id[:12])
|
||||
|
||||
# ── Step 4: Auf Bot-Antwort warten (Move-Request-Buttons) ───────────
|
||||
# Butler-Mode: Bot sendet Move-Request-Buttons mit Zielraum-Vorschlag.
|
||||
# Timeout 60s, initial_interval 8s (rate-limit-freundlich).
|
||||
# Step 2: Wait for bot response in main room
|
||||
# The bot should acknowledge the message (even if auto-routed)
|
||||
# Pause 10s to let rate-limit window reset after test_03
|
||||
time.sleep(10.0)
|
||||
try:
|
||||
bot_response = wait_for_bot_message(
|
||||
client=rc_client,
|
||||
room_id=test_room_id,
|
||||
bot_username=bot_username,
|
||||
cursor=main_cursor,
|
||||
timeout=60.0,
|
||||
timeout=30.0, # increased from 25s
|
||||
rate_limiter=rate_limiter,
|
||||
initial_interval=8.0,
|
||||
)
|
||||
except RateLimitSkip as e:
|
||||
pytest.skip(f"Rate limit triggered: {e}")
|
||||
except PollTimeout as e:
|
||||
pytest.fail(
|
||||
f"Bot did not respond in main room within 60s. "
|
||||
f"Bot did not respond in main room within 25s. "
|
||||
f"Check that .45 MyTestBot is running and the Archivar "
|
||||
f"is processing messages. Error: {e}"
|
||||
)
|
||||
|
||||
response_text = bot_response.get("msg", "")
|
||||
logger.info("Test 04: bot responded in main room: '%s'", response_text[:200])
|
||||
logger.info("Test 04: bot responded in main room: '%s'", response_text[:120])
|
||||
posted_ids_main.append(bot_response.get("_id", ""))
|
||||
|
||||
# ── Step 5: Verifiziere Butler-Mode Move-Request ────────────────────
|
||||
# Der Bot sollte Move-Request-Buttons gesendet haben (nicht Auto-Route).
|
||||
# Move-Request-Indikatoren: "kopieren", "rüber", "verschieben", "move",
|
||||
# "Zielraum", "Button", "bestätigen", "Vorschlag"
|
||||
response_lower = response_text.lower()
|
||||
move_request_indicators = [
|
||||
"kopieren", "rüber", "verschieben", "move",
|
||||
"zielraum", "button", "bestätigen", "vorschlag",
|
||||
]
|
||||
has_move_request = any(ind in response_lower for ind in move_request_indicators)
|
||||
|
||||
if has_move_request:
|
||||
logger.info(
|
||||
"Test 04: Butler-Mode Move-Request detected — "
|
||||
"Archivar sent move-request buttons correctly"
|
||||
)
|
||||
else:
|
||||
# Fallback: Bot hat geantwortet, aber ohne Move-Request.
|
||||
# Das ist OK — der Test verifiziert, dass der Bot auf eine
|
||||
# keywords_context-Nachricht reagiert. Auto-Route wurde nicht
|
||||
# getriggert (kein keywords_100-Match), also ist der Flow korrekt.
|
||||
logger.info(
|
||||
"Test 04: Bot responded to context-keyword message. "
|
||||
"No move-request buttons detected, but message was processed. "
|
||||
"Response: '%s'", response_text[:200]
|
||||
)
|
||||
|
||||
# ── Step 6: Prüfe ob Nachricht in Projektraum kopiert wurde ─────────
|
||||
# (Nur relevant wenn Auto-Route getriggert wurde — bei Butler-Mode
|
||||
# wird erst nach Button-Klick kopiert.)
|
||||
# Step 3: Check if message was copied to project room
|
||||
# The Archivar auto-routes at FAISS >= 0.85. For keyword_100 matches
|
||||
# like 'rocketchat' → #Rocketchat-Plugin, this should trigger.
|
||||
project_cursor = get_latest_timestamp(rc_client, project_room, rate_limiter=rate_limiter)
|
||||
logger.info("Test 04: project room cursor = %s", project_cursor[:19])
|
||||
|
||||
time.sleep(3.0)
|
||||
# Give the Archivar a moment to complete the copy
|
||||
# Increased from 2s to 5s — fewer API calls, less rate-limit pressure
|
||||
time.sleep(5.0)
|
||||
|
||||
try:
|
||||
project_messages = rc_client.get_history(
|
||||
@@ -177,6 +135,7 @@ def test_04_multi_room(
|
||||
logger.warning("Test 04: failed to fetch project room history: %s", e)
|
||||
project_messages = []
|
||||
|
||||
# Step 4: Verify copied message in project room
|
||||
copied_found = False
|
||||
for msg in project_messages:
|
||||
ts = msg.get("ts", "")
|
||||
@@ -186,7 +145,8 @@ def test_04_multi_room(
|
||||
username = (u.get("username", "") or "").lower()
|
||||
msg_text = msg.get("msg", "")
|
||||
|
||||
if username == bot_username.lower() and "plugin" in msg_text.lower():
|
||||
# The copied message should be from the bot and contain our keyword
|
||||
if username == bot_username.lower() and "rocketchat" in msg_text.lower():
|
||||
copied_found = True
|
||||
logger.info(
|
||||
"Test 04: found copied message in project room: '%s'",
|
||||
@@ -196,10 +156,29 @@ def test_04_multi_room(
|
||||
break
|
||||
|
||||
if not copied_found:
|
||||
logger.info(
|
||||
"Test 04: no auto-routed copy found in project room — "
|
||||
"expected for Butler mode (copy happens after button click)"
|
||||
# Auto-route might not have triggered (score below threshold,
|
||||
# or Archivar sent move-request buttons instead).
|
||||
# This is not a failure — the test verifies the flow works
|
||||
# when auto-route conditions are met.
|
||||
logger.warning(
|
||||
"Test 04: no auto-routed copy found in project room. "
|
||||
"This may be expected if FAISS score < 0.85 or if the "
|
||||
"Archivar sent move-request buttons instead. "
|
||||
"Check bot response in main room for move-request prompt."
|
||||
)
|
||||
# Check if the bot sent a move-request instead
|
||||
if "kopieren" in response_text.lower() or "rüber" in response_text.lower():
|
||||
logger.info(
|
||||
"Test 04: bot sent move-request buttons (Butler mode) — "
|
||||
"auto-route threshold not met, but flow is working correctly"
|
||||
)
|
||||
else:
|
||||
# The bot responded but didn't auto-route or send move-request.
|
||||
# This is still a valid outcome — the message was processed.
|
||||
logger.info(
|
||||
"Test 04: bot processed message without routing — "
|
||||
"message may not have matched any room strongly enough"
|
||||
)
|
||||
|
||||
# Cleanup
|
||||
for mid in posted_ids_main:
|
||||
|
||||
@@ -84,11 +84,6 @@ def test_05_contextvar_isolation_parallel_load(
|
||||
posted_ids_test: list = []
|
||||
posted_ids_target: list = []
|
||||
|
||||
# ── Startup grace: 10s Pause für Bot-Startup und Rate-Limit-Reset ──
|
||||
# Vermeidet 429-Kaskaden durch zu schnelles Posten nach Test-Start.
|
||||
logger.info("Test 05: 10s startup grace — letting rate-limit window reset")
|
||||
time.sleep(10.0)
|
||||
|
||||
# ── Step 1: Cursor für beide Räume holen ───────────────────────────
|
||||
cursor_test = get_latest_timestamp(
|
||||
rc_client, test_room_id, rate_limiter=rate_limiter
|
||||
@@ -119,10 +114,7 @@ def test_05_contextvar_isolation_parallel_load(
|
||||
long_msg_id[:12], long_cursor[:19],
|
||||
)
|
||||
|
||||
# ── 5s Delay: RC-Rate-Limit atmen lassen vor zweitem Post ──────────
|
||||
time.sleep(5.0)
|
||||
|
||||
# ── Step 3: Kurze Keyword-Nachricht in test-rc-target ──────────────
|
||||
# ── Step 3: Sofort kurze Keyword-Nachricht in test-rc-target ───────
|
||||
# "rocketchat ddp bug" — 100% keyword match für #Rocketchat-Plugin
|
||||
short_text = "rocketchat ddp bug"
|
||||
short_msg_id, short_cursor = post_test_message(
|
||||
@@ -138,22 +130,22 @@ def test_05_contextvar_isolation_parallel_load(
|
||||
# Zuerst die kurze Antwort (sollte schneller kommen), dann die lange.
|
||||
# Reihenfolge ist nicht-deterministisch — das ist OK.
|
||||
|
||||
# 4a: Kurze Antwort in test-rc-target (initial_interval=8s, timeout=120s)
|
||||
# 4a: Kurze Antwort in test-rc-target
|
||||
try:
|
||||
short_answer = wait_for_bot_message(
|
||||
client=rc_client,
|
||||
room_id=target_room,
|
||||
bot_username=bot_username,
|
||||
cursor=short_cursor,
|
||||
timeout=120.0,
|
||||
timeout=60.0,
|
||||
rate_limiter=rate_limiter,
|
||||
initial_interval=8.0,
|
||||
initial_interval=5.0,
|
||||
)
|
||||
except RateLimitSkip as e:
|
||||
pytest.skip(f"Rate limit triggered: {e}")
|
||||
except PollTimeout as e:
|
||||
pytest.fail(
|
||||
f"Bot did not respond in target_room within 120s. Error: {e}"
|
||||
f"Bot did not respond in target_room within 60s. Error: {e}"
|
||||
)
|
||||
|
||||
short_text_answer = short_answer.get("msg", "")
|
||||
@@ -164,22 +156,22 @@ def test_05_contextvar_isolation_parallel_load(
|
||||
)
|
||||
posted_ids_target.append(short_answer.get("_id", ""))
|
||||
|
||||
# 4b: Lange Antwort in test_room (timeout 120s für langen Stream)
|
||||
# 4b: Lange Antwort in test_room (timeout 90s für langen Stream)
|
||||
try:
|
||||
long_answer = wait_for_bot_message(
|
||||
client=rc_client,
|
||||
room_id=test_room_id,
|
||||
bot_username=bot_username,
|
||||
cursor=long_cursor,
|
||||
timeout=120.0,
|
||||
timeout=90.0,
|
||||
rate_limiter=rate_limiter,
|
||||
initial_interval=8.0,
|
||||
initial_interval=5.0,
|
||||
)
|
||||
except RateLimitSkip as e:
|
||||
pytest.skip(f"Rate limit triggered: {e}")
|
||||
except PollTimeout as e:
|
||||
pytest.fail(
|
||||
f"Bot did not respond in test_room within 120s. "
|
||||
f"Bot did not respond in test_room within 90s. "
|
||||
f"The long answer may have timed out. Error: {e}"
|
||||
)
|
||||
|
||||
|
||||
@@ -85,11 +85,6 @@ def test_06_concurrent_isolation(
|
||||
posted_ids_test: list = []
|
||||
posted_ids_source: list = []
|
||||
|
||||
# ── Startup grace: 10s Pause für Bot-Startup und Rate-Limit-Reset ──
|
||||
# Vermeidet 429-Kaskaden durch zu schnelles Posten nach Test-Start.
|
||||
logger.info("Test 06: 10s startup grace — letting rate-limit window reset")
|
||||
time.sleep(10.0)
|
||||
|
||||
# ── Step 1: /reset in beiden Räumen ────────────────────────────────
|
||||
# Clear sticky topics from previous tests.
|
||||
_reset_test_id, _ = post_test_message(
|
||||
@@ -104,8 +99,8 @@ def test_06_concurrent_isolation(
|
||||
"Test 06: sent /reset to test_room (msg %s) and source_room (msg %s)",
|
||||
_reset_test_id[:12], _reset_source_id[:12],
|
||||
)
|
||||
# Wait for /reset responses (increased from 5s to 8s for rate-limit headroom)
|
||||
time.sleep(8.0)
|
||||
# Wait for /reset responses
|
||||
time.sleep(5.0)
|
||||
|
||||
# ── Step 2: Cursor für beide Räume holen ───────────────────────────
|
||||
cursor_test = get_latest_timestamp(
|
||||
@@ -119,11 +114,10 @@ def test_06_concurrent_isolation(
|
||||
cursor_test[:19], cursor_source[:19],
|
||||
)
|
||||
|
||||
# ── Step 3: Beide Nachrichten sequenziell mit 8s Delay posten ──────
|
||||
# 8s Delay zur Interrupt-Recursion-Vermeidung UND Rate-Limit-Entlastung:
|
||||
# ── Step 3: Beide Nachrichten sequenziell mit 3s Delay posten ──────
|
||||
# 3s Delay zur Interrupt-Recursion-Vermeidung:
|
||||
# Hermes-Core serialisiert eingehende Nachrichten pro Bot-Instanz
|
||||
# mit Tiefe-3-Limit. Zwei Posts ohne Delay triggern Interrupt-Recursion.
|
||||
# RC's 30/min-Bucket braucht Atempausen zwischen Posts.
|
||||
# Nachricht A: test_room — "lan subnetz maskieren" (keyword "lan" → #LAN-Dokumentation)
|
||||
text_a = "lan subnetz maskieren"
|
||||
msg_a_id, cursor_a = post_test_message(
|
||||
@@ -131,9 +125,9 @@ def test_06_concurrent_isolation(
|
||||
posted_ids_test, rate_limiter,
|
||||
)
|
||||
|
||||
# 8s Delay: Kern-Antwort auf Nachricht A beginnen lassen,
|
||||
# bevor Nachricht B gepostet wird (Interrupt-Recursion-Vermeidung + Rate-Limit)
|
||||
time.sleep(8.0)
|
||||
# 3s Delay: Kern-Antwort auf Nachricht A beginnen lassen,
|
||||
# bevor Nachricht B gepostet wird (Interrupt-Recursion-Vermeidung)
|
||||
time.sleep(3.0)
|
||||
|
||||
# Nachricht B: test-rc-source — "rocketchat ddp bug" (keyword "rocketchat" → #Rocketchat-Plugin)
|
||||
text_b = "rocketchat ddp bug"
|
||||
@@ -150,22 +144,22 @@ def test_06_concurrent_isolation(
|
||||
# ── Step 4: Auf Bot-Antworten warten (sequenziell) ─────────────────
|
||||
start_time = time.monotonic()
|
||||
|
||||
# 4a: Antwort in test_room (LAN-Routing) — timeout 120s, initial_interval 8s
|
||||
# 4a: Antwort in test_room (LAN-Routing)
|
||||
try:
|
||||
answer_a = wait_for_bot_message(
|
||||
client=rc_client,
|
||||
room_id=test_room_id,
|
||||
bot_username=bot_username,
|
||||
cursor=cursor_a,
|
||||
timeout=120.0,
|
||||
timeout=60.0,
|
||||
rate_limiter=rate_limiter,
|
||||
initial_interval=8.0,
|
||||
initial_interval=5.0,
|
||||
)
|
||||
except RateLimitSkip as e:
|
||||
pytest.skip(f"Rate limit triggered: {e}")
|
||||
except PollTimeout as e:
|
||||
pytest.fail(
|
||||
f"Bot did not respond in test_room within 120s. Error: {e}"
|
||||
f"Bot did not respond in test_room within 60s. Error: {e}"
|
||||
)
|
||||
|
||||
answer_a_text = answer_a.get("msg", "")
|
||||
@@ -176,22 +170,22 @@ def test_06_concurrent_isolation(
|
||||
)
|
||||
posted_ids_test.append(answer_a.get("_id", ""))
|
||||
|
||||
# 4b: Antwort in test-rc-source (Rocketchat-Routing) — timeout 120s, initial_interval 8s
|
||||
# 4b: Antwort in test-rc-source (Rocketchat-Routing)
|
||||
try:
|
||||
answer_b = wait_for_bot_message(
|
||||
client=rc_client,
|
||||
room_id=source_room,
|
||||
bot_username=bot_username,
|
||||
cursor=cursor_b,
|
||||
timeout=120.0,
|
||||
timeout=60.0,
|
||||
rate_limiter=rate_limiter,
|
||||
initial_interval=8.0,
|
||||
initial_interval=5.0,
|
||||
)
|
||||
except RateLimitSkip as e:
|
||||
pytest.skip(f"Rate limit triggered: {e}")
|
||||
except PollTimeout as e:
|
||||
pytest.fail(
|
||||
f"Bot did not respond in source_room within 120s. Error: {e}"
|
||||
f"Bot did not respond in source_room within 60s. Error: {e}"
|
||||
)
|
||||
|
||||
answer_b_text = answer_b.get("msg", "")
|
||||
|
||||
@@ -1,233 +0,0 @@
|
||||
"""
|
||||
Test 07 — Room-Map Integrity Check.
|
||||
|
||||
Prüft die room-map.json auf .45 (via SSH bat-preprod) auf strukturelle
|
||||
Integrität. Stellt sicher, dass jeder Raum Keywords und Theme hat, damit
|
||||
der Archivar korrekt routen kann.
|
||||
|
||||
Checks:
|
||||
1. JSON ist valid und loadable
|
||||
2. version > 0
|
||||
3. Jeder Raum in rooms hat:
|
||||
- keywords_100: nicht-leere Liste
|
||||
- theme: nicht-leerer String
|
||||
- name: nicht-leerer String
|
||||
- type: in ['c', 'p', 'd']
|
||||
4. excluded_rooms enthält keine IDs die auch in rooms sind
|
||||
5. catch_all ist boolean (wenn vorhanden)
|
||||
6. (P6) Keine Test-Keywords kollidieren mit produktiven Keywords
|
||||
|
||||
ENV-Vars:
|
||||
- RC_LIVE_SSH_HOST: SSH-Host für .45 (default: 'bat-preprod')
|
||||
Test wird geskipped wenn nicht gesetzt.
|
||||
|
||||
Dieser Test ist READ-ONLY — kein Gateway-Restart, kein Side-Effect.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Constants ───────────────────────────────────────────────────────────────
|
||||
|
||||
_ROOMMAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
|
||||
_VALID_ROOM_TYPES = frozenset({"c", "p", "d"})
|
||||
|
||||
# P6: Keywords die in Test-Nachrichten verwendet werden und NICHT
|
||||
# in produktiven room-maps auftauchen dürfen (Kollisionsschutz).
|
||||
_TEST_KEYWORDS = frozenset({
|
||||
"echo-test",
|
||||
"test",
|
||||
"pytest",
|
||||
"unittest",
|
||||
"debug",
|
||||
"sandbox",
|
||||
})
|
||||
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _get_ssh_host() -> str:
|
||||
"""Get SSH host from env, skip test if not set."""
|
||||
host = (os.getenv("RC_LIVE_SSH_HOST") or "").strip()
|
||||
if not host:
|
||||
pytest.skip("RC_LIVE_SSH_HOST not set — skipping room-map integrity test")
|
||||
return host
|
||||
|
||||
|
||||
def _fetch_roommap(host: str) -> dict:
|
||||
"""Fetch room-map.json from remote host via SSH.
|
||||
|
||||
Returns the parsed JSON dict.
|
||||
|
||||
Raises:
|
||||
pytest.skip: if SSH fails (host unreachable, file not found, etc.)
|
||||
pytest.fail: if JSON is invalid
|
||||
"""
|
||||
cmd = ["ssh", host, "cat", _ROOMMAP_PATH]
|
||||
logger.info("Fetching room-map.json from %s:%s", host, _ROOMMAP_PATH)
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=15,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
pytest.skip("ssh command not found — skipping room-map integrity test")
|
||||
except subprocess.TimeoutExpired:
|
||||
pytest.skip(f"SSH to {host} timed out — skipping room-map integrity test")
|
||||
|
||||
if result.returncode != 0:
|
||||
stderr = result.stderr.strip()
|
||||
pytest.skip(
|
||||
f"SSH to {host} failed (exit {result.returncode}): {stderr[:200]}"
|
||||
)
|
||||
|
||||
raw = result.stdout.strip()
|
||||
if not raw:
|
||||
pytest.fail(f"room-map.json on {host} is empty")
|
||||
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError as e:
|
||||
pytest.fail(
|
||||
f"room-map.json on {host} is not valid JSON: {e}\n"
|
||||
f"First 200 chars: {raw[:200]}"
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
# ── Test ───────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.live_rc
|
||||
def test_07_roommap_integrity():
|
||||
"""Room-Map Integrity: Jeder Raum hat Keywords und Theme.
|
||||
|
||||
Verhindert Regression: room-map.json ohne Keywords/Themes führt dazu,
|
||||
dass der Archivar nicht routen kann (kein Keyword-Match → kein Routing).
|
||||
"""
|
||||
host = _get_ssh_host()
|
||||
data = _fetch_roommap(host)
|
||||
|
||||
# ── Check 1: version > 0 ───────────────────────────────────────────
|
||||
version = data.get("version", 0)
|
||||
assert isinstance(version, (int, float)), (
|
||||
f"room-map.json version is not numeric: {type(version).__name__} = {version!r}"
|
||||
)
|
||||
assert version > 0, (
|
||||
f"room-map.json version is {version}, expected > 0"
|
||||
)
|
||||
logger.info("Room-map version: %s", version)
|
||||
|
||||
# ── Check 2: rooms is a dict ───────────────────────────────────────
|
||||
rooms = data.get("rooms")
|
||||
assert isinstance(rooms, dict), (
|
||||
f"room-map.json 'rooms' is not a dict: {type(rooms).__name__}"
|
||||
)
|
||||
assert len(rooms) > 0, "room-map.json 'rooms' is empty"
|
||||
|
||||
# ── Check 3: Jeder Raum hat Pflichtfelder ──────────────────────────
|
||||
errors: list[str] = []
|
||||
all_keywords: set[str] = set()
|
||||
|
||||
for room_id, room in rooms.items():
|
||||
if not isinstance(room, dict):
|
||||
errors.append(f"Room '{room_id}': value is not a dict ({type(room).__name__})")
|
||||
continue
|
||||
|
||||
# name
|
||||
name = room.get("name")
|
||||
if not name or not isinstance(name, str) or not name.strip():
|
||||
errors.append(
|
||||
f"Room '{room_id}': 'name' fehlt oder ist leer "
|
||||
f"(value={name!r})"
|
||||
)
|
||||
|
||||
# theme
|
||||
theme = room.get("theme")
|
||||
if not theme or not isinstance(theme, str) or not theme.strip():
|
||||
errors.append(
|
||||
f"Room '{room_id}' (name={name!r}): 'theme' fehlt oder ist leer "
|
||||
f"(value={theme!r})"
|
||||
)
|
||||
|
||||
# keywords_100
|
||||
keywords = room.get("keywords_100")
|
||||
if not isinstance(keywords, list):
|
||||
errors.append(
|
||||
f"Room '{room_id}' (name={name!r}): 'keywords_100' ist keine Liste "
|
||||
f"(type={type(keywords).__name__}, value={keywords!r})"
|
||||
)
|
||||
elif len(keywords) == 0:
|
||||
errors.append(
|
||||
f"Room '{room_id}' (name={name!r}): 'keywords_100' ist leer"
|
||||
)
|
||||
else:
|
||||
# Collect all keywords for P6 collision check
|
||||
for kw in keywords:
|
||||
if isinstance(kw, str):
|
||||
all_keywords.add(kw.lower().strip())
|
||||
|
||||
# type
|
||||
rtype = room.get("type")
|
||||
if rtype not in _VALID_ROOM_TYPES:
|
||||
errors.append(
|
||||
f"Room '{room_id}' (name={name!r}): 'type' ist {rtype!r}, "
|
||||
f"erwartet eines von {sorted(_VALID_ROOM_TYPES)}"
|
||||
)
|
||||
|
||||
if errors:
|
||||
pytest.fail(
|
||||
f"room-map.json integrity check FAILED — {len(errors)} Fehler:\n" +
|
||||
"\n".join(f" [{i+1}] {e}" for i, e in enumerate(errors))
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"All %d rooms have required fields (name, theme, keywords_100, type)",
|
||||
len(rooms),
|
||||
)
|
||||
|
||||
# ── Check 4: excluded_rooms enthält keine IDs aus rooms ────────────
|
||||
excluded = data.get("excluded_rooms", [])
|
||||
if isinstance(excluded, list):
|
||||
overlap = set(excluded) & set(rooms.keys())
|
||||
if overlap:
|
||||
pytest.fail(
|
||||
f"excluded_rooms enthält IDs die auch in rooms sind: "
|
||||
f"{sorted(overlap)}"
|
||||
)
|
||||
logger.info("excluded_rooms (%d entries) has no overlap with rooms", len(excluded))
|
||||
|
||||
# ── Check 5: catch_all ist boolean (wenn vorhanden) ────────────────
|
||||
if "catch_all" in data:
|
||||
catch_all = data["catch_all"]
|
||||
assert isinstance(catch_all, bool), (
|
||||
f"room-map.json 'catch_all' ist kein boolean: "
|
||||
f"{type(catch_all).__name__} = {catch_all!r}"
|
||||
)
|
||||
logger.info("catch_all: %s", catch_all)
|
||||
|
||||
# ── Check 6 (P6): Keine Test-Keywords kollidieren ──────────────────
|
||||
collisions = _TEST_KEYWORDS & all_keywords
|
||||
if collisions:
|
||||
logger.warning(
|
||||
"P6: Test-Keywords kollidieren mit produktiven Keywords: %s",
|
||||
sorted(collisions),
|
||||
)
|
||||
# P6 ist optional — kein Fail, nur Warning
|
||||
else:
|
||||
logger.info("P6: Keine Test-Keyword-Kollisionen")
|
||||
|
||||
logger.info("Test 07 PASSED: room-map.json integrity OK")
|
||||
+13
-15
@@ -553,7 +553,7 @@ class TestBoosterCleanup:
|
||||
|
||||
def test_cleanup_rebuilds_mapping(self, booster: KeywordBooster) -> None:
|
||||
"""cleanup_orphaned_rooms() baut das Mapping aus der aktuellen RoomMap neu."""
|
||||
before = len(booster._kw100_to_rooms) + len(booster._kwctx_to_rooms)
|
||||
before = len(booster._keyword_to_rooms)
|
||||
|
||||
# Entferne room_b aus der RoomMap (simuliert GC)
|
||||
del booster._room_map._rooms["room_b"]
|
||||
@@ -564,17 +564,16 @@ class TestBoosterCleanup:
|
||||
# Mapping sollte kleiner sein (room_b's unique keywords sind weg)
|
||||
assert after < before
|
||||
|
||||
# "bat" war unique für room_b (kw100) → sollte nicht mehr im Mapping sein
|
||||
assert "bat" not in booster._kw100_to_rooms
|
||||
assert "bat" not in booster._kwctx_to_rooms
|
||||
# "bat" war unique für room_b → sollte nicht mehr im Mapping sein
|
||||
assert "bat" not in booster._keyword_to_rooms
|
||||
|
||||
# "plugin" war unique für room_a (kwctx) → sollte noch da sein
|
||||
assert "plugin" in booster._kwctx_to_rooms
|
||||
assert booster._kwctx_to_rooms["plugin"] == {"room_a"}
|
||||
# "plugin" war unique für room_a → sollte noch da sein
|
||||
assert "plugin" in booster._keyword_to_rooms
|
||||
assert booster._keyword_to_rooms["plugin"] == {"room_a"}
|
||||
|
||||
def test_cleanup_no_orphans_returns_same_count(self, booster: KeywordBooster) -> None:
|
||||
"""Keine orphaned Räume → Mapping bleibt gleich groß."""
|
||||
before = len(booster._kw100_to_rooms) + len(booster._kwctx_to_rooms)
|
||||
before = len(booster._keyword_to_rooms)
|
||||
after = booster.cleanup_orphaned_rooms({"room_a", "room_b", "room_catchall"})
|
||||
assert after == before
|
||||
|
||||
@@ -586,8 +585,7 @@ class TestBoosterCleanup:
|
||||
# room_catchall bleibt (catch_all=True, wird von _build_mapping ignoriert)
|
||||
after = booster.cleanup_orphaned_rooms({"room_catchall"})
|
||||
assert after == 0
|
||||
assert len(booster._kw100_to_rooms) == 0
|
||||
assert len(booster._kwctx_to_rooms) == 0
|
||||
assert len(booster._keyword_to_rooms) == 0
|
||||
|
||||
def test_cleanup_then_boost_still_works(self, booster: KeywordBooster) -> None:
|
||||
"""Nach Cleanup: Boost funktioniert korrekt mit bereinigtem Mapping."""
|
||||
@@ -685,8 +683,8 @@ class TestV82A3BoosterDemotion:
|
||||
old_date = (datetime.now() - timedelta(days=91)).isoformat()
|
||||
booster._room_map.set_keyword_last_matched("room_a", "rocketchat", old_date)
|
||||
|
||||
# Vorher: "rocketchat" ist im kw100-Mapping
|
||||
assert "rocketchat" in booster._kw100_to_rooms
|
||||
# Vorher: "rocketchat" ist im Mapping
|
||||
assert "rocketchat" in booster._keyword_to_rooms
|
||||
|
||||
demoted = booster.demote_stale_keywords(max_age_days=90)
|
||||
assert demoted >= 1
|
||||
@@ -697,7 +695,7 @@ class TestV82A3BoosterDemotion:
|
||||
assert "rocketchat" in entry.keywords_context
|
||||
|
||||
# Mapping wurde neu gebaut → "rocketchat" ist jetzt als context-Keyword im Mapping
|
||||
assert "rocketchat" in booster._kwctx_to_rooms
|
||||
assert "rocketchat" in booster._keyword_to_rooms
|
||||
|
||||
def test_demote_no_stale_returns_zero(self, booster: KeywordBooster) -> None:
|
||||
"""Keine stale Keywords → demote_stale_keywords() gibt 0 zurück."""
|
||||
@@ -717,8 +715,8 @@ class TestV82A3BoosterDemotion:
|
||||
assert demoted == 2
|
||||
|
||||
# Beide Keywords sind jetzt im Mapping (als context)
|
||||
assert "rocketchat" in booster._kwctx_to_rooms
|
||||
assert "ddp" in booster._kwctx_to_rooms
|
||||
assert "rocketchat" in booster._keyword_to_rooms
|
||||
assert "ddp" in booster._keyword_to_rooms
|
||||
|
||||
def test_demote_then_boost_still_works(self, booster: KeywordBooster) -> None:
|
||||
"""Nach Demotion: boost() funktioniert korrekt mit neuem Mapping."""
|
||||
|
||||
Reference in New Issue
Block a user