From d9951fa822dd105b101687be2dc11feb14a8d98b Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 2 Aug 2026 12:28:53 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20Presence-Engine=20Stale-Recovery=20?= =?UTF-8?q?=E2=80=94=20complete()=20aus=20finally=20entfernt=20+=20PID-Tra?= =?UTF-8?q?cking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 5 Schritte: 1. adapter.py: complete('background_task') aus finally-Block entfernt. Der Turn endet bevor der Background-Prozess endet — register() beim Turn-Start bleibt, Stale-Recovery räumt tote Einträge auf. 2. subagent_tracker.py: register() speichert jetzt pid (os.getpid()) und expected_done_at (started_at + 600s). Neues remove_by_task_id() für Stale-Recovery durch DetectionTimer. 3. presence_engine.py DetectionTimer: _stale_recovery() prüft jeden aktiven Eintrag in subagent_status.json: - os.kill(pid, 0) + /proc// Fallback - PID tot → Eintrag entfernt - PID lebend + expected_done_at überschritten → Eintrag bleibt (long-running Task) 4. expected_done_at als Sekundär-Indikator: DetectionTimer nutzt es für Logging/Diagnose, aber PID ist der primäre Indikator. 5. Lock-Order dokumentiert: _busy_honeymoon_lock vor _mode_lock. Race-Bedingung zwischen Honeymoon-Expiry und set_pulse_target() explizit im PresenceEngine-Docstring dokumentiert. Tests: 40/40 passed (19 tracker + 21 presence, inkl. 5 neue Stale-Recovery-Tests) --- .../2026-07-31-f6-r27-quick-reply-dedup.md | 675 ++++++++++++++++++ plugin/adapter.py | 9 +- plugin/archivar/presence_engine.py | 111 ++- plugin/archivar/subagent_tracker.py | 46 +- .../tests/test_subagent_status_presence.py | 277 +++++++ 5 files changed, 1108 insertions(+), 10 deletions(-) create mode 100644 docs/plans/2026-07-31-f6-r27-quick-reply-dedup.md diff --git a/docs/plans/2026-07-31-f6-r27-quick-reply-dedup.md b/docs/plans/2026-07-31-f6-r27-quick-reply-dedup.md new file mode 100644 index 0000000..33455e4 --- /dev/null +++ b/docs/plans/2026-07-31-f6-r27-quick-reply-dedup.md @@ -0,0 +1,675 @@ +# 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). diff --git a/plugin/adapter.py b/plugin/adapter.py index 7c4fd1d..a94ca54 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -3589,12 +3589,9 @@ class RocketChatAdapter(BasePlatformAdapter): self._presence_engine.set_current_room("") logger.info("[presence] mark_busy_done (turn complete)") - # Phase 5: SubagentTracker — complete background task (symmetrisch zu register) - if _has_tracker: - try: - self._subagent_tracker.complete("background_task") - except Exception as e: - logger.debug("[subagent_tracker] complete failed (non-critical): %s", e) + # 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: diff --git a/plugin/archivar/presence_engine.py b/plugin/archivar/presence_engine.py index 9bef2ae..d470242 100644 --- a/plugin/archivar/presence_engine.py +++ b/plugin/archivar/presence_engine.py @@ -152,6 +152,23 @@ 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) @@ -1511,7 +1528,8 @@ class DetectionTimer: try: from archivar.subagent_tracker import _read_subagent_state, _get_subagent_state_path subagent_state = _read_subagent_state(_get_subagent_state_path()) - subagent_count = len(subagent_state.get("active", [])) + active_entries = subagent_state.get("active", []) + subagent_count = len(active_entries) if subagent_count > 0: result = True subagent_used = True @@ -1519,6 +1537,11 @@ class DetectionTimer: except Exception as e: logger.debug("[detection] subagent_status.json read failed: %s", e) + # ── Phase 5: Stale-Recovery — räumt tote PID-Einträge auf ────────── + # Läuft IMMER (nicht nur wenn subagent_used), damit auch Einträge + # aufgeräumt werden wenn PID-Sentinel oder gateway_state aktiv sind. + self._stale_recovery() + # ── P2 QUATERNARY: pgrep — erweitertes Pattern 'gateway run' ──────── if not pid_used and not gateway_used and not plugin_used and not subagent_used: try: @@ -1581,6 +1604,92 @@ class DetectionTimer: self._last_result = result return result + def _stale_recovery(self) -> int: + """Phase 5: Stale-Recovery — räumt tote PID-Einträge aus subagent_status.json. + + Für jeden aktiven Eintrag prüfen: + - os.kill(pid, 0) oder /proc// — lebt der Prozess noch? + - Wenn PID tot → Eintrag entfernen (remove_by_task_id) + - Wenn expected_done_at überschritten UND PID tot → aufräumen + - Wenn expected_done_at überschritten UND PID noch lebend → Eintrag bleibt + + Returns: + Number of entries removed. + """ + removed = 0 + try: + from archivar.subagent_tracker import ( + _read_subagent_state, _get_subagent_state_path, get_tracker, + ) + state = _read_subagent_state(_get_subagent_state_path()) + active = state.get("active", []) + if not active: + return 0 + + tracker = get_tracker() + now = datetime.now(timezone.utc) + + for entry in list(active): # iterate over copy + task_id = entry.get("task_id", "") + pid = entry.get("pid", 0) + if not task_id or not pid: + continue + + # Check if PID is alive + pid_alive = self._pid_is_alive(pid) + + if not pid_alive: + # PID is dead — always clean up + tracker.remove_by_task_id(task_id) + removed += 1 + logger.info( + "[detection] stale recovery: removed dead PID %d (task_id=%s)", + pid, task_id, + ) + else: + # PID is alive — check expected_done_at + expected_done_str = entry.get("expected_done_at", "") + if expected_done_str: + try: + expected_done = datetime.fromisoformat(expected_done_str) + if now > expected_done: + # expected_done_at überschritten, aber PID lebt noch + # → Eintrag bleibt (long-running Task) + logger.debug( + "[detection] stale recovery: task_id=%s pid=%d " + "exceeded expected_done_at but still alive — keeping", + task_id, pid, + ) + except (ValueError, TypeError): + pass + + except Exception as e: + logger.debug("[detection] stale recovery failed: %s", e) + + if removed > 0: + logger.info("[detection] stale recovery: removed %d stale entries", removed) + return removed + + @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// 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// check + return os.path.exists(f"/proc/{pid}") + def _detection_loop(self) -> None: """Background thread: periodically check for background agents.""" tick = 0 diff --git a/plugin/archivar/subagent_tracker.py b/plugin/archivar/subagent_tracker.py index 6669141..d88b20c 100644 --- a/plugin/archivar/subagent_tracker.py +++ b/plugin/archivar/subagent_tracker.py @@ -102,26 +102,37 @@ class SubagentTracker: self._state_path = state_path self._lock = threading.Lock() - def register(self, subagent_type: str, room_name: str = "", task_id: str = "") -> dict: + def register(self, subagent_type: str, room_name: str = "", task_id: str = "", pid: int = 0) -> dict: """Register a new active subagent. Args: subagent_type: One of 'delegate_task', 'terminal_background', 'task_management'. room_name: Owner room (e.g. 'user:bernd'). task_id: Optional task identifier. Auto-generated if empty. + pid: Process ID of the background task. Defaults to os.getpid(). Returns: The created entry dict. """ if not task_id: task_id = f"t_{int(time.time() * 1_000_000)}" + if not pid: + pid = os.getpid() + + now = datetime.now(timezone.utc) + expected_duration_s = 600 + expected_done_at = datetime.fromtimestamp( + now.timestamp() + expected_duration_s, tz=timezone.utc + ).isoformat() entry = { "task_id": task_id, "type": subagent_type, "owner_room": room_name, - "started_at": datetime.now(timezone.utc).isoformat(), - "expected_duration_s": 600, + "pid": pid, + "started_at": now.isoformat(), + "expected_duration_s": expected_duration_s, + "expected_done_at": expected_done_at, "plugin_state_source": "adapter.subagent_tracker", } @@ -173,6 +184,35 @@ class SubagentTracker: ) return len(active) + def remove_by_task_id(self, task_id: str) -> bool: + """Remove a subagent entry by task_id (for stale recovery). + + Used by DetectionTimer to clean up entries whose PID is dead. + + Args: + task_id: The task_id to remove. + + Returns: + True if an entry was removed, False if not found. + """ + with self._lock: + state = _read_subagent_state(self._state_path) + active = state.get("active", []) + original_len = len(active) + active = [e for e in active if e.get("task_id") != task_id] + removed = len(active) < original_len + + if removed: + state["active"] = active + state["last_change_iso"] = datetime.now(timezone.utc).isoformat() + _write_subagent_state(self._state_path, state) + logger.info( + "[subagent_tracker] stale recovery: removed task_id=%s, remaining=%d", + task_id, len(active), + ) + + return removed + def list(self) -> List[Dict]: """List all currently active subagent entries. diff --git a/plugin/archivar/tests/test_subagent_status_presence.py b/plugin/archivar/tests/test_subagent_status_presence.py index e9e3bf6..d7e063a 100644 --- a/plugin/archivar/tests/test_subagent_status_presence.py +++ b/plugin/archivar/tests/test_subagent_status_presence.py @@ -430,3 +430,280 @@ class TestReadSubagentCount: except OSError: pass assert engine._read_subagent_count() == 0 + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 9: Stale-Recovery — PID tot → Eintrag wird entfernt +# ═══════════════════════════════════════════════════════════════════════════ + +class TestStaleRecoveryPidDead: + """Test 9: Stale-Recovery entfernt Einträge mit toter PID.""" + + def test_pid_dead_entry_removed(self): + """Wenn PID tot ist, wird der Eintrag aus subagent_status.json entfernt.""" + from plugin.archivar.presence_engine import DetectionTimer + from plugin.archivar.subagent_tracker import ( + _write_subagent_state, _get_subagent_state_path, get_tracker, + ) + + subagent_path = _get_subagent_state_path() + tracker = get_tracker() + + # Schreibe einen Eintrag mit einer garantiert toten PID (99999) + _write_subagent_state(subagent_path, { + "active": [{ + "task_id": "t_dead_pid", + "type": "background_task", + "owner_room": "user:bernd", + "pid": 99999, + "started_at": "2025-01-01T00:00:00+00:00", + "expected_duration_s": 600, + "expected_done_at": "2025-01-01T00:10:00+00:00", + "plugin_state_source": "adapter.subagent_tracker", + }], + "last_change_iso": "", + "schema_version": 1, + "source": "plugin_internal", + }) + + # Verify entry exists + assert tracker.count() == 1 + + # Create DetectionTimer and run stale recovery + 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, + ) + removed = timer._stale_recovery() + + # PID 99999 ist tot → sollte entfernt worden sein + assert removed == 1, f"Expected 1 removed, got {removed}" + assert tracker.count() == 0, f"Expected 0 entries, got {tracker.count()}" + finally: + os.unlink(gateway_path) + # Cleanup + try: + os.unlink(subagent_path) + except OSError: + pass + + def test_pid_dead_multiple_entries_cleanup(self): + """Mehrere tote PIDs → alle werden entfernt.""" + from plugin.archivar.presence_engine import DetectionTimer + from plugin.archivar.subagent_tracker import ( + _write_subagent_state, _get_subagent_state_path, get_tracker, + ) + + subagent_path = _get_subagent_state_path() + tracker = get_tracker() + + _write_subagent_state(subagent_path, { + "active": [ + { + "task_id": "t_dead_1", + "type": "background_task", + "pid": 99998, + "started_at": "2025-01-01T00:00:00+00:00", + "expected_duration_s": 600, + "expected_done_at": "2025-01-01T00:10:00+00:00", + }, + { + "task_id": "t_dead_2", + "type": "delegate_task", + "pid": 99997, + "started_at": "2025-01-01T00:00:00+00:00", + "expected_duration_s": 600, + "expected_done_at": "2025-01-01T00:10:00+00:00", + }, + ], + "last_change_iso": "", + "schema_version": 1, + "source": "plugin_internal", + }) + + assert tracker.count() == 2 + + 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, + ) + removed = timer._stale_recovery() + + assert removed == 2, f"Expected 2 removed, got {removed}" + assert tracker.count() == 0 + finally: + os.unlink(gateway_path) + try: + os.unlink(subagent_path) + except OSError: + pass + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 10: Stale-Recovery — PID lebend → Eintrag bleibt +# ═══════════════════════════════════════════════════════════════════════════ + +class TestStaleRecoveryPidAlive: + """Test 10: Stale-Recovery lässt Einträge mit lebender PID in Ruhe.""" + + def test_pid_alive_entry_kept(self): + """Wenn PID lebt, bleibt der Eintrag erhalten.""" + from plugin.archivar.presence_engine import DetectionTimer + from plugin.archivar.subagent_tracker import ( + _write_subagent_state, _get_subagent_state_path, get_tracker, + ) + + subagent_path = _get_subagent_state_path() + tracker = get_tracker() + + # Nutze die eigene PID (dieser Testprozess lebt garantiert) + own_pid = os.getpid() + + _write_subagent_state(subagent_path, { + "active": [{ + "task_id": "t_alive_pid", + "type": "background_task", + "owner_room": "user:bernd", + "pid": own_pid, + "started_at": "2025-01-01T00:00:00+00:00", + "expected_duration_s": 600, + "expected_done_at": "2099-01-01T00:00:00+00:00", # weit in der Zukunft + "plugin_state_source": "adapter.subagent_tracker", + }], + "last_change_iso": "", + "schema_version": 1, + "source": "plugin_internal", + }) + + assert tracker.count() == 1 + + 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, + ) + removed = timer._stale_recovery() + + # Eigene PID lebt → kein Eintrag entfernt + assert removed == 0, f"Expected 0 removed, got {removed}" + assert tracker.count() == 1, f"Expected 1 entry, got {tracker.count()}" + finally: + os.unlink(gateway_path) + try: + os.unlink(subagent_path) + except OSError: + pass + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 11: Stale-Recovery — expected_done_at überschritten + PID tot +# ═══════════════════════════════════════════════════════════════════════════ + +class TestStaleRecoveryExpectedDoneAt: + """Test 11: expected_done_at als Sekundär-Indikator.""" + + def test_expected_done_at_exceeded_pid_dead_removed(self): + """expected_done_at überschritten + PID tot → Eintrag entfernt.""" + from plugin.archivar.presence_engine import DetectionTimer + from plugin.archivar.subagent_tracker import ( + _write_subagent_state, _get_subagent_state_path, get_tracker, + ) + + subagent_path = _get_subagent_state_path() + tracker = get_tracker() + + # expected_done_at in der Vergangenheit + tote PID + _write_subagent_state(subagent_path, { + "active": [{ + "task_id": "t_expired_dead", + "type": "background_task", + "owner_room": "user:bernd", + "pid": 99996, + "started_at": "2025-01-01T00:00:00+00:00", + "expected_duration_s": 600, + "expected_done_at": "2025-01-01T00:10:00+00:00", # lange überschritten + "plugin_state_source": "adapter.subagent_tracker", + }], + "last_change_iso": "", + "schema_version": 1, + "source": "plugin_internal", + }) + + assert tracker.count() == 1 + + 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, + ) + removed = timer._stale_recovery() + + # PID tot → entfernt (expected_done_at ist sekundär, PID ist primär) + assert removed == 1, f"Expected 1 removed, got {removed}" + assert tracker.count() == 0 + finally: + os.unlink(gateway_path) + try: + os.unlink(subagent_path) + except OSError: + pass + + def test_expected_done_at_exceeded_pid_alive_kept(self): + """expected_done_at überschritten aber PID lebt → Eintrag bleibt (long-running).""" + from plugin.archivar.presence_engine import DetectionTimer + from plugin.archivar.subagent_tracker import ( + _write_subagent_state, _get_subagent_state_path, get_tracker, + ) + + subagent_path = _get_subagent_state_path() + tracker = get_tracker() + + own_pid = os.getpid() + + # expected_done_at in der Vergangenheit, aber PID lebt + _write_subagent_state(subagent_path, { + "active": [{ + "task_id": "t_long_running", + "type": "background_task", + "owner_room": "user:bernd", + "pid": own_pid, + "started_at": "2025-01-01T00:00:00+00:00", + "expected_duration_s": 600, + "expected_done_at": "2025-01-01T00:10:00+00:00", # überschritten + "plugin_state_source": "adapter.subagent_tracker", + }], + "last_change_iso": "", + "schema_version": 1, + "source": "plugin_internal", + }) + + assert tracker.count() == 1 + + 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, + ) + removed = timer._stale_recovery() + + # PID lebt → Eintrag bleibt, auch wenn expected_done_at überschritten + assert removed == 0, f"Expected 0 removed, got {removed}" + assert tracker.count() == 1, f"Expected 1 entry, got {tracker.count()}" + finally: + os.unlink(gateway_path) + try: + os.unlink(subagent_path) + except OSError: + pass