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
+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",
)