From 7657cd3665ac4cd3279d6d0f5c67ca010f988ccd Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Thu, 23 Jul 2026 19:04:38 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20DetectionTimer=20pgrep=20als=20Prim?= =?UTF-8?q?=C3=A4rsignal=20=E2=80=94=20gateway=5Fstate=20unbrauchbar=20fue?= =?UTF-8?q?r=20Subagenten-Erkennung?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/archivar/presence_engine.py | 79 +++--- plugin/archivar/tests/test_presence_engine.py | 236 ++++++++++-------- 2 files changed, 170 insertions(+), 145 deletions(-) diff --git a/plugin/archivar/presence_engine.py b/plugin/archivar/presence_engine.py index 7a09509..bbbab71 100644 --- a/plugin/archivar/presence_engine.py +++ b/plugin/archivar/presence_engine.py @@ -704,66 +704,55 @@ class DetectionTimer: def check(self) -> bool: """Check if background agents are active. + pgrep is the PRIMARY signal — always executed, regardless of gateway_state. + gateway_state is SECONDARY — read only for diagnostic logging, never for decisions. + Returns: - True if active_agents > 1 (background agent active), + True if pgrep finds other hermes chat processes (self-excluded), False otherwise. """ self._check_count += 1 self._increment_telemetry() result = False - source = "none" + pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error - # Try gateway_state.json first + # ── PRIMARY: pgrep — ALWAYS run ────────────────────────────────── + try: + own_pid = os.getpid() + proc = subprocess.run( + ["pgrep", "-f", "hermes chat --profile"], + 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 + except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: + logger.debug("[detection] pgrep failed: %s", e) + # pgrep_pids stays -1 (error sentinel) + + # ── SECONDARY: gateway_state — diagnostic only ──────────────────── + gateway_active = 0 try: if os.path.exists(self._gateway_state_path): with open(self._gateway_state_path, 'r') as f: state = json.load(f) - active = state.get("active_agents", 0) - result = active > 1 - source = "gateway_state" - logger.info( - "[detection] check #%d: gateway_state=%d, result=%s", - self._check_count, active, "active" if result else "inactive", - ) + gateway_active = state.get("active_agents", 0) except (json.JSONDecodeError, IOError, OSError) as e: logger.debug("[detection] gateway_state.json read failed: %s", e) - # Fallback: pgrep (only if gateway_state didn't produce a result) - if source == "none": - try: - own_pid = os.getpid() - proc = subprocess.run( - ["pgrep", "-f", "hermes chat --profile"], - 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] - result = len(pids) > 0 - source = "pgrep" - logger.info( - "[detection] check #%d: pgrep=%d pids (self-excluded), result=%s", - self._check_count, len(pids), "active" if result else "inactive", - ) - except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: - logger.debug("[detection] pgrep fallback failed: %s", e) - result = False - source = "pgrep_error" - logger.info( - "[detection] check #%d: detection unavailable (pgrep failed)", - self._check_count, - ) - - # If no source produced a result, log inactive - if source == "none": - logger.info( - "[detection] check #%d: no background activity detected", - self._check_count, - ) + # ── Log: both signals, result ───────────────────────────────────── + pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error" + logger.info( + "[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s", + self._check_count, pgrep_str, gateway_active, + "active" if result else "inactive", + ) # Notify on change (P1-2: callback fires from check() itself) if result != self._last_result and self._on_change is not None: diff --git a/plugin/archivar/tests/test_presence_engine.py b/plugin/archivar/tests/test_presence_engine.py index 57317dc..cf07e6c 100644 --- a/plugin/archivar/tests/test_presence_engine.py +++ b/plugin/archivar/tests/test_presence_engine.py @@ -879,104 +879,146 @@ class TestPulseControllerLastSentPhase: # ═══════════════════════════════════════════════════════════════════════════ -class TestDetectionTimerGatewayState: - """Test 20: DetectionTimer liest gateway_state.json.""" +class TestDetectionTimerPgrepPrimary: + """Test 20: DetectionTimer — pgrep als Primärsignal, gateway_state nur diagnostisch.""" - def test_detection_from_gateway_state(self): - """DetectionTimer erkennt aktive Agents aus gateway_state.json.""" + def test_pgrep_finds_other_agents(self): + """pgrep findet andere hermes-Prozesse → result=True (gateway_state irrelevant).""" from plugin.archivar.presence_engine import DetectionTimer import tempfile import json - # Erstelle gateway_state.json mit active_agents > 1 - state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]} - with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: - json.dump(state, f) - state_path = f.name - - try: - dt = DetectionTimer( - gateway_state_path=state_path, - detection_interval=0.1, - ) - result = dt.check() - assert result is True # active_agents > 1 - finally: - os.unlink(state_path) - - def test_detection_single_agent(self): - """DetectionTimer erkennt wenn nur ein Agent aktiv ist.""" - from plugin.archivar.presence_engine import DetectionTimer - import tempfile - import json + own_pid = os.getpid() + # gateway_state mit active_agents=1 (würde früher False liefern) state = {"active_agents": 1, "profiles": ["default"]} with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: json.dump(state, f) state_path = f.name try: - dt = DetectionTimer( - gateway_state_path=state_path, - detection_interval=0.1, - ) - result = dt.check() - assert result is False # nur ein Agent + # 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() + # pgrep findet anderen Prozess → True (gateway_state=1 wird ignoriert) + assert result is True finally: os.unlink(state_path) - -class TestDetectionTimerPgrepFallback: - """Test 21: DetectionTimer pgrep-Fallback.""" - - def test_pgrep_fallback_when_no_gateway_state(self): - """Wenn gateway_state.json nicht existiert, wird pgrep verwendet.""" - from plugin.archivar.presence_engine import DetectionTimer - - dt = DetectionTimer( - gateway_state_path="/tmp/nonexistent_gateway_state.json", - detection_interval=0.1, - ) - # Sollte nicht crashen, sondern pgrep-Fallback nutzen - result = dt.check() - # Ergebnis ist bool (True/False) - assert isinstance(result, bool) - - def test_pgrep_fallback_returns_bool(self): - """pgrep-Fallback liefert immer bool zurück.""" - from plugin.archivar.presence_engine import DetectionTimer - - dt = DetectionTimer( - gateway_state_path="/tmp/nonexistent_gateway_state.json", - detection_interval=0.1, - ) - result = dt.check() - assert result is True or result is False - - -class TestDetectionTimerIntegration: - """Test 22: DetectionTimer start/stop + Callback.""" - - def test_detection_timer_start_stop(self): - """DetectionTimer startet und stoppt korrekt.""" + def test_pgrep_finds_no_other_agents(self): + """pgrep findet nur eigenen Prozess → result=False (gateway_state irrelevant).""" from plugin.archivar.presence_engine import DetectionTimer import tempfile import json - # Erstelle gateway_state.json mit active_agents > 1 (True) + own_pid = os.getpid() + + # gateway_state mit active_agents=3 (würde früher True liefern) state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]} with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: json.dump(state, f) state_path = f.name + try: + # 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=state_path, + detection_interval=0.1, + ) + result = dt.check() + # pgrep findet nur eigenen Prozess → False (gateway_state=3 wird ignoriert) + assert result is False + finally: + os.unlink(state_path) + + +class TestDetectionTimerPgrepNoGatewayState: + """Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json.""" + + def test_pgrep_works_without_gateway_state(self): + """Wenn gateway_state.json nicht existiert, pgrep ist trotzdem Primärsignal.""" + from plugin.archivar.presence_engine import DetectionTimer + + 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 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 + + 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, + ) + result = dt.check() + assert result is True or result is False + + +class TestDetectionTimerIntegration: + """Test 22: DetectionTimer start/stop + Callback (pgrep als Primärsignal).""" + + def test_detection_timer_start_stop(self): + """DetectionTimer startet und stoppt korrekt, pgrep als Primärsignal.""" + from plugin.archivar.presence_engine import DetectionTimer + + own_pid = os.getpid() callback_results = [] def on_detection_change(is_active): callback_results.append(is_active) - try: + # Mock pgrep: findet anderen Prozess → True + 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, + gateway_state_path="/tmp/nonexistent_gateway_state.json", detection_interval=0.1, on_change=on_detection_change, ) @@ -989,8 +1031,6 @@ class TestDetectionTimerIntegration: # Alle Ergebnisse sind bool for r in callback_results: assert isinstance(r, bool) - finally: - os.unlink(state_path) # ═══════════════════════════════════════════════════════════════════════════ @@ -1304,65 +1344,61 @@ class TestDetectionTimerPgrepSelfExclude: class TestDetectionTimerOnChangeCallback: - """P1-2: DetectionTimer on_change callback feuert bei Zustandswechsel.""" + """P1-2: DetectionTimer on_change callback feuert bei pgrep-Zustandswechsel.""" def test_on_change_callback_fires_on_state_change(self): - """Mock gateway_state: active_agents wechselt → on_change feuert.""" + """Mock pgrep: Prozesse erscheinen/verschwinden → on_change feuert.""" from plugin.archivar.presence_engine import DetectionTimer - import tempfile - import json - - # Start with active_agents=1 (inactive) - state_inactive = {"active_agents": 1} - with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: - json.dump(state_inactive, f) - state_path = f.name + own_pid = os.getpid() callback_results = [] def on_change(is_active): callback_results.append(is_active) - try: + # 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('plugin.archivar.presence_engine.subprocess.run') as mock_run: + mock_run.side_effect = mock_results + dt = DetectionTimer( - gateway_state_path=state_path, + gateway_state_path="/tmp/nonexistent_gateway_state.json", detection_interval=0.1, on_change=on_change, ) - # First check: active_agents=1 → False (no callback, _last_result starts 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 # No change from initial False + assert len(callback_results) == 0 - # Now change gateway_state to active_agents=3 - state_active = {"active_agents": 3} - with open(state_path, 'w') as f: - json.dump(state_active, f) - - # Second check: active_agents=3 → True (callback fires: 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 - # Third check: still active_agents=3 → True (no callback, no change) + # Check 3: immer noch da → True (kein Callback, kein Wechsel) result3 = dt.check() assert result3 is True - assert len(callback_results) == 1 # No new callback + assert len(callback_results) == 1 - # Change back to inactive - with open(state_path, 'w') as f: - json.dump(state_inactive, f) - - # Fourth check: active_agents=1 → False (callback fires: 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 - finally: - os.unlink(state_path) - class TestPulseControllerStartWithoutDdp: """P1-1: PulseController.start() ohne DDP-Bindung → log warning, kein Crash."""