""" V10: PresenceEngine — Mediator Layer Architecture Tests. Tests für die V10 PresenceEngine mit 3-Schicht-Trennung: - Phase-Resolver (I1) - Mediator (I2-I10) - Counter + Hook-Trigger (aus V9 übernommen) - 429-Cooldown + Reconciliation (neu) - Puls-Timer (neu) V10: Alle Hooks bleiben SYNCHRON (P-024). """ from __future__ import annotations import sys import os import time import threading from pathlib import Path from unittest.mock import MagicMock, patch import pytest # Ensure the plugin package is importable sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # ═══════════════════════════════════════════════════════════════════════════ # Hilfsfunktionen # ═══════════════════════════════════════════════════════════════════════════ def _make_mock_rest(): """Erzeuge einen Mock-REST-Client für Tests.""" rest = MagicMock() rest.auth_token = "test-token" rest.user_id = "test-user" rest._request = MagicMock() return rest def _make_engine(rest=None, enabled=True, away_grace_s=0.1): """Erzeuge eine PresenceEngine V10 für Tests (mit kurzem away-grace).""" from plugin.archivar.presence_engine import PresenceEngine if rest is None: rest = _make_mock_rest() engine = PresenceEngine(rest=rest, enabled=enabled, away_grace_s=away_grace_s) return engine # ═══════════════════════════════════════════════════════════════════════════ # V10 NEU: Phase-Resolver Tests (I1) # ═══════════════════════════════════════════════════════════════════════════ class TestPhaseResolver: """resolve_phase() pure Funktion — deterministisch + pure (I1).""" def test_all_zero_green_static(self): """sum(counters) == 0 → GREEN_STATIC (P1).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 0, "delegate_subagent": 0, "chat_profile": 0, "background_term": 0} assert resolve_phase(counters) == Phase.GREEN_STATIC def test_main_agent_only_red_static(self): """Nur main_agent > 0 → RED_STATIC (P2).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 1, "delegate_subagent": 0, "chat_profile": 0, "background_term": 0} assert resolve_phase(counters) == Phase.RED_STATIC def test_delegate_subagent_only_green_pulse(self): """Nur delegate_subagent > 0 → GREEN_PULSE (P3).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 0, "delegate_subagent": 1, "chat_profile": 0, "background_term": 0} assert resolve_phase(counters) == Phase.GREEN_PULSE def test_main_agent_plus_subagent_red_pulse(self): """main_agent > 0 + subagent_active → RED_PULSE (P4).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 1, "delegate_subagent": 1, "chat_profile": 0, "background_term": 0} assert resolve_phase(counters) == Phase.RED_PULSE def test_chat_profile_green_pulse(self): """chat_profile > 0 → GREEN_PULSE (P3).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 0, "delegate_subagent": 0, "chat_profile": 1, "background_term": 0} assert resolve_phase(counters) == Phase.GREEN_PULSE def test_background_term_green_pulse(self): """background_term > 0 → GREEN_PULSE (P3).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 0, "delegate_subagent": 0, "chat_profile": 0, "background_term": 1} assert resolve_phase(counters) == Phase.GREEN_PULSE def test_main_agent_plus_chat_profile_red_pulse(self): """main_agent + chat_profile → RED_PULSE (P4).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 2, "delegate_subagent": 0, "chat_profile": 1, "background_term": 0} assert resolve_phase(counters) == Phase.RED_PULSE def test_multiple_subagents_green_pulse(self): """Mehrere Subagent-Typen, kein main_agent → GREEN_PULSE.""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 0, "delegate_subagent": 2, "chat_profile": 1, "background_term": 3} assert resolve_phase(counters) == Phase.GREEN_PULSE def test_deterministic_same_input_same_output(self): """Gleicher Input → gleicher Output (Determinismus).""" from plugin.archivar.presence_engine import resolve_phase, Phase counters = {"main_agent": 1, "delegate_subagent": 0, "chat_profile": 0, "background_term": 0} r1 = resolve_phase(counters) r2 = resolve_phase(dict(counters)) assert r1 == r2 == Phase.RED_STATIC def test_pure_no_side_effects(self): """resolve_phase() mutiert den Input nicht.""" from plugin.archivar.presence_engine import resolve_phase counters = {"main_agent": 1, "delegate_subagent": 0, "chat_profile": 0, "background_term": 0} original = dict(counters) resolve_phase(counters) assert counters == original # ═══════════════════════════════════════════════════════════════════════════ # V10 NEU: Mediator Phase Mapping Tests # ═══════════════════════════════════════════════════════════════════════════ class TestMediatorPhaseMapping: """Phase → sichtbarer Status korrekt.""" def test_green_static_online(self): """P1 → online.""" engine = _make_engine() assert engine.get_visible_status() == "online" assert engine.get_current_phase().name == "GREEN_STATIC" def test_red_static_busy(self): """P2 → busy.""" engine = _make_engine() engine.on_pre_gateway_dispatch() assert engine.get_visible_status() == "busy" assert engine.get_current_phase().name == "RED_STATIC" def test_green_pulse_online_then_away(self): """P3 → online (primary), dann away (toggle).""" engine = _make_engine() engine.on_subagent_start() assert engine.get_current_phase().name == "GREEN_PULSE" # Primary side = online assert engine.get_visible_status() == "online" def test_red_pulse_busy_then_away(self): """P4 → busy (primary), dann away (toggle).""" engine = _make_engine() engine.on_pre_gateway_dispatch() engine.on_subagent_start() assert engine.get_current_phase().name == "RED_PULSE" # Primary side = busy assert engine.get_visible_status() == "busy" def test_get_status_compatibility(self): """get_status() liefert ONLINE|BUSY für Kompatibilität.""" engine = _make_engine() assert engine.get_status() == "ONLINE" engine.on_pre_gateway_dispatch() assert engine.get_status() == "BUSY" engine.on_subagent_start() # P4 RED_PULSE → interner Status BUSY assert engine.get_status() == "BUSY" # ═══════════════════════════════════════════════════════════════════════════ # V10 NEU: Phasen-Übergang REST-Call Tests (I2, I3) # ═══════════════════════════════════════════════════════════════════════════ class TestPhaseTransitionRestCall: """Phasen-Übergang erzeugt maximal 1 REST-Call (I2). Counter-Delta ohne Phasen-Übergang erzeugt 0 REST-Calls (I3).""" def test_single_phase_transition_one_rest_call(self): """P1 → P2: genau 1 REST-Call.""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() time.sleep(0.2) # Mindestens 1 REST-Call (BUSY) assert rest._request.call_count >= 1 def test_multiple_counters_same_phase_no_extra_calls(self): """3 Subagenten in P3: nur 1 REST-Call (beim ersten Übergang).""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) # Erster Subagent: P1 → P3 (1 REST-Call) engine.on_subagent_start() time.sleep(0.1) calls_after_first = rest._request.call_count # Zweiter Subagent: Phase bleibt P3 (0 REST-Calls) engine.on_subagent_start() time.sleep(0.1) calls_after_second = rest._request.call_count # Dritter Subagent: Phase bleibt P3 (0 REST-Calls) engine.on_subagent_start() time.sleep(0.1) calls_after_third = rest._request.call_count # Keine zusätzlichen Calls nach dem ersten assert calls_after_second == calls_after_first assert calls_after_third == calls_after_first def test_counter_delta_without_phase_change_no_rest(self): """main_agent=1 → main_agent=2: Phase bleibt RED_STATIC, 0 REST-Calls.""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() # P1 → P2 time.sleep(0.1) calls_after_transition = rest._request.call_count # Zweiter pre_gateway: Phase bleibt P2 engine.on_pre_gateway_dispatch() time.sleep(0.1) # Keine neuen REST-Calls assert rest._request.call_count == calls_after_transition # ═══════════════════════════════════════════════════════════════════════════ # V10 NEU: Puls-Timer Tests (I4) # ═══════════════════════════════════════════════════════════════════════════ class TestPulseTimerLifecycle: """Puls-Timer startet/stoppt bei P3/P4-Eintritt/Austritt (I4).""" def test_pulse_starts_on_green_pulse_entry(self): """P1 → P3: Puls-Timer wird gestartet.""" engine = _make_engine(away_grace_s=0.05) engine.on_subagent_start() # Mediator sollte Puls-Timer haben assert engine._mediator._pulse_timer is not None def test_pulse_stops_on_green_pulse_exit(self): """P3 → P1: Puls-Timer wird gestoppt.""" engine = _make_engine(away_grace_s=0.05) engine.on_subagent_start() assert engine._mediator._pulse_timer is not None engine.on_subagent_stop() time.sleep(0.2) # Puls-Timer sollte gestoppt sein (Phase ist P1) assert engine._mediator._pulse_timer is None def test_pulse_starts_on_red_pulse_entry(self): """P2 → P4: Puls-Timer wird gestartet.""" engine = _make_engine(away_grace_s=0.05) engine.on_pre_gateway_dispatch() # P1 → P2 engine.on_subagent_start() # P2 → P4 assert engine._mediator._pulse_timer is not None def test_pulse_stops_on_red_pulse_exit(self): """P4 → P2: Puls-Timer wird gestoppt.""" engine = _make_engine(away_grace_s=0.05) engine.on_pre_gateway_dispatch() engine.on_subagent_start() # P2 → P4 assert engine._mediator._pulse_timer is not None engine.on_subagent_stop() # P4 → P2 assert engine._mediator._pulse_timer is None def test_pulse_tick_toggles_visible_status(self): """Puls-Tick toggelt sichtbaren Status.""" engine = _make_engine(away_grace_s=0.05) engine.on_subagent_start() # P3, primary=online assert engine.get_visible_status() == "online" # Simuliere einen Puls-Tick engine._mediator._pulse_toggle = True assert engine.get_visible_status() == "away" engine._mediator._pulse_toggle = False assert engine.get_visible_status() == "online" def test_pulse_interval_is_2_5_seconds(self): """PULSE_INTERVAL_S = 2.5 (P-041b: 5.0→2.5 für sichtbares Pulsieren).""" from plugin.archivar.presence_engine import _Mediator assert _Mediator.PULSE_INTERVAL_S == 2.5 # ═══════════════════════════════════════════════════════════════════════════ # V10 NEU: Cooldown + Reconciliation Tests (I5, I6, I10) # ═══════════════════════════════════════════════════════════════════════════ class TestCooldownSuppression: """Während Cooldown: keine REST-Calls (I6).""" def test_cooldown_suppresses_phase_transition(self): """Phasen-Übergang während Cooldown → kein REST-Call.""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) # Setze Cooldown manuell engine._mediator._rest_cooldown_until = time.monotonic() + 10.0 # Phasen-Übergang P1 → P2 engine.on_pre_gateway_dispatch() time.sleep(0.1) # Kein REST-Call wegen Cooldown assert rest._request.call_count == 0 # Telemetrie: suppressed assert engine._mediator.telemetry_phase_transitions_suppressed >= 1 def test_cooldown_suppresses_pulse_tick(self): """Puls-Tick während Cooldown → kein REST-Call, suppressed gezählt.""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_subagent_start() # P3 time.sleep(0.1) calls_before = rest._request.call_count # Setze Cooldown engine._mediator._rest_cooldown_until = time.monotonic() + 10.0 # Simuliere Puls-Tick engine._mediator._on_pulse_tick() time.sleep(0.1) # Kein neuer REST-Call assert rest._request.call_count == calls_before # Telemetrie: suppressed assert engine._mediator.telemetry_pulse_ticks_suppressed >= 1 class TestReconcileAfterCooldown: """Nach Cooldown-Ende: Reconciliation-Call (I6, I10).""" def test_reconcile_sends_after_cooldown(self): """Nach Cooldown-Ende wird aktueller Status gesendet (wenn Phase geändert).""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() # P2 time.sleep(0.1) calls_before = rest._request.call_count # Setze kurzen Cooldown (0.05s) engine._mediator._rest_cooldown_until = time.monotonic() + 0.05 # Ändere Phase während Cooldown (P2 → P4), aber unterdrückt engine.on_subagent_start() # P2 → P4, suppressed by cooldown # P-039: Reconciliation-Schutz umgehen (last_counter_change auf 0 setzen) engine._mediator._last_counter_change = 0.0 # Plane Reconciliation engine._mediator._schedule_reconcile_locked() # Warte auf Reconciliation time.sleep(0.3) # Reconciliation sollte einen Call gesendet haben (Phase hat sich geändert) assert rest._request.call_count > calls_before def test_reconcile_idempotent(self): """Reconciliation wenn Phase identisch zu last_sent → Caching skip (I10). V10.0.1: Verschaerft auf == 0 REST-Calls nach Reconciliation, da Caching jetzt korrekt greift (P1 B1 fix). """ rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() # P2, sendet BUSY time.sleep(0.2) calls_after_first = rest._request.call_count # Setze kurzen Cooldown engine._mediator._rest_cooldown_until = time.monotonic() + 0.05 engine._mediator._schedule_reconcile_locked() time.sleep(0.3) # Reconciliation: Phase ist immer noch P2, Caching muss greifen # → 0 neue REST-Calls (last_sent_phase == current_phase, last_sent_status == status) assert rest._request.call_count == calls_after_first class TestRestBackoffActivation: """429 setzt rest_cooldown_until = now() + 5s (I5).""" def test_429_sets_cooldown(self): """429-Antwort → rest_cooldown_until gesetzt.""" rest = _make_mock_rest() rest._request.side_effect = Exception("HTTP 429 Too Many Requests") engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() time.sleep(0.2) # Cooldown sollte gesetzt sein assert engine._mediator._rest_cooldown_until > time.monotonic() assert engine._mediator.telemetry_cooldown_set_count >= 1 def test_429_telemetry_counted(self): """Telemetrie zählt 429 + cooldown_set_count.""" rest = _make_mock_rest() rest._request.side_effect = Exception("HTTP 429 Too Many Requests") engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() time.sleep(0.2) telemetry = engine.get_telemetry() assert telemetry["rest_429"] >= 1 assert telemetry["cooldown_set_count"] >= 1 def test_backoff_duration_is_5_seconds(self): """REST_BACKOFF_429_S = 5.0.""" from plugin.archivar.presence_engine import _Mediator assert _Mediator.REST_BACKOFF_429_S == 5.0 # ═══════════════════════════════════════════════════════════════════════════ # 1. Hook-Trigger-Tests (aus V9 übernommen, unverändert) # ═══════════════════════════════════════════════════════════════════════════ class TestHookPreGatewayDispatch: """pre_gateway_dispatch → main_agent += 1 (ROT Start).""" def test_pre_gateway_dispatch_increments_main_agent(self): engine = _make_engine() engine.on_pre_gateway_dispatch() counters = engine.get_counters() assert counters["main_agent"] == 1 assert counters["delegate_subagent"] == 0 assert counters["chat_profile"] == 0 assert counters["background_term"] == 0 assert engine.get_status() == "BUSY" def test_pre_gateway_dispatch_disabled_engine_noop(self): engine = _make_engine(enabled=False) engine.on_pre_gateway_dispatch() counters = engine.get_counters() assert counters["main_agent"] == 0 assert engine.get_status() == "ONLINE" class TestHookPostLlmCall: """post_llm_call → main_agent -= 1 (ROT Ende).""" def test_post_llm_call_decrements_main_agent(self): engine = _make_engine() engine.on_pre_gateway_dispatch() engine.on_post_llm_call() time.sleep(engine._away_grace_s + 0.05) counters = engine.get_counters() assert counters["main_agent"] == 0 assert engine.get_status() == "ONLINE" def test_post_llm_call_without_pre_gateway_no_negative(self): engine = _make_engine() engine.on_post_llm_call() counters = engine.get_counters() assert counters["main_agent"] == 0 class TestHookSubagentStartStop: """subagent_start/stop → delegate_subagent += 1 / -= 1 (GELB).""" def test_subagent_start_increments_delegate(self): engine = _make_engine() engine.on_subagent_start() counters = engine.get_counters() assert counters["delegate_subagent"] == 1 # V10: P3 GREEN_PULSE → interner Status ONLINE assert engine.get_status() == "ONLINE" assert engine.get_visible_status() == "online" def test_subagent_start_stop_balanced(self): engine = _make_engine() engine.on_subagent_start() engine.on_subagent_stop() time.sleep(engine._away_grace_s + 0.05) counters = engine.get_counters() assert counters["delegate_subagent"] == 0 assert engine.get_status() == "ONLINE" def test_multiple_subagents_counter_accurate(self): engine = _make_engine() engine.on_subagent_start() engine.on_subagent_start() engine.on_subagent_start() engine.on_subagent_stop() engine.on_subagent_stop() counters = engine.get_counters() assert counters["delegate_subagent"] == 1 # P3 GREEN_PULSE assert engine.get_current_phase().name == "GREEN_PULSE" class TestHookSessionStartEnd: """on_session_start/end/finalize/reset → chat_profile (P-032 Fix).""" def test_session_start_increments_chat_profile(self): engine = _make_engine() engine.on_session_start() counters = engine.get_counters() assert counters["chat_profile"] == 1 assert engine.get_current_phase().name == "GREEN_PULSE" def test_session_end_is_noop(self): """P-032: on_session_end feuert PRO TURN — No-Op, chat_profile unverändert.""" engine = _make_engine() engine.on_session_start() engine.on_session_end() # No-Op counters = engine.get_counters() assert counters["chat_profile"] == 1 # unverändert assert engine.get_current_phase().name == "GREEN_PULSE" def test_session_finalize_decrements_chat_profile(self): """P-032: on_session_finalize (echtes Session-Ende) → chat_profile -= 1.""" engine = _make_engine() engine.on_session_start() engine.on_session_finalize() time.sleep(engine._away_grace_s + 0.05) counters = engine.get_counters() assert counters["chat_profile"] == 0 assert engine.get_status() == "ONLINE" def test_session_reset_zeros_all_counters(self): """P-032: on_session_reset → alle Counter auf 0, Status ONLINE.""" engine = _make_engine() engine.on_session_start() engine.on_pre_gateway_dispatch() engine.on_subagent_start() # Alle Counter > 0 assert engine.get_counters()["chat_profile"] == 1 assert engine.get_counters()["main_agent"] == 1 assert engine.get_counters()["delegate_subagent"] == 1 assert engine.get_status() == "BUSY" # Reset engine.on_session_reset() counters = engine.get_counters() assert counters["chat_profile"] == 0 assert counters["main_agent"] == 0 assert counters["delegate_subagent"] == 0 assert counters["background_term"] == 0 assert engine.get_status() == "ONLINE" def test_session_reset_disabled_engine_noop(self): """P-032: on_session_reset bei deaktivierter Engine → No-Op.""" engine = _make_engine(enabled=False) engine.on_session_start() engine.on_session_reset() counters = engine.get_counters() assert counters["chat_profile"] == 0 # disabled → kein Inkrement assert engine.get_status() == "ONLINE" class TestHookBackgroundTerminal: """pre/post_tool_call → background_term += 1 / -= 1 (O-1 Workaround).""" def test_pre_tool_call_terminal_bg_increments(self): engine = _make_engine() engine.on_pre_tool_call( tool_name="terminal", args={"background": True, "command": "sleep 10"}, ) counters = engine.get_counters() assert counters["background_term"] == 1 assert engine.get_current_phase().name == "GREEN_PULSE" def test_pre_tool_call_non_terminal_noop(self): engine = _make_engine() engine.on_pre_tool_call( tool_name="read_file", args={"path": "/tmp/test"}, ) counters = engine.get_counters() assert counters["background_term"] == 0 assert engine.get_status() == "ONLINE" def test_pre_tool_call_terminal_no_background_noop(self): engine = _make_engine() engine.on_pre_tool_call( tool_name="terminal", args={"background": False, "command": "echo hi"}, ) counters = engine.get_counters() assert counters["background_term"] == 0 def test_post_tool_call_terminal_bg_noop(self): """P-043: post_tool_call dekrementiert NICHT mehr background_term.""" engine = _make_engine() engine.on_pre_tool_call( tool_name="terminal", args={"background": True, "command": "sleep 10"}, ) engine.on_post_tool_call( tool_name="terminal", args={"background": True, "command": "sleep 10"}, ) time.sleep(engine._away_grace_s + 0.05) counters = engine.get_counters() # P-043: background_term bleibt > 0 — Dekrement erfolgt via # on_background_process_stop (echtes Prozess-Ende) assert counters["background_term"] == 1 # Phase ist GREEN_PULSE (Subagent aktiv) assert engine.get_status() == "ONLINE" # P3 → ONLINE (visible toggled) def test_background_process_stop_decrements(self): """P-043: on_background_process_stop dekrementiert background_term.""" engine = _make_engine() engine.on_pre_tool_call( tool_name="terminal", args={"background": True, "command": "sleep 10"}, ) assert engine.get_counters()["background_term"] == 1 engine.on_background_process_stop() time.sleep(engine._away_grace_s + 0.05) counters = engine.get_counters() assert counters["background_term"] == 0 assert engine.get_status() == "ONLINE" # ═══════════════════════════════════════════════════════════════════════════ # 2. Counter-Tests (aus V9 übernommen) # ═══════════════════════════════════════════════════════════════════════════ class TestCounterIncrement: """Counter-Inkrement: +1 auf jeden Counter-Typ.""" def test_main_agent_increment(self): engine = _make_engine() engine.on_pre_gateway_dispatch() assert engine.get_counters()["main_agent"] == 1 def test_delegate_subagent_increment(self): engine = _make_engine() engine.on_subagent_start() assert engine.get_counters()["delegate_subagent"] == 1 def test_chat_profile_increment(self): engine = _make_engine() engine.on_session_start() assert engine.get_counters()["chat_profile"] == 1 def test_background_term_increment(self): engine = _make_engine() engine.on_pre_tool_call( tool_name="terminal", args={"background": True}, ) assert engine.get_counters()["background_term"] == 1 class TestCounterDecrement: """Counter-Dekrement: -1, kein negativ.""" def test_decrement_to_zero(self): engine = _make_engine() engine.on_pre_gateway_dispatch() engine.on_post_llm_call() time.sleep(engine._away_grace_s + 0.05) assert engine.get_counters()["main_agent"] == 0 def test_decrement_below_zero_clamped(self): engine = _make_engine() engine.on_post_llm_call() assert engine.get_counters()["main_agent"] == 0 class TestCounterSum: """Summe aller Counter bestimmt Status.""" def test_sum_zero_means_online(self): engine = _make_engine() assert engine.get_status() == "ONLINE" def test_sum_positive_means_busy(self): engine = _make_engine() engine.on_pre_gateway_dispatch() assert engine.get_status() == "BUSY" def test_mixed_counters_sum_correct(self): engine = _make_engine() engine.on_pre_gateway_dispatch() engine.on_subagent_start() engine.on_subagent_start() total = sum(engine.get_counters().values()) assert total == 3 # P4 RED_PULSE → interner Status BUSY assert engine.get_status() == "BUSY" assert engine.get_current_phase().name == "RED_PULSE" class TestCounterTransition: """Transition bei Counter-Änderungen (adaptiert für V10).""" def test_online_to_busy_transition(self): engine = _make_engine() assert engine.get_status() == "ONLINE" engine.on_pre_gateway_dispatch() assert engine.get_status() == "BUSY" def test_busy_to_online_transition_after_away_grace(self): engine = _make_engine() engine.on_pre_gateway_dispatch() assert engine.get_status() == "BUSY" engine.on_post_llm_call() time.sleep(engine._away_grace_s + 0.05) assert engine.get_status() == "ONLINE" def test_busy_stays_busy_during_away_grace(self): """Während away-grace läuft, ist interner Status ONLINE, REST-Call verzögert.""" engine = _make_engine(away_grace_s=0.5) engine.on_pre_gateway_dispatch() engine.on_post_llm_call() time.sleep(0.1) # Interner Status ist ONLINE (total=0), REST-Call folgt nach away-grace assert engine.get_status() == "ONLINE" # ═══════════════════════════════════════════════════════════════════════════ # 3. Race-Tests (aus V9 übernommen, adaptiert) # ═══════════════════════════════════════════════════════════════════════════ class TestRaceParallelHooks: """Parallele Hooks — Counter unter Lock konsistent (I8).""" def test_parallel_increments_consistent(self): engine = _make_engine() threads = [] for _ in range(10): t = threading.Thread(target=engine.on_pre_gateway_dispatch) threads.append(t) t.start() for t in threads: t.join() assert engine.get_counters()["main_agent"] == 10 def test_parallel_mixed_operations_consistent(self): engine = _make_engine() threads = [] for _ in range(5): t = threading.Thread(target=engine.on_subagent_start) threads.append(t) t.start() for _ in range(3): t = threading.Thread(target=engine.on_subagent_stop) threads.append(t) t.start() for t in threads: t.join() assert engine.get_counters()["delegate_subagent"] == 2 class TestRaceLastWins: """Last-wins: Caching auf Phase-Ebene.""" def test_last_wins_overwrites_pending_transition(self): rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() # P1 → P2 engine.on_post_llm_call() # P2 → P1 (away-grace startet) engine.on_pre_gateway_dispatch() # P1 → P2 (away-grace gecancelt) time.sleep(0.2) assert engine.get_status() == "BUSY" assert rest._request.call_count >= 1 class TestRaceAwayGraceCancel: """away-grace wird gecancelt wenn neuer Hook feuert.""" def test_away_grace_cancelled_by_busy_hook(self): engine = _make_engine(away_grace_s=0.5) engine.on_pre_gateway_dispatch() # P2 engine.on_post_llm_call() # P1 (away-grace startet) time.sleep(0.1) engine.on_subagent_start() # P3 → cancel away-grace time.sleep(0.6) # Sollte P3 sein weil subagent_start den away-grace gecancelt hat assert engine.get_current_phase().name == "GREEN_PULSE" def test_away_grace_completes_when_no_interrupt(self): engine = _make_engine(away_grace_s=0.1) engine.on_pre_gateway_dispatch() engine.on_post_llm_call() time.sleep(0.3) assert engine.get_status() == "ONLINE" # ═══════════════════════════════════════════════════════════════════════════ # 4. Telemetrie, Enable/Disable, Shutdown (adaptiert) # ═══════════════════════════════════════════════════════════════════════════ class TestTelemetry: """Telemetrie: REST-Calls, Erfolg, 429, Fehler + V10-Felder.""" def test_telemetry_initial_zero(self): engine = _make_engine() t = engine.get_telemetry() assert t["rest_calls"] == 0 assert t["rest_success"] == 0 assert t["rest_429"] == 0 assert t["rest_errors"] == 0 assert t["phase_transitions"] == 0 assert t["pulse_ticks"] == 0 assert t["pulse_ticks_suppressed"] == 0 assert t["phase_transitions_suppressed"] == 0 assert t["cooldown_set_count"] == 0 class TestEnableDisable: """enable()/disable() — korrektes Verhalten (I7).""" def test_disable_stops_processing(self): engine = _make_engine() engine.disable() engine.on_pre_gateway_dispatch() assert engine.get_counters()["main_agent"] == 0 def test_enable_re_enables_processing(self): engine = _make_engine() engine.disable() engine.enable() engine.on_pre_gateway_dispatch() assert engine.get_counters()["main_agent"] == 1 def test_disable_stops_pulse_timer(self): """disable() stoppt Puls-Timer (I7).""" engine = _make_engine() engine.on_subagent_start() # P3, startet Puls-Timer assert engine._mediator._pulse_timer is not None engine.disable() assert engine._mediator._pulse_timer is None class TestShutdown: """shutdown() — sauberes Aufräumen (I7).""" def test_shutdown_cancels_away_grace(self): engine = _make_engine(away_grace_s=10.0) engine.on_pre_gateway_dispatch() engine.on_post_llm_call() engine.shutdown() assert True def test_shutdown_stops_pulse_timer(self): """shutdown() stoppt Puls-Timer (I7).""" engine = _make_engine() engine.on_subagent_start() # P3, startet Puls-Timer assert engine._mediator._pulse_timer is not None engine.shutdown() assert engine._mediator._pulse_timer is None # ═══════════════════════════════════════════════════════════════════════════ # 5. 429-Tests (adaptiert für V10) # ═══════════════════════════════════════════════════════════════════════════ class TestHttp429Handling: """HTTP 429 von users.setStatus — kein Crash, Cooldown gesetzt.""" def test_429_no_crash_status_unchanged(self): rest = _make_mock_rest() rest._request.side_effect = Exception("HTTP 429 Too Many Requests") engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() assert engine.get_status() == "BUSY" time.sleep(0.2) # Status bleibt BUSY — Counter wurde nicht zurückgesetzt assert engine.get_status() == "BUSY" assert engine.get_counters()["main_agent"] == 1 def test_429_retry_on_next_hook(self): rest = _make_mock_rest() call_count = [0] def _side_effect(*args, **kwargs): call_count[0] += 1 if call_count[0] == 1: raise Exception("HTTP 429 Too Many Requests") return {"success": True} rest._request.side_effect = _side_effect engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() time.sleep(0.15) engine.on_post_llm_call() time.sleep(0.2) assert engine.get_status() == "ONLINE" assert call_count[0] == 1 # V10: Cooldown unterdrückt zweiten Call def test_429_telemetry_counted(self): rest = _make_mock_rest() rest._request.side_effect = Exception("HTTP 429 Too Many Requests") engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() time.sleep(0.2) telemetry = engine.get_telemetry() assert telemetry["rest_429"] >= 1 assert telemetry["rest_calls"] >= 1 assert telemetry["rest_success"] == 0 # ═══════════════════════════════════════════════════════════════════════════ # 6. GELB-Logik Tests (adaptiert für V10 Phasen) # ═══════════════════════════════════════════════════════════════════════════ class TestGelbLogic: """V10: Subagent aktiv → P3/P4 (GREEN_PULSE/RED_PULSE).""" def test_main_agent_only_busy(self): engine = _make_engine() engine.on_pre_gateway_dispatch() assert engine.get_status() == "BUSY" assert engine.get_current_phase().name == "RED_STATIC" def test_delegate_subagent_only_away(self): engine = _make_engine() engine.on_subagent_start() assert engine.get_current_phase().name == "GREEN_PULSE" assert engine.get_visible_status() == "online" def test_main_agent_plus_delegate_subagent_red_pulse(self): engine = _make_engine() engine.on_pre_gateway_dispatch() engine.on_subagent_start() assert engine.get_current_phase().name == "RED_PULSE" assert engine.get_visible_status() == "busy" def test_all_zero_online(self): engine = _make_engine() assert engine.get_status() == "ONLINE" engine.on_pre_gateway_dispatch() engine.on_post_llm_call() time.sleep(engine._away_grace_s + 0.05) assert engine.get_status() == "ONLINE" def test_chat_profile_green_pulse(self): engine = _make_engine() engine.on_session_start() assert engine.get_current_phase().name == "GREEN_PULSE" def test_background_term_green_pulse(self): engine = _make_engine() engine.on_pre_tool_call( tool_name="terminal", args={"background": True, "command": "sleep 10"}, ) assert engine.get_current_phase().name == "GREEN_PULSE" def test_subagent_to_online_transition(self): engine = _make_engine() engine.on_subagent_start() assert engine.get_current_phase().name == "GREEN_PULSE" engine.on_subagent_stop() time.sleep(engine._away_grace_s + 0.05) assert engine.get_status() == "ONLINE" def test_busy_to_red_pulse_transition(self): engine = _make_engine() engine.on_pre_gateway_dispatch() assert engine.get_current_phase().name == "RED_STATIC" engine.on_subagent_start() assert engine.get_current_phase().name == "RED_PULSE" def test_red_pulse_to_busy_transition(self): engine = _make_engine() engine.on_pre_gateway_dispatch() engine.on_subagent_start() assert engine.get_current_phase().name == "RED_PULSE" engine.on_subagent_stop() assert engine.get_current_phase().name == "RED_STATIC" # ═══════════════════════════════════════════════════════════════════════════ # V10 NEU: Caching Tests (I9) # ═══════════════════════════════════════════════════════════════════════════ class TestCaching: """Caching überspringt identische (Phase, Message) — I9.""" def test_caching_skips_identical_phase_message(self): """Gleiche Phase + Message → kein zweiter REST-Call.""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) engine.on_pre_gateway_dispatch() # P2 time.sleep(0.1) calls_after_first = rest._request.call_count # Zweiter pre_gateway: Phase bleibt P2, kein Phasen-Übergang engine.on_pre_gateway_dispatch() time.sleep(0.1) # Kein neuer REST-Call (kein Phasen-Übergang) assert rest._request.call_count == calls_after_first # ═══════════════════════════════════════════════════════════════════════════ # V10 NEU: Multiple Subagents Test (I3) # ═══════════════════════════════════════════════════════════════════════════ class TestMultipleSubagents: """N Subagenten in derselben Phase → nur 1-2 REST-Calls.""" def test_three_subagents_two_rest_calls(self): """3 Starts + 3 Stops → 2 REST-Calls (P1→P3, P3→P1).""" rest = _make_mock_rest() engine = _make_engine(rest=rest, away_grace_s=0.05) # 3 Subagenten starten engine.on_subagent_start() engine.on_subagent_start() engine.on_subagent_start() time.sleep(0.1) calls_after_starts = rest._request.call_count # 3 Subagenten stoppen engine.on_subagent_stop() engine.on_subagent_stop() engine.on_subagent_stop() time.sleep(0.2) calls_after_stops = rest._request.call_count # Maximal 2 REST-Calls: P1→P3 + P3→P1 assert calls_after_stops <= calls_after_starts + 2