Files
Hermes_rocket.chat_Plugin/plugin/archivar/tests/test_subagent_status_presence.py
T
Bernd (Hermes) 30015f0cfe feat: V8.7 pgrep-basierte Subagent-Erkennung ersetzt subagent_status.json
- adapter.py: register()-Block entfernt (wurde bei jedem Turn aufgerufen)
- subagent_tracker.py: register()/complete() zu no-ops, Modul bleibt kompatibel
- presence_engine.py: _pgrep_hermes_subagents() scannt /proc/*/cmdline
  nach 'hermes chat --profile' Prozessen (exkl. eigene PID, <1ms)
- DetectionTimer.check(): pgrep als vierte Quelle (nach PID-Sentinel,
  gateway_state, plugin_state), ersetzt subagent_status.json
- _stale_recovery() entfernt (pgrep braucht kein Cleanup)
- _read_subagent_count() delegiert an _pgrep_hermes_subagents()
- subprocess-Import entfernt
- 1434 Tests grün (test_subagent_tracker, test_subagent_status_presence,
  test_presence_engine alle angepasst)
2026-08-02 13:24:10 +02:00

515 lines
22 KiB
Python

"""
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."""
def test_pgrep_finds_hermes_chat_profile_process(self):
"""_pgrep_hermes_subagents() findet einen simulierten hermes-Prozess."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
# Mock /proc: nur ein simulierter hermes chat --profile Prozess
mock_proc_entries = ["1", "2", str(own_pid), "99999", "12345"]
def mock_cmdline_read(pid_dir):
"""Simuliere /proc/<pid>/cmdline."""
if pid_dir == "12345":
return b"python\x00hermes\x00chat\x00--profile\x00miguel\x00--model\x00deepseek\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:
# Simuliere open() für /proc/<pid>/cmdline
def open_side_effect(path, mode="r"):
# Extrahiere PID aus Pfad: /proc/<pid>/cmdline
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
count = DetectionTimer._pgrep_hermes_subagents()
# Sollte 1 Prozess finden (PID 12345, nicht own_pid)
assert count == 1, f"Expected 1, 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
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"python\x00hermes\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
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"python\x00hermes\x00serve\x00" # hermes aber kein chat
elif pid_dir == "66666":
return b"python\x00chat\x00--profile\x00" # chat aber kein hermes
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
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
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