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:
@@ -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.
|
||||
Thread-safe. Atomic write via temp+rename (Pattern aus _write_plugin_state).
|
||||
Die subagent_status.json-basierte Erkennung wurde durch pgrep-basierte
|
||||
/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.
|
||||
"""
|
||||
@@ -14,14 +15,12 @@ import logging
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Constants
|
||||
# Constants (beibehalten für Kompatibilität)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
SUBAGENT_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
|
||||
@@ -30,218 +29,67 @@ SUBAGENT_STATE_SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _read_subagent_state(path: str) -> dict:
|
||||
"""Read the subagent state file, returning default empty dict if missing or corrupt."""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
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"}
|
||||
"""Read the subagent state file, returning default empty dict if missing or corrupt.
|
||||
|
||||
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"}
|
||||
|
||||
|
||||
def _write_subagent_state(path: str, data: dict) -> None:
|
||||
"""Atomically write the subagent state file (write-temp + rename).
|
||||
|
||||
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
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.debug("[subagent_tracker] write failed: %s", e)
|
||||
"""V8.7: No-op — subagent_status.json wird nicht mehr geschrieben."""
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# SubagentTracker
|
||||
# SubagentTracker (no-ops)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
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.
|
||||
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() # → []
|
||||
Alle Methoden sind no-ops. Das Modul bleibt für Kompatibilität erhalten.
|
||||
"""
|
||||
|
||||
def __init__(self, state_path: str = ""):
|
||||
"""Initialize SubagentTracker.
|
||||
|
||||
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._state_path = state_path or _get_subagent_state_path()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def register(self, subagent_type: str, room_name: str = "", task_id: str = "", pid: int = 0) -> dict:
|
||||
"""Register a new active subagent.
|
||||
|
||||
Args:
|
||||
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
|
||||
"""V8.7: No-op — pgrep-basierte Erkennung ersetzt register()."""
|
||||
logger.debug("[subagent_tracker] register() no-op (pgrep mode): type=%s", subagent_type)
|
||||
return {"task_id": "", "type": subagent_type, "owner_room": room_name, "pid": 0}
|
||||
|
||||
def complete(self, subagent_type: str, task_id: str = "") -> int:
|
||||
"""Remove a subagent entry by type (and optionally task_id).
|
||||
|
||||
If task_id is provided, only removes the matching entry.
|
||||
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)
|
||||
"""V8.7: No-op — pgrep-basierte Erkennung ersetzt complete()."""
|
||||
logger.debug("[subagent_tracker] complete() no-op (pgrep mode): type=%s", subagent_type)
|
||||
return 0
|
||||
|
||||
def remove_by_task_id(self, task_id: str) -> bool:
|
||||
"""Remove a subagent entry by task_id (for stale recovery).
|
||||
|
||||
Used by DetectionTimer to clean up entries whose PID is dead.
|
||||
|
||||
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
|
||||
"""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)
|
||||
return False
|
||||
|
||||
def list(self) -> List[Dict]:
|
||||
"""List all currently active subagent entries.
|
||||
|
||||
Returns:
|
||||
List of active entry dicts.
|
||||
"""
|
||||
state = _read_subagent_state(self._state_path)
|
||||
return state.get("active", [])
|
||||
"""V8.7: Immer leere Liste — pgrep ist die Quelle der Wahrheit."""
|
||||
return []
|
||||
|
||||
def count(self) -> int:
|
||||
"""Return the number of active subagents.
|
||||
|
||||
Returns:
|
||||
Count of active entries.
|
||||
"""
|
||||
return len(self.list())
|
||||
"""V8.7: Immer 0 — pgrep ist die Quelle der Wahrheit."""
|
||||
return 0
|
||||
|
||||
def clear_all(self) -> None:
|
||||
"""Remove all active entries (for testing/reset)."""
|
||||
with self._lock:
|
||||
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")
|
||||
"""V8.7: No-op."""
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Module-level convenience (singleton pattern for adapter use)
|
||||
# Module-level convenience (singleton pattern, no-op)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_default_tracker: Optional[SubagentTracker] = None
|
||||
@@ -249,7 +97,7 @@ _tracker_lock = threading.Lock()
|
||||
|
||||
|
||||
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
|
||||
if _default_tracker is None:
|
||||
with _tracker_lock:
|
||||
|
||||
Reference in New Issue
Block a user