fix: DetectionTimer pgrep als Primärsignal — gateway_state unbrauchbar fuer Subagenten-Erkennung

This commit is contained in:
Bernd (Hermes)
2026-07-23 19:04:38 +02:00
parent 2019630144
commit 7657cd3665
2 changed files with 170 additions and 145 deletions
+25 -36
View File
@@ -704,33 +704,20 @@ 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
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",
)
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":
# ── PRIMARY: pgrep — ALWAYS run ──────────────────────────────────
try:
own_pid = os.getpid()
proc = subprocess.run(
@@ -743,26 +730,28 @@ class DetectionTimer:
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",
)
pgrep_pids = len(pids)
result = pgrep_pids > 0
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,
)
logger.debug("[detection] pgrep failed: %s", e)
# pgrep_pids stays -1 (error sentinel)
# If no source produced a result, log inactive
if source == "none":
# ── 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 ─────────────────────────────────────
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
logger.info(
"[detection] check #%d: no background activity detected",
self._check_count,
"[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)
+115 -79
View File
@@ -879,73 +879,115 @@ 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:
# 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()
assert result is False # nur ein Agent
# pgrep findet anderen Prozess → True (gateway_state=1 wird ignoriert)
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)."""
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)
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 TestDetectionTimerPgrepFallback:
"""Test 21: DetectionTimer pgrep-Fallback."""
class TestDetectionTimerPgrepNoGatewayState:
"""Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json."""
def test_pgrep_fallback_when_no_gateway_state(self):
"""Wenn gateway_state.json nicht existiert, wird pgrep verwendet."""
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,
)
# Sollte nicht crashen, sondern pgrep-Fallback nutzen
result = dt.check()
# Ergebnis ist bool (True/False)
assert isinstance(result, bool)
# pgrep findet anderen Prozess → True
assert result is True
def test_pgrep_fallback_returns_bool(self):
"""pgrep-Fallback liefert immer bool zurück."""
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,
@@ -955,28 +997,28 @@ class TestDetectionTimerPgrepFallback:
class TestDetectionTimerIntegration:
"""Test 22: DetectionTimer start/stop + Callback."""
"""Test 22: DetectionTimer start/stop + Callback (pgrep als Primärsignal)."""
def test_detection_timer_start_stop(self):
"""DetectionTimer startet und stoppt korrekt."""
"""DetectionTimer startet und stoppt korrekt, pgrep als Primärsignal."""
from plugin.archivar.presence_engine import DetectionTimer
import tempfile
import json
# Erstelle gateway_state.json mit active_agents > 1 (True)
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
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."""