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,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).
|
||||
+71
-193
@@ -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)"
|
||||
# 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
|
||||
warn "Python 3.13 nicht installiert — empfohlen, aber nicht zwingend (>= 3.11 reicht)"
|
||||
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..."
|
||||
# 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
|
||||
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"
|
||||
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 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"
|
||||
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"
|
||||
@@ -465,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
|
||||
@@ -539,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"
|
||||
@@ -552,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)
|
||||
@@ -665,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:
|
||||
@@ -769,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)
|
||||
@@ -1150,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
|
||||
@@ -1335,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
|
||||
|
||||
@@ -1387,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
|
||||
@@ -1560,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.
|
||||
@@ -1590,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"
|
||||
}
|
||||
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
||||
VENV_PY="$PIPX_VENV/bin/python"
|
||||
|
||||
# Ziel-Pfad: User-Space (Variante B)
|
||||
@@ -1615,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
|
||||
@@ -1783,9 +1664,6 @@ deploy_plugin
|
||||
# 4. config.yaml
|
||||
write_config_yaml
|
||||
|
||||
# 4b. Toolset-Registrierung sicherstellen (idempotent)
|
||||
ensure_toolset
|
||||
|
||||
# 5. .env
|
||||
write_env_file
|
||||
|
||||
|
||||
+12
-90
@@ -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:
|
||||
@@ -1186,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
|
||||
@@ -1251,18 +1242,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift
|
||||
|
||||
# Phase 5: SubagentTracker — Subagent-Status für PresenceEngine
|
||||
try:
|
||||
from archivar.subagent_tracker import get_tracker
|
||||
self._subagent_tracker = get_tracker()
|
||||
logger.info("[rocketchat] Phase 5: SubagentTracker initialisiert")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] Phase 5: SubagentTracker-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
self._subagent_tracker = None # Graceful degradation
|
||||
|
||||
def _build_room_map_summary(self) -> str:
|
||||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||||
|
||||
@@ -3569,21 +3548,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
finally:
|
||||
# ── V8.6 P1a: PresenceEngine — mark_busy_done (Honeymoon-Timer) ──
|
||||
# try/finally garantiert decrement auch bei Exceptions/Errors.
|
||||
# Phase 5: Reihenfolge getauscht — decrement_background_tasks VOR
|
||||
# mark_busy_done, damit mark_busy_done den aktuellen background_tasks
|
||||
# Stand sieht und entscheiden kann ob Subagent-Pulse nötig ist.
|
||||
if _has_presence:
|
||||
self._presence_engine.mark_busy_done()
|
||||
# B12: Background-Tasks decrement — Heartbeat-Message aktualisieren
|
||||
self._presence_engine.decrement_background_tasks()
|
||||
# P1a: mark_busy_done prüft jetzt intern background_tasks > 0
|
||||
self._presence_engine.mark_busy_done()
|
||||
# P1-2: current_room zurücksetzen nach Verarbeitung
|
||||
self._presence_engine.set_current_room("")
|
||||
logger.info("[presence] mark_busy_done (turn complete)")
|
||||
|
||||
# Phase 5: SubagentTracker — complete() NICHT im finally!
|
||||
# Der Background-Prozess läuft noch wenn der Turn endet.
|
||||
# Stale-Recovery im DetectionTimer räumt tote Einträge auf.
|
||||
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||
# W2: release in try/except BaseException im finally-Block.
|
||||
try:
|
||||
@@ -4732,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
|
||||
@@ -6693,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
|
||||
@@ -6704,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")
|
||||
|
||||
@@ -6783,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:
|
||||
@@ -7167,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:
|
||||
@@ -7176,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:
|
||||
@@ -7247,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:
|
||||
@@ -7435,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:
|
||||
|
||||
@@ -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,16 +287,6 @@ 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",
|
||||
|
||||
@@ -13,6 +13,7 @@ import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
@@ -151,23 +152,6 @@ class PresenceEngine:
|
||||
|
||||
P1a: Honeymoon-Timer ensures busy status is visible for at least
|
||||
MIN_BUSY_VISIBLE_S (1.0s) before transitioning to online.
|
||||
|
||||
Lock-Order (Rainers Pflicht-Nachbesserung #1):
|
||||
─────────────────────────────────────────────
|
||||
Race-Bedingung: Honeymoon-Expiry (_honeymoon_expired) kann parallel zu
|
||||
PulseController.set_pulse_target() laufen. Beide greifen auf
|
||||
_transition_from_busy → _update_presence_with_subagents → set_pulse_target.
|
||||
|
||||
LOCK-ORDER (immer in dieser Reihenfolge):
|
||||
1. _busy_honeymoon_lock (PresenceEngine)
|
||||
2. _mode_lock (PulseController)
|
||||
|
||||
_honeymoon_expired() acquired _busy_honeymoon_lock zuerst, dann
|
||||
ruft es _transition_from_busy() → set_pulse_target() → _mode_lock.
|
||||
|
||||
Externe Aufrufer von set_pulse_target() (z.B. mark_busy_done) MÜSSEN
|
||||
sicherstellen dass _busy_honeymoon_lock NICHT gehalten wird wenn sie
|
||||
_mode_lock anfordern — sonst Deadlock.
|
||||
"""
|
||||
|
||||
# P1a: Minimum time busy status must be visible (prevents coalesce race)
|
||||
@@ -365,9 +349,6 @@ class PresenceEngine:
|
||||
If the honeymoon hasn't elapsed yet, the timer callback will
|
||||
handle the transition when it fires.
|
||||
|
||||
Phase 5: Wenn background_tasks > 0, NICHT auf online gehen.
|
||||
Stattdessen _update_presence_with_subagents() aufrufen.
|
||||
|
||||
Must be called in a finally block to ensure counter balance
|
||||
even on exceptions.
|
||||
"""
|
||||
@@ -382,12 +363,11 @@ class PresenceEngine:
|
||||
if counter == 0:
|
||||
elapsed = time.monotonic() - self._busy_started_at
|
||||
if elapsed >= self.MIN_BUSY_VISIBLE_S:
|
||||
# Honeymoon already elapsed — transition now
|
||||
# Honeymoon already elapsed — transition to online now
|
||||
self._cancel_honeymoon_timer()
|
||||
# Phase 5: Check background_tasks before going online
|
||||
self._transition_from_busy()
|
||||
self.update_presence()
|
||||
logger.debug(
|
||||
"[presence] Honeymoon abgelaufen (%.2fs) → transition", elapsed,
|
||||
"[presence] Honeymoon abgelaufen (%.2fs) → online", elapsed,
|
||||
)
|
||||
else:
|
||||
# Honeymoon still running — timer callback will handle it
|
||||
@@ -400,79 +380,6 @@ class PresenceEngine:
|
||||
"[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter,
|
||||
)
|
||||
|
||||
def _transition_from_busy(self) -> None:
|
||||
"""Phase 5: Transition from busy — check subagents before going online.
|
||||
|
||||
Called when mark_busy_done or _honeymoon_expired would normally
|
||||
transition to online. If background_tasks > 0 or pgrep finds subagents,
|
||||
has active entries, start/keep PulseController instead.
|
||||
"""
|
||||
with self._background_tasks_lock:
|
||||
bg = self._background_tasks
|
||||
|
||||
# Phase 5: Auch pgrep prüfen
|
||||
subagent_count = self._read_subagent_count()
|
||||
|
||||
if bg > 0 or subagent_count > 0:
|
||||
# Subagenten laufen noch — Pulse-Modus statt online
|
||||
self._update_presence_with_subagents(max(bg, subagent_count))
|
||||
else:
|
||||
# Keine Subagenten — klassischer Pfad: online
|
||||
self.update_presence()
|
||||
|
||||
def _read_subagent_count(self) -> int:
|
||||
"""V8.7: Read active subagent count via pgrep /proc scan.
|
||||
|
||||
Scannt /proc/*/cmdline nach 'hermes' + 'chat' + '--profile' Prozessen.
|
||||
Schließt die eigene PID aus. Kein subprocess — direkt /proc lesen.
|
||||
|
||||
Returns:
|
||||
Number of active hermes chat --profile processes (excluding self).
|
||||
"""
|
||||
return DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
def _update_presence_with_subagents(self, subagent_count: int) -> None:
|
||||
"""Phase 5: Set presence when subagents are active.
|
||||
|
||||
Two modes:
|
||||
1. Hauptagent busy (_active_tasks > 0): Status bleibt "busy",
|
||||
Message = "Verarbeitet in X (N Subagent)"
|
||||
2. Hauptagent idle (_active_tasks == 0): PulseController mit
|
||||
pulse_target="away", Message = "N Subagent läuft"
|
||||
|
||||
Args:
|
||||
subagent_count: Number of active subagents.
|
||||
"""
|
||||
with self._active_tasks_lock:
|
||||
active = self._active_tasks
|
||||
|
||||
if active > 0:
|
||||
# Hauptagent busy + Subagenten → busy mit erweiterter Message
|
||||
msg = f"Verarbeitet in {self._current_room_name} ({subagent_count} Subagent)" if self._current_room_name else f"Verarbeitet ({subagent_count} Subagent)"
|
||||
self._set_presence("busy", msg)
|
||||
# PulseController im busy-Modus halten für Message-Pulse
|
||||
if not self._pulse_controller.is_running():
|
||||
self._pulse_controller.set_pulse_target("busy")
|
||||
self._pulse_controller.start()
|
||||
else:
|
||||
self._pulse_controller.set_pulse_target("busy")
|
||||
logger.info(
|
||||
"[presence] Subagent-Pulse: busy+%d subagents (active_tasks=%d)",
|
||||
subagent_count, active,
|
||||
)
|
||||
else:
|
||||
# Hauptagent idle + Subagenten → Pulse online↔away
|
||||
msg = f"{subagent_count} Subagent läuft"
|
||||
self._pulse_controller.set_pulse_target("away")
|
||||
if not self._pulse_controller.is_running():
|
||||
self._pulse_controller.start()
|
||||
# Set initial status to away (Pulse toggles from here)
|
||||
self._set_presence("away", msg)
|
||||
logger.info(
|
||||
"[presence] Subagent-Pulse: idle+%d subagents → away-pulse",
|
||||
subagent_count,
|
||||
)
|
||||
|
||||
def _honeymoon_expired(self) -> None:
|
||||
"""P1a: Honeymoon timer callback — transition to online if idle.
|
||||
|
||||
@@ -480,9 +387,6 @@ class PresenceEngine:
|
||||
If no active tasks remain, sets status to online.
|
||||
B3: Checks pending_status under _active_tasks_lock to prevent
|
||||
race with mark_busy_started.
|
||||
|
||||
Phase 5: Nutzt _transition_from_busy() statt direkt update_presence(),
|
||||
damit Subagent-Check auch im Honeymoon-Pfad greift.
|
||||
"""
|
||||
with self._busy_honeymoon_lock:
|
||||
self._busy_honeymoon_timer = None
|
||||
@@ -506,10 +410,9 @@ class PresenceEngine:
|
||||
# and no active tasks remain — next busy cycle starts fresh.
|
||||
self._busy_started_at = 0.0
|
||||
logger.info(
|
||||
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → transition"
|
||||
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → online"
|
||||
)
|
||||
# Phase 5: _transition_from_busy prüft pgrep
|
||||
self._transition_from_busy()
|
||||
self.update_presence()
|
||||
else:
|
||||
logger.debug(
|
||||
"[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel",
|
||||
@@ -579,9 +482,6 @@ class PresenceEngine:
|
||||
_background_tasks_lock aufgerufen, sodass kein veralteter Count
|
||||
persistiert werden kann (Race zwischen zwei konkurrierenden Threads).
|
||||
|
||||
Phase 5: stop()-Aufruf entfernt. PulseController wird jetzt von
|
||||
_update_presence_with_subagents() gesteuert, nicht vom Counter.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
@@ -590,8 +490,8 @@ class PresenceEngine:
|
||||
self._background_tasks -= 1
|
||||
count = self._background_tasks
|
||||
self._pulse_controller.set_background_count(count)
|
||||
# Phase 5: stop() NICHT hier — _update_presence_with_subagents()
|
||||
# entscheidet basierend auf pgrep + background_tasks
|
||||
if count == 0:
|
||||
self._pulse_controller.stop()
|
||||
self._persist_plugin_state(count)
|
||||
return count
|
||||
|
||||
@@ -844,32 +744,7 @@ class PulseController:
|
||||
self._cancel_pending_event = threading.Event() # B6: thread-safe via Event statt bool
|
||||
# P1-2 O-2: Async-await bridge
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._await_timeout: float = 1.0 # V8.8: 1.0s statt 2.0s — schneller fail bei 429
|
||||
|
||||
# Phase 5: pulse_target — "away" (default) oder "busy"
|
||||
# "away": pulsiert online↔away (Subagent läuft, Hauptagent idle)
|
||||
# "busy": pulsiert Message bei busy-Status (Subagent läuft, Hauptagent busy)
|
||||
self._pulse_target: str = "away"
|
||||
self._mode_lock = threading.Lock() # Mode-Sentinel (Risiko #2)
|
||||
self._tick_counter: int = 0 # für Message-only-every-2-ticks
|
||||
|
||||
# V8.8: Mode-abhängige Pulse-Intervalle
|
||||
# away-pulse: 3.0s (weniger aggressiv, vermeidet 429)
|
||||
# busy-pulse: 1.5s (schnelle Reaktion auf busy-Status)
|
||||
self._away_pulse_interval: float = 3.0
|
||||
self._busy_pulse_interval: float = 1.5
|
||||
|
||||
# P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway
|
||||
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
|
||||
self._breaker_state: str = "CLOSED"
|
||||
self._consecutive_429s: int = 0
|
||||
self._breaker_opened_at: float = 0.0
|
||||
self._breaker_cooldown_s: float = 30.0
|
||||
self._breaker_429_threshold: int = 1 # V8.8: 1 statt 3 — sofort nach erstem 429
|
||||
self._base_pulse_interval: float = self._pulse_interval
|
||||
self._backoff_level: int = 0
|
||||
# Adaptive Backoff: pulse_interval wird bei OPEN eskaliert
|
||||
self._backoff_intervals: tuple = (5.0, 15.0, 60.0)
|
||||
self._await_timeout: float = 2.0
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -905,48 +780,6 @@ class PulseController:
|
||||
"""Set the background task count for heartbeat messages."""
|
||||
self._background_count = count
|
||||
|
||||
def set_pulse_target(self, target: str) -> bool:
|
||||
"""Phase 5: Set the pulse target mode with Mode-Sentinel.
|
||||
|
||||
V8.8: Mode-abhängige Pulse-Intervalle:
|
||||
- "away": 3.0s (weniger aggressiv, vermeidet 429)
|
||||
- "busy": 1.5s (schnelle Reaktion auf busy-Status)
|
||||
|
||||
Args:
|
||||
target: "away" (pulse online↔away) or "busy" (pulse message while busy).
|
||||
|
||||
Returns:
|
||||
True if mode was changed, False if already in that mode.
|
||||
|
||||
Raises:
|
||||
ValueError: if target is not "away" or "busy".
|
||||
"""
|
||||
if target not in ("away", "busy"):
|
||||
raise ValueError(f"pulse_target must be 'away' or 'busy', got '{target}'")
|
||||
with self._mode_lock:
|
||||
if self._pulse_target == target:
|
||||
return False
|
||||
old = self._pulse_target
|
||||
self._pulse_target = target
|
||||
# V8.8: Dynamisches Pulse-Interval je nach Mode
|
||||
# Nur anpassen wenn Circuit-Breaker CLOSED (nicht im Backoff)
|
||||
if self._breaker_state == "CLOSED":
|
||||
if target == "away":
|
||||
self._pulse_interval = self._away_pulse_interval
|
||||
self._base_pulse_interval = self._away_pulse_interval
|
||||
else: # busy
|
||||
self._pulse_interval = self._busy_pulse_interval
|
||||
self._base_pulse_interval = self._busy_pulse_interval
|
||||
logger.info(
|
||||
"[pulse] pulse_target: %s → %s (interval=%.1fs)",
|
||||
old, target, self._pulse_interval,
|
||||
)
|
||||
return True
|
||||
|
||||
def get_pulse_target(self) -> str:
|
||||
"""Phase 5: Get the current pulse target mode."""
|
||||
return self._pulse_target
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the pulse thread."""
|
||||
logger.info(
|
||||
@@ -1022,121 +855,6 @@ class PulseController:
|
||||
self._cancel_pending_event.set()
|
||||
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
||||
|
||||
# ── P1: Circuit-Breaker — 429-Schutz ──────────────────────────────────
|
||||
|
||||
def _classify_ddp_error(self, error: Exception) -> str:
|
||||
"""Classify a DDP error to decide whether it triggers REST fallback.
|
||||
|
||||
'server returned false' is a transient DDP protocol quirk — NOT a
|
||||
real error. It must NOT trigger a REST fallback, because that REST
|
||||
call would itself hit 429 and cascade into the Gateway hang.
|
||||
|
||||
Returns:
|
||||
'429' — rate-limit error (triggers breaker)
|
||||
'ddp_transient' — DDP protocol noise, no fallback
|
||||
'other' — real error, REST fallback allowed
|
||||
"""
|
||||
error_str = str(error).lower()
|
||||
if "429" in error_str or "too many requests" in error_str or "rate limit" in error_str:
|
||||
return "429"
|
||||
if "server returned false" in error_str:
|
||||
return "ddp_transient"
|
||||
return "other"
|
||||
|
||||
def _record_429(self) -> None:
|
||||
"""Record a 429 error and transition breaker state.
|
||||
|
||||
CLOSED + consecutive_429s >= threshold → OPEN (pause + backoff)
|
||||
HALF_OPEN + 429 → OPEN (stay open, escalate backoff)
|
||||
"""
|
||||
self._consecutive_429s += 1
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: 429 #%d/%d (state=%s)",
|
||||
self._consecutive_429s, self._breaker_429_threshold, self._breaker_state,
|
||||
)
|
||||
|
||||
if self._breaker_state == "CLOSED" and self._consecutive_429s >= self._breaker_429_threshold:
|
||||
self._breaker_state = "OPEN"
|
||||
self._breaker_opened_at = time.monotonic()
|
||||
# Use current backoff_level, THEN increment for next cycle
|
||||
self._pulse_interval = self._backoff_intervals[self._backoff_level]
|
||||
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: CLOSED→OPEN (cooldown=%.0fs, backoff_level=%d, "
|
||||
"pulse_interval=%.1fs)",
|
||||
self._breaker_cooldown_s, self._backoff_level, self._pulse_interval,
|
||||
)
|
||||
elif self._breaker_state == "HALF_OPEN":
|
||||
self._breaker_state = "OPEN"
|
||||
self._breaker_opened_at = time.monotonic()
|
||||
# Use current backoff_level, THEN increment for next cycle
|
||||
self._pulse_interval = self._backoff_intervals[self._backoff_level]
|
||||
self._backoff_level = min(self._backoff_level + 1, len(self._backoff_intervals) - 1)
|
||||
logger.warning(
|
||||
"[pulse] Circuit-Breaker: HALF_OPEN→OPEN (test ping failed, "
|
||||
"backoff_level=%d, pulse_interval=%.1fs)",
|
||||
self._backoff_level, self._pulse_interval,
|
||||
)
|
||||
|
||||
def _record_success(self) -> None:
|
||||
"""Record a successful status set and reset breaker to CLOSED."""
|
||||
if self._breaker_state != "CLOSED":
|
||||
logger.info(
|
||||
"[pulse] Circuit-Breaker: %s→CLOSED (success, backoff_level=%d→0, "
|
||||
"pulse_interval=%.1fs→%.1fs)",
|
||||
self._breaker_state, self._backoff_level,
|
||||
self._pulse_interval, self._base_pulse_interval,
|
||||
)
|
||||
self._breaker_state = "CLOSED"
|
||||
self._consecutive_429s = 0
|
||||
self._backoff_level = 0
|
||||
self._pulse_interval = self._base_pulse_interval
|
||||
|
||||
def _check_breaker(self) -> bool:
|
||||
"""Check if the circuit breaker allows a tick.
|
||||
|
||||
CLOSED: allow
|
||||
OPEN: if cooldown elapsed → HALF_OPEN (allow one test ping), else block
|
||||
HALF_OPEN: allow (the test ping)
|
||||
|
||||
Returns:
|
||||
True if tick is allowed, False if blocked.
|
||||
"""
|
||||
if self._breaker_state == "CLOSED":
|
||||
return True
|
||||
|
||||
if self._breaker_state == "OPEN":
|
||||
elapsed = time.monotonic() - self._breaker_opened_at
|
||||
if elapsed >= self._breaker_cooldown_s:
|
||||
self._breaker_state = "HALF_OPEN"
|
||||
logger.info(
|
||||
"[pulse] Circuit-Breaker: OPEN→HALF_OPEN (cooldown elapsed, "
|
||||
"sending test ping, pulse_interval=%.1fs)",
|
||||
self._pulse_interval,
|
||||
)
|
||||
return True
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] Circuit-Breaker: OPEN (cooldown %.0f/%.0fs remaining)",
|
||||
self._breaker_cooldown_s - elapsed, self._breaker_cooldown_s,
|
||||
)
|
||||
return False
|
||||
|
||||
# HALF_OPEN: allow the test ping
|
||||
return True
|
||||
|
||||
def get_breaker_state(self) -> str:
|
||||
"""Return current breaker state (for testing)."""
|
||||
return self._breaker_state
|
||||
|
||||
def get_consecutive_429s(self) -> int:
|
||||
"""Return current consecutive 429 count (for testing)."""
|
||||
return self._consecutive_429s
|
||||
|
||||
def get_effective_pulse_interval(self) -> float:
|
||||
"""Return current effective pulse interval (for testing)."""
|
||||
return self._pulse_interval
|
||||
|
||||
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
||||
|
||||
def _pulse_loop(self) -> None:
|
||||
@@ -1174,22 +892,16 @@ class PulseController:
|
||||
def _pulse_tick(self) -> None:
|
||||
"""Execute one pulse tick: toggle phase and send status.
|
||||
|
||||
P1: Circuit-Breaker check before any I/O — if OPEN and cooldown
|
||||
not elapsed, skip the tick entirely. DDP errors are classified:
|
||||
'server returned false' does NOT trigger REST fallback.
|
||||
|
||||
P1-2 O-2: When an asyncio loop is bound, delegates to
|
||||
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
|
||||
uses the legacy sync path (graceful degradation).
|
||||
"""
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, "
|
||||
"breaker=%s, loop=%s",
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, loop=%s",
|
||||
self._phase,
|
||||
self._ddp is not None,
|
||||
self._paused.is_set(),
|
||||
self._cancel_pending_event.is_set(),
|
||||
self._breaker_state,
|
||||
self._loop is not None,
|
||||
)
|
||||
|
||||
@@ -1200,11 +912,6 @@ class PulseController:
|
||||
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
||||
return
|
||||
|
||||
# P1: Circuit-Breaker — block tick if OPEN and cooldown not elapsed
|
||||
if not self._check_breaker():
|
||||
logger.debug("[pulse] _pulse_tick skip: circuit breaker OPEN")
|
||||
return
|
||||
|
||||
# Toggle phase
|
||||
self._phase = not self._phase
|
||||
|
||||
@@ -1247,30 +954,17 @@ class PulseController:
|
||||
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
|
||||
|
||||
# Try DDP first (K1: DDP set_status has no message variant)
|
||||
ddp_error_type = None
|
||||
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||
try:
|
||||
self._ddp.set_status(status)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
ddp_error_type = self._classify_ddp_error(e)
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick DDP set_status failed: %s (classified=%s)",
|
||||
e, ddp_error_type,
|
||||
)
|
||||
if ddp_error_type == "429":
|
||||
self._record_429()
|
||||
return # P1: 429 → no REST fallback, stop here
|
||||
# ddp_transient: no REST fallback, just skip
|
||||
if ddp_error_type == "ddp_transient":
|
||||
return
|
||||
# 'other': fall through to REST fallback
|
||||
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
||||
|
||||
# REST fallback for message text (only for non-429, non-transient DDP errors)
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
@@ -1286,13 +980,8 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
error_str = str(e).lower()
|
||||
if "429" in error_str or "too many requests" in error_str:
|
||||
self._record_429()
|
||||
return # P1: 429 → stop here, symmetric with DDP path
|
||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
@@ -1304,9 +993,6 @@ class PulseController:
|
||||
async def _pulse_tick_async(self) -> None:
|
||||
"""P1-2 O-2: Async pulse tick using await set_status_async.
|
||||
|
||||
P1: DDP errors are classified — 'server returned false' does NOT
|
||||
trigger REST fallback. 429 errors trigger circuit breaker.
|
||||
|
||||
Runs on the asyncio event loop (dispatched via
|
||||
run_coroutine_threadsafe from the pulse thread).
|
||||
Uses DDPClient.set_status_async for true await-semantics
|
||||
@@ -1321,23 +1007,16 @@ class PulseController:
|
||||
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
ddp_error_type = self._classify_ddp_error(e)
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s (classified=%s)",
|
||||
e, ddp_error_type,
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
|
||||
"falling back to REST",
|
||||
e,
|
||||
)
|
||||
if ddp_error_type == "429":
|
||||
self._record_429()
|
||||
return # P1: 429 → no REST fallback
|
||||
if ddp_error_type == "ddp_transient":
|
||||
return # P1: transient → no REST fallback
|
||||
# 'other': fall through to REST fallback
|
||||
|
||||
# REST fallback for message text (only for non-429, non-transient DDP errors)
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
@@ -1353,13 +1032,8 @@ class PulseController:
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
self._record_success()
|
||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
error_str = str(e).lower()
|
||||
if "429" in error_str or "too many requests" in error_str:
|
||||
self._record_429()
|
||||
return # P1: 429 → stop here, symmetric with DDP path
|
||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
@@ -1387,17 +1061,13 @@ class PulseController:
|
||||
class DetectionTimer:
|
||||
"""Detects whether background agents are active.
|
||||
|
||||
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
|
||||
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
|
||||
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
|
||||
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
|
||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
||||
|
||||
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
|
||||
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
|
||||
|
||||
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
|
||||
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
|
||||
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
|
||||
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
|
||||
subprocesses). Self-pid exclude is preserved.
|
||||
|
||||
Calls on_change callback when detection state changes.
|
||||
"""
|
||||
@@ -1462,37 +1132,17 @@ class DetectionTimer:
|
||||
self._thread = None
|
||||
logger.info("[detection] DetectionTimer stopped")
|
||||
|
||||
def _check_gateway_pid_alive(self) -> bool:
|
||||
"""P2 Fix Option D: PID-Sentinel — prüft ob der Gateway-Prozess lebt.
|
||||
|
||||
Verwendet os.getppid() um den Parent-PID (Gateway-Prozess) zu ermitteln
|
||||
und prüft ob /proc/<ppid> existiert. Dies ist das zuverlässigste Signal
|
||||
für die Gateway-Präsenz, da es keine Datei-I/O oder Prozess-Suche benötigt.
|
||||
|
||||
Returns:
|
||||
True wenn der Gateway-Parent-Prozess existiert, False sonst.
|
||||
"""
|
||||
try:
|
||||
ppid = os.getppid()
|
||||
# /proc/<ppid> existiert nur wenn der Prozess lebt
|
||||
return os.path.exists(f"/proc/{ppid}")
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
def check(self) -> bool:
|
||||
"""Check if background agents are active.
|
||||
|
||||
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
|
||||
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
|
||||
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
|
||||
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
|
||||
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
||||
|
||||
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
|
||||
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
|
||||
|
||||
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
|
||||
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
|
||||
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
|
||||
pgrep pattern expanded from 'hermes chat --profile' to
|
||||
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
|
||||
Self-pid exclude is preserved.
|
||||
|
||||
Returns:
|
||||
True if background agents are detected, False otherwise.
|
||||
@@ -1501,28 +1151,20 @@ class DetectionTimer:
|
||||
self._increment_telemetry()
|
||||
|
||||
result = False
|
||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||
gateway_active = 0
|
||||
pid_used = False # P2: True if PID-Sentinel was the deciding signal
|
||||
gateway_used = False # True if gateway_state was the deciding signal
|
||||
plugin_used = False # P1-2: True if plugin_state was the deciding signal
|
||||
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
|
||||
detection_source = "none" # P1-2: which signal decided
|
||||
|
||||
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
|
||||
if self._check_gateway_pid_alive():
|
||||
result = True
|
||||
pid_used = True
|
||||
detection_source = "gateway_pid"
|
||||
|
||||
# ── P2 SECONDARY: gateway_state.json (Schwelle >0, war >1) ──────────
|
||||
if not pid_used:
|
||||
# ── PRIMARY: gateway_state.json ────────────────────────────────────
|
||||
try:
|
||||
if os.path.exists(self._gateway_state_path):
|
||||
with open(self._gateway_state_path, 'r') as f:
|
||||
state = json.load(f)
|
||||
gateway_active = state.get("active_agents", 0)
|
||||
# P2 Fix: Schwelle >0 statt >1
|
||||
if gateway_active > 0:
|
||||
if gateway_active > 1:
|
||||
result = True
|
||||
gateway_used = True
|
||||
detection_source = "gateway"
|
||||
@@ -1530,8 +1172,8 @@ class DetectionTimer:
|
||||
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
||||
# Fall through to plugin_state
|
||||
|
||||
# ── P1-2: TERTIARY: plugin_state.json ────────────────────────────────
|
||||
if not pid_used and not gateway_used:
|
||||
# ── P1-2: SECONDARY: plugin_state.json ─────────────────────────────
|
||||
if not gateway_used:
|
||||
plugin_state = _read_plugin_state(self._plugin_state_path)
|
||||
plugin_bg_tasks = plugin_state.get("background_tasks", 0)
|
||||
if plugin_bg_tasks > 0:
|
||||
@@ -1539,29 +1181,41 @@ class DetectionTimer:
|
||||
plugin_used = True
|
||||
detection_source = "plugin_state"
|
||||
|
||||
# ── V8.7: pgrep /proc scan — hermes chat --profile Prozesse ──
|
||||
# Ersetzt subagent_status.json als vierte Quelle.
|
||||
# Direkt /proc lesen, kein subprocess.
|
||||
pgrep_count = 0
|
||||
if not pid_used and not gateway_used and not plugin_used:
|
||||
pgrep_count = self._pgrep_hermes_subagents()
|
||||
if pgrep_count > 0:
|
||||
result = True
|
||||
# ── TERTIARY: pgrep — run when neither gateway nor plugin decided ──
|
||||
if not gateway_used and not plugin_used:
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
# P1b: Expanded pattern catches subagents AND gateway subprocesses
|
||||
proc = subprocess.run(
|
||||
["pgrep", "-f", "hermes_cli|hermes chat"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
# Parse PIDs and self-exclude
|
||||
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
|
||||
all_pids = [int(l) for l in raw_lines if l.isdigit()]
|
||||
pids = [p for p in all_pids if p != own_pid]
|
||||
pgrep_pids = len(pids)
|
||||
result = pgrep_pids > 0
|
||||
if result:
|
||||
detection_source = "pgrep"
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
||||
logger.debug("[detection] pgrep failed: %s", e)
|
||||
# pgrep_pids stays -1 (error sentinel)
|
||||
|
||||
# ── Log: all signals, result, source ───────────────────────────────
|
||||
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
||||
plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a"
|
||||
logger.info(
|
||||
"[detection] check #%d: pid_sentinel=%s, gateway_state=%d (primary=%s), "
|
||||
"plugin_state=%s (bg_tasks=%s), pgrep=%d, "
|
||||
"[detection] check #%d: gateway_state=%d (primary=%s), "
|
||||
"plugin_state=%s (bg_tasks=%s), pgrep=%s, "
|
||||
"result=%s, source=%s",
|
||||
self._check_count,
|
||||
"alive" if pid_used else "dead",
|
||||
gateway_active,
|
||||
self._check_count, gateway_active,
|
||||
"yes" if gateway_used else "no",
|
||||
"yes" if plugin_used else "no",
|
||||
plugin_str,
|
||||
pgrep_count,
|
||||
pgrep_str,
|
||||
"active" if result else "inactive",
|
||||
detection_source,
|
||||
)
|
||||
@@ -1584,123 +1238,6 @@ class DetectionTimer:
|
||||
self._last_result = result
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _pgrep_hermes_subagents() -> int:
|
||||
"""V8.7: Scan /proc/*/cmdline for 'hermes chat --profile' processes.
|
||||
|
||||
V8.8: argv-basierter Scanner — verhindert False-Positives auf
|
||||
Shell-Befehle die 'hermes'+'chat'+'--profile' als Text enthalten.
|
||||
|
||||
Algorithmus:
|
||||
1. /proc/<pid>/cmdline lesen → null-byte-split → argv array
|
||||
2. argv[0] basename prüfen: 'hermes', 'python', 'python3'
|
||||
3. 'hermes': 'chat' und '--profile' als eigene argv-Elemente
|
||||
4. 'python'/'python3': '-m hermes_cli.main' oder hermes-Skript-Pfad
|
||||
in argv, UND 'chat' UND '--profile' als eigene Elemente
|
||||
5. 'chat' muss eigenes argv-Element sein (kein Substring)
|
||||
6. '--profile' muss eigenes argv-Element sein
|
||||
7. Gateway-PID aus gateway_state.json ausschließen
|
||||
8. Eigene PID ausschließen
|
||||
|
||||
Returns:
|
||||
Number of matching processes (excluding self and gateway).
|
||||
"""
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Gateway-PID aus gateway_state.json lesen
|
||||
gateway_pid = DetectionTimer._read_gateway_pid()
|
||||
|
||||
count = 0
|
||||
try:
|
||||
for entry in os.listdir("/proc"):
|
||||
if not entry.isdigit():
|
||||
continue
|
||||
pid = int(entry)
|
||||
if pid == own_pid:
|
||||
continue
|
||||
if pid == gateway_pid:
|
||||
continue
|
||||
try:
|
||||
with open(f"/proc/{entry}/cmdline", "rb") as f:
|
||||
raw = f.read()
|
||||
# cmdline is null-separated; decode and split into argv
|
||||
argv = [a for a in raw.decode("utf-8", errors="replace").split("\x00") if a]
|
||||
|
||||
if not argv:
|
||||
continue
|
||||
|
||||
# argv[0] basename
|
||||
argv0 = os.path.basename(argv[0])
|
||||
|
||||
# Check: 'chat' and '--profile' must be separate argv elements
|
||||
has_chat = "chat" in argv
|
||||
has_profile = "--profile" in argv
|
||||
|
||||
if not (has_chat and has_profile):
|
||||
continue
|
||||
|
||||
if argv0 == "hermes":
|
||||
count += 1
|
||||
elif argv0 in ("python", "python3"):
|
||||
# Check for '-m hermes_cli.main' or hermes script path
|
||||
is_hermes_python = False
|
||||
for i, arg in enumerate(argv):
|
||||
if arg == "-m" and i + 1 < len(argv):
|
||||
if argv[i + 1].startswith("hermes_cli"):
|
||||
is_hermes_python = True
|
||||
break
|
||||
elif os.path.basename(arg) == "hermes":
|
||||
is_hermes_python = True
|
||||
break
|
||||
if is_hermes_python:
|
||||
count += 1
|
||||
except (OSError, IOError, PermissionError):
|
||||
# Process may have exited or be inaccessible
|
||||
continue
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
return count
|
||||
|
||||
@staticmethod
|
||||
def _read_gateway_pid() -> Optional[int]:
|
||||
"""V8.8: Gateway-PID aus gateway_state.json lesen.
|
||||
|
||||
Returns:
|
||||
Gateway PID or None if not available.
|
||||
"""
|
||||
gateway_state_path = os.environ.get(
|
||||
"ROCKETCHAT_GATEWAY_STATE_PATH",
|
||||
os.path.expanduser("~/.hermes/gateway_state.json"),
|
||||
)
|
||||
try:
|
||||
if os.path.exists(gateway_state_path):
|
||||
with open(gateway_state_path, 'r') as f:
|
||||
state = json.load(f)
|
||||
return state.get("pid")
|
||||
except (json.JSONDecodeError, IOError, OSError):
|
||||
pass
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _pid_is_alive(pid: int) -> bool:
|
||||
"""Check if a process with the given PID is alive.
|
||||
|
||||
Uses os.kill(pid, 0) which sends no signal but checks permissions
|
||||
and process existence. Falls back to /proc/<pid>/ check.
|
||||
|
||||
Args:
|
||||
pid: Process ID to check.
|
||||
|
||||
Returns:
|
||||
True if the process exists, False otherwise.
|
||||
"""
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
return True
|
||||
except OSError:
|
||||
# Fallback: /proc/<pid>/ check
|
||||
return os.path.exists(f"/proc/{pid}")
|
||||
|
||||
def _detection_loop(self) -> None:
|
||||
"""Background thread: periodically check for background agents."""
|
||||
tick = 0
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
"""
|
||||
V8.7: SubagentTracker — Kompatibilitätsmodul (no-ops).
|
||||
|
||||
Die subagent_status.json-basierte Erkennung wurde durch pgrep-basierte
|
||||
/proc-Erkennung in presence_engine.py ersetzt. Dieses Modul bleibt als
|
||||
Kompatibilitätsschicht erhalten, aber register()/complete() sind no-ops.
|
||||
|
||||
Zero external dependencies — stdlib only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Constants (beibehalten für Kompatibilität)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
SUBAGENT_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
|
||||
SUBAGENT_STATE_FILENAME = "subagent_status.json"
|
||||
SUBAGENT_STATE_SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def _get_subagent_state_path() -> str:
|
||||
"""Return the path to the subagent status file (Kompatibilität)."""
|
||||
return os.path.join(SUBAGENT_STATE_DIR, SUBAGENT_STATE_FILENAME)
|
||||
|
||||
|
||||
def _read_subagent_state(path: str) -> dict:
|
||||
"""Read the subagent state file, returning default empty dict if missing or corrupt.
|
||||
|
||||
V8.7: Immer leeres dict — subagent_status.json wird nicht mehr verwendet.
|
||||
"""
|
||||
return {"active": [], "last_change_iso": "", "schema_version": SUBAGENT_STATE_SCHEMA_VERSION, "source": "plugin_internal"}
|
||||
|
||||
|
||||
def _write_subagent_state(path: str, data: dict) -> None:
|
||||
"""V8.7: No-op — subagent_status.json wird nicht mehr geschrieben."""
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# SubagentTracker (no-ops)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class SubagentTracker:
|
||||
"""V8.7: No-op Tracker — pgrep ersetzt subagent_status.json.
|
||||
|
||||
Alle Methoden sind no-ops. Das Modul bleibt für Kompatibilität erhalten.
|
||||
"""
|
||||
|
||||
def __init__(self, state_path: str = ""):
|
||||
self._state_path = state_path or _get_subagent_state_path()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def register(self, subagent_type: str, room_name: str = "", task_id: str = "", pid: int = 0) -> dict:
|
||||
"""V8.7: No-op — pgrep-basierte Erkennung ersetzt register()."""
|
||||
logger.debug("[subagent_tracker] register() no-op (pgrep mode): type=%s", subagent_type)
|
||||
return {"task_id": "", "type": subagent_type, "owner_room": room_name, "pid": 0}
|
||||
|
||||
def complete(self, subagent_type: str, task_id: str = "") -> int:
|
||||
"""V8.7: No-op — pgrep-basierte Erkennung ersetzt complete()."""
|
||||
logger.debug("[subagent_tracker] complete() no-op (pgrep mode): type=%s", subagent_type)
|
||||
return 0
|
||||
|
||||
def remove_by_task_id(self, task_id: str) -> bool:
|
||||
"""V8.7: No-op — pgrep-basierte Erkennung braucht kein Stale-Recovery."""
|
||||
logger.debug("[subagent_tracker] remove_by_task_id() no-op (pgrep mode): task_id=%s", task_id)
|
||||
return False
|
||||
|
||||
def list(self) -> List[Dict]:
|
||||
"""V8.7: Immer leere Liste — pgrep ist die Quelle der Wahrheit."""
|
||||
return []
|
||||
|
||||
def count(self) -> int:
|
||||
"""V8.7: Immer 0 — pgrep ist die Quelle der Wahrheit."""
|
||||
return 0
|
||||
|
||||
def clear_all(self) -> None:
|
||||
"""V8.7: No-op."""
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Module-level convenience (singleton pattern, no-op)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_default_tracker: Optional[SubagentTracker] = None
|
||||
_tracker_lock = threading.Lock()
|
||||
|
||||
|
||||
def get_tracker() -> SubagentTracker:
|
||||
"""Get or create the module-level SubagentTracker singleton (no-op)."""
|
||||
global _default_tracker
|
||||
if _default_tracker is None:
|
||||
with _tracker_lock:
|
||||
if _default_tracker is None:
|
||||
_default_tracker = SubagentTracker()
|
||||
return _default_tracker
|
||||
@@ -936,14 +936,16 @@ class TestPulseControllerLastSentPhase:
|
||||
|
||||
|
||||
class TestDetectionTimerPgrepPrimary:
|
||||
"""Test 20: DetectionTimer — gateway_state PRIMARY, pgrep SECONDARY (V8.7)."""
|
||||
"""Test 20: DetectionTimer — gateway_state PRIMARY, pgrep SECONDARY (P1b)."""
|
||||
|
||||
def test_pgrep_finds_other_agents(self):
|
||||
"""gateway_state=1 (nicht >1) → pgrep findet anderen Prozess → result=True."""
|
||||
"""gateway_state=1 (nicht >1) → pgrep-Fallback findet anderen Prozess → result=True."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
import tempfile
|
||||
import json
|
||||
|
||||
own_pid = os.getpid()
|
||||
|
||||
# gateway_state mit active_agents=1 (nicht >1 → fällt auf pgrep zurück)
|
||||
state = {"active_agents": 1, "profiles": ["default"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
@@ -951,14 +953,20 @@ class TestDetectionTimerPgrepPrimary:
|
||||
state_path = f.name
|
||||
|
||||
try:
|
||||
# Mock _pgrep_hermes_subagents: findet 2 Prozesse
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||
# Mock pgrep: findet eigenen + fremden Prozess
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=1 → pgrep findet 2 Prozesse → True
|
||||
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
|
||||
assert result is True
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
@@ -976,8 +984,8 @@ class TestDetectionTimerPgrepPrimary:
|
||||
state_path = f.name
|
||||
|
||||
try:
|
||||
# Mock _pgrep_hermes_subagents: sollte NICHT aufgerufen werden
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep:
|
||||
# Mock pgrep: sollte NICHT aufgerufen werden
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=state_path,
|
||||
detection_interval=0.1,
|
||||
@@ -986,34 +994,50 @@ class TestDetectionTimerPgrepPrimary:
|
||||
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
||||
assert result is True
|
||||
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||
mock_pgrep.assert_not_called()
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(state_path)
|
||||
|
||||
|
||||
class TestDetectionTimerPgrepNoGatewayState:
|
||||
"""Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json (V8.7)."""
|
||||
"""Test 21: DetectionTimer pgrep-Fallback funktioniert auch ohne gateway_state.json (P1b)."""
|
||||
|
||||
def test_pgrep_works_without_gateway_state(self):
|
||||
"""Wenn gateway_state.json nicht existiert, pgrep greift."""
|
||||
"""Wenn gateway_state.json nicht existiert, pgrep-Fallback greift."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
# Mock _pgrep_hermes_subagents: findet 2 Prozesse
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Mock pgrep: findet anderen Prozess
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet 2 Prozesse → True
|
||||
# pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
def test_pgrep_returns_bool(self):
|
||||
"""pgrep liefert immer bool zurück."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
# Mock _pgrep_hermes_subagents: 0 Prozesse
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0):
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Mock pgrep: findet nur eigenen Prozess
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
@@ -1023,19 +1047,26 @@ class TestDetectionTimerPgrepNoGatewayState:
|
||||
|
||||
|
||||
class TestDetectionTimerIntegration:
|
||||
"""Test 22: DetectionTimer start/stop + Callback (V8.7: pgrep PRIMARY)."""
|
||||
"""Test 22: DetectionTimer start/stop + Callback (P1b: gateway_state PRIMARY, pgrep SECONDARY)."""
|
||||
|
||||
def test_detection_timer_start_stop(self):
|
||||
"""DetectionTimer startet und stoppt korrekt, pgrep bei fehlendem gateway_state."""
|
||||
"""DetectionTimer startet und stoppt korrekt, pgrep-Fallback bei fehlendem gateway_state."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
callback_results = []
|
||||
|
||||
def on_detection_change(is_active):
|
||||
callback_results.append(is_active)
|
||||
|
||||
# Mock _pgrep_hermes_subagents: findet 2 Prozesse → True
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||
# Mock pgrep: findet anderen Prozess → True (gateway_state fehlt → Fallback)
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
@@ -1322,171 +1353,110 @@ class TestP0LiveVerdrahtung:
|
||||
|
||||
|
||||
class TestDetectionTimerPgrepSelfExclude:
|
||||
"""V8.7: _pgrep_hermes_subagents() self-exclude — eigene PID wird ignoriert."""
|
||||
"""P1-2: DetectionTimer pgrep self-exclude — eigene PID wird ignoriert."""
|
||||
|
||||
def test_pgrep_self_exclude_own_pid(self):
|
||||
"""_pgrep_hermes_subagents() findet nur eigenen Prozess → 0."""
|
||||
"""pgrep findet nur den eigenen Prozess → check() returns False."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
# Mock _pgrep_hermes_subagents: 0 (eigene PID ausgeschlossen)
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0), \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Mock subprocess.run: pgrep returns only our own PID
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state_v8_7.json",
|
||||
)
|
||||
result = dt.check()
|
||||
# Own PID excluded → no background agents → False
|
||||
# Own PID should be excluded → no background agents → False
|
||||
assert result is False
|
||||
|
||||
def test_pgrep_self_exclude_with_other_pids(self):
|
||||
"""_pgrep_hermes_subagents() findet 2 Prozesse → True."""
|
||||
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
# Mock _pgrep_hermes_subagents: 2 (eigene PID + anderer)
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||
own_pid = os.getpid()
|
||||
|
||||
# Mock subprocess.run: pgrep returns own PID + another PID
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
)
|
||||
result = dt.check()
|
||||
# 2 Prozesse gefunden → True
|
||||
# After excluding own PID, one other PID remains → True
|
||||
assert result is True
|
||||
|
||||
|
||||
class TestDetectionTimerOnChangeCallback:
|
||||
"""V8.7: DetectionTimer on_change callback feuert bei pgrep-Zustandswechsel."""
|
||||
"""P1-2: DetectionTimer on_change callback feuert bei pgrep-Zustandswechsel."""
|
||||
|
||||
def test_on_change_callback_fires_on_state_change(self):
|
||||
"""Mock _pgrep_hermes_subagents: Prozesse erscheinen/verschwinden → on_change feuert."""
|
||||
"""Mock pgrep: Prozesse erscheinen/verschwinden → on_change feuert."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
callback_results = []
|
||||
|
||||
def on_change(is_active):
|
||||
callback_results.append(is_active)
|
||||
|
||||
# Mock _pgrep_hermes_subagents: 0 → 2 → 2 → 0
|
||||
mock_counts = [0, 2, 2, 0]
|
||||
# Mock pgrep: zuerst nur eigener Prozess (inactive), dann anderer erscheint
|
||||
mock_results = [
|
||||
# Check 1: nur eigener Prozess → False
|
||||
MagicMock(stdout=f"{own_pid}\n", stderr="", returncode=0),
|
||||
# Check 2: anderer Prozess erscheint → True
|
||||
MagicMock(stdout=f"{own_pid}\n99999\n", stderr="", returncode=0),
|
||||
# Check 3: immer noch da → True (kein Callback)
|
||||
MagicMock(stdout=f"{own_pid}\n99999\n", stderr="", returncode=0),
|
||||
# Check 4: verschwindet → False
|
||||
MagicMock(stdout=f"{own_pid}\n", stderr="", returncode=0),
|
||||
]
|
||||
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
mock_pgrep.side_effect = mock_counts
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.side_effect = mock_results
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
on_change=on_change,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state_v8_7.json",
|
||||
)
|
||||
|
||||
# Check 1: 0 Prozesse → False (kein Callback, _last_result startet False)
|
||||
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
||||
result1 = dt.check()
|
||||
assert result1 is False
|
||||
assert len(callback_results) == 0
|
||||
|
||||
# Check 2: 2 Prozesse → True (Callback: False→True)
|
||||
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
||||
result2 = dt.check()
|
||||
assert result2 is True
|
||||
assert len(callback_results) == 1
|
||||
assert callback_results[0] is True
|
||||
|
||||
# Check 3: immer noch 2 → True (kein Callback, kein Wechsel)
|
||||
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
||||
result3 = dt.check()
|
||||
assert result3 is True
|
||||
assert len(callback_results) == 1
|
||||
|
||||
# Check 4: 0 → False (Callback: True→False)
|
||||
# Check 4: verschwindet → False (Callback: True→False)
|
||||
result4 = dt.check()
|
||||
assert result4 is False
|
||||
assert len(callback_results) == 2
|
||||
assert callback_results[1] is False
|
||||
|
||||
|
||||
class TestPgrepArgvParsing:
|
||||
"""V8.9: _pgrep_hermes_subagents() argv-Parsing — erkennt hermes-Binary ohne .py-Endung."""
|
||||
|
||||
def test_hermes_binary_in_argv(self):
|
||||
"""argv = ['python3', '/home/bernd/.local/bin/hermes', 'chat', '--profile', 'rainer'] → match."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
# Simuliere /proc/<pid>/cmdline
|
||||
cmdline = b"python3\x00/home/bernd/.local/bin/hermes\x00chat\x00--profile\x00rainer\x00"
|
||||
fake_pid = 99999
|
||||
|
||||
with patch("os.listdir", return_value=[str(fake_pid)]), \
|
||||
patch("os.getpid", return_value=1), \
|
||||
patch.object(DetectionTimer, "_read_gateway_pid", return_value=None):
|
||||
with patch("builtins.open", create=True) as mock_open:
|
||||
mock_open.return_value.__enter__.return_value.read.return_value = cmdline
|
||||
result = DetectionTimer._pgrep_hermes_subagents()
|
||||
assert result == 1, f"Expected 1, got {result}"
|
||||
|
||||
def test_hermes_binary_generic_path(self):
|
||||
"""argv = ['python3', '/pfad/zu/hermes', 'chat', '--profile', 'miguel'] → match."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
cmdline = b"python3\x00/pfad/zu/hermes\x00chat\x00--profile\x00miguel\x00"
|
||||
fake_pid = 99998
|
||||
|
||||
with patch("os.listdir", return_value=[str(fake_pid)]), \
|
||||
patch("os.getpid", return_value=1), \
|
||||
patch.object(DetectionTimer, "_read_gateway_pid", return_value=None):
|
||||
with patch("builtins.open", create=True) as mock_open:
|
||||
mock_open.return_value.__enter__.return_value.read.return_value = cmdline
|
||||
result = DetectionTimer._pgrep_hermes_subagents()
|
||||
assert result == 1, f"Expected 1, got {result}"
|
||||
|
||||
def test_hermes_direct_binary(self):
|
||||
"""argv = ['hermes', 'chat', '--profile', 'default'] → match (argv0 == 'hermes')."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
cmdline = b"hermes\x00chat\x00--profile\x00default\x00"
|
||||
fake_pid = 99997
|
||||
|
||||
with patch("os.listdir", return_value=[str(fake_pid)]), \
|
||||
patch("os.getpid", return_value=1), \
|
||||
patch.object(DetectionTimer, "_read_gateway_pid", return_value=None):
|
||||
with patch("builtins.open", create=True) as mock_open:
|
||||
mock_open.return_value.__enter__.return_value.read.return_value = cmdline
|
||||
result = DetectionTimer._pgrep_hermes_subagents()
|
||||
assert result == 1, f"Expected 1, got {result}"
|
||||
|
||||
def test_hermes_py_script_still_works(self):
|
||||
"""argv = ['python3', '/path/hermes.py', 'chat', '--profile', 'miguel'] → match (via -m check)."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
# .py-Skript wird nicht mehr über endswith('.py') erkannt,
|
||||
# aber '-m hermes_cli.main' funktioniert weiterhin.
|
||||
# Dieser Test stellt sicher, dass der -m-Pfad intakt ist.
|
||||
cmdline = b"python3\x00-m\x00hermes_cli.main\x00chat\x00--profile\x00miguel\x00"
|
||||
fake_pid = 99996
|
||||
|
||||
with patch("os.listdir", return_value=[str(fake_pid)]), \
|
||||
patch("os.getpid", return_value=1), \
|
||||
patch.object(DetectionTimer, "_read_gateway_pid", return_value=None):
|
||||
with patch("builtins.open", create=True) as mock_open:
|
||||
mock_open.return_value.__enter__.return_value.read.return_value = cmdline
|
||||
result = DetectionTimer._pgrep_hermes_subagents()
|
||||
assert result == 1, f"Expected 1, got {result}"
|
||||
|
||||
def test_non_hermes_python_not_matched(self):
|
||||
"""argv = ['python3', '/usr/bin/some_script.py', 'chat', '--profile'] → NO match."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
cmdline = b"python3\x00/usr/bin/some_script.py\x00chat\x00--profile\x00default\x00"
|
||||
fake_pid = 99995
|
||||
|
||||
with patch("os.listdir", return_value=[str(fake_pid)]), \
|
||||
patch("os.getpid", return_value=1), \
|
||||
patch.object(DetectionTimer, "_read_gateway_pid", return_value=None):
|
||||
with patch("builtins.open", create=True) as mock_open:
|
||||
mock_open.return_value.__enter__.return_value.read.return_value = cmdline
|
||||
result = DetectionTimer._pgrep_hermes_subagents()
|
||||
assert result == 0, f"Expected 0, got {result}"
|
||||
|
||||
|
||||
class TestPulseControllerStartWithoutDdp:
|
||||
"""P1-1: PulseController.start() ohne DDP-Bindung → log warning, kein Crash."""
|
||||
|
||||
@@ -1644,9 +1614,6 @@ class TestHoneymoonBusyMinVisible:
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# V8.7: Mock _read_subagent_count → 0 (keine echten Prozesse)
|
||||
engine._read_subagent_count = lambda: 0
|
||||
|
||||
# Start busy
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 1
|
||||
@@ -1687,9 +1654,6 @@ class TestHoneymoonBusyMinVisible:
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# V8.7: Mock _read_subagent_count → 0
|
||||
engine._read_subagent_count = lambda: 0
|
||||
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
assert engine._active_tasks == 1
|
||||
|
||||
@@ -1716,9 +1680,6 @@ class TestHoneymoonBusyMinVisible:
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# V8.7: Mock _read_subagent_count → 0
|
||||
engine._read_subagent_count = lambda: 0
|
||||
|
||||
# Erster busy
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
first_timer = engine._busy_honeymoon_timer
|
||||
@@ -1781,9 +1742,6 @@ class TestHoneymoonBusyMinVisible:
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# V8.7: Mock _read_subagent_count → 0
|
||||
engine._read_subagent_count = lambda: 0
|
||||
|
||||
try:
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
raise RuntimeError("simulated dispatch failure")
|
||||
@@ -1815,9 +1773,6 @@ class TestHoneymoonBusyMinVisible:
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
|
||||
# V8.7: Mock _read_subagent_count → 0
|
||||
engine._read_subagent_count = lambda: 0
|
||||
|
||||
engine.mark_busy_started(room_name="#Test")
|
||||
time.sleep(0.05)
|
||||
engine.mark_busy_done()
|
||||
@@ -2132,29 +2087,40 @@ class TestDetectionTimerPluginState:
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0), \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# background_tasks=0, gateway_state fehlt, pgrep=0 → False
|
||||
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
||||
assert result is False
|
||||
|
||||
def test_plugin_state_missing_file_no_error(self):
|
||||
"""Plugin-State-Datei fehlt → kein Fehler, fällt zurück auf pgrep."""
|
||||
"""Plugin-State-Datei fehlt → kein Fehler, fällt zurück auf gateway_state+pgrep."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet 2 Prozesse → True
|
||||
# pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
||||
@@ -2167,14 +2133,20 @@ class TestDetectionTimerPluginState:
|
||||
with open(state_path, 'w') as f:
|
||||
f.write("{invalid json {{{")
|
||||
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# Sollte nicht crashen, pgrep findet 2 Prozesse → True
|
||||
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
def test_plugin_state_priority_after_gateway(self, tmp_path):
|
||||
@@ -2199,7 +2171,7 @@ class TestDetectionTimerPluginState:
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
@@ -2208,7 +2180,7 @@ class TestDetectionTimerPluginState:
|
||||
result = dt.check()
|
||||
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
|
||||
assert result is True
|
||||
mock_pgrep.assert_not_called()
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(gw_path)
|
||||
|
||||
@@ -2243,7 +2215,6 @@ class TestDetectionSourceTelemetry:
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
||||
|
||||
@@ -2254,8 +2225,13 @@ class TestDetectionSourceTelemetry:
|
||||
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0), \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
@@ -2271,8 +2247,13 @@ class TestDetectionSourceTelemetry:
|
||||
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2), \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
own_pid = os.getpid()
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
stdout=f"{own_pid}\n99999\n",
|
||||
stderr="",
|
||||
returncode=0,
|
||||
)
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
@@ -2295,15 +2276,14 @@ class TestDetectionSourceTelemetry:
|
||||
gw_path = f.name
|
||||
|
||||
try:
|
||||
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep, \
|
||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
||||
mock_pgrep.assert_not_called()
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(gw_path)
|
||||
|
||||
@@ -2328,386 +2308,3 @@ class TestPresenceEnginePluginStateIntegration:
|
||||
assert engine._detection_timer._plugin_state_path is not None
|
||||
assert "plugin_state" in engine._detection_timer._plugin_state_path
|
||||
assert "hermes_rocket_plugin.json" in engine._detection_timer._plugin_state_path
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1: Circuit-Breaker — 429-Schutz im PulseController
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestCircuitBreakerStateTransitions:
|
||||
"""P1: Circuit-Breaker state machine — CLOSED → OPEN → HALF_OPEN → CLOSED."""
|
||||
|
||||
def test_breaker_starts_closed(self):
|
||||
"""Neuer PulseController startet im CLOSED state."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
|
||||
def test_one_429_opens_breaker(self):
|
||||
"""V8.8: 1×429 → CLOSED→OPEN sofort (threshold=1)."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
# DDP wirft 429-Fehler
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
base_interval = pc.get_effective_pulse_interval()
|
||||
|
||||
# Tick 1: 429 #1 → OPEN (threshold=1)
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_consecutive_429s() == 1
|
||||
# pulse_interval sollte auf backoff_level=0 → 5.0s gestiegen sein
|
||||
assert pc.get_effective_pulse_interval() > base_interval
|
||||
|
||||
def test_breaker_blocks_ticks_when_open(self):
|
||||
"""OPEN state blockiert Ticks bis Cooldown abläuft."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 1×429 → OPEN (threshold=1)
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
# Weitere Ticks werden geblockt (kein DDP-Call mehr)
|
||||
call_count_before = mock_ddp.set_status.call_count
|
||||
for _ in range(5):
|
||||
pc._pulse_tick()
|
||||
# Keine neuen DDP-Calls (breaker blockiert)
|
||||
assert mock_ddp.set_status.call_count == call_count_before
|
||||
|
||||
|
||||
class TestCircuitBreakerHalfOpen:
|
||||
"""P1: HALF_OPEN-Pfad — Test-Ping nach Cooldown."""
|
||||
|
||||
def test_half_open_success_returns_to_closed(self):
|
||||
"""HALF_OPEN Test-Ping success → CLOSED, pulse_interval reset."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
# DDP wirft 1×429, dann success (threshold=1)
|
||||
call_count = [0]
|
||||
|
||||
def ddp_side_effect(status):
|
||||
call_count[0] += 1
|
||||
if call_count[0] <= 1:
|
||||
raise Exception("HTTP 429 Too Many Requests")
|
||||
return True
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=ddp_side_effect)
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 1×429 → OPEN (threshold=1)
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
# Simuliere Cooldown-Ablauf: setze _breaker_opened_at in die Vergangenheit
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
|
||||
# Nächster Tick: _check_breaker → HALF_OPEN, dann success → CLOSED
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
# pulse_interval zurück auf base
|
||||
assert pc.get_effective_pulse_interval() == 0.05
|
||||
|
||||
def test_half_open_429_returns_to_open(self):
|
||||
"""HALF_OPEN Test-Ping bekommt 429 → OPEN, backoff eskaliert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
# DDP wirft IMMER 429
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 1×429 → OPEN (threshold=1, backoff_level=0, pulse_interval=5.0)
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
first_open_interval = pc.get_effective_pulse_interval()
|
||||
|
||||
# Simuliere Cooldown-Ablauf
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
|
||||
# HALF_OPEN Test-Ping → 429 → OPEN again, backoff_level=1 → 15.0s
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_effective_pulse_interval() > first_open_interval
|
||||
|
||||
|
||||
class TestCircuitBreakerSustained429:
|
||||
"""P1: sustained-429 — adaptives pulse_interval steigt unter Last."""
|
||||
|
||||
def test_sustained_429_escalates_pulse_interval(self):
|
||||
"""Anhaltende 429 → pulse_interval: 1.5s → 5s → 15s → 60s."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
intervals_seen = [pc.get_effective_pulse_interval()]
|
||||
|
||||
# Zyklus 1: 1×429 → OPEN (threshold=1, backoff 0: 5.0s)
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Cooldown ablaufen lassen → HALF_OPEN → 429 → OPEN (backoff 1: 15.0s)
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Cooldown ablaufen lassen → HALF_OPEN → 429 → OPEN (backoff 2: 60.0s)
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||
|
||||
# Intervalle müssen monoton steigen
|
||||
for i in range(1, len(intervals_seen)):
|
||||
assert intervals_seen[i] >= intervals_seen[i - 1], (
|
||||
f"pulse_interval nicht monoton: {intervals_seen}"
|
||||
)
|
||||
|
||||
# Letztes Intervall sollte 60.0 sein (max backoff)
|
||||
assert intervals_seen[-1] == 60.0, (
|
||||
f"Erwartet 60.0s max backoff, bekam {intervals_seen[-1]}"
|
||||
)
|
||||
|
||||
def test_backoff_capped_at_max(self):
|
||||
"""Backoff-Level capped bei len(backoff_intervals)-1 (60s)."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 5 Zyklen OPEN→HALF_OPEN→OPEN (mehr als backoff_intervals Länge)
|
||||
for cycle in range(5):
|
||||
# 1×429 → OPEN (threshold=1)
|
||||
pc._pulse_tick()
|
||||
# Cooldown ablaufen → HALF_OPEN → 429 → OPEN
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
|
||||
# Sollte bei 60.0 gecapped sein, nicht höher
|
||||
assert pc.get_effective_pulse_interval() == 60.0
|
||||
|
||||
|
||||
class TestCircuitBreakerDdpErrorClassification:
|
||||
"""P1: DDP-Error-Klassifizierung — 'server returned false' kein REST-Fallback."""
|
||||
|
||||
def test_server_returned_false_is_transient(self):
|
||||
"""'server returned false' wird als ddp_transient klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("DDP: server returned false"))
|
||||
assert result == "ddp_transient"
|
||||
|
||||
def test_429_error_is_classified_as_429(self):
|
||||
"""HTTP 429 wird als '429' klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("HTTP 429 Too Many Requests"))
|
||||
assert result == "429"
|
||||
|
||||
def test_other_error_is_classified_as_other(self):
|
||||
"""Andere Fehler werden als 'other' klassifiziert."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
result = pc._classify_ddp_error(Exception("Connection refused"))
|
||||
assert result == "other"
|
||||
|
||||
def test_ddp_transient_does_not_trigger_rest_fallback(self):
|
||||
"""'server returned false' DDP-Fehler → kein REST-Fallback, kein 429-Count."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("DDP: server returned false"))
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# 10 Ticks mit 'server returned false' → kein REST-Fallback, kein 429
|
||||
for _ in range(10):
|
||||
pc._pulse_tick()
|
||||
|
||||
# REST wurde NICHT aufgerufen (kein Fallback)
|
||||
mock_rest._request.assert_not_called()
|
||||
# Kein 429 gezählt
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
# Breaker bleibt CLOSED
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
|
||||
def test_429_ddp_error_does_not_trigger_rest_fallback(self):
|
||||
"""429 DDP-Fehler → kein REST-Fallback (verhindert Kaskade)."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=Exception("HTTP 429 Too Many Requests"))
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# 1×429 DDP → OPEN (threshold=1), REST wurde NIE aufgerufen
|
||||
pc._pulse_tick()
|
||||
|
||||
# REST wurde NICHT aufgerufen (429 blockiert Fallback)
|
||||
mock_rest._request.assert_not_called()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
|
||||
|
||||
class TestCircuitBreakerRecordSuccess:
|
||||
"""P1: _record_success() resetet Breaker und pulse_interval."""
|
||||
|
||||
def test_record_success_resets_everything(self):
|
||||
"""_record_success() → CLOSED, 429s=0, backoff=0, pulse_interval=base."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
|
||||
# Manuell in OPEN setzen
|
||||
pc._breaker_state = "OPEN"
|
||||
pc._consecutive_429s = 5
|
||||
pc._backoff_level = 2
|
||||
pc._pulse_interval = 60.0
|
||||
|
||||
pc._record_success()
|
||||
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_consecutive_429s() == 0
|
||||
assert pc.get_effective_pulse_interval() == 1.5
|
||||
|
||||
def test_success_after_open_resets_interval(self):
|
||||
"""Nach OPEN→HALF_OPEN→success: pulse_interval zurück auf base."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
call_count = [0]
|
||||
|
||||
def ddp_side_effect(status):
|
||||
call_count[0] += 1
|
||||
if call_count[0] <= 1:
|
||||
raise Exception("HTTP 429 Too Many Requests")
|
||||
return True
|
||||
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(side_effect=ddp_side_effect)
|
||||
|
||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# 1×429 → OPEN (threshold=1, pulse_interval=5.0)
|
||||
pc._pulse_tick()
|
||||
assert pc.get_breaker_state() == "OPEN"
|
||||
assert pc.get_effective_pulse_interval() == 5.0
|
||||
|
||||
# Cooldown ablaufen → HALF_OPEN → success → CLOSED
|
||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||
pc._pulse_tick()
|
||||
|
||||
assert pc.get_breaker_state() == "CLOSED"
|
||||
assert pc.get_effective_pulse_interval() == 1.5
|
||||
|
||||
|
||||
class TestCircuitBreakerRest429Return:
|
||||
"""P1: REST 429 path has explicit return — symmetric with DDP path."""
|
||||
|
||||
def test_rest_429_stops_execution(self):
|
||||
"""Nach _record_429() im REST-Pfad wird kein weiterer Code ausgeführt."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
# REST wirft 429
|
||||
mock_rest._request = MagicMock(
|
||||
side_effect=Exception("HTTP 429 Too Many Requests")
|
||||
)
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_rest(mock_rest)
|
||||
# Kein DDP → fällt direkt in REST-Fallback
|
||||
# Phase=True → away (damit message gesetzt wird)
|
||||
|
||||
# Mock _record_429 um Aufruf zu verfolgen
|
||||
record_calls = []
|
||||
pc._record_429 = lambda: record_calls.append(1)
|
||||
|
||||
with patch.object(pc.__class__, "_record_429", side_effect=lambda self: record_calls.append(1)) as mock_record:
|
||||
pc._pulse_tick()
|
||||
|
||||
# _record_429 wurde aufgerufen
|
||||
assert len(record_calls) == 1, (
|
||||
f"Expected _record_429 to be called once, got {len(record_calls)}"
|
||||
)
|
||||
# REST._request wurde aufgerufen (hat 429 geworfen)
|
||||
assert mock_rest._request.call_count == 1
|
||||
|
||||
def test_rest_429_does_not_log_failure(self):
|
||||
"""Nach _record_429() im REST-Pfad wird 'REST setStatus failed' NICHT geloggt."""
|
||||
import logging
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(
|
||||
side_effect=Exception("HTTP 429 Too Many Requests")
|
||||
)
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
# Capture logger output
|
||||
with patch.object(logging.getLogger("plugin.archivar.presence_engine"), "info") as mock_info:
|
||||
pc._pulse_tick()
|
||||
|
||||
# Prüfe dass "REST setStatus failed" NICHT geloggt wurde
|
||||
failure_logged = any(
|
||||
"REST setStatus failed" in str(call_args)
|
||||
for call_args in mock_info.call_args_list
|
||||
)
|
||||
assert not failure_logged, (
|
||||
"REST setStatus failed should NOT be logged after _record_429 returns"
|
||||
)
|
||||
|
||||
@@ -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,687 +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
|
||||
|
||||
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
|
||||
@@ -1,252 +0,0 @@
|
||||
"""
|
||||
V8.7: SubagentTracker — No-op Tests.
|
||||
|
||||
Alle register()/complete() sind no-ops. Tests prüfen dass:
|
||||
- register() keine Datei schreibt
|
||||
- complete() immer 0 returned
|
||||
- list()/count() immer leer/0
|
||||
- get_tracker() Singleton funktioniert weiterhin
|
||||
"""
|
||||
|
||||
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
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.archivar.subagent_tracker import (
|
||||
SubagentTracker,
|
||||
_get_subagent_state_path,
|
||||
_read_subagent_state,
|
||||
_write_subagent_state,
|
||||
get_tracker,
|
||||
SUBAGENT_STATE_DIR,
|
||||
SUBAGENT_STATE_FILENAME,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Fixtures
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@pytest.fixture
|
||||
def tmp_state_path():
|
||||
"""Create a temporary subagent_status.json for isolated testing."""
|
||||
fd, path = tempfile.mkstemp(suffix=".json", prefix="subagent_test_")
|
||||
os.close(fd)
|
||||
yield path
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tracker(tmp_state_path):
|
||||
"""Create a SubagentTracker with isolated state file."""
|
||||
return SubagentTracker(state_path=tmp_state_path)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 1: register ist no-op
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestRegisterIsNoOp:
|
||||
"""Test 1: register() ist no-op — schreibt keine Datei, list() bleibt leer."""
|
||||
|
||||
def test_register_does_not_write_file(self, tracker, tmp_state_path):
|
||||
"""Nach register() ist die Datei unverändert (kein Eintrag)."""
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
|
||||
# list() ist immer leer
|
||||
active = tracker.list()
|
||||
assert len(active) == 0
|
||||
|
||||
def test_register_returns_empty_dict(self, tracker):
|
||||
"""register() gibt leeres dict zurück."""
|
||||
entry = tracker.register("delegate_task", room_name="user:bernd")
|
||||
assert entry["task_id"] == ""
|
||||
assert entry["type"] == "delegate_task"
|
||||
|
||||
def test_register_multiple_still_empty(self, tracker):
|
||||
"""Mehrere register() → list() bleibt leer."""
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
tracker.register("terminal_background", room_name="user:alice")
|
||||
tracker.register("delegate_task", room_name="user:bernd")
|
||||
|
||||
assert tracker.list() == []
|
||||
assert tracker.count() == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 2: complete ist no-op
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestCompleteIsNoOp:
|
||||
"""Test 2: complete() ist no-op — returned immer 0."""
|
||||
|
||||
def test_complete_returns_zero(self, tracker):
|
||||
"""complete() returned immer 0."""
|
||||
remaining = tracker.complete("delegate_task")
|
||||
assert remaining == 0
|
||||
|
||||
def test_complete_by_task_id_returns_zero(self, tracker):
|
||||
"""complete(type, task_id) returned immer 0."""
|
||||
remaining = tracker.complete("delegate_task", task_id="id_1")
|
||||
assert remaining == 0
|
||||
|
||||
def test_complete_nonexistent_type_returns_zero(self, tracker):
|
||||
"""complete() eines nicht existierenden Typs → 0."""
|
||||
remaining = tracker.complete("nonexistent")
|
||||
assert remaining == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: list und count immer leer/0
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestListAndCount:
|
||||
"""Test 3: list() und count() sind immer leer/0."""
|
||||
|
||||
def test_list_empty_initially(self, tracker):
|
||||
"""Frischer Tracker hat leere Liste."""
|
||||
assert tracker.list() == []
|
||||
assert tracker.count() == 0
|
||||
|
||||
def test_count_always_zero(self, tracker):
|
||||
"""count() ist immer 0, auch nach register()."""
|
||||
tracker.register("delegate_task")
|
||||
tracker.register("terminal_background")
|
||||
assert tracker.count() == 0
|
||||
|
||||
def test_list_returns_empty_list(self, tracker):
|
||||
"""list() gibt immer leere Liste zurück."""
|
||||
tracker.register("delegate_task")
|
||||
active = tracker.list()
|
||||
assert active == []
|
||||
# Mutation ändert nichts
|
||||
active.append({"fake": "entry"})
|
||||
assert tracker.list() == []
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 4: _read_subagent_state immer leer
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestReadSubagentState:
|
||||
"""Test 4: _read_subagent_state() returned immer leeres dict."""
|
||||
|
||||
def test_read_returns_empty(self, tmp_state_path):
|
||||
"""_read_subagent_state() → leeres dict."""
|
||||
state = _read_subagent_state(tmp_state_path)
|
||||
assert state["active"] == []
|
||||
assert state["schema_version"] == 1
|
||||
|
||||
def test_read_ignores_file_content(self, tmp_state_path):
|
||||
"""Auch wenn die Datei Daten enthält → leeres dict."""
|
||||
with open(tmp_state_path, 'w') as f:
|
||||
json.dump({"active": [{"task_id": "t_1"}]}, f)
|
||||
|
||||
state = _read_subagent_state(tmp_state_path)
|
||||
assert state["active"] == []
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: clear_all ist no-op
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestClearAll:
|
||||
"""Test 5: clear_all() ist no-op."""
|
||||
|
||||
def test_clear_all_does_nothing(self, tracker):
|
||||
"""clear_all() wirft keinen Fehler."""
|
||||
tracker.clear_all()
|
||||
assert tracker.count() == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: Thread-safety (no-ops sind inhärent thread-safe)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestThreadSafety:
|
||||
"""Test 6: No-ops sind thread-safe."""
|
||||
|
||||
def test_concurrent_registers_no_errors(self, tracker):
|
||||
"""Parallele register() Aufrufe werfen keine Fehler."""
|
||||
errors = []
|
||||
|
||||
def register_many(n: int):
|
||||
try:
|
||||
for i in range(n):
|
||||
tracker.register("delegate_task", task_id=f"thread_{i}")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
threads = []
|
||||
for _ in range(4):
|
||||
t = threading.Thread(target=register_many, args=(25,))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert len(errors) == 0, f"Errors: {errors}"
|
||||
# No-ops → count immer 0
|
||||
assert tracker.count() == 0
|
||||
|
||||
def test_concurrent_register_and_complete_no_errors(self, tracker):
|
||||
"""Gleichzeitiges register() und complete() wirft keine Fehler."""
|
||||
errors = []
|
||||
|
||||
def register_more():
|
||||
try:
|
||||
for i in range(25):
|
||||
tracker.register("delegate_task", task_id=f"new_{i}")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
def complete_some():
|
||||
try:
|
||||
for i in range(25):
|
||||
tracker.complete("delegate_task", task_id=f"pre_{i}")
|
||||
except Exception as e:
|
||||
errors.append(e)
|
||||
|
||||
t1 = threading.Thread(target=register_more)
|
||||
t2 = threading.Thread(target=complete_some)
|
||||
t1.start()
|
||||
t2.start()
|
||||
t1.join()
|
||||
t2.join()
|
||||
|
||||
assert len(errors) == 0, f"Errors: {errors}"
|
||||
assert tracker.count() == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: Singleton get_tracker
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestGetTracker:
|
||||
"""Test 7: get_tracker() Singleton funktioniert weiterhin."""
|
||||
|
||||
def test_get_tracker_returns_same_instance(self):
|
||||
"""get_tracker() gibt immer dieselbe Instanz zurück."""
|
||||
t1 = get_tracker()
|
||||
t2 = get_tracker()
|
||||
assert t1 is t2
|
||||
|
||||
def test_get_tracker_is_subagent_tracker(self):
|
||||
"""get_tracker() gibt SubagentTracker-Instanz zurück."""
|
||||
t = get_tracker()
|
||||
assert isinstance(t, SubagentTracker)
|
||||
@@ -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")
|
||||
|
||||
@@ -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.)
|
||||
|
||||
Reference in New Issue
Block a user