feat: Phase 2 Verhaltensänderung — _update_presence_with_subagents + pulse_target

presence_engine.py:
- PulseController: pulse_target Feld + Mode-Sentinel (_mode_lock)
  - set_pulse_target('away'|'busy') mit Mutex-Logik (Risiko #2)
  - get_pulse_target() für Tests
- Neue Methode _update_presence_with_subagents(N):
  - active_tasks > 0 → busy + Message 'Verarbeitet in X (N Subagent)'
  - active_tasks == 0 → PulseController mit pulse_target='away'
- Neue Methode _transition_from_busy():
  - Prüft background_tasks + subagent_status.json
  - Entscheidet: online vs. Subagent-Pulse
- mark_busy_done: _transition_from_busy() statt direkt update_presence()
- _honeymoon_expired: _transition_from_busy() statt direkt update_presence()
- _read_subagent_count(): liest subagent_status.json (graceful degradation)

Production-Impact: none (read path exists but DetectionTimer not yet wired)
This commit is contained in:
Bernd (Hermes)
2026-08-02 11:16:01 +02:00
parent b5fa6e22f5
commit 309b0ddc85
+121 -5
View File
@@ -349,6 +349,9 @@ class PresenceEngine:
If the honeymoon hasn't elapsed yet, the timer callback will If the honeymoon hasn't elapsed yet, the timer callback will
handle the transition when it fires. handle the transition when it fires.
Phase 5: Wenn background_tasks > 0, NICHT auf online gehen.
Stattdessen _update_presence_with_subagents() aufrufen.
Must be called in a finally block to ensure counter balance Must be called in a finally block to ensure counter balance
even on exceptions. even on exceptions.
""" """
@@ -363,11 +366,12 @@ class PresenceEngine:
if counter == 0: if counter == 0:
elapsed = time.monotonic() - self._busy_started_at elapsed = time.monotonic() - self._busy_started_at
if elapsed >= self.MIN_BUSY_VISIBLE_S: if elapsed >= self.MIN_BUSY_VISIBLE_S:
# Honeymoon already elapsed — transition to online now # Honeymoon already elapsed — transition now
self._cancel_honeymoon_timer() self._cancel_honeymoon_timer()
self.update_presence() # Phase 5: Check background_tasks before going online
self._transition_from_busy()
logger.debug( logger.debug(
"[presence] Honeymoon abgelaufen (%.2fs) → online", elapsed, "[presence] Honeymoon abgelaufen (%.2fs) → transition", elapsed,
) )
else: else:
# Honeymoon still running — timer callback will handle it # Honeymoon still running — timer callback will handle it
@@ -380,6 +384,81 @@ class PresenceEngine:
"[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter, "[presence] mark_busy_done: counter=%d (weitere Tasks aktiv)", counter,
) )
def _transition_from_busy(self) -> None:
"""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
has active entries, start/keep PulseController instead.
"""
with self._background_tasks_lock:
bg = self._background_tasks
# Phase 5: Auch subagent_status.json prüfen
subagent_count = self._read_subagent_count()
if bg > 0 or subagent_count > 0:
# Subagenten laufen noch — Pulse-Modus statt online
self._update_presence_with_subagents(max(bg, subagent_count))
else:
# Keine Subagenten — klassischer Pfad: online
self.update_presence()
def _read_subagent_count(self) -> int:
"""Phase 5: Read active subagent count from subagent_status.json.
Returns:
Number of active subagent entries, or 0 on any error.
"""
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
def _update_presence_with_subagents(self, subagent_count: int) -> None:
"""Phase 5: Set presence when subagents are active.
Two modes:
1. Hauptagent busy (_active_tasks > 0): Status bleibt "busy",
Message = "Verarbeitet in X (N Subagent)"
2. Hauptagent idle (_active_tasks == 0): PulseController mit
pulse_target="away", Message = "N Subagent läuft"
Args:
subagent_count: Number of active subagents.
"""
with self._active_tasks_lock:
active = self._active_tasks
if active > 0:
# Hauptagent busy + Subagenten → busy mit erweiterter Message
msg = f"Verarbeitet in {self._current_room_name} ({subagent_count} Subagent)" if self._current_room_name else f"Verarbeitet ({subagent_count} Subagent)"
self._set_presence("busy", msg)
# PulseController im busy-Modus halten für Message-Pulse
if not self._pulse_controller.is_running():
self._pulse_controller.set_pulse_target("busy")
self._pulse_controller.start()
else:
self._pulse_controller.set_pulse_target("busy")
logger.info(
"[presence] Subagent-Pulse: busy+%d subagents (active_tasks=%d)",
subagent_count, active,
)
else:
# Hauptagent idle + Subagenten → Pulse online↔away
msg = f"{subagent_count} Subagent läuft"
self._pulse_controller.set_pulse_target("away")
if not self._pulse_controller.is_running():
self._pulse_controller.start()
# Set initial status to away (Pulse toggles from here)
self._set_presence("away", msg)
logger.info(
"[presence] Subagent-Pulse: idle+%d subagents → away-pulse",
subagent_count,
)
def _honeymoon_expired(self) -> None: def _honeymoon_expired(self) -> None:
"""P1a: Honeymoon timer callback — transition to online if idle. """P1a: Honeymoon timer callback — transition to online if idle.
@@ -387,6 +466,9 @@ class PresenceEngine:
If no active tasks remain, sets status to online. If no active tasks remain, sets status to online.
B3: Checks pending_status under _active_tasks_lock to prevent B3: Checks pending_status under _active_tasks_lock to prevent
race with mark_busy_started. race with mark_busy_started.
Phase 5: Nutzt _transition_from_busy() statt direkt update_presence(),
damit Subagent-Check auch im Honeymoon-Pfad greift.
""" """
with self._busy_honeymoon_lock: with self._busy_honeymoon_lock:
self._busy_honeymoon_timer = None self._busy_honeymoon_timer = None
@@ -410,9 +492,10 @@ class PresenceEngine:
# and no active tasks remain — next busy cycle starts fresh. # and no active tasks remain — next busy cycle starts fresh.
self._busy_started_at = 0.0 self._busy_started_at = 0.0
logger.info( logger.info(
"[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → online" "[presence] Honeymoon-Timer abgelaufen, active_tasks=0 → transition"
) )
self.update_presence() # Phase 5: _transition_from_busy prüft subagent_status.json
self._transition_from_busy()
else: else:
logger.debug( logger.debug(
"[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel", "[presence] Honeymoon-Timer abgelaufen, aber active_tasks=%d — kein Wechsel",
@@ -749,6 +832,13 @@ class PulseController:
self._loop: Optional[asyncio.AbstractEventLoop] = None self._loop: Optional[asyncio.AbstractEventLoop] = None
self._await_timeout: float = 2.0 self._await_timeout: float = 2.0
# Phase 5: pulse_target — "away" (default) oder "busy"
# "away": pulsiert online↔away (Subagent läuft, Hauptagent idle)
# "busy": pulsiert Message bei busy-Status (Subagent läuft, Hauptagent busy)
self._pulse_target: str = "away"
self._mode_lock = threading.Lock() # Mode-Sentinel (Risiko #2)
self._tick_counter: int = 0 # für Message-only-every-2-ticks
# P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway # P1: Circuit-Breaker — verhindert 429-Endlosschleife im Gateway
# States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping) # States: CLOSED (normal) → OPEN (nach N×429: Pause) → HALF_OPEN (Test-Ping)
self._breaker_state: str = "CLOSED" self._breaker_state: str = "CLOSED"
@@ -795,6 +885,32 @@ class PulseController:
"""Set the background task count for heartbeat messages.""" """Set the background task count for heartbeat messages."""
self._background_count = count self._background_count = count
def set_pulse_target(self, target: str) -> bool:
"""Phase 5: Set the pulse target mode with Mode-Sentinel.
Args:
target: "away" (pulse online↔away) or "busy" (pulse message while busy).
Returns:
True if mode was changed, False if already in that mode.
Raises:
ValueError: if target is not "away" or "busy".
"""
if target not in ("away", "busy"):
raise ValueError(f"pulse_target must be 'away' or 'busy', got '{target}'")
with self._mode_lock:
if self._pulse_target == target:
return False
old = self._pulse_target
self._pulse_target = target
logger.info("[pulse] pulse_target: %s → %s", old, target)
return True
def get_pulse_target(self) -> str:
"""Phase 5: Get the current pulse target mode."""
return self._pulse_target
def start(self) -> None: def start(self) -> None:
"""Start the pulse thread.""" """Start the pulse thread."""
logger.info( logger.info(