""" 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