fix: DetectionTimer pgrep als Primärsignal — gateway_state unbrauchbar fuer Subagenten-Erkennung
This commit is contained in:
@@ -704,33 +704,20 @@ 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.
|
||||||
|
gateway_state is SECONDARY — read only for diagnostic logging, never for decisions.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if active_agents > 1 (background agent active),
|
True if pgrep finds other hermes chat processes (self-excluded),
|
||||||
False otherwise.
|
False otherwise.
|
||||||
"""
|
"""
|
||||||
self._check_count += 1
|
self._check_count += 1
|
||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
|
||||||
result = False
|
result = False
|
||||||
source = "none"
|
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||||
|
|
||||||
# Try gateway_state.json first
|
# ── PRIMARY: pgrep — ALWAYS run ──────────────────────────────────
|
||||||
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":
|
|
||||||
try:
|
try:
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
proc = subprocess.run(
|
proc = subprocess.run(
|
||||||
@@ -743,26 +730,28 @@ class DetectionTimer:
|
|||||||
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
|
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()]
|
all_pids = [int(l) for l in raw_lines if l.isdigit()]
|
||||||
pids = [p for p in all_pids if p != own_pid]
|
pids = [p for p in all_pids if p != own_pid]
|
||||||
result = len(pids) > 0
|
pgrep_pids = len(pids)
|
||||||
source = "pgrep"
|
result = pgrep_pids > 0
|
||||||
logger.info(
|
|
||||||
"[detection] check #%d: pgrep=%d pids (self-excluded), result=%s",
|
|
||||||
self._check_count, len(pids), "active" if result else "inactive",
|
|
||||||
)
|
|
||||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
||||||
logger.debug("[detection] pgrep fallback failed: %s", e)
|
logger.debug("[detection] pgrep failed: %s", e)
|
||||||
result = False
|
# pgrep_pids stays -1 (error sentinel)
|
||||||
source = "pgrep_error"
|
|
||||||
logger.info(
|
|
||||||
"[detection] check #%d: detection unavailable (pgrep failed)",
|
|
||||||
self._check_count,
|
|
||||||
)
|
|
||||||
|
|
||||||
# If no source produced a result, log inactive
|
# ── SECONDARY: gateway_state — diagnostic only ────────────────────
|
||||||
if source == "none":
|
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(
|
logger.info(
|
||||||
"[detection] check #%d: no background activity detected",
|
"[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s",
|
||||||
self._check_count,
|
self._check_count, pgrep_str, gateway_active,
|
||||||
|
"active" if result else "inactive",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Notify on change (P1-2: callback fires from check() itself)
|
# Notify on change (P1-2: callback fires from check() itself)
|
||||||
|
|||||||
@@ -879,73 +879,115 @@ class TestPulseControllerLastSentPhase:
|
|||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerGatewayState:
|
class TestDetectionTimerPgrepPrimary:
|
||||||
"""Test 20: DetectionTimer liest gateway_state.json."""
|
"""Test 20: DetectionTimer — pgrep als Primärsignal, gateway_state nur diagnostisch."""
|
||||||
|
|
||||||
def test_detection_from_gateway_state(self):
|
def test_pgrep_finds_other_agents(self):
|
||||||
"""DetectionTimer erkennt aktive Agents aus gateway_state.json."""
|
"""pgrep findet andere hermes-Prozesse → result=True (gateway_state irrelevant)."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
import tempfile
|
import tempfile
|
||||||
import json
|
import json
|
||||||
|
|
||||||
# Erstelle gateway_state.json mit active_agents > 1
|
own_pid = os.getpid()
|
||||||
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
|
|
||||||
|
|
||||||
|
# gateway_state mit active_agents=1 (würde früher False liefern)
|
||||||
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)
|
||||||
state_path = f.name
|
state_path = f.name
|
||||||
|
|
||||||
try:
|
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(
|
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()
|
||||||
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:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepFallback:
|
class TestDetectionTimerPgrepNoGatewayState:
|
||||||
"""Test 21: DetectionTimer pgrep-Fallback."""
|
"""Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json."""
|
||||||
|
|
||||||
def test_pgrep_fallback_when_no_gateway_state(self):
|
def test_pgrep_works_without_gateway_state(self):
|
||||||
"""Wenn gateway_state.json nicht existiert, wird pgrep verwendet."""
|
"""Wenn gateway_state.json nicht existiert, pgrep ist trotzdem Primärsignal."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
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(
|
dt = DetectionTimer(
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
)
|
)
|
||||||
# Sollte nicht crashen, sondern pgrep-Fallback nutzen
|
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# Ergebnis ist bool (True/False)
|
# pgrep findet anderen Prozess → True
|
||||||
assert isinstance(result, bool)
|
assert result is True
|
||||||
|
|
||||||
def test_pgrep_fallback_returns_bool(self):
|
def test_pgrep_returns_bool(self):
|
||||||
"""pgrep-Fallback liefert immer bool zurück."""
|
"""pgrep liefert immer bool zurück."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
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(
|
dt = DetectionTimer(
|
||||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
@@ -955,28 +997,28 @@ class TestDetectionTimerPgrepFallback:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerIntegration:
|
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):
|
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
|
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 = []
|
callback_results = []
|
||||||
|
|
||||||
def on_detection_change(is_active):
|
def on_detection_change(is_active):
|
||||||
callback_results.append(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(
|
dt = DetectionTimer(
|
||||||
gateway_state_path=state_path,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
on_change=on_detection_change,
|
on_change=on_detection_change,
|
||||||
)
|
)
|
||||||
@@ -989,8 +1031,6 @@ class TestDetectionTimerIntegration:
|
|||||||
# Alle Ergebnisse sind bool
|
# Alle Ergebnisse sind bool
|
||||||
for r in callback_results:
|
for r in callback_results:
|
||||||
assert isinstance(r, bool)
|
assert isinstance(r, bool)
|
||||||
finally:
|
|
||||||
os.unlink(state_path)
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -1304,65 +1344,61 @@ class TestDetectionTimerPgrepSelfExclude:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerOnChangeCallback:
|
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):
|
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
|
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 = []
|
callback_results = []
|
||||||
|
|
||||||
def on_change(is_active):
|
def on_change(is_active):
|
||||||
callback_results.append(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(
|
dt = DetectionTimer(
|
||||||
gateway_state_path=state_path,
|
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
on_change=on_change,
|
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()
|
result1 = dt.check()
|
||||||
assert result1 is False
|
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
|
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
||||||
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)
|
|
||||||
result2 = dt.check()
|
result2 = dt.check()
|
||||||
assert result2 is True
|
assert result2 is True
|
||||||
assert len(callback_results) == 1
|
assert len(callback_results) == 1
|
||||||
assert callback_results[0] is True
|
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()
|
result3 = dt.check()
|
||||||
assert result3 is True
|
assert result3 is True
|
||||||
assert len(callback_results) == 1 # No new callback
|
assert len(callback_results) == 1
|
||||||
|
|
||||||
# Change back to inactive
|
# Check 4: verschwindet → False (Callback: True→False)
|
||||||
with open(state_path, 'w') as f:
|
|
||||||
json.dump(state_inactive, f)
|
|
||||||
|
|
||||||
# Fourth check: active_agents=1 → False (callback fires: True→False)
|
|
||||||
result4 = dt.check()
|
result4 = dt.check()
|
||||||
assert result4 is False
|
assert result4 is False
|
||||||
assert len(callback_results) == 2
|
assert len(callback_results) == 2
|
||||||
assert callback_results[1] is False
|
assert callback_results[1] is False
|
||||||
|
|
||||||
finally:
|
|
||||||
os.unlink(state_path)
|
|
||||||
|
|
||||||
|
|
||||||
class TestPulseControllerStartWithoutDdp:
|
class TestPulseControllerStartWithoutDdp:
|
||||||
"""P1-1: PulseController.start() ohne DDP-Bindung → log warning, kein Crash."""
|
"""P1-1: PulseController.start() ohne DDP-Bindung → log warning, kein Crash."""
|
||||||
|
|||||||
Reference in New Issue
Block a user