P2 Fix: Presence-Engine Detection — Option D (PID-Sentinel + Semantik-Korrektur)

Root Cause: Gateway erkannte sich selbst nicht als aktiv im Idle-Zustand.
- gateway_state.json: active_agents=0 im Idle, Schwellwert >1 griff nie
- plugin_state.json: background_tasks=0 im Idle → inactive
- pgrep: Pattern 'hermes_cli|hermes chat' matchte 'gateway run' nicht

Fix (Rainer approved, Option D):

1. PID-Sentinel (neues PRIMARY Signal)
   - _check_gateway_pid_alive() prüft /proc/<ppid> auf Existenz
   - detection_source='gateway_pid' wenn PID-Sentinel entscheidet

2. gateway_state.json Schwelle korrigiert
   - >1 → >0 (active_agents=1 reicht jetzt)

3. pgrep-Pattern erweitert
   - 'hermes_cli|hermes chat' → 'hermes_cli|hermes chat|gateway run'

4. Semantik: Idle ≠ Abwesend
   - PID-Sentinel alive + keine Subagenten → Status 'online' (grün)
   - 'inactive' (gelb) nur wenn Gateway-Prozess nicht gefunden

Tests: 94 passed (86 existing + 8 new T1-T8)
- T1: PID-Sentinel erkennt lebenden Gateway
- T2: PID-Sentinel erkennt toten Gateway
- T3: gateway_state Schwelle >0
- T4: pgrep-Pattern matcht 'gateway run'
- T5: Idle-Puls läuft weiter wenn Gateway alive (zentraler Test)
- T6: Subagent-Aktivität pulsiert gelb
- T7: Kein False-Positive wenn Gateway tot
- T8: detection_source='gateway_pid'
This commit is contained in:
Bernd (Hermes)
2026-08-01 10:53:19 +02:00
parent 0310bd5fd5
commit 8fba9a4a39
2 changed files with 464 additions and 172 deletions
+69 -34
View File
@@ -1061,13 +1061,17 @@ class PulseController:
class DetectionTimer:
"""Detects whether background agents are active.
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
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).
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
subprocesses). Self-pid exclude is preserved.
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
Calls on_change callback when detection state changes.
"""
@@ -1132,17 +1136,37 @@ class DetectionTimer:
self._thread = None
logger.info("[detection] DetectionTimer stopped")
def _check_gateway_pid_alive(self) -> bool:
"""P2 Fix Option D: PID-Sentinel — prüft ob der Gateway-Prozess lebt.
Verwendet os.getppid() um den Parent-PID (Gateway-Prozess) zu ermitteln
und prüft ob /proc/<ppid> existiert. Dies ist das zuverlässigste Signal
für die Gateway-Präsenz, da es keine Datei-I/O oder Prozess-Suche benötigt.
Returns:
True wenn der Gateway-Parent-Prozess existiert, False sonst.
"""
try:
ppid = os.getppid()
# /proc/<ppid> existiert nur wenn der Prozess lebt
return os.path.exists(f"/proc/{ppid}")
except (OSError, ValueError):
return False
def check(self) -> bool:
"""Check if background agents are active.
P1b: gateway_state.json is PRIMARY — active_agents > 1 means active.
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).
P2 Fix Option D: PID-Sentinel ist PRIMARY — prüft ob Gateway-Prozess lebt.
gateway_state.json ist SECONDARY — active_agents > 0 bedeutet Subagenten aktiv.
plugin_state.json ist TERTIARY — background_tasks > 0 bedeutet aktiv.
pgrep ist QUATERNARY/FALLBACK — 'hermes_cli|hermes chat|gateway run'.
pgrep pattern expanded from 'hermes chat --profile' to
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
Self-pid exclude is preserved.
pgrep pattern: 'hermes_cli|hermes chat|gateway run' (fängt Subagenten
UND Gateway-Prozess). Self-pid exclude bleibt erhalten.
Semantik: Idle ≠ Abwesend. Wenn PID-Sentinel 'alive' liefert UND keine
Subagenten aktiv → Status 'online' (grün), nicht 'inactive'.
'inactive' (gelb) bedeutet NUR: Gateway-Prozess nicht gefunden.
Returns:
True if background agents are detected, False otherwise.
@@ -1153,27 +1177,36 @@ class DetectionTimer:
result = False
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
gateway_active = 0
pid_used = False # P2: True if PID-Sentinel was the deciding signal
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:
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
detection_source = "gateway"
except (json.JSONDecodeError, IOError, OSError) as e:
logger.debug("[detection] gateway_state.json read failed: %s", e)
# Fall through to plugin_state
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
if self._check_gateway_pid_alive():
result = True
pid_used = True
detection_source = "gateway_pid"
# ── P1-2: SECONDARY: plugin_state.json ─────────────────────────────
if not gateway_used:
# ── P2 SECONDARY: gateway_state.json (Schwelle >0, war >1) ──────────
if not pid_used:
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)
# P2 Fix: Schwelle >0 statt >1
if gateway_active > 0:
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 plugin_state
# ── P1-2: TERTIARY: plugin_state.json ────────────────────────────────
if not pid_used and 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:
@@ -1181,13 +1214,13 @@ class DetectionTimer:
plugin_used = True
detection_source = "plugin_state"
# ── TERTIARY: pgrep — run when neither gateway nor plugin decided ──
if not gateway_used and not plugin_used:
# ── P2 QUATERNARY: pgrep — erweitertes Pattern 'gateway run' ────────
if not pid_used and not gateway_used and not plugin_used:
try:
own_pid = os.getpid()
# P1b: Expanded pattern catches subagents AND gateway subprocesses
# P2 Fix: Pattern um 'gateway run' erweitert
proc = subprocess.run(
["pgrep", "-f", "hermes_cli|hermes chat"],
["pgrep", "-f", "hermes_cli|hermes chat|gateway run"],
capture_output=True,
text=True,
timeout=5,
@@ -1208,10 +1241,12 @@ class DetectionTimer:
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), "
"[detection] check #%d: pid_sentinel=%s, gateway_state=%d (primary=%s), "
"plugin_state=%s (bg_tasks=%s), pgrep=%s, "
"result=%s, source=%s",
self._check_count, gateway_active,
self._check_count,
"alive" if pid_used else "dead",
gateway_active,
"yes" if gateway_used else "no",
"yes" if plugin_used else "no",
plugin_str,
+395 -138
View File
@@ -960,24 +960,25 @@ class TestDetectionTimerPgrepPrimary:
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
assert result is True
# P2: PID-Sentinel deaktivieren, damit gateway_state/pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# gateway_state=1 > 0 → SECONDARY entscheidet → True
assert result is True
finally:
os.unlink(state_path)
def test_gateway_state_primary_active(self):
"""P1b: gateway_state active_agents=3 (>1) → PRIMARY entscheidet → result=True, pgrep NICHT aufgerufen."""
"""P1b: gateway_state active_agents=3 (>0) → SECONDARY entscheidet → result=True, pgrep NICHT aufgerufen."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
# gateway_state mit active_agents=3 (>0 → SECONDARY entscheidet)
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
@@ -986,15 +987,17 @@ class TestDetectionTimerPgrepPrimary:
try:
# Mock pgrep: sollte NICHT aufgerufen werden
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# gateway_state=3 > 1 → PRIMARY entscheidet → True
assert result is True
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
mock_run.assert_not_called()
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# gateway_state=3 > 0 → SECONDARY entscheidet → True
assert result is True
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
mock_run.assert_not_called()
finally:
os.unlink(state_path)
@@ -1015,14 +1018,15 @@ class TestDetectionTimerPgrepNoGatewayState:
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
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
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."""
@@ -1037,13 +1041,14 @@ class TestDetectionTimerPgrepNoGatewayState:
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
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
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:
@@ -1368,14 +1373,15 @@ class TestDetectionTimerPgrepSelfExclude:
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# Own PID should be excluded → no background agents → False
assert result is False
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# Own PID should be excluded → no background agents → False
assert result is False
def test_pgrep_self_exclude_with_other_pids(self):
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
@@ -1390,14 +1396,15 @@ class TestDetectionTimerPgrepSelfExclude:
stderr="",
returncode=0,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# After excluding own PID, one other PID remains → True
assert result is True
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# After excluding own PID, one other PID remains → True
assert result is True
class TestDetectionTimerOnChangeCallback:
@@ -1428,33 +1435,35 @@ class TestDetectionTimerOnChangeCallback:
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.side_effect = mock_results
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
on_change=on_change,
)
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
on_change=on_change,
)
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
result1 = dt.check()
assert result1 is False
assert len(callback_results) == 0
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
result1 = dt.check()
assert result1 is False
assert len(callback_results) == 0
# 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
# 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
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
result3 = dt.check()
assert result3 is True
assert len(callback_results) == 1
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
result3 = dt.check()
assert result3 is True
assert len(callback_results) == 1
# 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
# 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
class TestPulseControllerStartWithoutDdp:
@@ -2066,13 +2075,15 @@ class TestDetectionTimerPluginState:
"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
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
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."""
@@ -2094,13 +2105,15 @@ class TestDetectionTimerPluginState:
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
# P2: PID-Sentinel deaktivieren, damit plugin_state/pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
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):
@@ -2114,14 +2127,16 @@ class TestDetectionTimerPluginState:
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
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
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."""
@@ -2140,12 +2155,14 @@ class TestDetectionTimerPluginState:
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()
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
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
@@ -2154,7 +2171,7 @@ class TestDetectionTimerPluginState:
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
import tempfile, json
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
# gateway_state mit active_agents=3 (>0 → SECONDARY entscheidet)
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
@@ -2172,15 +2189,17 @@ class TestDetectionTimerPluginState:
})
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()
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path=gw_path,
detection_interval=0.1,
plugin_state_path=plugin_path,
)
result = dt.check()
# gateway_state=3 > 0 → SECONDARY → True (pgrep NICHT aufgerufen)
assert result is True
mock_run.assert_not_called()
finally:
os.unlink(gw_path)
@@ -2210,12 +2229,14 @@ class TestDetectionSourceTelemetry:
"schema_version": 1,
})
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path=state_path,
)
dt.check()
# P2: PID-Sentinel deaktivieren, damit plugin_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path=state_path,
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
def test_detection_source_none_when_inactive(self):
@@ -2232,13 +2253,15 @@ class TestDetectionSourceTelemetry:
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",
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "none"
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path="/tmp/nonexistent_plugin_state.json",
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "none"
def test_detection_source_pgrep(self):
"""pgrep findet Agenten → source='pgrep'."""
@@ -2254,13 +2277,15 @@ class TestDetectionSourceTelemetry:
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",
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "pgrep"
# P2: PID-Sentinel deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
plugin_state_path="/tmp/nonexistent_plugin_state.json",
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "pgrep"
def test_detection_source_gateway(self, tmp_path):
"""gateway_state entscheidet → source='gateway'."""
@@ -2277,13 +2302,15 @@ class TestDetectionSourceTelemetry:
try:
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
dt = DetectionTimer(
gateway_state_path=gw_path,
detection_interval=0.1,
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "gateway"
mock_run.assert_not_called()
# P2: PID-Sentinel deaktivieren, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path=gw_path,
detection_interval=0.1,
)
dt.check()
assert routing_telemetry.heartbeat_detection_source == "gateway"
mock_run.assert_not_called()
finally:
os.unlink(gw_path)
@@ -2308,3 +2335,233 @@ class TestPresenceEnginePluginStateIntegration:
assert engine._detection_timer._plugin_state_path is not None
assert "plugin_state" in engine._detection_timer._plugin_state_path
assert "hermes_rocket_plugin.json" in engine._detection_timer._plugin_state_path
# ═══════════════════════════════════════════════════════════════════════════
# P2 Fix: Presence-Engine Detection — Option D (PID-Sentinel + Semantik)
# Tests T1-T8 (Rainer approved)
# ═══════════════════════════════════════════════════════════════════════════
class TestPidSentinelDetectsAliveGateway:
"""T1: PID-Sentinel erkennt lebenden Gateway-Prozess."""
def test_pid_sentinel_detects_alive_gateway(self):
"""_check_gateway_pid_alive() liefert True wenn /proc/<ppid> existiert."""
from plugin.archivar.presence_engine import DetectionTimer
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
# Der Parent-PID (os.getppid()) existiert immer im Testprozess
result = dt._check_gateway_pid_alive()
assert result is True
class TestPidSentinelDeadGateway:
"""T2: PID-Sentinel erkennt toten Gateway-Prozess."""
def test_pid_sentinel_dead_gateway(self):
"""_check_gateway_pid_alive() liefert False wenn /proc/<ppid> nicht existiert."""
from plugin.archivar.presence_engine import DetectionTimer
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
# Mock: os.getppid() liefert eine nicht-existente PID
with patch('plugin.archivar.presence_engine.os.getppid') as mock_getppid:
mock_getppid.return_value = 999999 # nicht-existente PID
result = dt._check_gateway_pid_alive()
assert result is False
class TestGatewayStateThresholdZero:
"""T3: gateway_state.json Schwelle >0 statt >1."""
def test_gateway_state_threshold_zero(self):
"""active_agents=1 → gateway_state erkennt als aktiv (Schwelle >0)."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
# gateway_state mit active_agents=1 (war vorher >1, jetzt >0)
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:
# Mock pgrep: findet nichts (damit gateway_state entscheidet)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
# PID-Sentinel deaktivieren via Mock, damit gateway_state getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# active_agents=1 > 0 → gateway_state erkennt als aktiv
assert result is True
finally:
os.unlink(state_path)
class TestPgrepPatternMatchesGatewayRun:
"""T4: pgrep-Pattern matcht 'gateway run'."""
def test_pgrep_pattern_matches_gateway_run(self):
"""pgrep -f 'hermes_cli|hermes chat|gateway run' findet Gateway-Prozess."""
from plugin.archivar.presence_engine import DetectionTimer
own_pid = os.getpid()
# Mock pgrep: findet einen 'gateway run'-Prozess (nicht eigenen PID)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="12345\n", # anderer PID, nicht own_pid
stderr="",
returncode=0,
)
# PID-Sentinel + gateway_state deaktivieren, damit pgrep getestet wird
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# pgrep findet 'gateway run'-Prozess → True
assert result is True
# Prüfe dass das pgrep-Pattern 'gateway run' enthält
call_args = mock_run.call_args[0][0]
pattern_arg = None
for i, arg in enumerate(call_args):
if arg == "-f" and i + 1 < len(call_args):
pattern_arg = call_args[i + 1]
break
assert pattern_arg is not None, "pgrep -f pattern not found in call"
assert "gateway run" in pattern_arg, (
f"Pattern should contain 'gateway run', got: {pattern_arg}"
)
class TestIdlePulseContinuesWhenGatewayAlive:
"""T5: Gateway läuft, keine Subagenten → Detection='active', Status='online'."""
def test_idle_pulse_continues_when_gateway_alive(self):
"""PID-Sentinel erkennt Gateway → check()=True auch ohne Subagenten."""
from plugin.archivar.presence_engine import DetectionTimer
# PID-Sentinel: Gateway lebt
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=True):
# gateway_state: active_agents=0 (keine Subagenten)
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# Gateway lebt → detection=active, auch ohne Subagenten
assert result is True, (
"PID-Sentinel sollte Gateway als aktiv erkennen, "
"auch wenn keine Subagenten laufen"
)
class TestSubagentActivityPulsesYellow:
"""T6: Subagent-Aktivität → Puls gelb (Detection erkennt Subagenten)."""
def test_subagent_activity_pulses_yellow(self):
"""gateway_state active_agents=2 → check()=True via gateway_state (Subagenten)."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
# gateway_state mit active_agents=2 (Subagenten aktiv)
state = {"active_agents": 2, "profiles": ["default", "miguel"]}
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
json.dump(state, f)
state_path = f.name
try:
# PID-Sentinel deaktivieren, gateway_state soll entscheiden
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
dt = DetectionTimer(
gateway_state_path=state_path,
detection_interval=0.1,
)
result = dt.check()
# active_agents=2 > 0 → gateway_state erkennt Subagenten
assert result is True
finally:
os.unlink(state_path)
class TestNoFalseActiveWhenGatewayDead:
"""T7: Kein False-Positive wenn Gateway tot ist."""
def test_no_false_active_when_gateway_dead(self):
"""PID-Sentinel tot + gateway_state=0 + pgrep=0 → check()=False."""
from plugin.archivar.presence_engine import DetectionTimer
# Alle drei Signale negativ
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(
stdout="",
stderr="",
returncode=1,
)
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
# Kein Gateway, keine Subagenten, kein pgrep → False
assert result is False, (
"Ohne Gateway-Prozess und ohne Subagenten darf "
"keine Aktivität gemeldet werden"
)
class TestDetectionSourcePidSentinel:
"""T8: detection_source='gateway_pid' wenn PID-Sentinel entscheidet."""
def test_detection_source_pid_sentinel(self):
"""PID-Sentinel entscheidet → detection_source='gateway_pid'."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.routing_telemetry import routing_telemetry
routing_telemetry.heartbeat_detection_source = "none"
# PID-Sentinel: Gateway lebt → PRIMARY entscheidet
with patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=True):
dt = DetectionTimer(
gateway_state_path="/tmp/nonexistent_gateway_state.json",
detection_interval=0.1,
)
result = dt.check()
assert result is True
# detection_source muss 'gateway_pid' sein
assert routing_telemetry.heartbeat_detection_source == "gateway_pid", (
f"Erwartet 'gateway_pid', bekam "
f"'{routing_telemetry.heartbeat_detection_source}'"
)