Personal AI, On Personal Devices
Python
feat: add warn-before-block escalation to LoopGuard
Tarun Suresh6371e7521d40
diff --git a/src/openjarvis/agents/loop_guard.py b/src/openjarvis/agents/loop_guard.pyindex 96af3b98..cd19983d 100644--- a/src/openjarvis/agents/loop_guard.py+++ b/src/openjarvis/agents/loop_guard.py@@ -18,6 +18,7 @@ class LoopGuardConfig:ping_pong_window: int = 6 # detect A-B-A-B cyclingpoll_tool_budget: int = 5 # max calls to same polling toolmax_context_messages: int = 100 # context overflow threshold+ warn_before_block: bool = True # warn on first cycle, block on second@dataclass(slots=True)@@ -25,6 +26,7 @@ class LoopVerdict:"""Result of a loop guard check."""blocked: bool = Falsereason: str = ""+ warned: bool = Falseclass LoopGuard:@@ -47,26 +49,49 @@ class LoopGuard:self._tool_sequence: deque[str] = deque(maxlen=config.ping_pong_window * 2)# Track per-tool call counts (for polling budget)self._per_tool_counts: dict[str, int] = {}-- from openjarvis._rust_bridge import get_rust_module- _rust = get_rust_module()- self._rust_impl = _rust.LoopGuard(- max_identical=config.max_identical_calls,- max_ping_pong=(- config.ping_pong_window // 2- if config.ping_pong_window > 1- else 2- ),- poll_budget=config.poll_tool_budget,- )+ # Track cycle keys that have already been warned (for warn-before-block)+ self._warned_cycles: set[str] = set()++ try:+ from openjarvis._rust_bridge import get_rust_module+ _rust = get_rust_module()+ self._rust_impl = _rust.LoopGuard(+ max_identical=config.max_identical_calls,+ max_ping_pong=(+ config.ping_pong_window // 2+ if config.ping_pong_window > 1+ else 2+ ),+ poll_budget=config.poll_tool_budget,+ )+ except Exception:+ self._rust_impl = Nonedef check_call(self, tool_name: str, arguments: str) -> LoopVerdict:"""Check whether a tool call should proceed or be blocked."""- reason = self._rust_impl.check(tool_name, arguments)- if reason is not None:- self._emit_triggered("rust_guard", tool_name)- return LoopVerdict(blocked=True, reason=reason)- return LoopVerdict()+ if self._rust_impl is not None:+ rust_result = self._rust_impl.check(tool_name, arguments)+ # Support both raw Rust return (str | None) and LoopVerdict+ if isinstance(rust_result, LoopVerdict):+ verdict = rust_result+ elif rust_result is not None:+ self._emit_triggered("rust_guard", tool_name)+ verdict = LoopVerdict(blocked=True, reason=rust_result)+ else:+ verdict = LoopVerdict()+ else:+ verdict = self._python_check(tool_name, arguments)++ # Wrap with warn-before-block logic+ if verdict.blocked and self._config.warn_before_block:+ cycle_key = verdict.reason+ if cycle_key not in self._warned_cycles:+ self._warned_cycles.add(cycle_key)+ return LoopVerdict(blocked=False, warned=True, reason=verdict.reason)+ return verdict++ def _python_check(self, tool_name: str, arguments: str) -> LoopVerdict:+ """Pure-Python fallback when Rust backend is not available."""# 1. Hash tracking — identical callscall_hash = hashlib.sha256(f"{tool_name}:{arguments}".encode()@@ -198,7 +223,9 @@ class LoopGuard:self._call_counts.clear()self._tool_sequence.clear()self._per_tool_counts.clear()- self._rust_impl.reset()+ self._warned_cycles.clear()+ if self._rust_impl is not None:+ self._rust_impl.reset()def _detect_ping_pong(self) -> bool:"""Detect repeating patterns in tool call sequence."""diff --git a/tests/agents/test_loop_guard.py b/tests/agents/test_loop_guard.pyindex 161add10..69ea11f6 100644--- a/tests/agents/test_loop_guard.py+++ b/tests/agents/test_loop_guard.py@@ -8,6 +8,7 @@ from openjarvis.core.events import EventBus, EventTypeclass TestLoopGuard:def _make_guard(self, **kwargs):from openjarvis.agents.loop_guard import LoopGuard, LoopGuardConfig+ kwargs.setdefault("warn_before_block", False)config = LoopGuardConfig(**kwargs)bus = EventBus(record_history=True)return LoopGuard(config, bus=bus), busdiff --git a/tests/agents/test_loop_guard_warn.py b/tests/agents/test_loop_guard_warn.pynew file mode 100644index 00000000..534082ad--- /dev/null+++ b/tests/agents/test_loop_guard_warn.py@@ -0,0 +1,62 @@+from __future__ import annotations++from unittest.mock import MagicMock++from openjarvis.agents.loop_guard import LoopGuard, LoopGuardConfig, LoopVerdict+++def test_warn_before_block_first_cycle_warns():+ config = LoopGuardConfig(+ enabled=True, max_identical_calls=2, warn_before_block=True,+ )+ guard = LoopGuard(config)+ # Simulate the Rust backend blocking on the second identical call+ mock_rust = MagicMock()+ mock_rust.check.side_effect = [+ LoopVerdict(blocked=False, reason=""),+ LoopVerdict(blocked=True, reason="identical_calls:search"),+ ]+ guard._rust_impl = mock_rust+ guard.check_call("search", '{"q": "test"}')+ v2 = guard.check_call("search", '{"q": "test"}')+ assert not v2.blocked+ assert v2.warned+++def test_warn_before_block_second_cycle_blocks():+ config = LoopGuardConfig(+ enabled=True, max_identical_calls=2, warn_before_block=True,+ )+ guard = LoopGuard(config)+ mock_rust = MagicMock()+ mock_rust.check.side_effect = [+ LoopVerdict(blocked=False, reason=""),+ LoopVerdict(blocked=True, reason="identical_calls:search"),+ LoopVerdict(blocked=False, reason=""),+ LoopVerdict(blocked=True, reason="identical_calls:search"),+ ]+ guard._rust_impl = mock_rust+ guard.check_call("search", '{"q": "test"}')+ v_warn = guard.check_call("search", '{"q": "test"}')+ assert v_warn.warned and not v_warn.blocked+ guard.check_call("search", '{"q": "test"}')+ v_block = guard.check_call("search", '{"q": "test"}')+ assert v_block.blocked+ assert not v_block.warned+++def test_default_behavior_unchanged():+ config = LoopGuardConfig(+ enabled=True, max_identical_calls=2, warn_before_block=False,+ )+ guard = LoopGuard(config)+ mock_rust = MagicMock()+ mock_rust.check.side_effect = [+ LoopVerdict(blocked=False, reason=""),+ LoopVerdict(blocked=True, reason="identical_calls:search"),+ ]+ guard._rust_impl = mock_rust+ guard.check_call("search", '{"q": "test"}')+ v = guard.check_call("search", '{"q": "test"}')+ assert v.blocked+ assert not v.warned