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:
@@ -844,7 +844,7 @@ class PulseController:
|
|||||||
self._cancel_pending_event = threading.Event() # B6: thread-safe via Event statt bool
|
self._cancel_pending_event = threading.Event() # B6: thread-safe via Event statt bool
|
||||||
# P1-2 O-2: Async-await bridge
|
# P1-2 O-2: Async-await bridge
|
||||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
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"
|
# Phase 5: pulse_target — "away" (default) oder "busy"
|
||||||
# "away": pulsiert online↔away (Subagent läuft, Hauptagent idle)
|
# "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._mode_lock = threading.Lock() # Mode-Sentinel (Risiko #2)
|
||||||
self._tick_counter: int = 0 # für Message-only-every-2-ticks
|
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
|
# P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway
|
||||||
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
|
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
|
||||||
self._breaker_state: str = "CLOSED"
|
self._breaker_state: str = "CLOSED"
|
||||||
self._consecutive_429s: int = 0
|
self._consecutive_429s: int = 0
|
||||||
self._breaker_opened_at: float = 0.0
|
self._breaker_opened_at: float = 0.0
|
||||||
self._breaker_cooldown_s: float = 30.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._base_pulse_interval: float = self._pulse_interval
|
||||||
self._backoff_level: int = 0
|
self._backoff_level: int = 0
|
||||||
# Adaptive Backoff: pulse_interval wird bei OPEN eskaliert
|
# Adaptive Backoff: pulse_interval wird bei OPEN eskaliert
|
||||||
@@ -902,6 +908,10 @@ class PulseController:
|
|||||||
def set_pulse_target(self, target: str) -> bool:
|
def set_pulse_target(self, target: str) -> bool:
|
||||||
"""Phase 5: Set the pulse target mode with Mode-Sentinel.
|
"""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:
|
Args:
|
||||||
target: "away" (pulse online↔away) or "busy" (pulse message while busy).
|
target: "away" (pulse online↔away) or "busy" (pulse message while busy).
|
||||||
|
|
||||||
@@ -918,7 +928,19 @@ class PulseController:
|
|||||||
return False
|
return False
|
||||||
old = self._pulse_target
|
old = self._pulse_target
|
||||||
self._pulse_target = 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
|
return True
|
||||||
|
|
||||||
def get_pulse_target(self) -> str:
|
def get_pulse_target(self) -> str:
|
||||||
@@ -1566,13 +1588,28 @@ class DetectionTimer:
|
|||||||
def _pgrep_hermes_subagents() -> int:
|
def _pgrep_hermes_subagents() -> int:
|
||||||
"""V8.7: Scan /proc/*/cmdline for 'hermes chat --profile' processes.
|
"""V8.7: Scan /proc/*/cmdline for 'hermes chat --profile' processes.
|
||||||
|
|
||||||
Iterates /proc/<pid>/cmdline, parses for 'hermes' + 'chat' + '--profile'.
|
V8.8: argv-basierter Scanner — verhindert False-Positives auf
|
||||||
Excludes own PID. No subprocess — direct /proc read, <1ms for ~100 procs.
|
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:
|
Returns:
|
||||||
Number of matching processes (excluding self).
|
Number of matching processes (excluding self and gateway).
|
||||||
"""
|
"""
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
|
|
||||||
|
# Gateway-PID aus gateway_state.json lesen
|
||||||
|
gateway_pid = DetectionTimer._read_gateway_pid()
|
||||||
|
|
||||||
count = 0
|
count = 0
|
||||||
try:
|
try:
|
||||||
for entry in os.listdir("/proc"):
|
for entry in os.listdir("/proc"):
|
||||||
@@ -1581,14 +1618,41 @@ class DetectionTimer:
|
|||||||
pid = int(entry)
|
pid = int(entry)
|
||||||
if pid == own_pid:
|
if pid == own_pid:
|
||||||
continue
|
continue
|
||||||
|
if pid == gateway_pid:
|
||||||
|
continue
|
||||||
try:
|
try:
|
||||||
with open(f"/proc/{entry}/cmdline", "rb") as f:
|
with open(f"/proc/{entry}/cmdline", "rb") as f:
|
||||||
raw = f.read()
|
raw = f.read()
|
||||||
# cmdline is null-separated; decode and split
|
# cmdline is null-separated; decode and split into argv
|
||||||
parts = raw.decode("utf-8", errors="replace").split("\x00")
|
argv = [a for a in raw.decode("utf-8", errors="replace").split("\x00") if a]
|
||||||
cmdline_str = " ".join(parts)
|
|
||||||
# Match: contains 'hermes' AND 'chat' AND '--profile'
|
if not argv:
|
||||||
if "hermes" in cmdline_str and "chat" in cmdline_str and "--profile" in cmdline_str:
|
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
|
count += 1
|
||||||
except (OSError, IOError, PermissionError):
|
except (OSError, IOError, PermissionError):
|
||||||
# Process may have exited or be inaccessible
|
# Process may have exited or be inaccessible
|
||||||
@@ -1597,6 +1661,26 @@ class DetectionTimer:
|
|||||||
pass
|
pass
|
||||||
return count
|
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
|
@staticmethod
|
||||||
def _pid_is_alive(pid: int) -> bool:
|
def _pid_is_alive(pid: int) -> bool:
|
||||||
"""Check if a process with the given PID is alive.
|
"""Check if a process with the given PID is alive.
|
||||||
|
|||||||
@@ -2263,8 +2263,8 @@ class TestCircuitBreakerStateTransitions:
|
|||||||
assert pc.get_breaker_state() == "CLOSED"
|
assert pc.get_breaker_state() == "CLOSED"
|
||||||
assert pc.get_consecutive_429s() == 0
|
assert pc.get_consecutive_429s() == 0
|
||||||
|
|
||||||
def test_three_consecutive_429s_open_breaker(self):
|
def test_one_429_opens_breaker(self):
|
||||||
"""3 aufeinanderfolgende 429 → CLOSED→OPEN, pulse_interval steigt."""
|
"""V8.8: 1×429 → CLOSED→OPEN sofort (threshold=1)."""
|
||||||
from plugin.archivar.presence_engine import PulseController
|
from plugin.archivar.presence_engine import PulseController
|
||||||
|
|
||||||
mock_ddp = MagicMock()
|
mock_ddp = MagicMock()
|
||||||
@@ -2277,20 +2277,10 @@ class TestCircuitBreakerStateTransitions:
|
|||||||
|
|
||||||
base_interval = pc.get_effective_pulse_interval()
|
base_interval = pc.get_effective_pulse_interval()
|
||||||
|
|
||||||
# Tick 1: 429 #1
|
# Tick 1: 429 #1 → OPEN (threshold=1)
|
||||||
pc._pulse_tick()
|
|
||||||
assert pc.get_breaker_state() == "CLOSED"
|
|
||||||
assert pc.get_consecutive_429s() == 1
|
|
||||||
|
|
||||||
# Tick 2: 429 #2
|
|
||||||
pc._pulse_tick()
|
|
||||||
assert pc.get_breaker_state() == "CLOSED"
|
|
||||||
assert pc.get_consecutive_429s() == 2
|
|
||||||
|
|
||||||
# Tick 3: 429 #3 → OPEN
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
assert pc.get_breaker_state() == "OPEN"
|
assert pc.get_breaker_state() == "OPEN"
|
||||||
assert pc.get_consecutive_429s() == 3
|
assert pc.get_consecutive_429s() == 1
|
||||||
# pulse_interval sollte auf backoff_level=0 → 5.0s gestiegen sein
|
# pulse_interval sollte auf backoff_level=0 → 5.0s gestiegen sein
|
||||||
assert pc.get_effective_pulse_interval() > base_interval
|
assert pc.get_effective_pulse_interval() > base_interval
|
||||||
|
|
||||||
@@ -2305,8 +2295,7 @@ class TestCircuitBreakerStateTransitions:
|
|||||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||||
pc.bind_ddp(mock_ddp)
|
pc.bind_ddp(mock_ddp)
|
||||||
|
|
||||||
# 3×429 → OPEN
|
# 1×429 → OPEN (threshold=1)
|
||||||
for _ in range(3):
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
assert pc.get_breaker_state() == "OPEN"
|
assert pc.get_breaker_state() == "OPEN"
|
||||||
|
|
||||||
@@ -2325,12 +2314,12 @@ class TestCircuitBreakerHalfOpen:
|
|||||||
"""HALF_OPEN Test-Ping success → CLOSED, pulse_interval reset."""
|
"""HALF_OPEN Test-Ping success → CLOSED, pulse_interval reset."""
|
||||||
from plugin.archivar.presence_engine import PulseController
|
from plugin.archivar.presence_engine import PulseController
|
||||||
|
|
||||||
# DDP wirft 3×429, dann success
|
# DDP wirft 1×429, dann success (threshold=1)
|
||||||
call_count = [0]
|
call_count = [0]
|
||||||
|
|
||||||
def ddp_side_effect(status):
|
def ddp_side_effect(status):
|
||||||
call_count[0] += 1
|
call_count[0] += 1
|
||||||
if call_count[0] <= 3:
|
if call_count[0] <= 1:
|
||||||
raise Exception("HTTP 429 Too Many Requests")
|
raise Exception("HTTP 429 Too Many Requests")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -2341,8 +2330,7 @@ class TestCircuitBreakerHalfOpen:
|
|||||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||||
pc.bind_ddp(mock_ddp)
|
pc.bind_ddp(mock_ddp)
|
||||||
|
|
||||||
# 3×429 → OPEN
|
# 1×429 → OPEN (threshold=1)
|
||||||
for _ in range(3):
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
assert pc.get_breaker_state() == "OPEN"
|
assert pc.get_breaker_state() == "OPEN"
|
||||||
|
|
||||||
@@ -2368,8 +2356,7 @@ class TestCircuitBreakerHalfOpen:
|
|||||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||||
pc.bind_ddp(mock_ddp)
|
pc.bind_ddp(mock_ddp)
|
||||||
|
|
||||||
# 3×429 → OPEN (backoff_level=0, pulse_interval=5.0)
|
# 1×429 → OPEN (threshold=1, backoff_level=0, pulse_interval=5.0)
|
||||||
for _ in range(3):
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
assert pc.get_breaker_state() == "OPEN"
|
assert pc.get_breaker_state() == "OPEN"
|
||||||
first_open_interval = pc.get_effective_pulse_interval()
|
first_open_interval = pc.get_effective_pulse_interval()
|
||||||
@@ -2399,8 +2386,7 @@ class TestCircuitBreakerSustained429:
|
|||||||
|
|
||||||
intervals_seen = [pc.get_effective_pulse_interval()]
|
intervals_seen = [pc.get_effective_pulse_interval()]
|
||||||
|
|
||||||
# Zyklus 1: 3×429 → OPEN (backoff 0: 5.0s)
|
# Zyklus 1: 1×429 → OPEN (threshold=1, backoff 0: 5.0s)
|
||||||
for _ in range(3):
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
intervals_seen.append(pc.get_effective_pulse_interval())
|
intervals_seen.append(pc.get_effective_pulse_interval())
|
||||||
|
|
||||||
@@ -2438,8 +2424,7 @@ class TestCircuitBreakerSustained429:
|
|||||||
|
|
||||||
# 5 Zyklen OPEN→HALF_OPEN→OPEN (mehr als backoff_intervals Länge)
|
# 5 Zyklen OPEN→HALF_OPEN→OPEN (mehr als backoff_intervals Länge)
|
||||||
for cycle in range(5):
|
for cycle in range(5):
|
||||||
# 3×429 → OPEN
|
# 1×429 → OPEN (threshold=1)
|
||||||
for _ in range(3):
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
# Cooldown ablaufen → HALF_OPEN → 429 → OPEN
|
# Cooldown ablaufen → HALF_OPEN → 429 → OPEN
|
||||||
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
pc._breaker_opened_at = time.monotonic() - pc._breaker_cooldown_s - 1.0
|
||||||
@@ -2521,8 +2506,7 @@ class TestCircuitBreakerDdpErrorClassification:
|
|||||||
pc.bind_ddp(mock_ddp)
|
pc.bind_ddp(mock_ddp)
|
||||||
pc.bind_rest(mock_rest)
|
pc.bind_rest(mock_rest)
|
||||||
|
|
||||||
# 3×429 DDP → OPEN, REST wurde NIE aufgerufen
|
# 1×429 DDP → OPEN (threshold=1), REST wurde NIE aufgerufen
|
||||||
for _ in range(3):
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
|
|
||||||
# REST wurde NICHT aufgerufen (429 blockiert Fallback)
|
# REST wurde NICHT aufgerufen (429 blockiert Fallback)
|
||||||
@@ -2559,7 +2543,7 @@ class TestCircuitBreakerRecordSuccess:
|
|||||||
|
|
||||||
def ddp_side_effect(status):
|
def ddp_side_effect(status):
|
||||||
call_count[0] += 1
|
call_count[0] += 1
|
||||||
if call_count[0] <= 3:
|
if call_count[0] <= 1:
|
||||||
raise Exception("HTTP 429 Too Many Requests")
|
raise Exception("HTTP 429 Too Many Requests")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -2570,8 +2554,7 @@ class TestCircuitBreakerRecordSuccess:
|
|||||||
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
pc = PulseController(pulse_interval=1.5, _clamp_pulse=False)
|
||||||
pc.bind_ddp(mock_ddp)
|
pc.bind_ddp(mock_ddp)
|
||||||
|
|
||||||
# 3×429 → OPEN (pulse_interval=5.0)
|
# 1×429 → OPEN (threshold=1, pulse_interval=5.0)
|
||||||
for _ in range(3):
|
|
||||||
pc._pulse_tick()
|
pc._pulse_tick()
|
||||||
assert pc.get_breaker_state() == "OPEN"
|
assert pc.get_breaker_state() == "OPEN"
|
||||||
assert pc.get_effective_pulse_interval() == 5.0
|
assert pc.get_effective_pulse_interval() == 5.0
|
||||||
|
|||||||
@@ -162,21 +162,25 @@ class TestHoneymoonExpiredWithBgTasks:
|
|||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestPgrepHermesSubagents:
|
class TestPgrepHermesSubagents:
|
||||||
"""Test 6: _pgrep_hermes_subagents() erkennt hermes chat --profile Prozesse."""
|
"""Test 6: _pgrep_hermes_subagents() erkennt hermes chat --profile Prozesse.
|
||||||
|
|
||||||
def test_pgrep_finds_hermes_chat_profile_process(self):
|
V8.8: argv-basierter Scanner — verhindert False-Positives auf
|
||||||
"""_pgrep_hermes_subagents() findet einen simulierten hermes-Prozess."""
|
Shell-Befehle die 'hermes'+'chat'+'--profile' als Text enthalten.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_pgrep_finds_hermes_binary_chat_profile(self):
|
||||||
|
"""_pgrep_hermes_subagents() findet 'hermes chat --profile rainer'."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
own_pid = os.getpid()
|
||||||
|
|
||||||
# Mock /proc: nur ein simulierter hermes chat --profile Prozess
|
# Mock /proc: ein echter hermes chat --profile Prozess
|
||||||
mock_proc_entries = ["1", "2", str(own_pid), "99999", "12345"]
|
mock_proc_entries = ["1", "2", str(own_pid), "99999", "12345"]
|
||||||
|
|
||||||
def mock_cmdline_read(pid_dir):
|
def mock_cmdline_read(pid_dir):
|
||||||
"""Simuliere /proc/<pid>/cmdline."""
|
|
||||||
if pid_dir == "12345":
|
if pid_dir == "12345":
|
||||||
return b"python\x00hermes\x00chat\x00--profile\x00miguel\x00--model\x00deepseek\x00"
|
# argv: ["hermes", "chat", "--profile", "rainer"]
|
||||||
|
return b"hermes\x00chat\x00--profile\x00rainer\x00"
|
||||||
elif pid_dir == str(own_pid):
|
elif pid_dir == str(own_pid):
|
||||||
return b"python\x00pytest\x00"
|
return b"python\x00pytest\x00"
|
||||||
else:
|
else:
|
||||||
@@ -184,9 +188,7 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
with patch("os.listdir", return_value=mock_proc_entries):
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
with patch("builtins.open") as mock_open:
|
with patch("builtins.open") as mock_open:
|
||||||
# Simuliere open() für /proc/<pid>/cmdline
|
|
||||||
def open_side_effect(path, mode="r"):
|
def open_side_effect(path, mode="r"):
|
||||||
# Extrahiere PID aus Pfad: /proc/<pid>/cmdline
|
|
||||||
parts = path.split("/")
|
parts = path.split("/")
|
||||||
if len(parts) >= 3 and parts[1] == "proc":
|
if len(parts) >= 3 and parts[1] == "proc":
|
||||||
pid_dir = parts[2]
|
pid_dir = parts[2]
|
||||||
@@ -197,11 +199,178 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
mock_open.side_effect = open_side_effect
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
# Mock _read_gateway_pid → None (kein Gateway)
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
count = DetectionTimer._pgrep_hermes_subagents()
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
|
||||||
# Sollte 1 Prozess finden (PID 12345, nicht own_pid)
|
|
||||||
assert count == 1, f"Expected 1, got {count}"
|
assert count == 1, f"Expected 1, got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_finds_python_m_hermes_cli_chat_profile(self):
|
||||||
|
"""_pgrep_hermes_subagents() findet 'python -m hermes_cli.main chat --profile miguel'."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if pid_dir == "12345":
|
||||||
|
# argv: ["python", "-m", "hermes_cli.main", "chat", "--profile", "miguel"]
|
||||||
|
return b"python\x00-m\x00hermes_cli.main\x00chat\x00--profile\x00miguel\x00"
|
||||||
|
elif pid_dir == str(own_pid):
|
||||||
|
return b"python\x00pytest\x00"
|
||||||
|
return b"bash\x00"
|
||||||
|
|
||||||
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
|
with patch("builtins.open") as mock_open:
|
||||||
|
def open_side_effect(path, mode="r"):
|
||||||
|
parts = path.split("/")
|
||||||
|
if len(parts) >= 3 and parts[1] == "proc":
|
||||||
|
pid_dir = parts[2]
|
||||||
|
mock_file = MagicMock()
|
||||||
|
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||||
|
return mock_file
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
|
||||||
|
assert count == 1, f"Expected 1, got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_false_positive_bash_grep(self):
|
||||||
|
"""V8.8: 'bash -c grep hermes.*chat.*--profile' → KEIN match (False-Positive)."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if pid_dir == "12345":
|
||||||
|
# argv: ["bash", "-c", "grep hermes.*chat.*--profile /var/log/..."]
|
||||||
|
return b"bash\x00-c\x00grep hermes.*chat.*--profile /var/log/syslog\x00"
|
||||||
|
elif pid_dir == str(own_pid):
|
||||||
|
return b"python\x00pytest\x00"
|
||||||
|
return b"bash\x00"
|
||||||
|
|
||||||
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
|
with patch("builtins.open") as mock_open:
|
||||||
|
def open_side_effect(path, mode="r"):
|
||||||
|
parts = path.split("/")
|
||||||
|
if len(parts) >= 3 and parts[1] == "proc":
|
||||||
|
pid_dir = parts[2]
|
||||||
|
mock_file = MagicMock()
|
||||||
|
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||||
|
return mock_file
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
|
||||||
|
assert count == 0, f"Expected 0 (false positive), got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_false_positive_hermes_snap_path(self):
|
||||||
|
"""V8.8: '/tmp/hermes-snap-xxx bash -c ...' → KEIN match (False-Positive)."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if pid_dir == "12345":
|
||||||
|
# argv: ["/tmp/hermes-snap-xxx", "bash", "-c", "hermes chat --profile"]
|
||||||
|
return b"/tmp/hermes-snap-abc123\x00bash\x00-c\x00hermes chat --profile rainer\x00"
|
||||||
|
elif pid_dir == str(own_pid):
|
||||||
|
return b"python\x00pytest\x00"
|
||||||
|
return b"bash\x00"
|
||||||
|
|
||||||
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
|
with patch("builtins.open") as mock_open:
|
||||||
|
def open_side_effect(path, mode="r"):
|
||||||
|
parts = path.split("/")
|
||||||
|
if len(parts) >= 3 and parts[1] == "proc":
|
||||||
|
pid_dir = parts[2]
|
||||||
|
mock_file = MagicMock()
|
||||||
|
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||||
|
return mock_file
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
|
||||||
|
assert count == 0, f"Expected 0 (false positive), got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_false_positive_gateway_process(self):
|
||||||
|
"""V8.8: Gateway 'python -m hermes_cli.main gateway run' → KEIN match."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
mock_proc_entries = ["1", str(own_pid), "12345"]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if pid_dir == "12345":
|
||||||
|
# argv: ["python", "-m", "hermes_cli.main", "gateway", "run"]
|
||||||
|
return b"python\x00-m\x00hermes_cli.main\x00gateway\x00run\x00"
|
||||||
|
elif pid_dir == str(own_pid):
|
||||||
|
return b"python\x00pytest\x00"
|
||||||
|
return b"bash\x00"
|
||||||
|
|
||||||
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
|
with patch("builtins.open") as mock_open:
|
||||||
|
def open_side_effect(path, mode="r"):
|
||||||
|
parts = path.split("/")
|
||||||
|
if len(parts) >= 3 and parts[1] == "proc":
|
||||||
|
pid_dir = parts[2]
|
||||||
|
mock_file = MagicMock()
|
||||||
|
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||||
|
return mock_file
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
|
||||||
|
assert count == 0, f"Expected 0 (gateway, no chat), got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_excludes_gateway_pid(self):
|
||||||
|
"""V8.8: Gateway-PID aus gateway_state.json wird ausgeschlossen."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
gateway_pid = 12345
|
||||||
|
mock_proc_entries = ["1", str(own_pid), str(gateway_pid)]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if pid_dir == str(gateway_pid):
|
||||||
|
# Sieht aus wie hermes chat --profile, ist aber Gateway
|
||||||
|
return b"hermes\x00chat\x00--profile\x00miguel\x00"
|
||||||
|
elif pid_dir == str(own_pid):
|
||||||
|
return b"python\x00pytest\x00"
|
||||||
|
return b"bash\x00"
|
||||||
|
|
||||||
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
|
with patch("builtins.open") as mock_open:
|
||||||
|
def open_side_effect(path, mode="r"):
|
||||||
|
parts = path.split("/")
|
||||||
|
if len(parts) >= 3 and parts[1] == "proc":
|
||||||
|
pid_dir = parts[2]
|
||||||
|
mock_file = MagicMock()
|
||||||
|
mock_file.__enter__.return_value.read.return_value = mock_cmdline_read(pid_dir)
|
||||||
|
return mock_file
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
|
||||||
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=gateway_pid):
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
|
||||||
|
assert count == 0, f"Expected 0 (gateway excluded), got {count}"
|
||||||
|
|
||||||
def test_pgrep_returns_zero_when_no_hermes_processes(self):
|
def test_pgrep_returns_zero_when_no_hermes_processes(self):
|
||||||
"""_pgrep_hermes_subagents() → 0 wenn keine hermes-Prozesse."""
|
"""_pgrep_hermes_subagents() → 0 wenn keine hermes-Prozesse."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
@@ -227,6 +396,7 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
mock_open.side_effect = open_side_effect
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
count = DetectionTimer._pgrep_hermes_subagents()
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
assert count == 0, f"Expected 0, got {count}"
|
assert count == 0, f"Expected 0, got {count}"
|
||||||
|
|
||||||
@@ -240,7 +410,7 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
def mock_cmdline_read(pid_dir):
|
def mock_cmdline_read(pid_dir):
|
||||||
# Eigener Prozess hat hermes chat --profile in cmdline
|
# Eigener Prozess hat hermes chat --profile in cmdline
|
||||||
return b"python\x00hermes\x00chat\x00--profile\x00miguel\x00"
|
return b"hermes\x00chat\x00--profile\x00miguel\x00"
|
||||||
|
|
||||||
with patch("os.listdir", return_value=mock_proc_entries):
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
with patch("builtins.open") as mock_open:
|
with patch("builtins.open") as mock_open:
|
||||||
@@ -255,6 +425,7 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
mock_open.side_effect = open_side_effect
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
count = DetectionTimer._pgrep_hermes_subagents()
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
# Eigene PID wird ausgeschlossen → 0
|
# Eigene PID wird ausgeschlossen → 0
|
||||||
assert count == 0, f"Expected 0 (own PID excluded), got {count}"
|
assert count == 0, f"Expected 0 (own PID excluded), got {count}"
|
||||||
@@ -268,9 +439,9 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
def mock_cmdline_read(pid_dir):
|
def mock_cmdline_read(pid_dir):
|
||||||
if pid_dir == "55555":
|
if pid_dir == "55555":
|
||||||
return b"python\x00hermes\x00serve\x00" # hermes aber kein chat
|
return b"hermes\x00serve\x00" # hermes binary aber kein chat
|
||||||
elif pid_dir == "66666":
|
elif pid_dir == "66666":
|
||||||
return b"python\x00chat\x00--profile\x00" # chat aber kein hermes
|
return b"python\x00chat\x00--profile\x00" # chat+profile aber argv0=python ohne -m hermes_cli
|
||||||
elif pid_dir == str(own_pid):
|
elif pid_dir == str(own_pid):
|
||||||
return b"python\x00pytest\x00"
|
return b"python\x00pytest\x00"
|
||||||
return b"bash\x00"
|
return b"bash\x00"
|
||||||
@@ -288,6 +459,7 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
mock_open.side_effect = open_side_effect
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
count = DetectionTimer._pgrep_hermes_subagents()
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
# Keiner der Prozesse hat hermes+chat+--profile → 0
|
# Keiner der Prozesse hat hermes+chat+--profile → 0
|
||||||
assert count == 0, f"Expected 0, got {count}"
|
assert count == 0, f"Expected 0, got {count}"
|
||||||
@@ -317,6 +489,7 @@ class TestPgrepHermesSubagents:
|
|||||||
|
|
||||||
mock_open.side_effect = open_side_effect
|
mock_open.side_effect = open_side_effect
|
||||||
|
|
||||||
|
with patch.object(DetectionTimer, '_read_gateway_pid', return_value=None):
|
||||||
count = DetectionTimer._pgrep_hermes_subagents()
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
# PermissionError → Prozess wird ignoriert, count=0
|
# PermissionError → Prozess wird ignoriert, count=0
|
||||||
assert count == 0, f"Expected 0, got {count}"
|
assert count == 0, f"Expected 0, got {count}"
|
||||||
|
|||||||
Reference in New Issue
Block a user