From 998ed2cedd5e769d58588cd3c68d1a91c3478a9b Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 26 Jul 2026 05:57:54 +0200 Subject: [PATCH] =?UTF-8?q?feat(p1-2):=20DetectionTimer=20erkennt=20Plugin?= =?UTF-8?q?-State-Datei=20(background=5Ftasks=20>=200=20=E2=86=92=20active?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/archivar/presence_engine.py | 63 +++++++- plugin/archivar/routing_telemetry.py | 2 + plugin/archivar/tests/test_presence_engine.py | 140 ++++++++++++++++++ 3 files changed, 197 insertions(+), 8 deletions(-) diff --git a/plugin/archivar/presence_engine.py b/plugin/archivar/presence_engine.py index ea8a0af..9c66368 100644 --- a/plugin/archivar/presence_engine.py +++ b/plugin/archivar/presence_engine.py @@ -1054,8 +1054,9 @@ class DetectionTimer: """Detects whether background agents are active. P1b: gateway_state.json is PRIMARY — active_agents > 1 means active. - pgrep is SECONDARY/CONFIRM — used as fallback when gateway_state is - unavailable or returns 0/1 (ambiguous). + P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active. + pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and + plugin_state are unavailable or return 0/1 (ambiguous). pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway subprocesses). Self-pid exclude is preserved. @@ -1068,6 +1069,7 @@ class DetectionTimer: gateway_state_path: str = "", detection_interval: float = 10.0, on_change: Optional[Callable[[bool], None]] = None, + plugin_state_path: str = "", ): """Initialize DetectionTimer. @@ -1075,6 +1077,8 @@ class DetectionTimer: gateway_state_path: Path to gateway_state.json. detection_interval: Check interval in seconds (default 10). on_change: Callback(is_active) when detection state changes. + plugin_state_path: P1-2: Path to plugin state file. Defaults to + ~/.hermes/plugin_state/hermes_rocket_plugin.json. """ if not gateway_state_path: gateway_state_path = os.environ.get( @@ -1082,6 +1086,12 @@ class DetectionTimer: os.path.expanduser("~/.hermes/gateway_state.json"), ) self._gateway_state_path = gateway_state_path + + # P1-2: Plugin-State-Datei für Gateway-interne Subagenten + if not plugin_state_path: + plugin_state_path = _get_plugin_state_path() + self._plugin_state_path = plugin_state_path + self._detection_interval = detection_interval self._on_change = on_change self._thread: Optional[threading.Thread] = None @@ -1118,8 +1128,9 @@ class DetectionTimer: """Check if background agents are active. P1b: gateway_state.json is PRIMARY — active_agents > 1 means active. - pgrep is SECONDARY/CONFIRM — used as fallback when gateway_state is - unavailable or returns 0/1 (ambiguous). + P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active. + pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and + plugin_state are unavailable or return 0/1 (ambiguous). pgrep pattern expanded from 'hermes chat --profile' to 'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses. @@ -1135,6 +1146,9 @@ class DetectionTimer: pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error gateway_active = 0 gateway_used = False # True if gateway_state was the deciding signal + plugin_used = False # P1-2: True if plugin_state was the deciding signal + plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count + detection_source = "none" # P1-2: which signal decided # ── PRIMARY: gateway_state.json ──────────────────────────────────── try: @@ -1145,12 +1159,22 @@ class DetectionTimer: if gateway_active > 1: result = True gateway_used = True + detection_source = "gateway" except (json.JSONDecodeError, IOError, OSError) as e: logger.debug("[detection] gateway_state.json read failed: %s", e) - # Fall through to pgrep + # Fall through to plugin_state - # ── SECONDARY: pgrep — run when gateway_state didn't decide ─────── + # ── P1-2: SECONDARY: plugin_state.json ───────────────────────────── if not gateway_used: + plugin_state = _read_plugin_state(self._plugin_state_path) + plugin_bg_tasks = plugin_state.get("background_tasks", 0) + if plugin_bg_tasks > 0: + result = True + plugin_used = True + detection_source = "plugin_state" + + # ── TERTIARY: pgrep — run when neither gateway nor plugin decided ── + if not gateway_used and not plugin_used: try: own_pid = os.getpid() # P1b: Expanded pattern catches subagents AND gateway subprocesses @@ -1166,20 +1190,31 @@ class DetectionTimer: pids = [p for p in all_pids if p != own_pid] pgrep_pids = len(pids) result = pgrep_pids > 0 + if result: + detection_source = "pgrep" except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: logger.debug("[detection] pgrep failed: %s", e) # pgrep_pids stays -1 (error sentinel) - # ── Log: both signals, result ───────────────────────────────────── + # ── Log: all signals, result, source ─────────────────────────────── pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error" + plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a" logger.info( - "[detection] check #%d: gateway_state=%d (primary=%s), pgrep=%s, result=%s", + "[detection] check #%d: gateway_state=%d (primary=%s), " + "plugin_state=%s (bg_tasks=%s), pgrep=%s, " + "result=%s, source=%s", self._check_count, gateway_active, "yes" if gateway_used else "no", + "yes" if plugin_used else "no", + plugin_str, pgrep_str, "active" if result else "inactive", + detection_source, ) + # P1-2: Set telemetry source + self._set_detection_source_telemetry(detection_source) + # Notify on change (P1-2: callback fires from check() itself) if result != self._last_result and self._on_change is not None: try: @@ -1227,3 +1262,15 @@ class DetectionTimer: routing_telemetry.heartbeat_detection += 1 except Exception: pass + + def _set_detection_source_telemetry(self, source: str) -> None: + """P1-2: Set the heartbeat_detection_source telemetry field. + + Args: + source: One of 'gateway', 'plugin_state', 'pgrep', 'none'. + """ + try: + from archivar.routing_telemetry import routing_telemetry + routing_telemetry.heartbeat_detection_source = source + except Exception: + pass diff --git a/plugin/archivar/routing_telemetry.py b/plugin/archivar/routing_telemetry.py index 13b7603..10c586e 100644 --- a/plugin/archivar/routing_telemetry.py +++ b/plugin/archivar/routing_telemetry.py @@ -52,6 +52,8 @@ class RoutingTelemetry: # Heartbeat-Pulsierung Telemetrie self.heartbeat_pulse: int = 0 self.heartbeat_detection: int = 0 + # P1-2: Detection source tracking + self.heartbeat_detection_source: str = "none" @staticmethod def _read_feature_flag() -> bool: diff --git a/plugin/archivar/tests/test_presence_engine.py b/plugin/archivar/tests/test_presence_engine.py index ef1da18..140208b 100644 --- a/plugin/archivar/tests/test_presence_engine.py +++ b/plugin/archivar/tests/test_presence_engine.py @@ -1909,3 +1909,143 @@ class TestPluginStatePersistence: state = _read_plugin_state(state_path) assert state["background_tasks"] == 0 + + +# ═══════════════════════════════════════════════════════════════════════════ +# P1-2: DetectionTimer erkennt Plugin-State-Datei +# ═══════════════════════════════════════════════════════════════════════════ + + +class TestDetectionTimerPluginState: + """P1-2: DetectionTimer erkennt Plugin-State-Datei.""" + + def test_plugin_state_background_tasks_positive_detected(self, tmp_path): + """Plugin-State mit background_tasks=3 → check() returns True.""" + from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state + + state_path = str(tmp_path / "hermes_rocket_plugin.json") + os.makedirs(os.path.dirname(state_path), exist_ok=True) + _write_plugin_state(state_path, { + "background_tasks": 3, + "last_update_iso": "2026-01-01T00:00:00", + "source": "plugin_internal", + "schema_version": 1, + }) + + dt = DetectionTimer( + gateway_state_path="/tmp/nonexistent_gateway_state.json", + detection_interval=0.1, + plugin_state_path=state_path, + ) + result = dt.check() + assert result is True + + def test_plugin_state_background_tasks_zero_not_detected(self, tmp_path): + """Plugin-State mit background_tasks=0 → check() fällt auf pgrep zurück.""" + from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state + + state_path = str(tmp_path / "hermes_rocket_plugin.json") + os.makedirs(os.path.dirname(state_path), exist_ok=True) + _write_plugin_state(state_path, { + "background_tasks": 0, + "last_update_iso": "2026-01-01T00:00:00", + "source": "plugin_internal", + "schema_version": 1, + }) + + own_pid = os.getpid() + with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: + mock_run.return_value = MagicMock( + stdout=f"{own_pid}\n", + stderr="", + returncode=0, + ) + dt = DetectionTimer( + gateway_state_path="/tmp/nonexistent_gateway_state.json", + detection_interval=0.1, + plugin_state_path=state_path, + ) + result = dt.check() + # background_tasks=0, gateway_state fehlt, pgrep nur self → False + assert result is False + + def test_plugin_state_missing_file_no_error(self): + """Plugin-State-Datei fehlt → kein Fehler, fällt zurück auf gateway_state+pgrep.""" + from plugin.archivar.presence_engine import DetectionTimer + + own_pid = os.getpid() + with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: + mock_run.return_value = MagicMock( + stdout=f"{own_pid}\n99999\n", + stderr="", + returncode=0, + ) + dt = DetectionTimer( + gateway_state_path="/tmp/nonexistent_gateway_state.json", + detection_interval=0.1, + plugin_state_path="/tmp/nonexistent_plugin_state.json", + ) + result = dt.check() + # pgrep findet anderen Prozess → True + assert result is True + + def test_plugin_state_corrupt_json_no_crash(self, tmp_path): + """Korrupte Plugin-State-Datei → kein Crash, graceful fallback.""" + from plugin.archivar.presence_engine import DetectionTimer + + state_path = str(tmp_path / "hermes_rocket_plugin.json") + os.makedirs(os.path.dirname(state_path), exist_ok=True) + # Schreibe korruptes JSON + with open(state_path, 'w') as f: + f.write("{invalid json {{{") + + own_pid = os.getpid() + with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: + mock_run.return_value = MagicMock( + stdout=f"{own_pid}\n99999\n", + stderr="", + returncode=0, + ) + dt = DetectionTimer( + gateway_state_path="/tmp/nonexistent_gateway_state.json", + detection_interval=0.1, + plugin_state_path=state_path, + ) + result = dt.check() + # Sollte nicht crashen, pgrep findet anderen Prozess → True + assert result is True + + def test_plugin_state_priority_after_gateway(self, tmp_path): + """Plugin-State wird NACH gateway_state geprüft (gateway hat Vorrang).""" + from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state + import tempfile, json + + # gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet) + state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]} + with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: + json.dump(state, f) + gw_path = f.name + + try: + # Plugin-State mit background_tasks=0 (würde allein nicht reichen) + plugin_path = str(tmp_path / "hermes_rocket_plugin.json") + os.makedirs(os.path.dirname(plugin_path), exist_ok=True) + _write_plugin_state(plugin_path, { + "background_tasks": 0, + "last_update_iso": "2026-01-01T00:00:00", + "source": "plugin_internal", + "schema_version": 1, + }) + + with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run: + dt = DetectionTimer( + gateway_state_path=gw_path, + detection_interval=0.1, + plugin_state_path=plugin_path, + ) + result = dt.check() + # gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen) + assert result is True + mock_run.assert_not_called() + finally: + os.unlink(gw_path)