fix(P1b): DetectionTimer pgrep-Pattern erweitert + gateway_state als Primärsignal
This commit is contained in:
@@ -1092,6 +1092,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
Sets initial online status and binds DDP to PulseController
|
Sets initial online status and binds DDP to PulseController
|
||||||
if PresenceEngine is active (EC-1: on_connected_cb race).
|
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:
|
if self.ddp:
|
||||||
self.ddp.set_status("online")
|
self.ddp.set_status("online")
|
||||||
@@ -1102,6 +1105,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", 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:
|
def _on_ddp_room_event(self, event: dict) -> None:
|
||||||
"""A1b: Callback für DDP rooms-changed Events.
|
"""A1b: Callback für DDP rooms-changed Events.
|
||||||
|
|||||||
@@ -150,9 +150,10 @@ class PresenceEngine:
|
|||||||
on_change=self._on_detection_change,
|
on_change=self._on_detection_change,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Start detection if enabled
|
# P1b: DetectionTimer NICHT im Init starten — erst nach on_connected_cb.
|
||||||
if self._enabled:
|
# Der Adapter ruft _detection_timer.start() explizit auf, sobald die
|
||||||
self._detection_timer.start()
|
# DDP-Verbindung steht. Das verhindert eine Race-Condition bei der
|
||||||
|
# ersten gateway_state.json-Auswertung (Datei existiert ggf. noch nicht).
|
||||||
|
|
||||||
# ── Public API ───────────────────────────────────────────────────────
|
# ── Public API ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -160,10 +161,20 @@ class PresenceEngine:
|
|||||||
"""Check if presence updates are enabled."""
|
"""Check if presence updates are enabled."""
|
||||||
return self._enabled
|
return self._enabled
|
||||||
|
|
||||||
def enable(self) -> None:
|
def start_detection(self) -> None:
|
||||||
"""Enable presence updates. Starts DetectionTimer."""
|
"""P1b: Start DetectionTimer — called after DDP connection is established.
|
||||||
self._enabled = True
|
|
||||||
|
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()
|
self._detection_timer.start()
|
||||||
|
|
||||||
|
def enable(self) -> None:
|
||||||
|
"""Enable presence updates. DetectionTimer must be started externally
|
||||||
|
via start_detection() after DDP connection is established."""
|
||||||
|
self._enabled = True
|
||||||
logger.info("[presence] PresenceEngine enabled")
|
logger.info("[presence] PresenceEngine enabled")
|
||||||
|
|
||||||
def disable(self) -> None:
|
def disable(self) -> None:
|
||||||
@@ -810,8 +821,12 @@ class PulseController:
|
|||||||
class DetectionTimer:
|
class DetectionTimer:
|
||||||
"""Detects whether background agents are active.
|
"""Detects whether background agents are active.
|
||||||
|
|
||||||
Checks gateway_state.json for active_agents > 1.
|
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||||
Falls back to pgrep for 'hermes chat --profile' processes.
|
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.
|
Calls on_change callback when detection state changes.
|
||||||
"""
|
"""
|
||||||
@@ -870,24 +885,45 @@ class DetectionTimer:
|
|||||||
def check(self) -> bool:
|
def check(self) -> bool:
|
||||||
"""Check if background agents are active.
|
"""Check if background agents are active.
|
||||||
|
|
||||||
pgrep is the PRIMARY signal — always executed, regardless of gateway_state.
|
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
|
||||||
gateway_state is SECONDARY — read only for diagnostic logging, never for decisions.
|
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:
|
Returns:
|
||||||
True if pgrep finds other hermes chat processes (self-excluded),
|
True if background agents are detected, False otherwise.
|
||||||
False otherwise.
|
|
||||||
"""
|
"""
|
||||||
self._check_count += 1
|
self._check_count += 1
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
|
||||||
result = False
|
result = False
|
||||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
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
|
||||||
|
|
||||||
# ── PRIMARY: pgrep — ALWAYS run ──────────────────────────────────
|
# ── 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:
|
try:
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
|
# P1b: Expanded pattern catches subagents AND gateway subprocesses
|
||||||
proc = subprocess.run(
|
proc = subprocess.run(
|
||||||
["pgrep", "-f", "hermes chat --profile"],
|
["pgrep", "-f", "hermes_cli|hermes chat"],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
@@ -902,21 +938,13 @@ class DetectionTimer:
|
|||||||
logger.debug("[detection] pgrep failed: %s", e)
|
logger.debug("[detection] pgrep failed: %s", e)
|
||||||
# pgrep_pids stays -1 (error sentinel)
|
# 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)
|
|
||||||
gateway_active = state.get("active_agents", 0)
|
|
||||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
|
||||||
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
|
||||||
|
|
||||||
# ── Log: both signals, result ─────────────────────────────────────
|
# ── Log: both signals, result ─────────────────────────────────────
|
||||||
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
||||||
logger.info(
|
logger.info(
|
||||||
"[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s",
|
"[detection] check #%d: gateway_state=%d (primary=%s), pgrep=%s, result=%s",
|
||||||
self._check_count, pgrep_str, gateway_active,
|
self._check_count, gateway_active,
|
||||||
|
"yes" if gateway_used else "no",
|
||||||
|
pgrep_str,
|
||||||
"active" if result else "inactive",
|
"active" if result else "inactive",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -880,17 +880,17 @@ class TestPulseControllerLastSentPhase:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepPrimary:
|
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):
|
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
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
import tempfile
|
import tempfile
|
||||||
import json
|
import json
|
||||||
|
|
||||||
own_pid = os.getpid()
|
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"]}
|
state = {"active_agents": 1, "profiles": ["default"]}
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||||
json.dump(state, f)
|
json.dump(state, f)
|
||||||
@@ -910,50 +910,44 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
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
|
assert result is True
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
def test_pgrep_finds_no_other_agents(self):
|
def test_gateway_state_primary_active(self):
|
||||||
"""pgrep findet nur eigenen Prozess → result=False (gateway_state irrelevant)."""
|
"""P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
import tempfile
|
import tempfile
|
||||||
import json
|
import json
|
||||||
|
|
||||||
own_pid = os.getpid()
|
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
|
||||||
|
|
||||||
# gateway_state mit active_agents=3 (würde früher True liefern)
|
|
||||||
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||||
json.dump(state, f)
|
json.dump(state, f)
|
||||||
state_path = f.name
|
state_path = f.name
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Mock pgrep: findet nur eigenen Prozess
|
# Mock pgrep: sollte NICHT aufgerufen werden
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
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(
|
dt = DetectionTimer(
|
||||||
gateway_state_path=state_path,
|
gateway_state_path=state_path,
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# pgrep findet nur eigenen Prozess → False (gateway_state=3 wird ignoriert)
|
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
||||||
assert result is False
|
assert result is True
|
||||||
|
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||||
|
mock_run.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepNoGatewayState:
|
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):
|
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
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
@@ -997,10 +991,10 @@ class TestDetectionTimerPgrepNoGatewayState:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerIntegration:
|
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):
|
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
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
@@ -1009,7 +1003,7 @@ class TestDetectionTimerIntegration:
|
|||||||
def on_detection_change(is_active):
|
def on_detection_change(is_active):
|
||||||
callback_results.append(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:
|
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||||
mock_run.return_value = MagicMock(
|
mock_run.return_value = MagicMock(
|
||||||
stdout=f"{own_pid}\n99999\n",
|
stdout=f"{own_pid}\n99999\n",
|
||||||
@@ -1264,7 +1258,7 @@ class TestP0LiveVerdrahtung:
|
|||||||
assert not engine._pulse_controller.is_running()
|
assert not engine._pulse_controller.is_running()
|
||||||
|
|
||||||
def test_detection_timer_starts_when_enabled(self):
|
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
|
from plugin.archivar.presence_engine import PresenceEngine
|
||||||
|
|
||||||
mock_rest = MagicMock()
|
mock_rest = MagicMock()
|
||||||
@@ -1273,7 +1267,11 @@ class TestP0LiveVerdrahtung:
|
|||||||
|
|
||||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
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()
|
assert engine._detection_timer._running.is_set()
|
||||||
|
|
||||||
def test_detection_timer_not_started_when_disabled(self):
|
def test_detection_timer_not_started_when_disabled(self):
|
||||||
|
|||||||
Reference in New Issue
Block a user