The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): recover active goals after compression exhaustion
Gille1439a65829c6
diff --git a/tests/tui_gateway/test_goal_command.py b/tests/tui_gateway/test_goal_command.pyindex ad2cb9f3449..e08e906b66e 100644--- a/tests/tui_gateway/test_goal_command.py+++ b/tests/tui_gateway/test_goal_command.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport importlibimport threading+import typesfrom pathlib import Pathfrom unittest.mock import MagicMock, patch@@ -95,6 +96,80 @@ def _call(server, method, **params):return handler(1, params)+class _InlineThread:+ """Run a turn synchronously so its automatic follow-up is observable."""++ def __init__(self, target=None, daemon=None, args=(), kwargs=None, **_extra):+ self._target = target+ self._args = args+ self._kwargs = kwargs or {}++ def start(self):+ if self._target is not None:+ self._target(*self._args, **self._kwargs)++ def is_alive(self):+ return False++ def join(self, timeout=None):+ return None+++def turn_env(server, monkeypatch, tmp_path):+ """Neutralize side paths unrelated to post-turn goal continuation."""+ emitted = []+ monkeypatch.setattr(server.threading, "Thread", _InlineThread)+ monkeypatch.setattr(+ server,+ "_emit",+ lambda event, sid, payload=None: emitted.append((event, sid, payload)),+ )+ monkeypatch.setattr(server, "_wire_callbacks", lambda sid: None)+ monkeypatch.setattr(+ server, "_sync_agent_model_with_config", lambda sid, session: None+ )+ monkeypatch.setattr(server, "_session_cwd", lambda session: str(tmp_path))+ monkeypatch.setattr(server, "_register_session_cwd", lambda session: None)+ monkeypatch.setattr(server, "_tts_stream_begin", lambda: None)+ monkeypatch.setattr(+ server, "_sync_session_key_after_compress", lambda *a, **k: None+ )+ monkeypatch.setattr(server, "_get_usage", lambda agent: {})+ monkeypatch.setattr(server, "_load_cfg", lambda: {})+ return emitted+++def _turn_session(agent, session_key):+ return {+ "agent": agent,+ "session_key": session_key,+ "history": [],+ "history_lock": threading.Lock(),+ "history_version": 0,+ "running": True,+ "attached_images": [],+ "image_counter": 0,+ "cols": 80,+ "slash_worker": None,+ "show_reasoning": False,+ "tool_progress_mode": "all",+ "inflight_turn": None,+ }+++def _compression_failure():+ message = "Context length exceeded: max compression attempts (3) reached."+ return {+ "final_response": message,+ "error": message,+ "failed": True,+ "partial": True,+ "compression_exhausted": True,+ "completed": False,+ }++# ── command.dispatch /goal ────────────────────────────────────────────@@ -127,6 +202,195 @@ def test_pending_input_commands_includes_goal(server):assert "goal" in server._PENDING_INPUT_COMMANDS+# ── active-goal recovery after compression exhaustion ───────────────+++def test_active_goal_retries_once_without_judging_failed_turn(+ server, turn_env, monkeypatch+):+ from hermes_cli.goals import GoalManager++ session_key = "goal-compression-retry"+ mgr = GoalManager(session_key)+ mgr.set("finish the current task")+ continuation = mgr.next_continuation_prompt()+ seen_prompts = []+ results = iter([_compression_failure(), {"final_response": "recovered work"}])++ def run_conversation(message, **_kwargs):+ seen_prompts.append(message)+ return next(results)++ judged = []++ def evaluate(self, response, **_kwargs):+ judged.append(response)+ return {"message": "", "should_continue": False}++ monkeypatch.setattr(GoalManager, "evaluate_after_turn", evaluate)+ agent = types.SimpleNamespace(+ session_id=session_key,+ run_conversation=run_conversation,+ clear_interrupt=lambda: None,+ )+ session = _turn_session(agent, session_key)++ server._run_prompt_submit("rid", "sid", session, "initial work")++ assert seen_prompts == ["initial work", continuation]+ assert judged == ["recovered work"]+ assert GoalManager(session_key).state.turns_used == 0+ assert server._GOAL_COMPRESSION_RECOVERY_ATTEMPTS not in session+ completes = [p for event, _sid, p in turn_env if event == "message.complete"]+ assert [p["status"] for p in completes] == ["error", "complete"]+++def test_second_consecutive_exhaustion_pauses_goal_instead_of_looping(+ server, turn_env, monkeypatch+):+ from hermes_cli.goals import GoalManager++ session_key = "goal-compression-pause"+ GoalManager(session_key).set("finish the current task")+ seen_prompts = []++ def run_conversation(message, **_kwargs):+ seen_prompts.append(message)+ return _compression_failure()++ judged = []+ monkeypatch.setattr(+ GoalManager,+ "evaluate_after_turn",+ lambda self, response, **kwargs: judged.append(response),+ )+ agent = types.SimpleNamespace(+ session_id=session_key,+ run_conversation=run_conversation,+ clear_interrupt=lambda: None,+ )+ session = _turn_session(agent, session_key)++ server._run_prompt_submit("rid", "sid", session, "initial work")++ assert len(seen_prompts) == 2+ assert judged == []+ state = GoalManager(session_key).state+ assert state.status == "paused"+ assert state.turns_used == 0+ assert "compression exhausted twice" in state.paused_reason+ assert server._GOAL_COMPRESSION_RECOVERY_ATTEMPTS not in session+ notices = [+ p["text"]+ for event, _sid, p in turn_env+ if event == "status.update" and p.get("kind") == "goal"+ ]+ assert any("Retrying the active goal once" in text for text in notices)+ assert any("Goal paused" in text for text in notices)+++def test_real_queued_prompt_preempts_goal_compression_retry(+ server, turn_env, monkeypatch+):+ from hermes_cli.goals import GoalManager++ session_key = "goal-compression-user-preempts"+ mgr = GoalManager(session_key)+ mgr.set("finish the current task")+ continuation = mgr.next_continuation_prompt()+ seen_prompts = []+ session_holder = {}++ def run_conversation(message, **_kwargs):+ seen_prompts.append(message)+ if len(seen_prompts) == 1:+ server._enqueue_prompt(session_holder["session"], "real user input", None)+ return _compression_failure()+ return {"final_response": "handled the user's update"}++ monkeypatch.setattr(+ GoalManager,+ "evaluate_after_turn",+ lambda self, response, **kwargs: {"message": "", "should_continue": False},+ )+ agent = types.SimpleNamespace(+ session_id=session_key,+ run_conversation=run_conversation,+ clear_interrupt=lambda: None,+ )+ session = _turn_session(agent, session_key)+ session_holder["session"] = session++ server._run_prompt_submit("rid", "sid", session, "initial work")++ assert seen_prompts == ["initial work", "real user input"]+ assert continuation not in seen_prompts+ assert server._GOAL_COMPRESSION_RECOVERY_ATTEMPTS not in session+++def test_compression_deferred_is_not_treated_as_exhaustion(server):+ from hermes_cli.goals import GoalManager++ session_key = "goal-compression-deferred"+ GoalManager(session_key).set("finish the current task")+ session = {"session_key": session_key}++ prompt, notice = server._plan_goal_compression_recovery(+ session,+ {"compression_deferred": True, "failed": True},+ status="error",+ raw="Compression is already in progress.",+ )++ assert prompt is None+ assert notice is None+ assert server._GOAL_COMPRESSION_RECOVERY_ATTEMPTS not in session+++def test_exhaustion_without_active_goal_keeps_error_only_behavior(server):+ session = {"session_key": "goal-compression-none"}++ prompt, notice = server._plan_goal_compression_recovery(+ session,+ _compression_failure(),+ status="error",+ raw="Context length exceeded.",+ )++ assert prompt is None+ assert notice is None+ assert server._GOAL_COMPRESSION_RECOVERY_ATTEMPTS not in session+++def test_new_goal_does_not_inherit_previous_goal_recovery_attempt(server):+ from hermes_cli.goals import GoalManager++ session_key = "goal-compression-replaced"+ mgr = GoalManager(session_key)+ mgr.set("first goal")+ session = {"session_key": session_key}++ first_prompt, _ = server._plan_goal_compression_recovery(+ session,+ _compression_failure(),+ status="error",+ raw="Context length exceeded.",+ )+ mgr.set("replacement goal")+ replacement_prompt, replacement_notice = server._plan_goal_compression_recovery(+ session,+ _compression_failure(),+ status="error",+ raw="Context length exceeded.",+ )++ assert first_prompt is not None+ assert replacement_prompt is not None+ assert "replacement goal" in replacement_prompt+ assert "Retrying the active goal once" in replacement_notice+ assert GoalManager(session_key).state.status == "active"++# ── command.dispatch /moa ────────────────────────────────────────────def _write_moa_config(home, text):@@ -152,5 +416,3 @@ moa:# Bare /moa is usage-only now; switching to a preset is via the model picker.assert "error" in rassert "model_override" not in s--diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex f46a2617e33..842e6e0c3fb 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -9585,6 +9585,101 @@ def _prepend_note(run_message: Any, note: str) -> Any:return run_message+_GOAL_COMPRESSION_RECOVERY_ATTEMPTS = "_goal_compression_recovery_attempts"+_GOAL_COMPRESSION_RECOVERY_LIMIT = 1+++def _is_successful_goal_turn(result: Any, status: str, raw: Any) -> bool:+ """Return whether a turn produced a real response the goal judge can use."""+ return bool(+ status == "complete"+ and isinstance(raw, str)+ and raw.strip()+ and not (isinstance(result, dict) and result.get("failed"))+ and not (isinstance(result, dict) and result.get("completed") is False)+ )+++def _plan_goal_compression_recovery(+ session: dict,+ result: Any,+ *,+ status: str,+ raw: Any,+) -> tuple[str | None, str | None]:+ """Plan a bounded active-goal retry after compression exhaustion.++ Compression exhaustion is a failed turn, so it must not be sent to the+ goal judge or consume the goal's turn budget. One fresh continuation turn+ is allowed. If that turn also exhausts compression, pause the goal rather+ than spinning until an arbitrary user message happens to wake it up.++ Returns ``(continuation_prompt, status_notice)``. Sessions without an+ active goal retain the existing error-only behavior.+ """+ compression_exhausted = bool(+ isinstance(result, dict) and result.get("compression_exhausted")+ )+ if not compression_exhausted:+ if _is_successful_goal_turn(result, status, raw):+ session.pop(_GOAL_COMPRESSION_RECOVERY_ATTEMPTS, None)+ return None, None++ from hermes_cli.goals import GoalManager++ sid_key = str(session.get("session_key") or "")+ if not sid_key:+ return None, None++ try:+ goals_cfg = _load_cfg().get("goals") or {}+ goal_max_turns = int(goals_cfg.get("max_turns", 20) or 20)+ except Exception:+ goal_max_turns = 20++ goal_mgr = GoalManager(+ session_id=sid_key,+ default_max_turns=goal_max_turns,+ )+ if not goal_mgr.is_active():+ session.pop(_GOAL_COMPRESSION_RECOVERY_ATTEMPTS, None)+ return None, None++ goal_created_at = float(getattr(goal_mgr.state, "created_at", 0.0) or 0.0)+ recovery_state = session.get(_GOAL_COMPRESSION_RECOVERY_ATTEMPTS)+ attempts = 0+ if (+ isinstance(recovery_state, dict)+ and recovery_state.get("goal_created_at") == goal_created_at+ and recovery_state.get("goal") == getattr(goal_mgr.state, "goal", "")+ ):+ try:+ attempts = int(recovery_state.get("attempts", 0) or 0)+ except (TypeError, ValueError):+ attempts = 0++ continuation_prompt = goal_mgr.next_continuation_prompt()+ if attempts < _GOAL_COMPRESSION_RECOVERY_LIMIT and continuation_prompt:+ session[_GOAL_COMPRESSION_RECOVERY_ATTEMPTS] = {+ "goal_created_at": goal_created_at,+ "goal": getattr(goal_mgr.state, "goal", ""),+ "attempts": attempts + 1,+ }+ return (+ continuation_prompt,+ "Context compression was exhausted. Retrying the active goal once.",+ )++ goal_mgr.pause(reason="context compression exhausted twice consecutively")+ # A later explicit /goal resume gets a fresh bounded recovery cycle.+ session.pop(_GOAL_COMPRESSION_RECOVERY_ATTEMPTS, None)+ return (+ None,+ "Goal paused after context compression was exhausted twice. "+ "Run /compress, then /goal resume to continue.",+ )++def _run_prompt_submit(rid,sid: str,@@ -10120,7 +10215,36 @@ def _run_prompt_submit(# ("✓ Goal achieved" / "⏸ budget exhausted") is surfaced as# a system line so the user sees progress regardless of# outcome. Mirrors gateway/run._post_turn_goal_continuation.- if status == "complete" and isinstance(raw, str) and raw.strip():+ compression_exhausted = bool(+ isinstance(result, dict) and result.get("compression_exhausted")+ )+ try:+ recovery_prompt, recovery_notice = _plan_goal_compression_recovery(+ session,+ result,+ status=status,+ raw=raw,+ )+ if recovery_notice:+ _emit(+ "status.update",+ sid,+ {"kind": "goal", "text": recovery_notice},+ )+ if recovery_prompt:+ goal_followup = recovery_prompt+ except Exception as _goal_recovery_exc:+ print(+ f"[tui_gateway] goal compression recovery failed: "+ f"{type(_goal_recovery_exc).__name__}: {_goal_recovery_exc}",+ file=sys.stderr,+ )++ # Compression failures are never judge input: the error text is+ # not work toward the goal, and evaluating it would spend a turn.+ if not compression_exhausted and _is_successful_goal_turn(+ result, status, raw+ ):try:from hermes_cli.goals import GoalManager