Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6d8aab83a0 | |||
| 0f6821fa9c | |||
| 998ed2cedd | |||
| 4ac1d10b44 | |||
| 56badac990 |
@@ -14,10 +14,12 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Dict, Callable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -30,6 +32,73 @@ if not logger.handlers:
|
||||
logger.propagate = False # Don't double-log to root
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-2: Plugin-State-Datei — atomare Hilfsfunktionen
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
PLUGIN_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
|
||||
PLUGIN_STATE_FILENAME = "hermes_rocket_plugin.json"
|
||||
PLUGIN_STATE_SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def _get_plugin_state_path() -> str:
|
||||
"""Return the path to the plugin state file.
|
||||
|
||||
Returns:
|
||||
Absolute path to ~/.hermes/plugin_state/hermes_rocket_plugin.json
|
||||
"""
|
||||
return os.path.join(PLUGIN_STATE_DIR, PLUGIN_STATE_FILENAME)
|
||||
|
||||
|
||||
def _read_plugin_state(path: str) -> dict:
|
||||
"""Read the plugin state file, returning {} if missing or corrupt.
|
||||
|
||||
Args:
|
||||
path: Absolute path to the plugin state JSON file.
|
||||
|
||||
Returns:
|
||||
Parsed dict, or empty dict on any error.
|
||||
"""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return {}
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||
logger.debug("[plugin_state] read failed: %s", e)
|
||||
return {}
|
||||
|
||||
|
||||
def _write_plugin_state(path: str, data: dict) -> None:
|
||||
"""Atomically write the plugin state file (write-temp + rename).
|
||||
|
||||
Args:
|
||||
path: Absolute path to the plugin state JSON file.
|
||||
data: Dict to serialize as JSON.
|
||||
"""
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
# Write to temp file in same directory (same filesystem → atomic rename)
|
||||
fd, tmp_path = tempfile.mkstemp(
|
||||
suffix=".tmp",
|
||||
prefix="plugin_state_",
|
||||
dir=os.path.dirname(path),
|
||||
)
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
os.replace(tmp_path, path) # atomic on POSIX
|
||||
except Exception:
|
||||
# Clean up temp file on write failure
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.debug("[plugin_state] write failed: %s", e)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Pure Function: _format_presence_message
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
@@ -143,6 +212,10 @@ class PresenceEngine:
|
||||
self._background_tasks: int = 0
|
||||
self._background_tasks_lock = threading.Lock()
|
||||
|
||||
# P1-2: Plugin-State-Datei für DetectionTimer (Gateway-interne Subagenten)
|
||||
self._plugin_state_path: str = _get_plugin_state_path()
|
||||
self._plugin_state_lock = threading.Lock() # Thread-safe, nicht asyncio
|
||||
|
||||
# P1a: Honeymoon-Timer — busy status minimum 1s sichtbar
|
||||
self._busy_started_at: float = 0.0 # time.monotonic() when busy started
|
||||
self._busy_honeymoon_timer: Optional[threading.Timer] = None
|
||||
@@ -384,6 +457,8 @@ class PresenceEngine:
|
||||
def increment_background_tasks(self) -> int:
|
||||
"""Increment background tasks counter. Thread-safe.
|
||||
|
||||
P1-2: Persists to plugin state file for DetectionTimer.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
@@ -391,11 +466,14 @@ class PresenceEngine:
|
||||
self._background_tasks += 1
|
||||
count = self._background_tasks
|
||||
self._pulse_controller.set_background_count(count)
|
||||
self._persist_plugin_state(count)
|
||||
return count
|
||||
|
||||
def decrement_background_tasks(self) -> int:
|
||||
"""Decrement background tasks counter. Thread-safe.
|
||||
|
||||
P1-2: Persists to plugin state file for DetectionTimer.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
@@ -406,8 +484,27 @@ class PresenceEngine:
|
||||
self._pulse_controller.set_background_count(count)
|
||||
if count == 0:
|
||||
self._pulse_controller.stop()
|
||||
self._persist_plugin_state(count)
|
||||
return count
|
||||
|
||||
def _persist_plugin_state(self, background_tasks: int) -> None:
|
||||
"""P1-2: Persist background_tasks to plugin state file.
|
||||
|
||||
Thread-safe via _plugin_state_lock. Writes atomically via
|
||||
_write_plugin_state (temp + rename).
|
||||
|
||||
Args:
|
||||
background_tasks: Current background tasks count.
|
||||
"""
|
||||
with self._plugin_state_lock:
|
||||
data = {
|
||||
"background_tasks": background_tasks,
|
||||
"last_update_iso": datetime.now(timezone.utc).isoformat(),
|
||||
"source": "plugin_internal",
|
||||
"schema_version": PLUGIN_STATE_SCHEMA_VERSION,
|
||||
}
|
||||
_write_plugin_state(self._plugin_state_path, data)
|
||||
|
||||
# ── Internal: Presence Setting ───────────────────────────────────────
|
||||
|
||||
def _set_presence(self, status: str, message: str) -> None:
|
||||
@@ -957,8 +1054,9 @@ class DetectionTimer:
|
||||
"""Detects whether background agents are active.
|
||||
|
||||
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).
|
||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
||||
|
||||
pgrep pattern: 'hermes_cli|hermes chat' (catches subagents AND gateway
|
||||
subprocesses). Self-pid exclude is preserved.
|
||||
@@ -971,6 +1069,7 @@ class DetectionTimer:
|
||||
gateway_state_path: str = "",
|
||||
detection_interval: float = 10.0,
|
||||
on_change: Optional[Callable[[bool], None]] = None,
|
||||
plugin_state_path: str = "",
|
||||
):
|
||||
"""Initialize DetectionTimer.
|
||||
|
||||
@@ -978,6 +1077,8 @@ class DetectionTimer:
|
||||
gateway_state_path: Path to gateway_state.json.
|
||||
detection_interval: Check interval in seconds (default 10).
|
||||
on_change: Callback(is_active) when detection state changes.
|
||||
plugin_state_path: P1-2: Path to plugin state file. Defaults to
|
||||
~/.hermes/plugin_state/hermes_rocket_plugin.json.
|
||||
"""
|
||||
if not gateway_state_path:
|
||||
gateway_state_path = os.environ.get(
|
||||
@@ -985,6 +1086,12 @@ class DetectionTimer:
|
||||
os.path.expanduser("~/.hermes/gateway_state.json"),
|
||||
)
|
||||
self._gateway_state_path = gateway_state_path
|
||||
|
||||
# P1-2: Plugin-State-Datei für Gateway-interne Subagenten
|
||||
if not plugin_state_path:
|
||||
plugin_state_path = _get_plugin_state_path()
|
||||
self._plugin_state_path = plugin_state_path
|
||||
|
||||
self._detection_interval = detection_interval
|
||||
self._on_change = on_change
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
@@ -1021,8 +1128,9 @@ class DetectionTimer:
|
||||
"""Check if background agents are active.
|
||||
|
||||
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).
|
||||
P1-2: plugin_state.json is SECONDARY — background_tasks > 0 means active.
|
||||
pgrep is TERTIARY/CONFIRM — used as fallback when gateway_state and
|
||||
plugin_state are unavailable or return 0/1 (ambiguous).
|
||||
|
||||
pgrep pattern expanded from 'hermes chat --profile' to
|
||||
'hermes_cli|hermes chat' to catch subagents AND gateway subprocesses.
|
||||
@@ -1038,6 +1146,9 @@ class DetectionTimer:
|
||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||
gateway_active = 0
|
||||
gateway_used = False # True if gateway_state was the deciding signal
|
||||
plugin_used = False # P1-2: True if plugin_state was the deciding signal
|
||||
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
|
||||
detection_source = "none" # P1-2: which signal decided
|
||||
|
||||
# ── PRIMARY: gateway_state.json ────────────────────────────────────
|
||||
try:
|
||||
@@ -1048,12 +1159,22 @@ class DetectionTimer:
|
||||
if gateway_active > 1:
|
||||
result = True
|
||||
gateway_used = True
|
||||
detection_source = "gateway"
|
||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
||||
# Fall through to pgrep
|
||||
# Fall through to plugin_state
|
||||
|
||||
# ── SECONDARY: pgrep — run when gateway_state didn't decide ───────
|
||||
# ── P1-2: SECONDARY: plugin_state.json ─────────────────────────────
|
||||
if not gateway_used:
|
||||
plugin_state = _read_plugin_state(self._plugin_state_path)
|
||||
plugin_bg_tasks = plugin_state.get("background_tasks", 0)
|
||||
if plugin_bg_tasks > 0:
|
||||
result = True
|
||||
plugin_used = True
|
||||
detection_source = "plugin_state"
|
||||
|
||||
# ── TERTIARY: pgrep — run when neither gateway nor plugin decided ──
|
||||
if not gateway_used and not plugin_used:
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
# P1b: Expanded pattern catches subagents AND gateway subprocesses
|
||||
@@ -1069,20 +1190,31 @@ class DetectionTimer:
|
||||
pids = [p for p in all_pids if p != own_pid]
|
||||
pgrep_pids = len(pids)
|
||||
result = pgrep_pids > 0
|
||||
if result:
|
||||
detection_source = "pgrep"
|
||||
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 ─────────────────────────────────────
|
||||
# ── Log: all signals, result, source ───────────────────────────────
|
||||
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
||||
plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a"
|
||||
logger.info(
|
||||
"[detection] check #%d: gateway_state=%d (primary=%s), pgrep=%s, result=%s",
|
||||
"[detection] check #%d: gateway_state=%d (primary=%s), "
|
||||
"plugin_state=%s (bg_tasks=%s), pgrep=%s, "
|
||||
"result=%s, source=%s",
|
||||
self._check_count, gateway_active,
|
||||
"yes" if gateway_used else "no",
|
||||
"yes" if plugin_used else "no",
|
||||
plugin_str,
|
||||
pgrep_str,
|
||||
"active" if result else "inactive",
|
||||
detection_source,
|
||||
)
|
||||
|
||||
# P1-2: Set telemetry source
|
||||
self._set_detection_source_telemetry(detection_source)
|
||||
|
||||
# Notify on change (P1-2: callback fires from check() itself)
|
||||
if result != self._last_result and self._on_change is not None:
|
||||
try:
|
||||
@@ -1130,3 +1262,21 @@ class DetectionTimer:
|
||||
routing_telemetry.heartbeat_detection += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _set_detection_source_telemetry(self, source: str) -> None:
|
||||
"""P1-2: Set the heartbeat_detection_source telemetry field.
|
||||
|
||||
Args:
|
||||
source: One of 'gateway', 'plugin_state', 'pgrep', 'none'.
|
||||
"""
|
||||
try:
|
||||
from plugin.archivar.routing_telemetry import routing_telemetry
|
||||
except ImportError:
|
||||
try:
|
||||
from archivar.routing_telemetry import routing_telemetry
|
||||
except ImportError:
|
||||
return
|
||||
try:
|
||||
routing_telemetry.heartbeat_detection_source = source
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -52,6 +52,8 @@ class RoutingTelemetry:
|
||||
# Heartbeat-Pulsierung Telemetrie
|
||||
self.heartbeat_pulse: int = 0
|
||||
self.heartbeat_detection: int = 0
|
||||
# P1-2: Detection source tracking
|
||||
self.heartbeat_detection_source: str = "none"
|
||||
|
||||
@staticmethod
|
||||
def _read_feature_flag() -> bool:
|
||||
|
||||
@@ -1777,3 +1777,400 @@ class TestHoneymoonBusyMinVisible:
|
||||
assert busy_idx < online_idx, (
|
||||
f"busy (idx={busy_idx}) muss vor online (idx={online_idx}) kommen: {statuses}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-2: Plugin-State-Datei — Pfad, atomares Lesen/Schreiben
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestPluginStateFile:
|
||||
"""P1-2: Plugin-State-Datei — Pfad, atomares Lesen/Schreiben."""
|
||||
|
||||
def test_get_plugin_state_path_default(self):
|
||||
"""_get_plugin_state_path() liefert ~/.hermes/plugin_state/hermes_rocket_plugin.json."""
|
||||
from plugin.archivar.presence_engine import _get_plugin_state_path
|
||||
path = _get_plugin_state_path()
|
||||
assert path.endswith("hermes_rocket_plugin.json")
|
||||
assert ".hermes" in path
|
||||
assert "plugin_state" in path
|
||||
|
||||
def test_read_plugin_state_missing_file(self):
|
||||
"""_read_plugin_state() bei fehlender Datei → {}."""
|
||||
from plugin.archivar.presence_engine import _read_plugin_state
|
||||
result = _read_plugin_state("/tmp/nonexistent_plugin_state.json")
|
||||
assert result == {}
|
||||
|
||||
def test_read_plugin_state_valid(self, tmp_path):
|
||||
"""_read_plugin_state() liest gültige JSON-Datei."""
|
||||
from plugin.archivar.presence_engine import _read_plugin_state
|
||||
import json
|
||||
p = tmp_path / "state.json"
|
||||
p.write_text(json.dumps({"background_tasks": 3, "last_update_iso": "2026-01-01T00:00:00", "source": "plugin_internal", "schema_version": 1}))
|
||||
result = _read_plugin_state(str(p))
|
||||
assert result["background_tasks"] == 3
|
||||
assert result["source"] == "plugin_internal"
|
||||
|
||||
def test_read_plugin_state_corrupt_json(self, tmp_path):
|
||||
"""_read_plugin_state() bei korrupter JSON → {} (kein Crash)."""
|
||||
from plugin.archivar.presence_engine import _read_plugin_state
|
||||
p = tmp_path / "state.json"
|
||||
p.write_text("{invalid json")
|
||||
result = _read_plugin_state(str(p))
|
||||
assert result == {}
|
||||
|
||||
def test_write_plugin_state_atomic(self, tmp_path):
|
||||
"""_write_plugin_state() schreibt atomar (temp + rename)."""
|
||||
from plugin.archivar.presence_engine import _write_plugin_state, _read_plugin_state
|
||||
import json
|
||||
p = tmp_path / "state.json"
|
||||
data = {"background_tasks": 5, "last_update_iso": "2026-01-01T00:00:00", "source": "plugin_internal", "schema_version": 1}
|
||||
_write_plugin_state(str(p), data)
|
||||
# Datei existiert
|
||||
assert p.exists()
|
||||
# Inhalt korrekt
|
||||
result = _read_plugin_state(str(p))
|
||||
assert result["background_tasks"] == 5
|
||||
# Keine .tmp-Datei liegt rum
|
||||
assert not list(tmp_path.glob("*.tmp"))
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-2: Plugin-State Persistenz in increment/decrement_background_tasks
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestPluginStatePersistence:
|
||||
"""P1-2: increment/decrement_background_tasks persistieren in Plugin-State-Datei."""
|
||||
|
||||
def test_increment_writes_plugin_state(self, tmp_path):
|
||||
"""increment_background_tasks() schreibt background_tasks in Plugin-State-Datei."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine, _read_plugin_state
|
||||
|
||||
state_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
# Override path for test
|
||||
engine._plugin_state_path = state_path
|
||||
|
||||
count = engine.increment_background_tasks()
|
||||
assert count == 1
|
||||
|
||||
# Read back from file
|
||||
state = _read_plugin_state(state_path)
|
||||
assert state["background_tasks"] == 1
|
||||
assert state["source"] == "plugin_internal"
|
||||
assert "last_update_iso" in state
|
||||
|
||||
def test_decrement_writes_plugin_state(self, tmp_path):
|
||||
"""decrement_background_tasks() schreibt reduzierten Wert in Plugin-State-Datei."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine, _read_plugin_state
|
||||
|
||||
state_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
engine._plugin_state_path = state_path
|
||||
|
||||
engine.increment_background_tasks()
|
||||
engine.increment_background_tasks()
|
||||
count = engine.decrement_background_tasks()
|
||||
assert count == 1
|
||||
|
||||
state = _read_plugin_state(state_path)
|
||||
assert state["background_tasks"] == 1
|
||||
|
||||
def test_decrement_to_zero_writes_zero(self, tmp_path):
|
||||
"""decrement auf 0 schreibt background_tasks=0 in Datei."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine, _read_plugin_state
|
||||
|
||||
state_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
engine._plugin_state_path = state_path
|
||||
|
||||
engine.increment_background_tasks()
|
||||
count = engine.decrement_background_tasks()
|
||||
assert count == 0
|
||||
|
||||
state = _read_plugin_state(state_path)
|
||||
assert state["background_tasks"] == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-2: DetectionTimer erkennt Plugin-State-Datei
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestDetectionTimerPluginState:
|
||||
"""P1-2: DetectionTimer erkennt Plugin-State-Datei."""
|
||||
|
||||
def test_plugin_state_background_tasks_positive_detected(self, tmp_path):
|
||||
"""Plugin-State mit background_tasks=3 → check() returns True."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
|
||||
|
||||
state_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
_write_plugin_state(state_path, {
|
||||
"background_tasks": 3,
|
||||
"last_update_iso": "2026-01-01T00:00:00",
|
||||
"source": "plugin_internal",
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
assert result is True
|
||||
|
||||
def test_plugin_state_background_tasks_zero_not_detected(self, tmp_path):
|
||||
"""Plugin-State mit background_tasks=0 → check() fällt auf pgrep zurück."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
|
||||
|
||||
state_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
_write_plugin_state(state_path, {
|
||||
"background_tasks": 0,
|
||||
"last_update_iso": "2026-01-01T00:00:00",
|
||||
"source": "plugin_internal",
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
own_pid = os.getpid()
|
||||
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,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
||||
assert result is False
|
||||
|
||||
def test_plugin_state_missing_file_no_error(self):
|
||||
"""Plugin-State-Datei fehlt → kein Fehler, fällt zurück auf gateway_state+pgrep."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
own_pid = os.getpid()
|
||||
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,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
result = dt.check()
|
||||
# pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
||||
"""Korrupte Plugin-State-Datei → kein Crash, graceful fallback."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
|
||||
state_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
# Schreibe korruptes JSON
|
||||
with open(state_path, 'w') as f:
|
||||
f.write("{invalid json {{{")
|
||||
|
||||
own_pid = os.getpid()
|
||||
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,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
||||
assert result is True
|
||||
|
||||
def test_plugin_state_priority_after_gateway(self, tmp_path):
|
||||
"""Plugin-State wird NACH gateway_state geprüft (gateway hat Vorrang)."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
|
||||
import tempfile, json
|
||||
|
||||
# gateway_state mit active_agents=3 (>1 → PRIMARY entscheidet)
|
||||
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
gw_path = f.name
|
||||
|
||||
try:
|
||||
# Plugin-State mit background_tasks=0 (würde allein nicht reichen)
|
||||
plugin_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(plugin_path), exist_ok=True)
|
||||
_write_plugin_state(plugin_path, {
|
||||
"background_tasks": 0,
|
||||
"last_update_iso": "2026-01-01T00:00:00",
|
||||
"source": "plugin_internal",
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=plugin_path,
|
||||
)
|
||||
result = dt.check()
|
||||
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
|
||||
assert result is True
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(gw_path)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-2: Telemetrie — heartbeat_detection_source Feld
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestDetectionSourceTelemetry:
|
||||
"""P1-2: heartbeat_detection_source Telemetrie-Feld."""
|
||||
|
||||
def test_detection_source_set_on_check_plugin_state(self, tmp_path):
|
||||
"""Nach check() mit plugin_state → source='plugin_state'."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer, _write_plugin_state
|
||||
from plugin.archivar.routing_telemetry import routing_telemetry
|
||||
|
||||
# Reset
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
state_path = str(tmp_path / "hermes_rocket_plugin.json")
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
_write_plugin_state(state_path, {
|
||||
"background_tasks": 3,
|
||||
"last_update_iso": "2026-01-01T00:00:00",
|
||||
"source": "plugin_internal",
|
||||
"schema_version": 1,
|
||||
})
|
||||
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path="/tmp/nonexistent_gateway_state.json",
|
||||
detection_interval=0.1,
|
||||
plugin_state_path=state_path,
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "plugin_state"
|
||||
|
||||
def test_detection_source_none_when_inactive(self):
|
||||
"""Wenn nichts gefunden → source='none'."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.routing_telemetry import routing_telemetry
|
||||
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
own_pid = os.getpid()
|
||||
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,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "none"
|
||||
|
||||
def test_detection_source_pgrep(self):
|
||||
"""pgrep findet Agenten → source='pgrep'."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.routing_telemetry import routing_telemetry
|
||||
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
own_pid = os.getpid()
|
||||
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,
|
||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "pgrep"
|
||||
|
||||
def test_detection_source_gateway(self, tmp_path):
|
||||
"""gateway_state entscheidet → source='gateway'."""
|
||||
from plugin.archivar.presence_engine import DetectionTimer
|
||||
from plugin.archivar.routing_telemetry import routing_telemetry
|
||||
import tempfile, json
|
||||
|
||||
routing_telemetry.heartbeat_detection_source = "none"
|
||||
|
||||
state = {"active_agents": 3, "profiles": ["default", "miguel", "anna"]}
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
|
||||
json.dump(state, f)
|
||||
gw_path = f.name
|
||||
|
||||
try:
|
||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
||||
dt = DetectionTimer(
|
||||
gateway_state_path=gw_path,
|
||||
detection_interval=0.1,
|
||||
)
|
||||
dt.check()
|
||||
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
||||
mock_run.assert_not_called()
|
||||
finally:
|
||||
os.unlink(gw_path)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-2: Integration — PresenceEngine übergibt plugin_state_path an DetectionTimer
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestPresenceEnginePluginStateIntegration:
|
||||
"""P1-2: PresenceEngine → DetectionTimer plugin_state_path Integration."""
|
||||
|
||||
def test_detection_timer_has_plugin_state_path(self):
|
||||
"""DetectionTimer bekommt plugin_state_path von PresenceEngine."""
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
|
||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||
assert engine._detection_timer._plugin_state_path is not None
|
||||
assert "plugin_state" in engine._detection_timer._plugin_state_path
|
||||
assert "hermes_rocket_plugin.json" in engine._detection_timer._plugin_state_path
|
||||
|
||||
Reference in New Issue
Block a user