feat: Phase 0 SubagentTracker mit atomic write und 19 Tests

This commit is contained in:
Bernd (Hermes)
2026-08-02 11:12:04 +02:00
parent 73638fd565
commit 7f2b57b436
2 changed files with 538 additions and 0 deletions
+218
View File
@@ -0,0 +1,218 @@
"""
V8.6 Phase 5: SubagentTracker — Adapter-seitiges Modul für Subagent-Status.
Persistiert aktive Subagenten nach ~/.hermes/plugin_state/subagent_status.json.
Thread-safe. Atomic write via temp+rename (Pattern aus _write_plugin_state).
Zero external dependencies — stdlib only.
"""
from __future__ import annotations
import json
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
# ═══════════════════════════════════════════════════════════════════════════
SUBAGENT_STATE_DIR = os.path.expanduser("~/.hermes/plugin_state")
SUBAGENT_STATE_FILENAME = "subagent_status.json"
SUBAGENT_STATE_SCHEMA_VERSION = 1
def _get_subagent_state_path() -> str:
"""Return the path to the subagent status file."""
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"}
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)
# ═══════════════════════════════════════════════════════════════════════════
# SubagentTracker
# ═══════════════════════════════════════════════════════════════════════════
class SubagentTracker:
"""Tracks active subagents for the PresenceEngine.
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() # → []
"""
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._lock = threading.Lock()
def register(self, subagent_type: str, room_name: str = "", task_id: str = "") -> 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.
Returns:
The created entry dict.
"""
if not task_id:
task_id = f"t_{int(time.time() * 1_000_000)}"
entry = {
"task_id": task_id,
"type": subagent_type,
"owner_room": room_name,
"started_at": datetime.now(timezone.utc).isoformat(),
"expected_duration_s": 600,
"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:
"""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)
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", [])
def count(self) -> int:
"""Return the number of active subagents.
Returns:
Count of active entries.
"""
return len(self.list())
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")
# ═══════════════════════════════════════════════════════════════════════════
# Module-level convenience (singleton pattern for adapter use)
# ═══════════════════════════════════════════════════════════════════════════
_default_tracker: Optional[SubagentTracker] = None
_tracker_lock = threading.Lock()
def get_tracker() -> SubagentTracker:
"""Get or create the module-level SubagentTracker singleton."""
global _default_tracker
if _default_tracker is None:
with _tracker_lock:
if _default_tracker is None:
_default_tracker = SubagentTracker()
return _default_tracker