feat: V8.7 pgrep-basierte Subagent-Erkennung ersetzt subagent_status.json
- adapter.py: register()-Block entfernt (wurde bei jedem Turn aufgerufen) - subagent_tracker.py: register()/complete() zu no-ops, Modul bleibt kompatibel - presence_engine.py: _pgrep_hermes_subagents() scannt /proc/*/cmdline nach 'hermes chat --profile' Prozessen (exkl. eigene PID, <1ms) - DetectionTimer.check(): pgrep als vierte Quelle (nach PID-Sentinel, gateway_state, plugin_state), ersetzt subagent_status.json - _stale_recovery() entfernt (pgrep braucht kein Cleanup) - _read_subagent_count() delegiert an _pgrep_hermes_subagents() - subprocess-Import entfernt - 1434 Tests grün (test_subagent_tracker, test_subagent_status_presence, test_presence_engine alle angepasst)
This commit is contained in:
@@ -2236,14 +2236,6 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._presence_engine.increment_background_tasks()
|
self._presence_engine.increment_background_tasks()
|
||||||
logger.info("[presence] mark_busy_started (room=%s)", room_name)
|
logger.info("[presence] mark_busy_started (room=%s)", room_name)
|
||||||
|
|
||||||
# Phase 5: SubagentTracker — register background task for subagent_status.json
|
|
||||||
_has_tracker = hasattr(self, '_subagent_tracker') and self._subagent_tracker is not None
|
|
||||||
if _has_tracker:
|
|
||||||
try:
|
|
||||||
self._subagent_tracker.register("background_task", room_name=room_name)
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug("[subagent_tracker] register failed (non-critical): %s", e)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||||
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import subprocess
|
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
@@ -405,13 +404,13 @@ class PresenceEngine:
|
|||||||
"""Phase 5: Transition from busy — check subagents before going online.
|
"""Phase 5: Transition from busy — check subagents before going online.
|
||||||
|
|
||||||
Called when mark_busy_done or _honeymoon_expired would normally
|
Called when mark_busy_done or _honeymoon_expired would normally
|
||||||
transition to online. If background_tasks > 0 or subagent_status.json
|
transition to online. If background_tasks > 0 or pgrep finds subagents,
|
||||||
has active entries, start/keep PulseController instead.
|
has active entries, start/keep PulseController instead.
|
||||||
"""
|
"""
|
||||||
with self._background_tasks_lock:
|
with self._background_tasks_lock:
|
||||||
bg = self._background_tasks
|
bg = self._background_tasks
|
||||||
|
|
||||||
# Phase 5: Auch subagent_status.json prüfen
|
# Phase 5: Auch pgrep prüfen
|
||||||
subagent_count = self._read_subagent_count()
|
subagent_count = self._read_subagent_count()
|
||||||
|
|
||||||
if bg > 0 or subagent_count > 0:
|
if bg > 0 or subagent_count > 0:
|
||||||
@@ -422,17 +421,15 @@ class PresenceEngine:
|
|||||||
self.update_presence()
|
self.update_presence()
|
||||||
|
|
||||||
def _read_subagent_count(self) -> int:
|
def _read_subagent_count(self) -> int:
|
||||||
"""Phase 5: Read active subagent count from subagent_status.json.
|
"""V8.7: Read active subagent count via pgrep /proc scan.
|
||||||
|
|
||||||
|
Scannt /proc/*/cmdline nach 'hermes' + 'chat' + '--profile' Prozessen.
|
||||||
|
Schließt die eigene PID aus. Kein subprocess — direkt /proc lesen.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Number of active subagent entries, or 0 on any error.
|
Number of active hermes chat --profile processes (excluding self).
|
||||||
"""
|
"""
|
||||||
try:
|
return DetectionTimer._pgrep_hermes_subagents()
|
||||||
from archivar.subagent_tracker import _read_subagent_state, _get_subagent_state_path
|
|
||||||
state = _read_subagent_state(_get_subagent_state_path())
|
|
||||||
return len(state.get("active", []))
|
|
||||||
except Exception:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
def _update_presence_with_subagents(self, subagent_count: int) -> None:
|
def _update_presence_with_subagents(self, subagent_count: int) -> None:
|
||||||
"""Phase 5: Set presence when subagents are active.
|
"""Phase 5: Set presence when subagents are active.
|
||||||
@@ -511,7 +508,7 @@ class PresenceEngine:
|
|||||||
logger.info(
|
logger.info(
|
||||||
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → transition"
|
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → transition"
|
||||||
)
|
)
|
||||||
# Phase 5: _transition_from_busy prüft subagent_status.json
|
# Phase 5: _transition_from_busy prüft pgrep
|
||||||
self._transition_from_busy()
|
self._transition_from_busy()
|
||||||
else:
|
else:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -594,7 +591,7 @@ class PresenceEngine:
|
|||||||
count = self._background_tasks
|
count = self._background_tasks
|
||||||
self._pulse_controller.set_background_count(count)
|
self._pulse_controller.set_background_count(count)
|
||||||
# Phase 5: stop() NICHT hier — _update_presence_with_subagents()
|
# Phase 5: stop() NICHT hier — _update_presence_with_subagents()
|
||||||
# entscheidet basierend auf subagent_status.json + background_tasks
|
# entscheidet basierend auf pgrep + background_tasks
|
||||||
self._persist_plugin_state(count)
|
self._persist_plugin_state(count)
|
||||||
return count
|
return count
|
||||||
|
|
||||||
@@ -1482,14 +1479,11 @@ class DetectionTimer:
|
|||||||
self._increment_telemetry()
|
self._increment_telemetry()
|
||||||
|
|
||||||
result = False
|
result = False
|
||||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
|
||||||
gateway_active = 0
|
gateway_active = 0
|
||||||
pid_used = False # P2: True if PID-Sentinel was the deciding signal
|
pid_used = False # P2: True if PID-Sentinel was the deciding signal
|
||||||
gateway_used = False # True if gateway_state was the deciding signal
|
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_used = False # P1-2: True if plugin_state was the deciding signal
|
||||||
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
|
plugin_bg_tasks = -1 # P1-2: -1 = not read, >=0 = count
|
||||||
subagent_used = False # Phase 5: True if subagent_status.json was the deciding signal
|
|
||||||
subagent_count = -1 # Phase 5: -1 = not read, >=0 = count
|
|
||||||
detection_source = "none" # P1-2: which signal decided
|
detection_source = "none" # P1-2: which signal decided
|
||||||
|
|
||||||
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
|
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
|
||||||
@@ -1523,55 +1517,21 @@ class DetectionTimer:
|
|||||||
plugin_used = True
|
plugin_used = True
|
||||||
detection_source = "plugin_state"
|
detection_source = "plugin_state"
|
||||||
|
|
||||||
# ── Phase 5: QUATERNARY: subagent_status.json ────────────────────────
|
# ── V8.7: pgrep /proc scan — hermes chat --profile Prozesse ──
|
||||||
|
# Ersetzt subagent_status.json als vierte Quelle.
|
||||||
|
# Direkt /proc lesen, kein subprocess.
|
||||||
|
pgrep_count = 0
|
||||||
if not pid_used and not gateway_used and not plugin_used:
|
if not pid_used and not gateway_used and not plugin_used:
|
||||||
try:
|
pgrep_count = self._pgrep_hermes_subagents()
|
||||||
from archivar.subagent_tracker import _read_subagent_state, _get_subagent_state_path
|
if pgrep_count > 0:
|
||||||
subagent_state = _read_subagent_state(_get_subagent_state_path())
|
|
||||||
active_entries = subagent_state.get("active", [])
|
|
||||||
subagent_count = len(active_entries)
|
|
||||||
if subagent_count > 0:
|
|
||||||
result = True
|
result = True
|
||||||
subagent_used = True
|
|
||||||
detection_source = "subagent_status"
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug("[detection] subagent_status.json read failed: %s", e)
|
|
||||||
|
|
||||||
# ── Phase 5: Stale-Recovery — räumt tote PID-Einträge auf ──────────
|
|
||||||
# Läuft IMMER (nicht nur wenn subagent_used), damit auch Einträge
|
|
||||||
# aufgeräumt werden wenn PID-Sentinel oder gateway_state aktiv sind.
|
|
||||||
self._stale_recovery()
|
|
||||||
|
|
||||||
# ── P2 QUATERNARY: pgrep — erweitertes Pattern 'gateway run' ────────
|
|
||||||
if not pid_used and not gateway_used and not plugin_used and not subagent_used:
|
|
||||||
try:
|
|
||||||
own_pid = os.getpid()
|
|
||||||
# P2 Fix: Pattern um 'gateway run' erweitert
|
|
||||||
proc = subprocess.run(
|
|
||||||
["pgrep", "-f", "hermes_cli|hermes chat|gateway run"],
|
|
||||||
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
|
|
||||||
if result:
|
|
||||||
detection_source = "pgrep"
|
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: all signals, result, source ───────────────────────────────
|
# ── 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"
|
plugin_str = str(plugin_bg_tasks) if plugin_bg_tasks >= 0 else "n/a"
|
||||||
subagent_str = str(subagent_count) if subagent_count >= 0 else "n/a"
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"[detection] check #%d: pid_sentinel=%s, gateway_state=%d (primary=%s), "
|
"[detection] check #%d: pid_sentinel=%s, gateway_state=%d (primary=%s), "
|
||||||
"plugin_state=%s (bg_tasks=%s), subagent_status=%s (active=%s), pgrep=%s, "
|
"plugin_state=%s (bg_tasks=%s), pgrep=%d, "
|
||||||
"result=%s, source=%s",
|
"result=%s, source=%s",
|
||||||
self._check_count,
|
self._check_count,
|
||||||
"alive" if pid_used else "dead",
|
"alive" if pid_used else "dead",
|
||||||
@@ -1579,9 +1539,7 @@ class DetectionTimer:
|
|||||||
"yes" if gateway_used else "no",
|
"yes" if gateway_used else "no",
|
||||||
"yes" if plugin_used else "no",
|
"yes" if plugin_used else "no",
|
||||||
plugin_str,
|
plugin_str,
|
||||||
"yes" if subagent_used else "no",
|
pgrep_count,
|
||||||
subagent_str,
|
|
||||||
pgrep_str,
|
|
||||||
"active" if result else "inactive",
|
"active" if result else "inactive",
|
||||||
detection_source,
|
detection_source,
|
||||||
)
|
)
|
||||||
@@ -1604,71 +1562,40 @@ class DetectionTimer:
|
|||||||
self._last_result = result
|
self._last_result = result
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def _stale_recovery(self) -> int:
|
@staticmethod
|
||||||
"""Phase 5: Stale-Recovery — räumt tote PID-Einträge aus subagent_status.json.
|
def _pgrep_hermes_subagents() -> int:
|
||||||
|
"""V8.7: Scan /proc/*/cmdline for 'hermes chat --profile' processes.
|
||||||
|
|
||||||
Für jeden aktiven Eintrag prüfen:
|
Iterates /proc/<pid>/cmdline, parses for 'hermes' + 'chat' + '--profile'.
|
||||||
- os.kill(pid, 0) oder /proc/<pid>/ — lebt der Prozess noch?
|
Excludes own PID. No subprocess — direct /proc read, <1ms for ~100 procs.
|
||||||
- Wenn PID tot → Eintrag entfernen (remove_by_task_id)
|
|
||||||
- Wenn expected_done_at überschritten UND PID tot → aufräumen
|
|
||||||
- Wenn expected_done_at überschritten UND PID noch lebend → Eintrag bleibt
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Number of entries removed.
|
Number of matching processes (excluding self).
|
||||||
"""
|
"""
|
||||||
removed = 0
|
own_pid = os.getpid()
|
||||||
|
count = 0
|
||||||
try:
|
try:
|
||||||
from archivar.subagent_tracker import (
|
for entry in os.listdir("/proc"):
|
||||||
_read_subagent_state, _get_subagent_state_path, get_tracker,
|
if not entry.isdigit():
|
||||||
)
|
continue
|
||||||
state = _read_subagent_state(_get_subagent_state_path())
|
pid = int(entry)
|
||||||
active = state.get("active", [])
|
if pid == own_pid:
|
||||||
if not active:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
tracker = get_tracker()
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
|
|
||||||
for entry in list(active): # iterate over copy
|
|
||||||
task_id = entry.get("task_id", "")
|
|
||||||
pid = entry.get("pid", 0)
|
|
||||||
if not task_id or not pid:
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Check if PID is alive
|
|
||||||
pid_alive = self._pid_is_alive(pid)
|
|
||||||
|
|
||||||
if not pid_alive:
|
|
||||||
# PID is dead — always clean up
|
|
||||||
tracker.remove_by_task_id(task_id)
|
|
||||||
removed += 1
|
|
||||||
logger.info(
|
|
||||||
"[detection] stale recovery: removed dead PID %d (task_id=%s)",
|
|
||||||
pid, task_id,
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
# PID is alive — check expected_done_at
|
|
||||||
expected_done_str = entry.get("expected_done_at", "")
|
|
||||||
if expected_done_str:
|
|
||||||
try:
|
try:
|
||||||
expected_done = datetime.fromisoformat(expected_done_str)
|
with open(f"/proc/{entry}/cmdline", "rb") as f:
|
||||||
if now > expected_done:
|
raw = f.read()
|
||||||
# expected_done_at überschritten, aber PID lebt noch
|
# cmdline is null-separated; decode and split
|
||||||
# → Eintrag bleibt (long-running Task)
|
parts = raw.decode("utf-8", errors="replace").split("\x00")
|
||||||
logger.debug(
|
cmdline_str = " ".join(parts)
|
||||||
"[detection] stale recovery: task_id=%s pid=%d "
|
# Match: contains 'hermes' AND 'chat' AND '--profile'
|
||||||
"exceeded expected_done_at but still alive — keeping",
|
if "hermes" in cmdline_str and "chat" in cmdline_str and "--profile" in cmdline_str:
|
||||||
task_id, pid,
|
count += 1
|
||||||
)
|
except (OSError, IOError, PermissionError):
|
||||||
except (ValueError, TypeError):
|
# Process may have exited or be inaccessible
|
||||||
|
continue
|
||||||
|
except (OSError, IOError):
|
||||||
pass
|
pass
|
||||||
|
return count
|
||||||
except Exception as e:
|
|
||||||
logger.debug("[detection] stale recovery failed: %s", e)
|
|
||||||
|
|
||||||
if removed > 0:
|
|
||||||
logger.info("[detection] stale recovery: removed %d stale entries", removed)
|
|
||||||
return removed
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _pid_is_alive(pid: int) -> bool:
|
def _pid_is_alive(pid: int) -> bool:
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
V8.6 Phase 5: SubagentTracker — Adapter-seitiges Modul für Subagent-Status.
|
V8.7: SubagentTracker — Kompatibilitätsmodul (no-ops).
|
||||||
|
|
||||||
Persistiert aktive Subagenten nach ~/.hermes/plugin_state/subagent_status.json.
|
Die subagent_status.json-basierte Erkennung wurde durch pgrep-basierte
|
||||||
Thread-safe. Atomic write via temp+rename (Pattern aus _write_plugin_state).
|
/proc-Erkennung in presence_engine.py ersetzt. Dieses Modul bleibt als
|
||||||
|
Kompatibilitätsschicht erhalten, aber register()/complete() sind no-ops.
|
||||||
|
|
||||||
Zero external dependencies — stdlib only.
|
Zero external dependencies — stdlib only.
|
||||||
"""
|
"""
|
||||||
@@ -14,14 +15,12 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
import time
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from typing import Optional, List, Dict
|
from typing import Optional, List, Dict
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Constants
|
# Constants (beibehalten für Kompatibilität)
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
SUBAGENT_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
|
SUBAGENT_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
|
||||||
@@ -30,218 +29,67 @@ SUBAGENT_STATE_SCHEMA_VERSION = 1
|
|||||||
|
|
||||||
|
|
||||||
def _get_subagent_state_path() -> str:
|
def _get_subagent_state_path() -> str:
|
||||||
"""Return the path to the subagent status file."""
|
"""Return the path to the subagent status file (Kompatibilität)."""
|
||||||
return os.path.join(SUBAGENT_STATE_DIR, SUBAGENT_STATE_FILENAME)
|
return os.path.join(SUBAGENT_STATE_DIR, SUBAGENT_STATE_FILENAME)
|
||||||
|
|
||||||
|
|
||||||
def _read_subagent_state(path: str) -> dict:
|
def _read_subagent_state(path: str) -> dict:
|
||||||
"""Read the subagent state file, returning default empty dict if missing or corrupt."""
|
"""Read the subagent state file, returning default empty dict if missing or corrupt.
|
||||||
try:
|
|
||||||
if not os.path.exists(path):
|
V8.7: Immer leeres dict — subagent_status.json wird nicht mehr verwendet.
|
||||||
return {"active": [], "last_change_iso": "", "schema_version": SUBAGENT_STATE_SCHEMA_VERSION, "source": "plugin_internal"}
|
"""
|
||||||
with open(path, 'r') as f:
|
|
||||||
return json.load(f)
|
|
||||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
|
||||||
logger.debug("[subagent_tracker] read failed: %s", e)
|
|
||||||
return {"active": [], "last_change_iso": "", "schema_version": SUBAGENT_STATE_SCHEMA_VERSION, "source": "plugin_internal"}
|
return {"active": [], "last_change_iso": "", "schema_version": SUBAGENT_STATE_SCHEMA_VERSION, "source": "plugin_internal"}
|
||||||
|
|
||||||
|
|
||||||
def _write_subagent_state(path: str, data: dict) -> None:
|
def _write_subagent_state(path: str, data: dict) -> None:
|
||||||
"""Atomically write the subagent state file (write-temp + rename).
|
"""V8.7: No-op — subagent_status.json wird nicht mehr geschrieben."""
|
||||||
|
|
||||||
Pattern from _write_plugin_state in presence_engine.py.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
||||||
fd, tmp_path = tempfile.mkstemp(
|
|
||||||
suffix=".tmp",
|
|
||||||
prefix="subagent_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:
|
|
||||||
try:
|
|
||||||
os.unlink(tmp_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
pass
|
||||||
raise
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug("[subagent_tracker] write failed: %s", e)
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# SubagentTracker
|
# SubagentTracker (no-ops)
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class SubagentTracker:
|
class SubagentTracker:
|
||||||
"""Tracks active subagents for the PresenceEngine.
|
"""V8.7: No-op Tracker — pgrep ersetzt subagent_status.json.
|
||||||
|
|
||||||
Thread-safe: uses threading.Lock for all state mutations.
|
Alle Methoden sind no-ops. Das Modul bleibt für Kompatibilität erhalten.
|
||||||
Atomic write: temp+rename pattern prevents corruption.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
tracker = SubagentTracker()
|
|
||||||
tracker.register("delegate_task", room_name="user:bernd")
|
|
||||||
# ... subagent runs ...
|
|
||||||
tracker.complete("delegate_task")
|
|
||||||
active = tracker.list() # → []
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, state_path: str = ""):
|
def __init__(self, state_path: str = ""):
|
||||||
"""Initialize SubagentTracker.
|
self._state_path = state_path or _get_subagent_state_path()
|
||||||
|
|
||||||
Args:
|
|
||||||
state_path: Path to subagent_status.json. Defaults to
|
|
||||||
~/.hermes/plugin_state/subagent_status.json.
|
|
||||||
"""
|
|
||||||
if not state_path:
|
|
||||||
state_path = _get_subagent_state_path()
|
|
||||||
self._state_path = state_path
|
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
def register(self, subagent_type: str, room_name: str = "", task_id: str = "", pid: int = 0) -> dict:
|
def register(self, subagent_type: str, room_name: str = "", task_id: str = "", pid: int = 0) -> dict:
|
||||||
"""Register a new active subagent.
|
"""V8.7: No-op — pgrep-basierte Erkennung ersetzt register()."""
|
||||||
|
logger.debug("[subagent_tracker] register() no-op (pgrep mode): type=%s", subagent_type)
|
||||||
Args:
|
return {"task_id": "", "type": subagent_type, "owner_room": room_name, "pid": 0}
|
||||||
subagent_type: One of 'delegate_task', 'terminal_background', 'task_management'.
|
|
||||||
room_name: Owner room (e.g. 'user:bernd').
|
|
||||||
task_id: Optional task identifier. Auto-generated if empty.
|
|
||||||
pid: Process ID of the background task. Defaults to os.getpid().
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The created entry dict.
|
|
||||||
"""
|
|
||||||
if not task_id:
|
|
||||||
task_id = f"t_{int(time.time() * 1_000_000)}"
|
|
||||||
if not pid:
|
|
||||||
pid = os.getpid()
|
|
||||||
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
expected_duration_s = 600
|
|
||||||
expected_done_at = datetime.fromtimestamp(
|
|
||||||
now.timestamp() + expected_duration_s, tz=timezone.utc
|
|
||||||
).isoformat()
|
|
||||||
|
|
||||||
entry = {
|
|
||||||
"task_id": task_id,
|
|
||||||
"type": subagent_type,
|
|
||||||
"owner_room": room_name,
|
|
||||||
"pid": pid,
|
|
||||||
"started_at": now.isoformat(),
|
|
||||||
"expected_duration_s": expected_duration_s,
|
|
||||||
"expected_done_at": expected_done_at,
|
|
||||||
"plugin_state_source": "adapter.subagent_tracker",
|
|
||||||
}
|
|
||||||
|
|
||||||
with self._lock:
|
|
||||||
state = _read_subagent_state(self._state_path)
|
|
||||||
active = state.get("active", [])
|
|
||||||
active.append(entry)
|
|
||||||
state["active"] = active
|
|
||||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
|
||||||
state["schema_version"] = SUBAGENT_STATE_SCHEMA_VERSION
|
|
||||||
state["source"] = "plugin_internal"
|
|
||||||
_write_subagent_state(self._state_path, state)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"[subagent_tracker] registered: type=%s, task_id=%s, room=%s, active_count=%d",
|
|
||||||
subagent_type, task_id, room_name, len(active),
|
|
||||||
)
|
|
||||||
return entry
|
|
||||||
|
|
||||||
def complete(self, subagent_type: str, task_id: str = "") -> int:
|
def complete(self, subagent_type: str, task_id: str = "") -> int:
|
||||||
"""Remove a subagent entry by type (and optionally task_id).
|
"""V8.7: No-op — pgrep-basierte Erkennung ersetzt complete()."""
|
||||||
|
logger.debug("[subagent_tracker] complete() no-op (pgrep mode): type=%s", subagent_type)
|
||||||
If task_id is provided, only removes the matching entry.
|
return 0
|
||||||
If task_id is empty, removes ALL entries of the given type.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
subagent_type: Type to remove.
|
|
||||||
task_id: Optional specific task_id to remove.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Number of remaining active entries.
|
|
||||||
"""
|
|
||||||
with self._lock:
|
|
||||||
state = _read_subagent_state(self._state_path)
|
|
||||||
active = state.get("active", [])
|
|
||||||
|
|
||||||
if task_id:
|
|
||||||
active = [e for e in active if not (e.get("type") == subagent_type and e.get("task_id") == task_id)]
|
|
||||||
else:
|
|
||||||
active = [e for e in active if e.get("type") != subagent_type]
|
|
||||||
|
|
||||||
state["active"] = active
|
|
||||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
|
||||||
_write_subagent_state(self._state_path, state)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"[subagent_tracker] completed: type=%s, task_id=%s, remaining=%d",
|
|
||||||
subagent_type, task_id, len(active),
|
|
||||||
)
|
|
||||||
return len(active)
|
|
||||||
|
|
||||||
def remove_by_task_id(self, task_id: str) -> bool:
|
def remove_by_task_id(self, task_id: str) -> bool:
|
||||||
"""Remove a subagent entry by task_id (for stale recovery).
|
"""V8.7: No-op — pgrep-basierte Erkennung braucht kein Stale-Recovery."""
|
||||||
|
logger.debug("[subagent_tracker] remove_by_task_id() no-op (pgrep mode): task_id=%s", task_id)
|
||||||
Used by DetectionTimer to clean up entries whose PID is dead.
|
return False
|
||||||
|
|
||||||
Args:
|
|
||||||
task_id: The task_id to remove.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
True if an entry was removed, False if not found.
|
|
||||||
"""
|
|
||||||
with self._lock:
|
|
||||||
state = _read_subagent_state(self._state_path)
|
|
||||||
active = state.get("active", [])
|
|
||||||
original_len = len(active)
|
|
||||||
active = [e for e in active if e.get("task_id") != task_id]
|
|
||||||
removed = len(active) < original_len
|
|
||||||
|
|
||||||
if removed:
|
|
||||||
state["active"] = active
|
|
||||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
|
||||||
_write_subagent_state(self._state_path, state)
|
|
||||||
logger.info(
|
|
||||||
"[subagent_tracker] stale recovery: removed task_id=%s, remaining=%d",
|
|
||||||
task_id, len(active),
|
|
||||||
)
|
|
||||||
|
|
||||||
return removed
|
|
||||||
|
|
||||||
def list(self) -> List[Dict]:
|
def list(self) -> List[Dict]:
|
||||||
"""List all currently active subagent entries.
|
"""V8.7: Immer leere Liste — pgrep ist die Quelle der Wahrheit."""
|
||||||
|
return []
|
||||||
Returns:
|
|
||||||
List of active entry dicts.
|
|
||||||
"""
|
|
||||||
state = _read_subagent_state(self._state_path)
|
|
||||||
return state.get("active", [])
|
|
||||||
|
|
||||||
def count(self) -> int:
|
def count(self) -> int:
|
||||||
"""Return the number of active subagents.
|
"""V8.7: Immer 0 — pgrep ist die Quelle der Wahrheit."""
|
||||||
|
return 0
|
||||||
Returns:
|
|
||||||
Count of active entries.
|
|
||||||
"""
|
|
||||||
return len(self.list())
|
|
||||||
|
|
||||||
def clear_all(self) -> None:
|
def clear_all(self) -> None:
|
||||||
"""Remove all active entries (for testing/reset)."""
|
"""V8.7: No-op."""
|
||||||
with self._lock:
|
pass
|
||||||
state = _read_subagent_state(self._state_path)
|
|
||||||
state["active"] = []
|
|
||||||
state["last_change_iso"] = datetime.now(timezone.utc).isoformat()
|
|
||||||
_write_subagent_state(self._state_path, state)
|
|
||||||
logger.info("[subagent_tracker] all entries cleared")
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Module-level convenience (singleton pattern for adapter use)
|
# Module-level convenience (singleton pattern, no-op)
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
_default_tracker: Optional[SubagentTracker] = None
|
_default_tracker: Optional[SubagentTracker] = None
|
||||||
@@ -249,7 +97,7 @@ _tracker_lock = threading.Lock()
|
|||||||
|
|
||||||
|
|
||||||
def get_tracker() -> SubagentTracker:
|
def get_tracker() -> SubagentTracker:
|
||||||
"""Get or create the module-level SubagentTracker singleton."""
|
"""Get or create the module-level SubagentTracker singleton (no-op)."""
|
||||||
global _default_tracker
|
global _default_tracker
|
||||||
if _default_tracker is None:
|
if _default_tracker is None:
|
||||||
with _tracker_lock:
|
with _tracker_lock:
|
||||||
|
|||||||
@@ -936,16 +936,14 @@ class TestPulseControllerLastSentPhase:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepPrimary:
|
class TestDetectionTimerPgrepPrimary:
|
||||||
"""Test 20: DetectionTimer — gateway_state PRIMARY, pgrep SECONDARY (P1b)."""
|
"""Test 20: DetectionTimer — gateway_state PRIMARY, pgrep SECONDARY (V8.7)."""
|
||||||
|
|
||||||
def test_pgrep_finds_other_agents(self):
|
def test_pgrep_finds_other_agents(self):
|
||||||
"""gateway_state=1 (nicht >1) → pgrep-Fallback findet anderen Prozess → result=True."""
|
"""gateway_state=1 (nicht >1) → pgrep findet anderen Prozess → result=True."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
import tempfile
|
import tempfile
|
||||||
import json
|
import json
|
||||||
|
|
||||||
own_pid = os.getpid()
|
|
||||||
|
|
||||||
# gateway_state mit active_agents=1 (nicht >1 → fällt auf pgrep zurück)
|
# gateway_state mit active_agents=1 (nicht >1 → fällt auf pgrep zurück)
|
||||||
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:
|
||||||
@@ -953,20 +951,14 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
state_path = f.name
|
state_path = f.name
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Mock pgrep: findet eigenen + fremden Prozess
|
# Mock _pgrep_hermes_subagents: findet 2 Prozesse
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||||
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()
|
||||||
# gateway_state=1 → pgrep-Fallback findet anderen Prozess → True
|
# gateway_state=1 → pgrep findet 2 Prozesse → True
|
||||||
assert result is True
|
assert result is True
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
@@ -984,8 +976,8 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
state_path = f.name
|
state_path = f.name
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Mock pgrep: sollte NICHT aufgerufen werden
|
# Mock _pgrep_hermes_subagents: sollte NICHT aufgerufen werden
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep:
|
||||||
dt = DetectionTimer(
|
dt = DetectionTimer(
|
||||||
gateway_state_path=state_path,
|
gateway_state_path=state_path,
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
@@ -994,50 +986,34 @@ class TestDetectionTimerPgrepPrimary:
|
|||||||
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
# gateway_state=3 > 1 → PRIMARY entscheidet → True
|
||||||
assert result is True
|
assert result is True
|
||||||
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
# pgrep wurde NICHT aufgerufen (gateway_state hat entschieden)
|
||||||
mock_run.assert_not_called()
|
mock_pgrep.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(state_path)
|
os.unlink(state_path)
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepNoGatewayState:
|
class TestDetectionTimerPgrepNoGatewayState:
|
||||||
"""Test 21: DetectionTimer pgrep-Fallback funktioniert auch ohne gateway_state.json (P1b)."""
|
"""Test 21: DetectionTimer pgrep funktioniert auch ohne gateway_state.json (V8.7)."""
|
||||||
|
|
||||||
def test_pgrep_works_without_gateway_state(self):
|
def test_pgrep_works_without_gateway_state(self):
|
||||||
"""Wenn gateway_state.json nicht existiert, pgrep-Fallback greift."""
|
"""Wenn gateway_state.json nicht existiert, pgrep greift."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
# Mock _pgrep_hermes_subagents: findet 2 Prozesse
|
||||||
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||||
# 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,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# pgrep findet anderen Prozess → True
|
# pgrep findet 2 Prozesse → True
|
||||||
assert result is True
|
assert result is True
|
||||||
|
|
||||||
def test_pgrep_returns_bool(self):
|
def test_pgrep_returns_bool(self):
|
||||||
"""pgrep 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_hermes_subagents: 0 Prozesse
|
||||||
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0):
|
||||||
# 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,
|
||||||
@@ -1047,26 +1023,19 @@ class TestDetectionTimerPgrepNoGatewayState:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerIntegration:
|
class TestDetectionTimerIntegration:
|
||||||
"""Test 22: DetectionTimer start/stop + Callback (P1b: gateway_state PRIMARY, pgrep SECONDARY)."""
|
"""Test 22: DetectionTimer start/stop + Callback (V8.7: pgrep PRIMARY)."""
|
||||||
|
|
||||||
def test_detection_timer_start_stop(self):
|
def test_detection_timer_start_stop(self):
|
||||||
"""DetectionTimer startet und stoppt korrekt, pgrep-Fallback bei fehlendem gateway_state."""
|
"""DetectionTimer startet und stoppt korrekt, pgrep bei fehlendem gateway_state."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
# Mock pgrep: findet anderen Prozess → True (gateway_state fehlt → Fallback)
|
# Mock _pgrep_hermes_subagents: findet 2 Prozesse → True
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||||
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,
|
||||||
@@ -1353,106 +1322,82 @@ class TestP0LiveVerdrahtung:
|
|||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerPgrepSelfExclude:
|
class TestDetectionTimerPgrepSelfExclude:
|
||||||
"""P1-2: DetectionTimer pgrep self-exclude — eigene PID wird ignoriert."""
|
"""V8.7: _pgrep_hermes_subagents() self-exclude — eigene PID wird ignoriert."""
|
||||||
|
|
||||||
def test_pgrep_self_exclude_own_pid(self):
|
def test_pgrep_self_exclude_own_pid(self):
|
||||||
"""pgrep findet nur den eigenen Prozess → check() returns False."""
|
"""_pgrep_hermes_subagents() findet nur eigenen Prozess → 0."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
# Mock _pgrep_hermes_subagents: 0 (eigene PID ausgeschlossen)
|
||||||
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0), \
|
||||||
# Mock subprocess.run: pgrep returns only our own PID
|
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
|
||||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
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,
|
||||||
|
plugin_state_path="/tmp/nonexistent_plugin_state_v8_7.json",
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# Own PID should be excluded → no background agents → False
|
# Own PID excluded → no background agents → False
|
||||||
assert result is False
|
assert result is False
|
||||||
|
|
||||||
def test_pgrep_self_exclude_with_other_pids(self):
|
def test_pgrep_self_exclude_with_other_pids(self):
|
||||||
"""pgrep findet eigenen + fremden Prozess → check() returns True."""
|
"""_pgrep_hermes_subagents() findet 2 Prozesse → True."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
# Mock _pgrep_hermes_subagents: 2 (eigene PID + anderer)
|
||||||
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||||
# Mock subprocess.run: pgrep returns own PID + another PID
|
|
||||||
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,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# After excluding own PID, one other PID remains → True
|
# 2 Prozesse gefunden → True
|
||||||
assert result is True
|
assert result is True
|
||||||
|
|
||||||
|
|
||||||
class TestDetectionTimerOnChangeCallback:
|
class TestDetectionTimerOnChangeCallback:
|
||||||
"""P1-2: DetectionTimer on_change callback feuert bei pgrep-Zustandswechsel."""
|
"""V8.7: 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 pgrep: Prozesse erscheinen/verschwinden → on_change feuert."""
|
"""Mock _pgrep_hermes_subagents: Prozesse erscheinen/verschwinden → on_change feuert."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
# Mock pgrep: zuerst nur eigener Prozess (inactive), dann anderer erscheint
|
# Mock _pgrep_hermes_subagents: 0 → 2 → 2 → 0
|
||||||
mock_results = [
|
mock_counts = [0, 2, 2, 0]
|
||||||
# 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, \
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep, \
|
||||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
mock_run.side_effect = mock_results
|
mock_pgrep.side_effect = mock_counts
|
||||||
|
|
||||||
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,
|
||||||
on_change=on_change,
|
on_change=on_change,
|
||||||
|
plugin_state_path="/tmp/nonexistent_plugin_state_v8_7.json",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Check 1: nur eigener Prozess → False (kein Callback, _last_result startet False)
|
# Check 1: 0 Prozesse → 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
|
assert len(callback_results) == 0
|
||||||
|
|
||||||
# Check 2: anderer Prozess erscheint → True (Callback: False→True)
|
# Check 2: 2 Prozesse → True (Callback: 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
|
||||||
|
|
||||||
# Check 3: immer noch da → True (kein Callback, kein Wechsel)
|
# Check 3: immer noch 2 → True (kein Callback, kein Wechsel)
|
||||||
result3 = dt.check()
|
result3 = dt.check()
|
||||||
assert result3 is True
|
assert result3 is True
|
||||||
assert len(callback_results) == 1
|
assert len(callback_results) == 1
|
||||||
|
|
||||||
# Check 4: verschwindet → False (Callback: True→False)
|
# Check 4: 0 → False (Callback: 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
|
||||||
@@ -1616,6 +1561,9 @@ class TestHoneymoonBusyMinVisible:
|
|||||||
|
|
||||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||||
|
|
||||||
|
# V8.7: Mock _read_subagent_count → 0 (keine echten Prozesse)
|
||||||
|
engine._read_subagent_count = lambda: 0
|
||||||
|
|
||||||
# Start busy
|
# Start busy
|
||||||
engine.mark_busy_started(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
assert engine._active_tasks == 1
|
assert engine._active_tasks == 1
|
||||||
@@ -1656,6 +1604,9 @@ class TestHoneymoonBusyMinVisible:
|
|||||||
|
|
||||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||||
|
|
||||||
|
# V8.7: Mock _read_subagent_count → 0
|
||||||
|
engine._read_subagent_count = lambda: 0
|
||||||
|
|
||||||
engine.mark_busy_started(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
assert engine._active_tasks == 1
|
assert engine._active_tasks == 1
|
||||||
|
|
||||||
@@ -1682,6 +1633,9 @@ class TestHoneymoonBusyMinVisible:
|
|||||||
|
|
||||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||||
|
|
||||||
|
# V8.7: Mock _read_subagent_count → 0
|
||||||
|
engine._read_subagent_count = lambda: 0
|
||||||
|
|
||||||
# Erster busy
|
# Erster busy
|
||||||
engine.mark_busy_started(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
first_timer = engine._busy_honeymoon_timer
|
first_timer = engine._busy_honeymoon_timer
|
||||||
@@ -1744,6 +1698,9 @@ class TestHoneymoonBusyMinVisible:
|
|||||||
|
|
||||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||||
|
|
||||||
|
# V8.7: Mock _read_subagent_count → 0
|
||||||
|
engine._read_subagent_count = lambda: 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
engine.mark_busy_started(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
raise RuntimeError("simulated dispatch failure")
|
raise RuntimeError("simulated dispatch failure")
|
||||||
@@ -1775,6 +1732,9 @@ class TestHoneymoonBusyMinVisible:
|
|||||||
|
|
||||||
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
engine = PresenceEngine(rest=mock_rest, enabled=True)
|
||||||
|
|
||||||
|
# V8.7: Mock _read_subagent_count → 0
|
||||||
|
engine._read_subagent_count = lambda: 0
|
||||||
|
|
||||||
engine.mark_busy_started(room_name="#Test")
|
engine.mark_busy_started(room_name="#Test")
|
||||||
time.sleep(0.05)
|
time.sleep(0.05)
|
||||||
engine.mark_busy_done()
|
engine.mark_busy_done()
|
||||||
@@ -2089,41 +2049,29 @@ class TestDetectionTimerPluginState:
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
own_pid = os.getpid()
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0), \
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
|
||||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
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,
|
||||||
plugin_state_path=state_path,
|
plugin_state_path=state_path,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# background_tasks=0, gateway_state fehlt, pgrep nur self → False
|
# background_tasks=0, gateway_state fehlt, pgrep=0 → False
|
||||||
assert result is False
|
assert result is False
|
||||||
|
|
||||||
def test_plugin_state_missing_file_no_error(self):
|
def test_plugin_state_missing_file_no_error(self):
|
||||||
"""Plugin-State-Datei fehlt → kein Fehler, fällt zurück auf gateway_state+pgrep."""
|
"""Plugin-State-Datei fehlt → kein Fehler, fällt zurück auf pgrep."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
own_pid = os.getpid()
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||||
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,
|
||||||
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
plugin_state_path="/tmp/nonexistent_plugin_state.json",
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# pgrep findet anderen Prozess → True
|
# pgrep findet 2 Prozesse → True
|
||||||
assert result is True
|
assert result is True
|
||||||
|
|
||||||
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
def test_plugin_state_corrupt_json_no_crash(self, tmp_path):
|
||||||
@@ -2136,20 +2084,14 @@ class TestDetectionTimerPluginState:
|
|||||||
with open(state_path, 'w') as f:
|
with open(state_path, 'w') as f:
|
||||||
f.write("{invalid json {{{")
|
f.write("{invalid json {{{")
|
||||||
|
|
||||||
own_pid = os.getpid()
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2):
|
||||||
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,
|
||||||
plugin_state_path=state_path,
|
plugin_state_path=state_path,
|
||||||
)
|
)
|
||||||
result = dt.check()
|
result = dt.check()
|
||||||
# Sollte nicht crashen, pgrep findet anderen Prozess → True
|
# Sollte nicht crashen, pgrep findet 2 Prozesse → True
|
||||||
assert result is True
|
assert result is True
|
||||||
|
|
||||||
def test_plugin_state_priority_after_gateway(self, tmp_path):
|
def test_plugin_state_priority_after_gateway(self, tmp_path):
|
||||||
@@ -2174,7 +2116,7 @@ class TestDetectionTimerPluginState:
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep:
|
||||||
dt = DetectionTimer(
|
dt = DetectionTimer(
|
||||||
gateway_state_path=gw_path,
|
gateway_state_path=gw_path,
|
||||||
detection_interval=0.1,
|
detection_interval=0.1,
|
||||||
@@ -2183,7 +2125,7 @@ class TestDetectionTimerPluginState:
|
|||||||
result = dt.check()
|
result = dt.check()
|
||||||
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
|
# gateway_state=3 > 1 → PRIMARY → True (pgrep NICHT aufgerufen)
|
||||||
assert result is True
|
assert result is True
|
||||||
mock_run.assert_not_called()
|
mock_pgrep.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gw_path)
|
os.unlink(gw_path)
|
||||||
|
|
||||||
@@ -2229,14 +2171,8 @@ class TestDetectionSourceTelemetry:
|
|||||||
|
|
||||||
routing_telemetry.heartbeat_detection_source = "none"
|
routing_telemetry.heartbeat_detection_source = "none"
|
||||||
|
|
||||||
own_pid = os.getpid()
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0), \
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
|
||||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
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,
|
||||||
@@ -2252,14 +2188,8 @@ class TestDetectionSourceTelemetry:
|
|||||||
|
|
||||||
routing_telemetry.heartbeat_detection_source = "none"
|
routing_telemetry.heartbeat_detection_source = "none"
|
||||||
|
|
||||||
own_pid = os.getpid()
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=2), \
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
|
||||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
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,
|
||||||
@@ -2282,7 +2212,7 @@ class TestDetectionSourceTelemetry:
|
|||||||
gw_path = f.name
|
gw_path = f.name
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run, \
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents') as mock_pgrep, \
|
||||||
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
patch.object(DetectionTimer, '_check_gateway_pid_alive', return_value=False):
|
||||||
dt = DetectionTimer(
|
dt = DetectionTimer(
|
||||||
gateway_state_path=gw_path,
|
gateway_state_path=gw_path,
|
||||||
@@ -2290,7 +2220,7 @@ class TestDetectionSourceTelemetry:
|
|||||||
)
|
)
|
||||||
dt.check()
|
dt.check()
|
||||||
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
assert routing_telemetry.heartbeat_detection_source == "gateway"
|
||||||
mock_run.assert_not_called()
|
mock_pgrep.assert_not_called()
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gw_path)
|
os.unlink(gw_path)
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
V8.6 Phase 5: Subagent-Status — PresenceEngine Integrationstests.
|
V8.7: Subagent-Status — PresenceEngine Integrationstests (pgrep-basiert).
|
||||||
|
|
||||||
Testet:
|
Testet:
|
||||||
- mark_busy_done mit background_tasks > 0 (kein online-Übergang)
|
- mark_busy_done mit background_tasks > 0 (kein online-Übergang)
|
||||||
- mark_busy_done mit background_tasks == 0 (Regression: online-Übergang)
|
- mark_busy_done mit background_tasks == 0 (Regression: online-Übergang)
|
||||||
- _honeymoon_expired mit background_tasks > 0
|
- _honeymoon_expired mit background_tasks > 0
|
||||||
- DetectionTimer liest subagent_status.json
|
- DetectionTimer._pgrep_hermes_subagents() — /proc-basierte Erkennung
|
||||||
- PulseController pulse_target="away" toggles
|
- PulseController pulse_target="away" toggles
|
||||||
- PulseController pulse_target="busy" message-pulses
|
- PulseController pulse_target="busy" message-pulses
|
||||||
"""
|
"""
|
||||||
@@ -98,13 +98,10 @@ class TestMarkBusyDoneWithBgTasks:
|
|||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
|
|
||||||
# Prüfe: letzter gesendeter Status ist NICHT "online"
|
# Prüfe: letzter gesendeter Status ist NICHT "online"
|
||||||
# (sollte "away" sein wegen Subagent-Pulse)
|
|
||||||
calls = mock_rest._request.call_args_list
|
calls = mock_rest._request.call_args_list
|
||||||
assert len(calls) > 0, "Expected at least one REST call"
|
assert len(calls) > 0, "Expected at least one REST call"
|
||||||
# Der letzte Call sollte nicht "online" mit leerer Message sein
|
|
||||||
last_call = calls[-1]
|
last_call = calls[-1]
|
||||||
last_data = last_call[1].get("data", {})
|
last_data = last_call[1].get("data", {})
|
||||||
# Entweder "away" (idle+subagent) oder "busy" (busy+subagent)
|
|
||||||
assert last_data.get("status") != "online", (
|
assert last_data.get("status") != "online", (
|
||||||
f"Expected non-online status, got {last_data}"
|
f"Expected non-online status, got {last_data}"
|
||||||
)
|
)
|
||||||
@@ -113,6 +110,9 @@ class TestMarkBusyDoneWithBgTasks:
|
|||||||
"""Regression: background_tasks == 0 → online (klassischer Pfad)."""
|
"""Regression: background_tasks == 0 → online (klassischer Pfad)."""
|
||||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||||
|
|
||||||
|
# Mock _pgrep_hermes_subagents → 0 (keine Subagenten)
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
with patch.object(DetectionTimer, '_pgrep_hermes_subagents', return_value=0):
|
||||||
engine.mark_busy_started(room_name="testroom")
|
engine.mark_busy_started(room_name="testroom")
|
||||||
# KEIN increment_background_tasks → bg=0
|
# KEIN increment_background_tasks → bg=0
|
||||||
|
|
||||||
@@ -140,15 +140,11 @@ class TestHoneymoonExpiredWithBgTasks:
|
|||||||
"""Honeymoon-Timer feuert, aber bg_tasks > 0 → kein online."""
|
"""Honeymoon-Timer feuert, aber bg_tasks > 0 → kein online."""
|
||||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||||
|
|
||||||
# Starte busy, dann sofort mark_busy_done (Honeymoon läuft noch)
|
|
||||||
engine.mark_busy_started(room_name="testroom")
|
engine.mark_busy_started(room_name="testroom")
|
||||||
engine.increment_background_tasks() # bg=1
|
engine.increment_background_tasks() # bg=1
|
||||||
|
|
||||||
# Honeymoon abwarten
|
|
||||||
time.sleep(1.2)
|
time.sleep(1.2)
|
||||||
|
|
||||||
# Honeymoon-Timer sollte gefeuert haben, aber bg=1 → kein online
|
|
||||||
# Rufe _transition_from_busy manuell auf um zu prüfen
|
|
||||||
engine._transition_from_busy()
|
engine._transition_from_busy()
|
||||||
|
|
||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
@@ -162,75 +158,195 @@ class TestHoneymoonExpiredWithBgTasks:
|
|||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test 6: DetectionTimer reads subagent_status.json
|
# Test 6: DetectionTimer._pgrep_hermes_subagents() — /proc-basierte Erkennung
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestDetectionTimerReadsSubagentStatus:
|
class TestPgrepHermesSubagents:
|
||||||
"""Test 6: DetectionTimer.check() liest subagent_status.json."""
|
"""Test 6: _pgrep_hermes_subagents() erkennt hermes chat --profile Prozesse."""
|
||||||
|
|
||||||
def test_detection_timer_detects_subagent_status(self):
|
def test_pgrep_finds_hermes_chat_profile_process(self):
|
||||||
"""DetectionTimer erkennt aktive Einträge in subagent_status.json."""
|
"""_pgrep_hermes_subagents() findet einen simulierten hermes-Prozess."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
|
||||||
|
|
||||||
# Schreibe einen aktiven Subagenten
|
own_pid = os.getpid()
|
||||||
subagent_path = _get_subagent_state_path()
|
|
||||||
_write_subagent_state(subagent_path, {
|
# Mock /proc: nur ein simulierter hermes chat --profile Prozess
|
||||||
"active": [{"task_id": "t_123", "type": "delegate_task", "owner_room": "user:bernd"}],
|
mock_proc_entries = ["1", "2", str(own_pid), "99999", "12345"]
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
def mock_cmdline_read(pid_dir):
|
||||||
"source": "plugin_internal",
|
"""Simuliere /proc/<pid>/cmdline."""
|
||||||
})
|
if pid_dir == "12345":
|
||||||
|
return b"python\x00hermes\x00chat\x00--profile\x00miguel\x00--model\x00deepseek\x00"
|
||||||
|
elif pid_dir == str(own_pid):
|
||||||
|
return b"python\x00pytest\x00"
|
||||||
|
else:
|
||||||
|
return b"bash\x00"
|
||||||
|
|
||||||
|
with patch("os.listdir", return_value=mock_proc_entries):
|
||||||
|
with patch("builtins.open") as mock_open:
|
||||||
|
# Simuliere open() für /proc/<pid>/cmdline
|
||||||
|
def open_side_effect(path, mode="r"):
|
||||||
|
# Extrahiere PID aus Pfad: /proc/<pid>/cmdline
|
||||||
|
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
|
||||||
|
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
|
||||||
|
# Sollte 1 Prozess finden (PID 12345, nicht own_pid)
|
||||||
|
assert count == 1, f"Expected 1, got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_returns_zero_when_no_hermes_processes(self):
|
||||||
|
"""_pgrep_hermes_subagents() → 0 wenn keine hermes-Prozesse."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
mock_proc_entries = ["1", "2", str(own_pid), "99999"]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if 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
|
||||||
|
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
assert count == 0, f"Expected 0, got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_excludes_own_pid(self):
|
||||||
|
"""_pgrep_hermes_subagents() schließt eigene PID aus."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
# Nur eigener Prozess (der wie hermes aussieht)
|
||||||
|
mock_proc_entries = [str(own_pid)]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
# Eigener Prozess hat hermes chat --profile in cmdline
|
||||||
|
return b"python\x00hermes\x00chat\x00--profile\x00miguel\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
|
||||||
|
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
# Eigene PID wird ausgeschlossen → 0
|
||||||
|
assert count == 0, f"Expected 0 (own PID excluded), got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_ignores_non_hermes_processes(self):
|
||||||
|
"""_pgrep_hermes_subagents() ignoriert nicht-hermes Prozesse."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
mock_proc_entries = ["1", "2", str(own_pid), "55555", "66666"]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if pid_dir == "55555":
|
||||||
|
return b"python\x00hermes\x00serve\x00" # hermes aber kein chat
|
||||||
|
elif pid_dir == "66666":
|
||||||
|
return b"python\x00chat\x00--profile\x00" # chat aber kein hermes
|
||||||
|
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
|
||||||
|
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
# Keiner der Prozesse hat hermes+chat+--profile → 0
|
||||||
|
assert count == 0, f"Expected 0, got {count}"
|
||||||
|
|
||||||
|
def test_pgrep_handles_permission_errors(self):
|
||||||
|
"""_pgrep_hermes_subagents() behandelt PermissionError graceful."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
|
own_pid = os.getpid()
|
||||||
|
mock_proc_entries = ["1", str(own_pid), "99999"]
|
||||||
|
|
||||||
|
def mock_cmdline_read(pid_dir):
|
||||||
|
if pid_dir == "99999":
|
||||||
|
raise PermissionError("Permission denied")
|
||||||
|
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
|
||||||
|
|
||||||
|
count = DetectionTimer._pgrep_hermes_subagents()
|
||||||
|
# PermissionError → Prozess wird ignoriert, count=0
|
||||||
|
assert count == 0, f"Expected 0, got {count}"
|
||||||
|
|
||||||
|
def test_detection_timer_check_uses_pgrep(self):
|
||||||
|
"""DetectionTimer.check() nutzt _pgrep_hermes_subagents() als Quelle."""
|
||||||
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
|
|
||||||
# DetectionTimer ohne gateway_state (damit PID-Sentinel + gateway fehlschlagen)
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||||
gateway_path = f.name
|
gateway_path = f.name
|
||||||
try:
|
try:
|
||||||
# Leeres gateway_state → PID-Sentinel greift (Gateway lebt)
|
|
||||||
# Um subagent_status zu testen, mocken wir _check_gateway_pid_alive
|
|
||||||
timer = DetectionTimer(
|
timer = DetectionTimer(
|
||||||
gateway_state_path=gateway_path,
|
gateway_state_path=gateway_path,
|
||||||
detection_interval=10.0,
|
detection_interval=10.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Mock: PID-Sentinel tot, gateway_state leer, plugin_state leer
|
||||||
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
with patch.object(timer, '_pgrep_hermes_subagents', return_value=2):
|
||||||
mock_run.return_value = MagicMock(stdout="", returncode=1)
|
|
||||||
result = timer.check()
|
result = timer.check()
|
||||||
|
|
||||||
# Sollte True sein weil subagent_status.json aktive Einträge hat
|
# pgrep findet 2 Prozesse → True
|
||||||
assert result is True, f"Expected True, got {result}"
|
assert result is True, f"Expected True, got {result}"
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gateway_path)
|
os.unlink(gateway_path)
|
||||||
# Cleanup subagent_status.json
|
|
||||||
try:
|
|
||||||
os.unlink(subagent_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def test_detection_timer_empty_subagent_status(self):
|
def test_detection_timer_check_zero_pgrep(self):
|
||||||
"""DetectionTimer erkennt leere subagent_status.json nicht als aktiv."""
|
"""DetectionTimer.check() → False wenn pgrep 0 findet."""
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
from plugin.archivar.presence_engine import DetectionTimer
|
||||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
|
||||||
|
|
||||||
subagent_path = _get_subagent_state_path()
|
|
||||||
_write_subagent_state(subagent_path, {
|
|
||||||
"active": [],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
|
|
||||||
# Auch plugin_state.json bereinigen (könnte bg_tasks vom vorherigen Test haben)
|
|
||||||
from plugin.archivar.presence_engine import _get_plugin_state_path, _write_plugin_state
|
|
||||||
plugin_path = _get_plugin_state_path()
|
|
||||||
_write_plugin_state(plugin_path, {
|
|
||||||
"background_tasks": 0,
|
|
||||||
"last_update_iso": "",
|
|
||||||
"source": "plugin_internal",
|
|
||||||
"schema_version": 1,
|
|
||||||
})
|
|
||||||
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||||
gateway_path = f.name
|
gateway_path = f.name
|
||||||
@@ -238,22 +354,17 @@ class TestDetectionTimerReadsSubagentStatus:
|
|||||||
timer = DetectionTimer(
|
timer = DetectionTimer(
|
||||||
gateway_state_path=gateway_path,
|
gateway_state_path=gateway_path,
|
||||||
detection_interval=10.0,
|
detection_interval=10.0,
|
||||||
|
plugin_state_path="/tmp/nonexistent_plugin_state_v8_7.json",
|
||||||
)
|
)
|
||||||
|
|
||||||
with patch.object(timer, '_check_gateway_pid_alive', return_value=False):
|
with patch.object(timer, '_check_gateway_pid_alive', return_value=False), \
|
||||||
with patch('plugin.archivar.presence_engine.subprocess.run') as mock_run:
|
patch.object(timer, '_pgrep_hermes_subagents', return_value=0):
|
||||||
mock_run.return_value = MagicMock(stdout="", returncode=1)
|
|
||||||
result = timer.check()
|
result = timer.check()
|
||||||
|
|
||||||
# Sollte False sein weil keine Quellen aktiv
|
|
||||||
assert result is False, f"Expected False, got {result}"
|
assert result is False, f"Expected False, got {result}"
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
os.unlink(gateway_path)
|
os.unlink(gateway_path)
|
||||||
try:
|
|
||||||
os.unlink(subagent_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -314,7 +425,6 @@ class TestPulseControllerAwayMode:
|
|||||||
t.join()
|
t.join()
|
||||||
|
|
||||||
assert len(errors) == 0, f"Errors: {errors}"
|
assert len(errors) == 0, f"Errors: {errors}"
|
||||||
# Final mode should be one of the two valid values
|
|
||||||
assert pc.get_pulse_target() in ("away", "busy")
|
assert pc.get_pulse_target() in ("away", "busy")
|
||||||
|
|
||||||
|
|
||||||
@@ -331,34 +441,27 @@ class TestPulseControllerBusyMode:
|
|||||||
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
|
||||||
pc.set_pulse_target("busy")
|
pc.set_pulse_target("busy")
|
||||||
|
|
||||||
# Mock DDP
|
|
||||||
mock_ddp = MagicMock()
|
mock_ddp = MagicMock()
|
||||||
mock_ddp.connected = True
|
mock_ddp.connected = True
|
||||||
mock_ddp.set_status = MagicMock()
|
mock_ddp.set_status = MagicMock()
|
||||||
pc.bind_ddp(mock_ddp)
|
pc.bind_ddp(mock_ddp)
|
||||||
|
|
||||||
# Start pulse
|
|
||||||
pc.start()
|
pc.start()
|
||||||
time.sleep(0.4) # Wait for a few ticks
|
time.sleep(0.4)
|
||||||
pc.stop()
|
pc.stop()
|
||||||
|
|
||||||
# Im busy-Modus sollte der PulseController NICHT online↔away togglen
|
|
||||||
# sondern den busy-Status halten (via _update_presence_with_subagents)
|
|
||||||
# Hier testen wir nur dass der Mode korrekt gesetzt ist
|
|
||||||
assert pc.get_pulse_target() == "busy"
|
assert pc.get_pulse_target() == "busy"
|
||||||
|
|
||||||
def test__update_presence_with_subagents_idle(self):
|
def test__update_presence_with_subagents_idle(self):
|
||||||
"""_update_presence_with_subagents bei idle startet away-Pulse."""
|
"""_update_presence_with_subagents bei idle startet away-Pulse."""
|
||||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||||
|
|
||||||
# Sicherstellen dass active_tasks == 0
|
|
||||||
assert engine._active_tasks == 0
|
assert engine._active_tasks == 0
|
||||||
|
|
||||||
engine._update_presence_with_subagents(3)
|
engine._update_presence_with_subagents(3)
|
||||||
|
|
||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
|
|
||||||
# Sollte "away" mit Message "3 Subagent läuft" gesendet haben
|
|
||||||
calls = mock_rest._request.call_args_list
|
calls = mock_rest._request.call_args_list
|
||||||
assert len(calls) > 0
|
assert len(calls) > 0
|
||||||
last_data = calls[-1][1].get("data", {})
|
last_data = calls[-1][1].get("data", {})
|
||||||
@@ -369,7 +472,6 @@ class TestPulseControllerBusyMode:
|
|||||||
"""_update_presence_with_subagents bei busy setzt busy+Message."""
|
"""_update_presence_with_subagents bei busy setzt busy+Message."""
|
||||||
engine, mock_rest = _make_engine(coalesce_ms=100)
|
engine, mock_rest = _make_engine(coalesce_ms=100)
|
||||||
|
|
||||||
# Simuliere busy
|
|
||||||
engine.increment_active_tasks()
|
engine.increment_active_tasks()
|
||||||
engine.set_current_room("testroom")
|
engine.set_current_room("testroom")
|
||||||
|
|
||||||
@@ -386,324 +488,27 @@ class TestPulseControllerBusyMode:
|
|||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test: _read_subagent_count
|
# Test: _read_subagent_count (pgrep-basiert)
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestReadSubagentCount:
|
class TestReadSubagentCount:
|
||||||
"""Test: _read_subagent_count() liest subagent_status.json."""
|
"""Test: _read_subagent_count() nutzt pgrep."""
|
||||||
|
|
||||||
def test_read_subagent_count_returns_zero_when_empty(self):
|
def test_read_subagent_count_returns_zero_when_no_processes(self):
|
||||||
"""Leere Datei → 0."""
|
"""Keine hermes-Prozesse → 0."""
|
||||||
engine, _ = _make_engine()
|
engine, _ = _make_engine()
|
||||||
# Clean state
|
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=0):
|
||||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
|
||||||
_write_subagent_state(_get_subagent_state_path(), {
|
|
||||||
"active": [],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
assert engine._read_subagent_count() == 0
|
assert engine._read_subagent_count() == 0
|
||||||
|
|
||||||
def test_read_subagent_count_returns_count(self):
|
def test_read_subagent_count_returns_count(self):
|
||||||
"""Datei mit 2 Einträgen → 2."""
|
"""2 hermes-Prozesse → 2."""
|
||||||
engine, _ = _make_engine()
|
engine, _ = _make_engine()
|
||||||
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
|
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=2):
|
||||||
_write_subagent_state(_get_subagent_state_path(), {
|
|
||||||
"active": [
|
|
||||||
{"task_id": "t_1", "type": "delegate_task"},
|
|
||||||
{"task_id": "t_2", "type": "terminal_background"},
|
|
||||||
],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
assert engine._read_subagent_count() == 2
|
assert engine._read_subagent_count() == 2
|
||||||
|
|
||||||
def test_read_subagent_count_missing_file_returns_zero(self):
|
def test_read_subagent_count_handles_errors(self):
|
||||||
"""Fehlende Datei → 0 (graceful degradation)."""
|
"""Fehler in pgrep → 0 (graceful degradation)."""
|
||||||
engine, _ = _make_engine()
|
engine, _ = _make_engine()
|
||||||
from plugin.archivar.subagent_tracker import _get_subagent_state_path
|
# _pgrep_hermes_subagents() fängt OSError intern → 0
|
||||||
path = _get_subagent_state_path()
|
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=0):
|
||||||
try:
|
|
||||||
os.unlink(path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
assert engine._read_subagent_count() == 0
|
assert engine._read_subagent_count() == 0
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# Test 9: Stale-Recovery — PID tot → Eintrag wird entfernt
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestStaleRecoveryPidDead:
|
|
||||||
"""Test 9: Stale-Recovery entfernt Einträge mit toter PID."""
|
|
||||||
|
|
||||||
def test_pid_dead_entry_removed(self):
|
|
||||||
"""Wenn PID tot ist, wird der Eintrag aus subagent_status.json entfernt."""
|
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
|
||||||
from plugin.archivar.subagent_tracker import (
|
|
||||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
|
||||||
)
|
|
||||||
|
|
||||||
subagent_path = _get_subagent_state_path()
|
|
||||||
tracker = get_tracker()
|
|
||||||
|
|
||||||
# Schreibe einen Eintrag mit einer garantiert toten PID (99999)
|
|
||||||
_write_subagent_state(subagent_path, {
|
|
||||||
"active": [{
|
|
||||||
"task_id": "t_dead_pid",
|
|
||||||
"type": "background_task",
|
|
||||||
"owner_room": "user:bernd",
|
|
||||||
"pid": 99999,
|
|
||||||
"started_at": "2025-01-01T00:00:00+00:00",
|
|
||||||
"expected_duration_s": 600,
|
|
||||||
"expected_done_at": "2025-01-01T00:10:00+00:00",
|
|
||||||
"plugin_state_source": "adapter.subagent_tracker",
|
|
||||||
}],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
|
|
||||||
# Verify entry exists
|
|
||||||
assert tracker.count() == 1
|
|
||||||
|
|
||||||
# Create DetectionTimer and run stale recovery
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
|
||||||
gateway_path = f.name
|
|
||||||
try:
|
|
||||||
timer = DetectionTimer(
|
|
||||||
gateway_state_path=gateway_path,
|
|
||||||
detection_interval=10.0,
|
|
||||||
)
|
|
||||||
removed = timer._stale_recovery()
|
|
||||||
|
|
||||||
# PID 99999 ist tot → sollte entfernt worden sein
|
|
||||||
assert removed == 1, f"Expected 1 removed, got {removed}"
|
|
||||||
assert tracker.count() == 0, f"Expected 0 entries, got {tracker.count()}"
|
|
||||||
finally:
|
|
||||||
os.unlink(gateway_path)
|
|
||||||
# Cleanup
|
|
||||||
try:
|
|
||||||
os.unlink(subagent_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def test_pid_dead_multiple_entries_cleanup(self):
|
|
||||||
"""Mehrere tote PIDs → alle werden entfernt."""
|
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
|
||||||
from plugin.archivar.subagent_tracker import (
|
|
||||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
|
||||||
)
|
|
||||||
|
|
||||||
subagent_path = _get_subagent_state_path()
|
|
||||||
tracker = get_tracker()
|
|
||||||
|
|
||||||
_write_subagent_state(subagent_path, {
|
|
||||||
"active": [
|
|
||||||
{
|
|
||||||
"task_id": "t_dead_1",
|
|
||||||
"type": "background_task",
|
|
||||||
"pid": 99998,
|
|
||||||
"started_at": "2025-01-01T00:00:00+00:00",
|
|
||||||
"expected_duration_s": 600,
|
|
||||||
"expected_done_at": "2025-01-01T00:10:00+00:00",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"task_id": "t_dead_2",
|
|
||||||
"type": "delegate_task",
|
|
||||||
"pid": 99997,
|
|
||||||
"started_at": "2025-01-01T00:00:00+00:00",
|
|
||||||
"expected_duration_s": 600,
|
|
||||||
"expected_done_at": "2025-01-01T00:10:00+00:00",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
|
|
||||||
assert tracker.count() == 2
|
|
||||||
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
|
||||||
gateway_path = f.name
|
|
||||||
try:
|
|
||||||
timer = DetectionTimer(
|
|
||||||
gateway_state_path=gateway_path,
|
|
||||||
detection_interval=10.0,
|
|
||||||
)
|
|
||||||
removed = timer._stale_recovery()
|
|
||||||
|
|
||||||
assert removed == 2, f"Expected 2 removed, got {removed}"
|
|
||||||
assert tracker.count() == 0
|
|
||||||
finally:
|
|
||||||
os.unlink(gateway_path)
|
|
||||||
try:
|
|
||||||
os.unlink(subagent_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# Test 10: Stale-Recovery — PID lebend → Eintrag bleibt
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestStaleRecoveryPidAlive:
|
|
||||||
"""Test 10: Stale-Recovery lässt Einträge mit lebender PID in Ruhe."""
|
|
||||||
|
|
||||||
def test_pid_alive_entry_kept(self):
|
|
||||||
"""Wenn PID lebt, bleibt der Eintrag erhalten."""
|
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
|
||||||
from plugin.archivar.subagent_tracker import (
|
|
||||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
|
||||||
)
|
|
||||||
|
|
||||||
subagent_path = _get_subagent_state_path()
|
|
||||||
tracker = get_tracker()
|
|
||||||
|
|
||||||
# Nutze die eigene PID (dieser Testprozess lebt garantiert)
|
|
||||||
own_pid = os.getpid()
|
|
||||||
|
|
||||||
_write_subagent_state(subagent_path, {
|
|
||||||
"active": [{
|
|
||||||
"task_id": "t_alive_pid",
|
|
||||||
"type": "background_task",
|
|
||||||
"owner_room": "user:bernd",
|
|
||||||
"pid": own_pid,
|
|
||||||
"started_at": "2025-01-01T00:00:00+00:00",
|
|
||||||
"expected_duration_s": 600,
|
|
||||||
"expected_done_at": "2099-01-01T00:00:00+00:00", # weit in der Zukunft
|
|
||||||
"plugin_state_source": "adapter.subagent_tracker",
|
|
||||||
}],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
|
|
||||||
assert tracker.count() == 1
|
|
||||||
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
|
||||||
gateway_path = f.name
|
|
||||||
try:
|
|
||||||
timer = DetectionTimer(
|
|
||||||
gateway_state_path=gateway_path,
|
|
||||||
detection_interval=10.0,
|
|
||||||
)
|
|
||||||
removed = timer._stale_recovery()
|
|
||||||
|
|
||||||
# Eigene PID lebt → kein Eintrag entfernt
|
|
||||||
assert removed == 0, f"Expected 0 removed, got {removed}"
|
|
||||||
assert tracker.count() == 1, f"Expected 1 entry, got {tracker.count()}"
|
|
||||||
finally:
|
|
||||||
os.unlink(gateway_path)
|
|
||||||
try:
|
|
||||||
os.unlink(subagent_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
# Test 11: Stale-Recovery — expected_done_at überschritten + PID tot
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
class TestStaleRecoveryExpectedDoneAt:
|
|
||||||
"""Test 11: expected_done_at als Sekundär-Indikator."""
|
|
||||||
|
|
||||||
def test_expected_done_at_exceeded_pid_dead_removed(self):
|
|
||||||
"""expected_done_at überschritten + PID tot → Eintrag entfernt."""
|
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
|
||||||
from plugin.archivar.subagent_tracker import (
|
|
||||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
|
||||||
)
|
|
||||||
|
|
||||||
subagent_path = _get_subagent_state_path()
|
|
||||||
tracker = get_tracker()
|
|
||||||
|
|
||||||
# expected_done_at in der Vergangenheit + tote PID
|
|
||||||
_write_subagent_state(subagent_path, {
|
|
||||||
"active": [{
|
|
||||||
"task_id": "t_expired_dead",
|
|
||||||
"type": "background_task",
|
|
||||||
"owner_room": "user:bernd",
|
|
||||||
"pid": 99996,
|
|
||||||
"started_at": "2025-01-01T00:00:00+00:00",
|
|
||||||
"expected_duration_s": 600,
|
|
||||||
"expected_done_at": "2025-01-01T00:10:00+00:00", # lange überschritten
|
|
||||||
"plugin_state_source": "adapter.subagent_tracker",
|
|
||||||
}],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
|
|
||||||
assert tracker.count() == 1
|
|
||||||
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
|
||||||
gateway_path = f.name
|
|
||||||
try:
|
|
||||||
timer = DetectionTimer(
|
|
||||||
gateway_state_path=gateway_path,
|
|
||||||
detection_interval=10.0,
|
|
||||||
)
|
|
||||||
removed = timer._stale_recovery()
|
|
||||||
|
|
||||||
# PID tot → entfernt (expected_done_at ist sekundär, PID ist primär)
|
|
||||||
assert removed == 1, f"Expected 1 removed, got {removed}"
|
|
||||||
assert tracker.count() == 0
|
|
||||||
finally:
|
|
||||||
os.unlink(gateway_path)
|
|
||||||
try:
|
|
||||||
os.unlink(subagent_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def test_expected_done_at_exceeded_pid_alive_kept(self):
|
|
||||||
"""expected_done_at überschritten aber PID lebt → Eintrag bleibt (long-running)."""
|
|
||||||
from plugin.archivar.presence_engine import DetectionTimer
|
|
||||||
from plugin.archivar.subagent_tracker import (
|
|
||||||
_write_subagent_state, _get_subagent_state_path, get_tracker,
|
|
||||||
)
|
|
||||||
|
|
||||||
subagent_path = _get_subagent_state_path()
|
|
||||||
tracker = get_tracker()
|
|
||||||
|
|
||||||
own_pid = os.getpid()
|
|
||||||
|
|
||||||
# expected_done_at in der Vergangenheit, aber PID lebt
|
|
||||||
_write_subagent_state(subagent_path, {
|
|
||||||
"active": [{
|
|
||||||
"task_id": "t_long_running",
|
|
||||||
"type": "background_task",
|
|
||||||
"owner_room": "user:bernd",
|
|
||||||
"pid": own_pid,
|
|
||||||
"started_at": "2025-01-01T00:00:00+00:00",
|
|
||||||
"expected_duration_s": 600,
|
|
||||||
"expected_done_at": "2025-01-01T00:10:00+00:00", # überschritten
|
|
||||||
"plugin_state_source": "adapter.subagent_tracker",
|
|
||||||
}],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
|
|
||||||
assert tracker.count() == 1
|
|
||||||
|
|
||||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
|
||||||
gateway_path = f.name
|
|
||||||
try:
|
|
||||||
timer = DetectionTimer(
|
|
||||||
gateway_state_path=gateway_path,
|
|
||||||
detection_interval=10.0,
|
|
||||||
)
|
|
||||||
removed = timer._stale_recovery()
|
|
||||||
|
|
||||||
# PID lebt → Eintrag bleibt, auch wenn expected_done_at überschritten
|
|
||||||
assert removed == 0, f"Expected 0 removed, got {removed}"
|
|
||||||
assert tracker.count() == 1, f"Expected 1 entry, got {tracker.count()}"
|
|
||||||
finally:
|
|
||||||
os.unlink(gateway_path)
|
|
||||||
try:
|
|
||||||
os.unlink(subagent_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
V8.6 Phase 5: SubagentTracker — Tests.
|
V8.7: SubagentTracker — No-op Tests.
|
||||||
|
|
||||||
Testet register, complete, list, count, atomic write, thread-safety.
|
Alle register()/complete() sind no-ops. Tests prüfen dass:
|
||||||
|
- register() keine Datei schreibt
|
||||||
|
- complete() immer 0 returned
|
||||||
|
- list()/count() immer leer/0
|
||||||
|
- get_tracker() Singleton funktioniert weiterhin
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -39,13 +43,6 @@ def tmp_state_path():
|
|||||||
"""Create a temporary subagent_status.json for isolated testing."""
|
"""Create a temporary subagent_status.json for isolated testing."""
|
||||||
fd, path = tempfile.mkstemp(suffix=".json", prefix="subagent_test_")
|
fd, path = tempfile.mkstemp(suffix=".json", prefix="subagent_test_")
|
||||||
os.close(fd)
|
os.close(fd)
|
||||||
# Start with clean state
|
|
||||||
_write_subagent_state(path, {
|
|
||||||
"active": [],
|
|
||||||
"last_change_iso": "",
|
|
||||||
"schema_version": 1,
|
|
||||||
"source": "plugin_internal",
|
|
||||||
})
|
|
||||||
yield path
|
yield path
|
||||||
try:
|
try:
|
||||||
os.unlink(path)
|
os.unlink(path)
|
||||||
@@ -60,192 +57,131 @@ def tracker(tmp_state_path):
|
|||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test 1: register schreibt atomic JSON
|
# Test 1: register ist no-op
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestRegisterWritesAtomicJson:
|
class TestRegisterIsNoOp:
|
||||||
"""Test 1: register() schreibt korrekt in subagent_status.json."""
|
"""Test 1: register() ist no-op — schreibt keine Datei, list() bleibt leer."""
|
||||||
|
|
||||||
def test_register_creates_entry(self, tracker, tmp_state_path):
|
def test_register_does_not_write_file(self, tracker, tmp_state_path):
|
||||||
"""Nach register() ist ein Eintrag in der Datei."""
|
"""Nach register() ist die Datei unverändert (kein Eintrag)."""
|
||||||
entry = tracker.register("delegate_task", room_name="user:bernd")
|
tracker.register("delegate_task", room_name="user:bernd")
|
||||||
|
|
||||||
# In-memory check
|
# list() ist immer leer
|
||||||
active = tracker.list()
|
active = tracker.list()
|
||||||
assert len(active) == 1
|
assert len(active) == 0
|
||||||
assert active[0]["type"] == "delegate_task"
|
|
||||||
assert active[0]["owner_room"] == "user:bernd"
|
|
||||||
assert "task_id" in active[0]
|
|
||||||
assert "started_at" in active[0]
|
|
||||||
|
|
||||||
# File check
|
def test_register_returns_empty_dict(self, tracker):
|
||||||
state = _read_subagent_state(tmp_state_path)
|
"""register() gibt leeres dict zurück."""
|
||||||
assert len(state["active"]) == 1
|
entry = tracker.register("delegate_task", room_name="user:bernd")
|
||||||
assert state["active"][0]["type"] == "delegate_task"
|
assert entry["task_id"] == ""
|
||||||
|
assert entry["type"] == "delegate_task"
|
||||||
|
|
||||||
def test_register_multiple_entries(self, tracker):
|
def test_register_multiple_still_empty(self, tracker):
|
||||||
"""Mehrere register() Aufrufe erzeugen mehrere Einträge."""
|
"""Mehrere register() → list() bleibt leer."""
|
||||||
tracker.register("delegate_task", room_name="user:bernd")
|
tracker.register("delegate_task", room_name="user:bernd")
|
||||||
tracker.register("terminal_background", room_name="user:alice")
|
tracker.register("terminal_background", room_name="user:alice")
|
||||||
tracker.register("delegate_task", room_name="user:bernd")
|
tracker.register("delegate_task", room_name="user:bernd")
|
||||||
|
|
||||||
active = tracker.list()
|
assert tracker.list() == []
|
||||||
assert len(active) == 3
|
assert tracker.count() == 0
|
||||||
types = [e["type"] for e in active]
|
|
||||||
assert types.count("delegate_task") == 2
|
|
||||||
assert types.count("terminal_background") == 1
|
|
||||||
|
|
||||||
def test_register_auto_generates_task_id(self, tracker):
|
|
||||||
"""Wenn kein task_id übergeben wird, wird eins generiert."""
|
|
||||||
entry = tracker.register("delegate_task")
|
|
||||||
assert entry["task_id"].startswith("t_")
|
|
||||||
assert len(entry["task_id"]) > 5
|
|
||||||
|
|
||||||
def test_register_custom_task_id(self, tracker):
|
|
||||||
"""Custom task_id wird übernommen."""
|
|
||||||
entry = tracker.register("delegate_task", task_id="my_custom_id")
|
|
||||||
assert entry["task_id"] == "my_custom_id"
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test 2: complete entfernt Eintrag
|
# Test 2: complete ist no-op
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestCompleteRemovesEntry:
|
class TestCompleteIsNoOp:
|
||||||
"""Test 2: complete() entfernt Einträge korrekt."""
|
"""Test 2: complete() ist no-op — returned immer 0."""
|
||||||
|
|
||||||
def test_complete_by_type_removes_all_of_type(self, tracker):
|
|
||||||
"""complete(type) entfernt ALLE Einträge dieses Typs."""
|
|
||||||
tracker.register("delegate_task", room_name="user:bernd")
|
|
||||||
tracker.register("delegate_task", room_name="user:alice")
|
|
||||||
tracker.register("terminal_background", room_name="user:bernd")
|
|
||||||
|
|
||||||
|
def test_complete_returns_zero(self, tracker):
|
||||||
|
"""complete() returned immer 0."""
|
||||||
remaining = tracker.complete("delegate_task")
|
remaining = tracker.complete("delegate_task")
|
||||||
assert remaining == 1
|
assert remaining == 0
|
||||||
|
|
||||||
active = tracker.list()
|
|
||||||
assert len(active) == 1
|
|
||||||
assert active[0]["type"] == "terminal_background"
|
|
||||||
|
|
||||||
def test_complete_by_task_id_removes_specific(self, tracker):
|
|
||||||
"""complete(type, task_id) entfernt nur den spezifischen Eintrag."""
|
|
||||||
e1 = tracker.register("delegate_task", task_id="id_1")
|
|
||||||
e2 = tracker.register("delegate_task", task_id="id_2")
|
|
||||||
|
|
||||||
|
def test_complete_by_task_id_returns_zero(self, tracker):
|
||||||
|
"""complete(type, task_id) returned immer 0."""
|
||||||
remaining = tracker.complete("delegate_task", task_id="id_1")
|
remaining = tracker.complete("delegate_task", task_id="id_1")
|
||||||
assert remaining == 1
|
assert remaining == 0
|
||||||
|
|
||||||
active = tracker.list()
|
def test_complete_nonexistent_type_returns_zero(self, tracker):
|
||||||
assert len(active) == 1
|
"""complete() eines nicht existierenden Typs → 0."""
|
||||||
assert active[0]["task_id"] == "id_2"
|
|
||||||
|
|
||||||
def test_complete_nonexistent_type_no_error(self, tracker):
|
|
||||||
"""complete() eines nicht existierenden Typs wirft keinen Fehler."""
|
|
||||||
remaining = tracker.complete("nonexistent")
|
remaining = tracker.complete("nonexistent")
|
||||||
assert remaining == 0
|
assert remaining == 0
|
||||||
|
|
||||||
def test_complete_nonexistent_task_id_no_error(self, tracker):
|
|
||||||
"""complete() mit nicht existierender task_id wirft keinen Fehler."""
|
|
||||||
tracker.register("delegate_task", task_id="real_id")
|
|
||||||
remaining = tracker.complete("delegate_task", task_id="fake_id")
|
|
||||||
assert remaining == 1 # real_id bleibt
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test 3: list und count
|
# Test 3: list und count immer leer/0
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestListAndCount:
|
class TestListAndCount:
|
||||||
"""Test 3: list() und count() liefern korrekte Werte."""
|
"""Test 3: list() und count() sind immer leer/0."""
|
||||||
|
|
||||||
def test_list_empty_initially(self, tracker):
|
def test_list_empty_initially(self, tracker):
|
||||||
"""Frischer Tracker hat leere Liste."""
|
"""Frischer Tracker hat leere Liste."""
|
||||||
assert tracker.list() == []
|
assert tracker.list() == []
|
||||||
assert tracker.count() == 0
|
assert tracker.count() == 0
|
||||||
|
|
||||||
def test_count_matches_list_length(self, tracker):
|
def test_count_always_zero(self, tracker):
|
||||||
"""count() == len(list())."""
|
"""count() ist immer 0, auch nach register()."""
|
||||||
tracker.register("delegate_task")
|
tracker.register("delegate_task")
|
||||||
tracker.register("terminal_background")
|
tracker.register("terminal_background")
|
||||||
tracker.register("delegate_task")
|
assert tracker.count() == 0
|
||||||
|
|
||||||
assert tracker.count() == 3
|
def test_list_returns_empty_list(self, tracker):
|
||||||
assert tracker.count() == len(tracker.list())
|
"""list() gibt immer leere Liste zurück."""
|
||||||
|
|
||||||
def test_list_returns_copy_not_reference(self, tracker):
|
|
||||||
"""list() gibt eine Kopie zurück, Mutation ändert nicht den State."""
|
|
||||||
tracker.register("delegate_task")
|
tracker.register("delegate_task")
|
||||||
active = tracker.list()
|
active = tracker.list()
|
||||||
|
assert active == []
|
||||||
|
# Mutation ändert nichts
|
||||||
active.append({"fake": "entry"})
|
active.append({"fake": "entry"})
|
||||||
|
assert tracker.list() == []
|
||||||
# Interner State unverändert
|
|
||||||
assert tracker.count() == 1
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test 4: Atomic write
|
# Test 4: _read_subagent_state immer leer
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestAtomicWrite:
|
class TestReadSubagentState:
|
||||||
"""Test 4: Atomic write verhindert Corruption."""
|
"""Test 4: _read_subagent_state() returned immer leeres dict."""
|
||||||
|
|
||||||
def test_write_then_read_is_consistent(self, tracker, tmp_state_path):
|
def test_read_returns_empty(self, tmp_state_path):
|
||||||
"""Nach write → read ist der State konsistent."""
|
"""_read_subagent_state() → leeres dict."""
|
||||||
tracker.register("delegate_task", room_name="user:bernd")
|
|
||||||
tracker.register("terminal_background", room_name="user:alice")
|
|
||||||
|
|
||||||
# Re-read from file
|
|
||||||
state = _read_subagent_state(tmp_state_path)
|
state = _read_subagent_state(tmp_state_path)
|
||||||
assert len(state["active"]) == 2
|
assert state["active"] == []
|
||||||
assert state["schema_version"] == 1
|
assert state["schema_version"] == 1
|
||||||
assert state["source"] == "plugin_internal"
|
|
||||||
assert state["last_change_iso"] != ""
|
|
||||||
|
|
||||||
def test_no_temp_files_left_behind(self, tracker, tmp_state_path):
|
def test_read_ignores_file_content(self, tmp_state_path):
|
||||||
"""Nach write gibt es keine .tmp-Dateien im Verzeichnis."""
|
"""Auch wenn die Datei Daten enthält → leeres dict."""
|
||||||
tracker.register("delegate_task")
|
|
||||||
|
|
||||||
state_dir = os.path.dirname(tmp_state_path)
|
|
||||||
tmp_files = [f for f in os.listdir(state_dir) if f.endswith(".tmp")]
|
|
||||||
assert len(tmp_files) == 0, f"Temp files left behind: {tmp_files}"
|
|
||||||
|
|
||||||
def test_corrupt_file_returns_empty(self, tmp_state_path):
|
|
||||||
"""Korrupte JSON-Datei → leere Liste (graceful degradation)."""
|
|
||||||
with open(tmp_state_path, 'w') as f:
|
with open(tmp_state_path, 'w') as f:
|
||||||
f.write("this is not json {{{")
|
json.dump({"active": [{"task_id": "t_1"}]}, f)
|
||||||
|
|
||||||
state = _read_subagent_state(tmp_state_path)
|
state = _read_subagent_state(tmp_state_path)
|
||||||
assert state["active"] == []
|
assert state["active"] == []
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test 5: clear_all
|
# Test 5: clear_all ist no-op
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestClearAll:
|
class TestClearAll:
|
||||||
"""Test 5: clear_all() entfernt alle Einträge."""
|
"""Test 5: clear_all() ist no-op."""
|
||||||
|
|
||||||
def test_clear_all_removes_everything(self, tracker):
|
def test_clear_all_does_nothing(self, tracker):
|
||||||
"""Nach clear_all() ist die Liste leer."""
|
"""clear_all() wirft keinen Fehler."""
|
||||||
tracker.register("delegate_task")
|
|
||||||
tracker.register("terminal_background")
|
|
||||||
tracker.register("delegate_task")
|
|
||||||
|
|
||||||
assert tracker.count() == 3
|
|
||||||
tracker.clear_all()
|
tracker.clear_all()
|
||||||
assert tracker.count() == 0
|
assert tracker.count() == 0
|
||||||
assert tracker.list() == []
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
# Test 6: Thread-safety
|
# Test 6: Thread-safety (no-ops sind inhärent thread-safe)
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestThreadSafety:
|
class TestThreadSafety:
|
||||||
"""Test 6: Thread-safety bei parallelen register/complete."""
|
"""Test 6: No-ops sind thread-safe."""
|
||||||
|
|
||||||
def test_concurrent_registers(self, tracker):
|
def test_concurrent_registers_no_errors(self, tracker):
|
||||||
"""Parallele register() Aufrufe produzieren korrekte Anzahl."""
|
"""Parallele register() Aufrufe werfen keine Fehler."""
|
||||||
errors = []
|
errors = []
|
||||||
|
|
||||||
def register_many(n: int):
|
def register_many(n: int):
|
||||||
@@ -265,14 +201,11 @@ class TestThreadSafety:
|
|||||||
t.join()
|
t.join()
|
||||||
|
|
||||||
assert len(errors) == 0, f"Errors: {errors}"
|
assert len(errors) == 0, f"Errors: {errors}"
|
||||||
assert tracker.count() == 100
|
# No-ops → count immer 0
|
||||||
|
assert tracker.count() == 0
|
||||||
def test_concurrent_register_and_complete(self, tracker):
|
|
||||||
"""Gleichzeitiges register() und complete() ist konsistent."""
|
|
||||||
# Pre-populate
|
|
||||||
for i in range(50):
|
|
||||||
tracker.register("delegate_task", task_id=f"pre_{i}")
|
|
||||||
|
|
||||||
|
def test_concurrent_register_and_complete_no_errors(self, tracker):
|
||||||
|
"""Gleichzeitiges register() und complete() wirft keine Fehler."""
|
||||||
errors = []
|
errors = []
|
||||||
|
|
||||||
def register_more():
|
def register_more():
|
||||||
@@ -297,8 +230,7 @@ class TestThreadSafety:
|
|||||||
t2.join()
|
t2.join()
|
||||||
|
|
||||||
assert len(errors) == 0, f"Errors: {errors}"
|
assert len(errors) == 0, f"Errors: {errors}"
|
||||||
# 50 pre + 25 new - 25 completed = 50
|
assert tracker.count() == 0
|
||||||
assert tracker.count() == 50
|
|
||||||
|
|
||||||
|
|
||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
@@ -306,7 +238,7 @@ class TestThreadSafety:
|
|||||||
# ═══════════════════════════════════════════════════════════════════════════
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
class TestGetTracker:
|
class TestGetTracker:
|
||||||
"""Test 7: get_tracker() Singleton."""
|
"""Test 7: get_tracker() Singleton funktioniert weiterhin."""
|
||||||
|
|
||||||
def test_get_tracker_returns_same_instance(self):
|
def test_get_tracker_returns_same_instance(self):
|
||||||
"""get_tracker() gibt immer dieselbe Instanz zurück."""
|
"""get_tracker() gibt immer dieselbe Instanz zurück."""
|
||||||
|
|||||||
Reference in New Issue
Block a user