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:
Bernd (Hermes)
2026-08-02 13:24:10 +02:00
parent 06e8d832df
commit 30015f0cfe
6 changed files with 418 additions and 984 deletions
@@ -1,11 +1,11 @@
"""
V8.6 Phase 5: Subagent-Status — PresenceEngine Integrationstests.
V8.7: Subagent-Status — PresenceEngine Integrationstests (pgrep-basiert).
Testet:
- mark_busy_done mit background_tasks > 0 (kein online-Übergang)
- mark_busy_done mit background_tasks == 0 (Regression: online-Übergang)
- _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="busy" message-pulses
"""
@@ -98,13 +98,10 @@ class TestMarkBusyDoneWithBgTasks:
time.sleep(0.3)
# Prüfe: letzter gesendeter Status ist NICHT "online"
# (sollte "away" sein wegen Subagent-Pulse)
calls = mock_rest._request.call_args_list
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_data = last_call[1].get("data", {})
# Entweder "away" (idle+subagent) oder "busy" (busy+subagent)
assert last_data.get("status") != "online", (
f"Expected non-online status, got {last_data}"
)
@@ -113,20 +110,23 @@ class TestMarkBusyDoneWithBgTasks:
"""Regression: background_tasks == 0 → online (klassischer Pfad)."""
engine, mock_rest = _make_engine(coalesce_ms=100)
engine.mark_busy_started(room_name="testroom")
# KEIN increment_background_tasks → bg=0
# 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")
# KEIN increment_background_tasks → bg=0
time.sleep(1.2)
time.sleep(1.2)
engine.mark_busy_done()
time.sleep(0.3)
engine.mark_busy_done()
time.sleep(0.3)
calls = mock_rest._request.call_args_list
last_call = calls[-1]
last_data = last_call[1].get("data", {})
assert last_data.get("status") == "online", (
f"Expected online status, got {last_data}"
)
calls = mock_rest._request.call_args_list
last_call = calls[-1]
last_data = last_call[1].get("data", {})
assert last_data.get("status") == "online", (
f"Expected online status, got {last_data}"
)
# ═══════════════════════════════════════════════════════════════════════════
@@ -140,15 +140,11 @@ class TestHoneymoonExpiredWithBgTasks:
"""Honeymoon-Timer feuert, aber bg_tasks > 0 → kein online."""
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.increment_background_tasks() # bg=1
# Honeymoon abwarten
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()
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:
"""Test 6: DetectionTimer.check() liest subagent_status.json."""
class TestPgrepHermesSubagents:
"""Test 6: _pgrep_hermes_subagents() erkennt hermes chat --profile Prozesse."""
def test_detection_timer_detects_subagent_status(self):
"""DetectionTimer erkennt aktive Einträge in subagent_status.json."""
def test_pgrep_finds_hermes_chat_profile_process(self):
"""_pgrep_hermes_subagents() findet einen simulierten hermes-Prozess."""
from plugin.archivar.presence_engine import DetectionTimer
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
# Schreibe einen aktiven Subagenten
subagent_path = _get_subagent_state_path()
_write_subagent_state(subagent_path, {
"active": [{"task_id": "t_123", "type": "delegate_task", "owner_room": "user:bernd"}],
"last_change_iso": "",
"schema_version": 1,
"source": "plugin_internal",
})
own_pid = os.getpid()
# Mock /proc: nur ein simulierter hermes chat --profile Prozess
mock_proc_entries = ["1", "2", str(own_pid), "99999", "12345"]
def mock_cmdline_read(pid_dir):
"""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:
gateway_path = f.name
try:
# Leeres gateway_state → PID-Sentinel greift (Gateway lebt)
# Um subagent_status zu testen, mocken wir _check_gateway_pid_alive
timer = DetectionTimer(
gateway_state_path=gateway_path,
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('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(stdout="", returncode=1)
with patch.object(timer, '_pgrep_hermes_subagents', return_value=2):
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}"
finally:
os.unlink(gateway_path)
# Cleanup subagent_status.json
try:
os.unlink(subagent_path)
except OSError:
pass
def test_detection_timer_empty_subagent_status(self):
"""DetectionTimer erkennt leere subagent_status.json nicht als aktiv."""
def test_detection_timer_check_zero_pgrep(self):
"""DetectionTimer.check() → False wenn pgrep 0 findet."""
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:
gateway_path = f.name
@@ -238,22 +354,17 @@ class TestDetectionTimerReadsSubagentStatus:
timer = DetectionTimer(
gateway_state_path=gateway_path,
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('plugin.archivar.presence_engine.subprocess.run') as mock_run:
mock_run.return_value = MagicMock(stdout="", returncode=1)
result = timer.check()
with patch.object(timer, '_check_gateway_pid_alive', return_value=False), \
patch.object(timer, '_pgrep_hermes_subagents', return_value=0):
result = timer.check()
# Sollte False sein weil keine Quellen aktiv
assert result is False, f"Expected False, got {result}"
finally:
os.unlink(gateway_path)
try:
os.unlink(subagent_path)
except OSError:
pass
# ═══════════════════════════════════════════════════════════════════════════
@@ -314,7 +425,6 @@ class TestPulseControllerAwayMode:
t.join()
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")
@@ -331,34 +441,27 @@ class TestPulseControllerBusyMode:
pc = PulseController(pulse_interval=0.1, _clamp_pulse=False)
pc.set_pulse_target("busy")
# Mock DDP
mock_ddp = MagicMock()
mock_ddp.connected = True
mock_ddp.set_status = MagicMock()
pc.bind_ddp(mock_ddp)
# Start pulse
pc.start()
time.sleep(0.4) # Wait for a few ticks
time.sleep(0.4)
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"
def test__update_presence_with_subagents_idle(self):
"""_update_presence_with_subagents bei idle startet away-Pulse."""
engine, mock_rest = _make_engine(coalesce_ms=100)
# Sicherstellen dass active_tasks == 0
assert engine._active_tasks == 0
engine._update_presence_with_subagents(3)
time.sleep(0.3)
# Sollte "away" mit Message "3 Subagent läuft" gesendet haben
calls = mock_rest._request.call_args_list
assert len(calls) > 0
last_data = calls[-1][1].get("data", {})
@@ -369,7 +472,6 @@ class TestPulseControllerBusyMode:
"""_update_presence_with_subagents bei busy setzt busy+Message."""
engine, mock_rest = _make_engine(coalesce_ms=100)
# Simuliere busy
engine.increment_active_tasks()
engine.set_current_room("testroom")
@@ -386,324 +488,27 @@ class TestPulseControllerBusyMode:
# ═══════════════════════════════════════════════════════════════════════════
# Test: _read_subagent_count
# Test: _read_subagent_count (pgrep-basiert)
# ═══════════════════════════════════════════════════════════════════════════
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):
"""Leere Datei → 0."""
def test_read_subagent_count_returns_zero_when_no_processes(self):
"""Keine hermes-Prozesse → 0."""
engine, _ = _make_engine()
# Clean state
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
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=0):
assert engine._read_subagent_count() == 0
def test_read_subagent_count_returns_count(self):
"""Datei mit 2 Einträgen → 2."""
"""2 hermes-Prozesse → 2."""
engine, _ = _make_engine()
from plugin.archivar.subagent_tracker import _write_subagent_state, _get_subagent_state_path
_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
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=2):
assert engine._read_subagent_count() == 2
def test_read_subagent_count_missing_file_returns_zero(self):
"""Fehlende Datei → 0 (graceful degradation)."""
def test_read_subagent_count_handles_errors(self):
"""Fehler in pgrep → 0 (graceful degradation)."""
engine, _ = _make_engine()
from plugin.archivar.subagent_tracker import _get_subagent_state_path
path = _get_subagent_state_path()
try:
os.unlink(path)
except OSError:
pass
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
# _pgrep_hermes_subagents() fängt OSError intern → 0
with patch.object(engine._detection_timer.__class__, '_pgrep_hermes_subagents', return_value=0):
assert engine._read_subagent_count() == 0