d9951fa822
5 Schritte:
1. adapter.py: complete('background_task') aus finally-Block entfernt.
Der Turn endet bevor der Background-Prozess endet — register() beim
Turn-Start bleibt, Stale-Recovery räumt tote Einträge auf.
2. subagent_tracker.py: register() speichert jetzt pid (os.getpid())
und expected_done_at (started_at + 600s). Neues remove_by_task_id()
für Stale-Recovery durch DetectionTimer.
3. presence_engine.py DetectionTimer: _stale_recovery() prüft jeden
aktiven Eintrag in subagent_status.json:
- os.kill(pid, 0) + /proc/<pid>/ Fallback
- PID tot → Eintrag entfernt
- PID lebend + expected_done_at überschritten → Eintrag bleibt
(long-running Task)
4. expected_done_at als Sekundär-Indikator: DetectionTimer nutzt es
für Logging/Diagnose, aber PID ist der primäre Indikator.
5. Lock-Order dokumentiert: _busy_honeymoon_lock vor _mode_lock.
Race-Bedingung zwischen Honeymoon-Expiry und set_pulse_target()
explizit im PresenceEngine-Docstring dokumentiert.
Tests: 40/40 passed (19 tracker + 21 presence, inkl. 5 neue Stale-Recovery-Tests)
259 lines
9.8 KiB
Python
259 lines
9.8 KiB
Python
"""
|
|
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 = "", 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
|
|
|
|
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 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
|
|
|
|
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
|