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:
@@ -13,7 +13,6 @@ import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
@@ -405,13 +404,13 @@ class PresenceEngine:
|
||||
"""Phase 5: Transition from busy — check subagents before going online.
|
||||
|
||||
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.
|
||||
"""
|
||||
with self._background_tasks_lock:
|
||||
bg = self._background_tasks
|
||||
|
||||
# Phase 5: Auch subagent_status.json prüfen
|
||||
# Phase 5: Auch pgrep prüfen
|
||||
subagent_count = self._read_subagent_count()
|
||||
|
||||
if bg > 0 or subagent_count > 0:
|
||||
@@ -422,17 +421,15 @@ class PresenceEngine:
|
||||
self.update_presence()
|
||||
|
||||
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:
|
||||
Number of active subagent entries, or 0 on any error.
|
||||
Number of active hermes chat --profile processes (excluding self).
|
||||
"""
|
||||
try:
|
||||
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
|
||||
return DetectionTimer._pgrep_hermes_subagents()
|
||||
|
||||
def _update_presence_with_subagents(self, subagent_count: int) -> None:
|
||||
"""Phase 5: Set presence when subagents are active.
|
||||
@@ -511,7 +508,7 @@ class PresenceEngine:
|
||||
logger.info(
|
||||
"[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()
|
||||
else:
|
||||
logger.debug(
|
||||
@@ -594,7 +591,7 @@ class PresenceEngine:
|
||||
count = self._background_tasks
|
||||
self._pulse_controller.set_background_count(count)
|
||||
# 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)
|
||||
return count
|
||||
|
||||
@@ -1482,14 +1479,11 @@ class DetectionTimer:
|
||||
self._increment_telemetry()
|
||||
|
||||
result = False
|
||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||
gateway_active = 0
|
||||
pid_used = False # P2: True if PID-Sentinel 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_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
|
||||
|
||||
# ── P2 PRIMARY: PID-Sentinel — prüft ob Gateway-Prozess lebt ────────
|
||||
@@ -1523,55 +1517,21 @@ class DetectionTimer:
|
||||
plugin_used = True
|
||||
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:
|
||||
try:
|
||||
from archivar.subagent_tracker import _read_subagent_state, _get_subagent_state_path
|
||||
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
|
||||
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"
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
||||
logger.debug("[detection] pgrep failed: %s", e)
|
||||
# pgrep_pids stays -1 (error sentinel)
|
||||
pgrep_count = self._pgrep_hermes_subagents()
|
||||
if pgrep_count > 0:
|
||||
result = True
|
||||
detection_source = "pgrep"
|
||||
|
||||
# ── 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"
|
||||
subagent_str = str(subagent_count) if subagent_count >= 0 else "n/a"
|
||||
logger.info(
|
||||
"[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",
|
||||
self._check_count,
|
||||
"alive" if pid_used else "dead",
|
||||
@@ -1579,9 +1539,7 @@ class DetectionTimer:
|
||||
"yes" if gateway_used else "no",
|
||||
"yes" if plugin_used else "no",
|
||||
plugin_str,
|
||||
"yes" if subagent_used else "no",
|
||||
subagent_str,
|
||||
pgrep_str,
|
||||
pgrep_count,
|
||||
"active" if result else "inactive",
|
||||
detection_source,
|
||||
)
|
||||
@@ -1604,71 +1562,40 @@ class DetectionTimer:
|
||||
self._last_result = result
|
||||
return result
|
||||
|
||||
def _stale_recovery(self) -> int:
|
||||
"""Phase 5: Stale-Recovery — räumt tote PID-Einträge aus subagent_status.json.
|
||||
@staticmethod
|
||||
def _pgrep_hermes_subagents() -> int:
|
||||
"""V8.7: Scan /proc/*/cmdline for 'hermes chat --profile' processes.
|
||||
|
||||
Für jeden aktiven Eintrag prüfen:
|
||||
- os.kill(pid, 0) oder /proc/<pid>/ — lebt der Prozess noch?
|
||||
- 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
|
||||
Iterates /proc/<pid>/cmdline, parses for 'hermes' + 'chat' + '--profile'.
|
||||
Excludes own PID. No subprocess — direct /proc read, <1ms for ~100 procs.
|
||||
|
||||
Returns:
|
||||
Number of entries removed.
|
||||
Number of matching processes (excluding self).
|
||||
"""
|
||||
removed = 0
|
||||
own_pid = os.getpid()
|
||||
count = 0
|
||||
try:
|
||||
from archivar.subagent_tracker import (
|
||||
_read_subagent_state, _get_subagent_state_path, get_tracker,
|
||||
)
|
||||
state = _read_subagent_state(_get_subagent_state_path())
|
||||
active = state.get("active", [])
|
||||
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:
|
||||
for entry in os.listdir("/proc"):
|
||||
if not entry.isdigit():
|
||||
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:
|
||||
expected_done = datetime.fromisoformat(expected_done_str)
|
||||
if now > expected_done:
|
||||
# expected_done_at überschritten, aber PID lebt noch
|
||||
# → Eintrag bleibt (long-running Task)
|
||||
logger.debug(
|
||||
"[detection] stale recovery: task_id=%s pid=%d "
|
||||
"exceeded expected_done_at but still alive — keeping",
|
||||
task_id, pid,
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
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
|
||||
pid = int(entry)
|
||||
if pid == own_pid:
|
||||
continue
|
||||
try:
|
||||
with open(f"/proc/{entry}/cmdline", "rb") as f:
|
||||
raw = f.read()
|
||||
# cmdline is null-separated; decode and split
|
||||
parts = raw.decode("utf-8", errors="replace").split("\x00")
|
||||
cmdline_str = " ".join(parts)
|
||||
# Match: contains 'hermes' AND 'chat' AND '--profile'
|
||||
if "hermes" in cmdline_str and "chat" in cmdline_str and "--profile" in cmdline_str:
|
||||
count += 1
|
||||
except (OSError, IOError, PermissionError):
|
||||
# Process may have exited or be inaccessible
|
||||
continue
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
return count
|
||||
|
||||
@staticmethod
|
||||
def _pid_is_alive(pid: int) -> bool:
|
||||
|
||||
Reference in New Issue
Block a user