fix(P1b): DetectionTimer pgrep-Pattern erweitert + gateway_state als Primärsignal

This commit is contained in:
Bernd (Hermes)
2026-07-24 09:06:40 +02:00
parent f61b0ba508
commit f028a30d6c
3 changed files with 94 additions and 59 deletions
+9
View File
@@ -1092,6 +1092,9 @@ class RocketChatAdapter(BasePlatformAdapter):
Sets initial online status and binds DDP to PulseController
if PresenceEngine is active (EC-1: on_connected_cb race).
P1b: Starts DetectionTimer after DDP connection is established
to prevent race condition with gateway_state.json.
"""
if self.ddp:
self.ddp.set_status("online")
@@ -1102,6 +1105,12 @@ class RocketChatAdapter(BasePlatformAdapter):
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
except Exception as e:
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e)
# P1b: DetectionTimer erst nach DDP-Connect starten
try:
self._presence_engine.start_detection()
logger.debug("[rocketchat] P1b: DetectionTimer gestartet (on_connected_cb)")
except Exception as e:
logger.debug("[rocketchat] P1b: DetectionTimer start failed: %s", e)
def _on_ddp_room_event(self, event: dict) -> None:
"""A1b: Callback für DDP rooms-changed Events.
+62 -34
View File
@@ -150,9 +150,10 @@ class PresenceEngine:
on_change=self._on_detection_change,
)
# Start detection if enabled
if self._enabled:
self._detection_timer.start()
# P1b: DetectionTimer NICHT im Init starten — erst nach on_connected_cb.
# Der Adapter ruft _detection_timer.start() explizit auf, sobald die
# DDP-Verbindung steht. Das verhindert eine Race-Condition bei der
# ersten gateway_state.json-Auswertung (Datei existiert ggf. noch nicht).
# ── Public API ───────────────────────────────────────────────────────
@@ -160,10 +161,20 @@ class PresenceEngine:
"""Check if presence updates are enabled."""
return self._enabled
def start_detection(self) -> None:
"""P1b: Start DetectionTimer — called after DDP connection is established.
Must be called explicitly by the adapter in on_connected_cb.
Prevents race condition where gateway_state.json doesn't exist yet
at PresenceEngine init time.
"""
if self._enabled:
self._detection_timer.start()
def enable(self) -> None:
"""Enable presence updates. Starts DetectionTimer."""
"""Enable presence updates. DetectionTimer must be started externally
via start_detection() after DDP connection is established."""
self._enabled = True
self._detection_timer.start()
logger.info("[presence] PresenceEngine enabled")
def disable(self) -> None:
@@ -810,8 +821,12 @@ class PulseController:
class DetectionTimer:
"""Detects whether background agents are active.
Checks gateway_state.json for active_agents > 1.
Falls back to pgrep for 'hermes chat --profile' processes.
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).
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
subprocesses). Self-pid exclude is preserved.
Calls on_change callback when detection state changes.
"""
@@ -870,53 +885,66 @@ 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.
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).
pgrep pattern expanded from 'hermes chat --profile' to
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
Self-pid exclude is preserved.
Returns:
True if pgrep finds other hermes chat processes (self-excluded),
False otherwise.
True if background agents are detected, False otherwise.
"""
self._check_count += 1
self._increment_telemetry()
result = False
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
# ── 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
gateway_used = False # True if gateway_state was the deciding signal
# ── PRIMARY: gateway_state.json ────────────────────────────────────
try:
if os.path.exists(self._gateway_state_path):
with open(self._gateway_state_path, 'r') as f:
state = json.load(f)
gateway_active = state.get("active_agents", 0)
if gateway_active > 1:
result = True
gateway_used = True
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fall through to pgrep
# ── SECONDARY: pgrep — run when gateway_state didn't decide ───────
if not gateway_used:
try:
own_pid = os.getpid()
# P1b: Expanded pattern catches subagents AND gateway subprocesses
proc = subprocess.run(
["pgrep", "-f", "hermes_cli|hermes chat"],
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)
# ── 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,
"[detection] check #%d: gateway_state=%d (primary=%s), pgrep=%s, result=%s",
self._check_count, gateway_active,
"yes" if gateway_used else "no",
pgrep_str,
"active" if result else "inactive",
)
+23 -25
View File
@@ -880,17 +880,17 @@ class TestPulseControllerLastSentPhase:
class TestDetectionTimerPgrepPrimary:
"""Test 20: DetectionTimer — pgrep als Primärsignal, gateway_state nur diagnostisch."""
"""Test 20: DetectionTimer — gateway_state PRIMARY, pgrep SECONDARY (P1b)."""
def test_pgrep_finds_other_agents(self):
"""pgrep findet andere hermes-Prozesse → result=True (gateway_state irrelevant)."""
"""gateway_state=1 (nicht >1) → pgrep-Fallback findet anderen Prozess → result=True."""
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)
# gateway_state mit active_agents=1 (nicht >1 → fällt auf pgrep zurück)
state = {"active_agents": 1, "profiles": ["default"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
@@ -910,50 +910,44 @@ class TestDetectionTimerPgrepPrimary:
detection_interval=0.1,
)
result = dt.check()
# pgrep findet anderen Prozess → True (gateway_state=1 wird ignoriert)
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
assert result is True
finally:
os.unlink(state_path)
def test_pgrep_finds_no_other_agents(self):
"""pgrep findet nur eigenen Prozess → result=False (gateway_state irrelevant)."""
def test_gateway_state_primary_active(self):
"""P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
own_pid = os.getpid()
# gateway_state mit active_agents=3 (würde früher True liefern)
# 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)
state_path = f.name
try:
# Mock pgrep: findet nur eigenen Prozess
# Mock pgrep: sollte NICHT aufgerufen werden
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
# gateway_state=3 > 1 → PRIMARY entscheidet → True
assert result is True
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
mock_run.assert_not_called()
finally:
os.unlink(state_path)
class TestDetectionTimerPgrepNoGatewayState:
"""Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json."""
"""Test 21: DetectionTimer pgrep-Fallback funktioniert auch ohne gateway_state.json (P1b)."""
def test_pgrep_works_without_gateway_state(self):
"""Wenn gateway_state.json nicht existiert, pgrep ist trotzdem Primärsignal."""
"""Wenn gateway_state.json nicht existiert, pgrep-Fallback greift."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
@@ -997,10 +991,10 @@ class TestDetectionTimerPgrepNoGatewayState:
class TestDetectionTimerIntegration:
"""Test 22: DetectionTimer start/stop + Callback (pgrep als Primärsignal)."""
"""Test 22: DetectionTimer start/stop + Callback (P1b: gateway_state PRIMARY, pgrep SECONDARY)."""
def test_detection_timer_start_stop(self):
"""DetectionTimer startet und stoppt korrekt, pgrep als Primärsignal."""
"""DetectionTimer startet und stoppt korrekt, pgrep-Fallback bei fehlendem gateway_state."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
@@ -1009,7 +1003,7 @@ class TestDetectionTimerIntegration:
def on_detection_change(is_active):
callback_results.append(is_active)
# Mock pgrep: findet anderen Prozess → True
# Mock pgrep: findet anderen Prozess → True (gateway_state fehlt → Fallback)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout=f"{own_pid}\n99999\n",
@@ -1264,7 +1258,7 @@ class TestP0LiveVerdrahtung:
assert not engine._pulse_controller.is_running()
def test_detection_timer_starts_when_enabled(self):
"""P0-5: DetectionTimer startet automatisch wenn enabled=True."""
"""P1b: DetectionTimer startet NICHT automatisch — muss via start_detection() gestartet werden."""
from plugin.archivar.presence_engine import PresenceEngine
mock_rest = MagicMock()
@@ -1273,7 +1267,11 @@ class TestP0LiveVerdrahtung:
engine = PresenceEngine(rest=mock_rest, enabled=True)
# DetectionTimer läuft (wurde in __init__ gestartet)
# P1b: DetectionTimer läuft NICHT nach __init__ (startet erst via start_detection())
assert not engine._detection_timer._running.is_set()
# start_detection() startet ihn
engine.start_detection()
assert engine._detection_timer._running.is_set()
def test_detection_timer_not_started_when_disabled(self):