fix(presence): pgrep False-Positive + DDP 429-Verbesserung (V8.8)

Bug 1 — pgrep argv-basierter Scanner:
- _pgrep_hermes_subagents() nutzt jetzt argv-basierte Erkennung
  statt Substring-Suche in der kompletten cmdline
- 'chat' und '--profile' muessen eigene argv-Elemente sein
- argv[0] basename pruefen: 'hermes', 'python', 'python3'
- python: '-m hermes_cli.main' oder hermes-Skript-Pfad in argv
- Gateway-PID aus gateway_state.json ausschliessen
- Neue _read_gateway_pid() Hilfsmethode
- 6 neue False-Positive-Tests (bash grep, snap-path, gateway)

Bug 2 — DDP 429 Circuit-Breaker + Pulse-Interval:
- Circuit-Breaker threshold: 3 → 1 (sofort nach erstem 429)
- DDP-Timeout: 2.0s → 1.0s (schneller fail)
- Mode-abhaengige Pulse-Intervalle: away=3.0s, busy=1.5s
- set_pulse_target() passt dynamisch das Interval an

Tests: 144/144 passed
This commit is contained in:
Bernd (Hermes)
2026-08-02 13:51:31 +02:00
parent 30015f0cfe
commit c3c995765f
3 changed files with 306 additions and 66 deletions
+95 -11
View File
@@ -844,7 +844,7 @@ class PulseController:
self._cancel_pending_event = threading.Event() # B6: thread-safe via Event statt bool
# P1-2 O-2: Async-await bridge
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._await_timeout: float = 2.0
self._await_timeout: float = 1.0 # V8.8: 1.0s statt 2.0s — schneller fail bei 429
# Phase 5: pulse_target — "away" (default) oder "busy"
# "away": pulsiert online↔away (Subagent läuft, Hauptagent idle)
@@ -853,13 +853,19 @@ class PulseController:
self._mode_lock = threading.Lock() # Mode-Sentinel (Risiko #2)
self._tick_counter: int = 0 # für Message-only-every-2-ticks
# V8.8: Mode-abhängige Pulse-Intervalle
# away-pulse: 3.0s (weniger aggressiv, vermeidet 429)
# busy-pulse: 1.5s (schnelle Reaktion auf busy-Status)
self._away_pulse_interval: float = 3.0
self._busy_pulse_interval: float = 1.5
# P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
self._breaker_state: str = "CLOSED"
self._consecutive_429s: int = 0
self._breaker_opened_at: float = 0.0
self._breaker_cooldown_s: float = 30.0
self._breaker_429_threshold: int = 3
self._breaker_429_threshold: int = 1 # V8.8: 1 statt 3 — sofort nach erstem 429
self._base_pulse_interval: float = self._pulse_interval
self._backoff_level: int = 0
# Adaptive Backoff: pulse_interval wird bei OPEN eskaliert
@@ -902,6 +908,10 @@ class PulseController:
def set_pulse_target(self, target: str) -> bool:
"""Phase 5: Set the pulse target mode with Mode-Sentinel.
V8.8: Mode-abhängige Pulse-Intervalle:
- "away": 3.0s (weniger aggressiv, vermeidet 429)
- "busy": 1.5s (schnelle Reaktion auf busy-Status)
Args:
target: "away" (pulse online↔away) or "busy" (pulse message while busy).
@@ -918,7 +928,19 @@ class PulseController:
return False
old = self._pulse_target
self._pulse_target = target
logger.info("[pulse] pulse_target: %s → %s", old, target)
# V8.8: Dynamisches Pulse-Interval je nach Mode
# Nur anpassen wenn Circuit-Breaker CLOSED (nicht im Backoff)
if self._breaker_state == "CLOSED":
if target == "away":
self._pulse_interval = self._away_pulse_interval
self._base_pulse_interval = self._away_pulse_interval
else: # busy
self._pulse_interval = self._busy_pulse_interval
self._base_pulse_interval = self._busy_pulse_interval
logger.info(
"[pulse] pulse_target: %s → %s (interval=%.1fs)",
old, target, self._pulse_interval,
)
return True
def get_pulse_target(self) -> str:
@@ -1566,13 +1588,28 @@ class DetectionTimer:
def _pgrep_hermes_subagents() -> int:
"""V8.7: Scan /proc/*/cmdline for 'hermes chat --profile' processes.
Iterates /proc/<pid>/cmdline, parses for 'hermes' + 'chat' + '--profile'.
Excludes own PID. No subprocess — direct /proc read, <1ms for ~100 procs.
V8.8: argv-basierter Scanner — verhindert False-Positives auf
Shell-Befehle die 'hermes'+'chat'+'--profile' als Text enthalten.
Algorithmus:
1. /proc/<pid>/cmdline lesen → null-byte-split → argv array
2. argv[0] basename prüfen: 'hermes', 'python', 'python3'
3. 'hermes': 'chat' und '--profile' als eigene argv-Elemente
4. 'python'/'python3': '-m hermes_cli.main' oder hermes-Skript-Pfad
in argv, UND 'chat' UND '--profile' als eigene Elemente
5. 'chat' muss eigenes argv-Element sein (kein Substring)
6. '--profile' muss eigenes argv-Element sein
7. Gateway-PID aus gateway_state.json ausschließen
8. Eigene PID ausschließen
Returns:
Number of matching processes (excluding self).
Number of matching processes (excluding self and gateway).
"""
own_pid = os.getpid()
# Gateway-PID aus gateway_state.json lesen
gateway_pid = DetectionTimer._read_gateway_pid()
count = 0
try:
for entry in os.listdir("/proc"):
@@ -1581,15 +1618,42 @@ class DetectionTimer:
pid = int(entry)
if pid == own_pid:
continue
if pid == gateway_pid:
continue
try:
with open(f"/proc/{entry}/cmdline", "rb") as f:
raw = f.read()
# cmdline is null-separated; decode and split
parts = raw.decode("utf-8", errors="replace").split("\x00")
cmdline_str = " ".join(parts)
# Match: contains 'hermes' AND 'chat' AND '--profile'
if "hermes" in cmdline_str and "chat" in cmdline_str and "--profile" in cmdline_str:
# cmdline is null-separated; decode and split into argv
argv = [a for a in raw.decode("utf-8", errors="replace").split("\x00") if a]
if not argv:
continue
# argv[0] basename
argv0 = os.path.basename(argv[0])
# Check: 'chat' and '--profile' must be separate argv elements
has_chat = "chat" in argv
has_profile = "--profile" in argv
if not (has_chat and has_profile):
continue
if argv0 == "hermes":
count += 1
elif argv0 in ("python", "python3"):
# Check for '-m hermes_cli.main' or hermes script path
is_hermes_python = False
for i, arg in enumerate(argv):
if arg == "-m" and i + 1 < len(argv):
if argv[i + 1].startswith("hermes_cli"):
is_hermes_python = True
break
elif "hermes" in os.path.basename(arg) and arg.endswith(".py"):
is_hermes_python = True
break
if is_hermes_python:
count += 1
except (OSError, IOError, PermissionError):
# Process may have exited or be inaccessible
continue
@@ -1597,6 +1661,26 @@ class DetectionTimer:
pass
return count
@staticmethod
def _read_gateway_pid() -> Optional[int]:
"""V8.8: Gateway-PID aus gateway_state.json lesen.
Returns:
Gateway PID or None if not available.
"""
gateway_state_path = os.environ.get(
"ROCKETCHAT_GATEWAY_STATE_PATH",
os.path.expanduser("~/.hermes/gateway_state.json"),
)
try:
if os.path.exists(gateway_state_path):
with open(gateway_state_path, 'r') as f:
state = json.load(f)
return state.get("pid")
except (json.JSONDecodeError, IOError, OSError):
pass
return None
@staticmethod
def _pid_is_alive(pid: int) -> bool:
"""Check if a process with the given PID is alive.