The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli-misc): loops.py — compact docstrings/comments, collapse small branches
Tekniumec13243b79f2
diff --git a/hermes_cli/loops.py b/hermes_cli/loops.pyindex 7bff26f1d5b..15ea2bb62fd 100644--- a/hermes_cli/loops.py+++ b/hermes_cli/loops.py@@ -1,9 +1,9 @@"""Recurring in-session wakeups — the /loop command (Claude Code parity).-- The agent ends a wakeup reply with ``LOOP_COMPLETE`` on its own line (the wakeup prompt teaches it-to do so when the task is done/moot). - ``--times N`` — stop after N ticks.--Design notes / invariants (same contract as ``hermes_cli/goals.py``):+A loop stops when the agent ends a wakeup reply with ``LOOP_COMPLETE`` on its own line, when+``--times N`` ticks have fired, when the ``--until`` judge rules the condition met, or when the+``loops.max_ticks`` backstop pauses it. State lives in SessionDB ``state_meta`` (same contract as+``hermes_cli/goals.py``); CLI, gateway, and TUI all drive it through :class:`LoopManager`."""from __future__ import annotations@@ -19,34 +19,22 @@ from typing import Any, Dict, List, Optional, Tuplelogger = logging.getLogger(__name__)-# ──────────────────────────────────────────────────────────────────────-# Constants & defaults-# ──────────────────────────────────────────────────────────────────────--# Floor for fixed intervals. Claude Code allows 30s; anything tighter is-# almost always an accident that burns tokens polling state that hasn't-# changed. Overridable via loops.min_interval_seconds (still clamped ≥ 5).+# Floor for fixed intervals. Claude Code allows 30s; anything tighter is almost always an+# accident that burns tokens polling unchanged state. Config loops.min_interval_seconds (clamped ≥ 5).DEFAULT_MIN_INTERVAL_SECONDS = 30--# Backstop tick budget so an unattended loop can't run forever by default.-# 0 = unlimited (Claude Code behavior); config loops.max_ticks.+# Backstop tick budget so an unattended loop can't run forever. 0 = unlimited; config loops.max_ticks.DEFAULT_MAX_TICKS = 100--# Self-paced mode: start at the floor, double while replies are unchanged,-# cap at the ceiling, snap back to the floor on any change.+# Self-paced mode: start at the floor, double while replies are unchanged, cap at the+# ceiling, snap back to the floor on any change.DEFAULT_SELF_PACED_FLOOR_SECONDS = 60DEFAULT_SELF_PACED_CEILING_SECONDS = 15 * 60-# The completion sentinel the wakeup prompt teaches the agent to emit when-# the loop's task is finished or no longer applicable.+# Completion sentinel the wakeup prompt teaches the agent to emit.LOOP_COMPLETE_MARKER = "LOOP_COMPLETE"--# Matches the marker on its own line (possibly with surrounding whitespace-# or trailing punctuation the model added despite instructions).+# Marker on its own line, tolerating surrounding whitespace / trailing punctuation._LOOP_COMPLETE_RE = re.compile(r"(?im)^\s*" + re.escape(LOOP_COMPLETE_MARKER) + r"\s*[.!]?\s*$")-# Interval token: 30s / 5m / 2h / 1h30m (compound units allowed, at least one)._INTERVAL_TOKEN_RE = re.compile(r"^(?=\d)(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$", re.IGNORECASE@@ -80,20 +68,15 @@ WAKEUP_PROMPT_WITH_UNTIL_TEMPLATE = ()-# ──────────────────────────────────────────────────────────────────────-# Interval parsing-# ──────────────────────────────────────────────────────────────────────+# --- interval parsing -------------------------------------------------------def parse_interval_token(token: str) -> Optional[int]:- """Parse a compact interval token (``30s``/``5m``/``2h``/``1h30m``).+ """Total seconds for ``30s``/``5m``/``2h``/``1h30m``, else None.- Returns total seconds, or None when the token is not an interval. A bare number is NOT an- interval (it collides with prompt text like ``/loop 3 things to check``); units are required.+ A bare number is NOT an interval (it collides with prompt text like ``/loop 3 things``)."""- if not token:- return None- m = _INTERVAL_TOKEN_RE.match(token.strip())+ m = _INTERVAL_TOKEN_RE.match(token.strip()) if token else Noneif not m:return Noneh, mnt, s = (int(g) if g else 0 for g in m.groups())@@ -102,11 +85,10 @@ def parse_interval_token(token: str) -> Optional[int]:def parse_loop_args(text: str) -> Dict[str, Any]:- """Parse the argument string of ``/loop [interval] <prompt> [flags]``.+ """Parse ``/loop [interval] <prompt> [--times N] [--until ...]``.- Returns ``{"interval_seconds": int|None, "prompt": str, "times": int, "until": str, "error":- str|None}``. ``interval_seconds`` None means self-paced. ``error`` is set for unusable input- (empty prompt, interval-only, bad --times).+ Returns ``{"interval_seconds": int|None, "prompt", "times", "until", "error"}``;+ ``interval_seconds`` None means self-paced, ``error`` is set for unusable input."""raw = (text or "").strip()result: Dict[str, Any] = {"interval_seconds": None, "prompt": "", "times": 0, "until": "", "error": None}@@ -114,10 +96,8 @@ def parse_loop_args(text: str) -> Dict[str, Any]:result["error"] = "empty"return result- # Pull trailing flags first so an interval-looking token inside the- # --until clause can't confuse the front parse. Flags may appear in- # either order at the end of the line; --until consumes to end-of-line- # (or to a following --times).+ # Pull trailing flags first so an interval-looking token inside the --until clause can't+ # confuse the front parse. --until consumes to end-of-line (or to a following --times).times, until = 0, ""m_times = re.search(r"\s--times\s+(\S+)", raw)if m_times:@@ -158,12 +138,9 @@ def parse_loop_args(text: str) -> Dict[str, Any]:def format_interval(seconds: float) -> str:"""Render seconds as a compact human interval (``90`` → ``1m30s``)."""- seconds = int(max(0, round(seconds)))- h, rem = divmod(seconds, 3600)+ h, rem = divmod(int(max(0, round(seconds))), 3600)m, s = divmod(rem, 60)- parts = []- if h:- parts.append(f"{h}h")+ parts = [f"{h}h"] if h else []if m:parts.append(f"{m}m")if s or not parts:@@ -171,13 +148,10 @@ def format_interval(seconds: float) -> str:return "".join(parts)-# ──────────────────────────────────────────────────────────────────────-# Config-# ──────────────────────────────────────────────────────────────────────+# --- config -----------------------------------------------------------------def _loops_config() -> Dict[str, Any]:- """Read the ``loops:`` config section (cached load_config underneath)."""try:from hermes_cli.config import load_config@@ -212,9 +186,7 @@ def self_paced_ceiling_seconds() -> int:return _config_int("self_paced_ceiling_seconds", max(floor, DEFAULT_SELF_PACED_CEILING_SECONDS), floor)-# ──────────────────────────────────────────────────────────────────────-# Dataclass-# ──────────────────────────────────────────────────────────────────────+# --- state ------------------------------------------------------------------@dataclass@@ -233,18 +205,14 @@ class LoopState:created_at: float = 0.0last_fired_at: float = 0.0next_due_at: float = 0.0- # True between "wakeup injected" and "that turn's response evaluated".- # Keeps a tick from double-firing while its turn is still running and- # tells the post-turn hook that the turn that just ended was ours.+ # True between "wakeup injected" and "that turn's response evaluated": stops a tick from+ # double-firing mid-turn and tells the post-turn hook the turn that just ended was ours.awaiting_response: bool = False- # Self-paced change detection: digest of the previous wakeup's reply.- last_response_digest: str = ""+ last_response_digest: str = "" # self-paced change detectionpaused_reason: Optional[str] = Nonelast_stop_reason: Optional[str] = None- # Gateway routing captured at creation time (platform / chat_id /- # chat_type / thread_id) so the idle wakeup watcher can inject the- # tick back into the right chat. Empty for CLI / TUI sessions, which- # drive ticks from their own session-local schedulers.+ # Gateway routing (platform / chat_id / chat_type / thread_id) captured at creation so the+ # idle watcher can inject ticks into the right chat. Empty for CLI/TUI (own schedulers).route: Dict[str, str] = field(default_factory=dict)def to_json(self) -> str:@@ -270,8 +238,6 @@ class LoopState:kwargs[f.name] = cast(data.get(f.name, f.default) or cast())return cls(**kwargs)- # --- helpers --------------------------------------------------------def cadence_label(self) -> str:if self.mode == "self_paced":live = f", currently {format_interval(self.current_delay)}" if self.current_delay else ""@@ -282,14 +248,10 @@ class LoopState:if self.status != "active":return ""remaining = self.next_due_at - time.time()- if remaining <= 0:- return "due now"- return f"next in {format_interval(remaining)}"+ return "due now" if remaining <= 0 else f"next in {format_interval(remaining)}"-# ──────────────────────────────────────────────────────────────────────-# Persistence (SessionDB state_meta)-# ──────────────────────────────────────────────────────────────────────+# --- persistence (SessionDB state_meta) -------------------------------------_META_PREFIX = "loop:"@@ -299,13 +261,8 @@ def _meta_key(session_id: str) -> str:def _get_session_db() -> Optional[Any]:- """One SessionDB per HERMES_HOME.-- Delegates to the goals module's cached SessionDB so goals, loops, and heartbeats share one- connection (same pattern as ``hermes_cli/heartbeat.py``). The delegation also inherits the off-- loop bootstrap and the window logic: a cold cache on the loop thread never runs ``SessionDB()``- inline.- """+ """The goals module's cached SessionDB, so goals/loops/heartbeats share one connection and+ its off-loop bootstrap (a cold cache on the loop thread never runs ``SessionDB()`` inline)."""try:from hermes_cli.goals import _get_session_db as _goals_dbexcept Exception as exc: # pragma: no cover@@ -356,17 +313,15 @@ def save_loop(session_id: str, state: LoopState) -> None:def clear_loop(session_id: str) -> None:"""Mark a loop cleared in the DB (preserved for audit, status=cleared)."""state = load_loop(session_id)- if state is None:- return- state.status = "cleared"- save_loop(session_id, state)+ if state is not None:+ state.status = "cleared"+ save_loop(session_id, state)def list_active_loops() -> List[Tuple[str, LoopState]]:- """Return ``[(session_id, LoopState), ...]`` for every ACTIVE loop.+ """``[(session_id, LoopState), ...]`` for every ACTIVE loop; ``[]`` on any DB error.- Used by the gateway's idle wakeup watcher, which has no per-session scheduler and scans for- due loops on a coarse tick. Best-effort: any DB error yields ``[]``.+ Used by the gateway's idle wakeup watcher, which scans for due loops on a coarse tick."""db = _get_session_db()if db is None:@@ -386,19 +341,16 @@ def list_active_loops() -> List[Tuple[str, LoopState]]:def migrate_loop_to_session(old_session_id: str, new_session_id: str, *, reason: str = "") -> bool:- """Carry a persistent /loop from a parent session to its continuation.+ """Carry a /loop from a parent session to its continuation. Best-effort, never raises.- Context compression rotates ``session_id`` to a fresh child session; without this the loop- silently dies at the compaction boundary (the same hazard /goal hit in #33618). Best-effort and- never raises.+ Context compression rotates ``session_id`` to a fresh child; without this the loop silently+ dies at the compaction boundary."""if not old_session_id or not new_session_id or old_session_id == new_session_id:return Falsetry:state = load_loop(old_session_id)- if state is None or state.status == "cleared":- return False- if load_loop(new_session_id) is not None:+ if state is None or state.status == "cleared" or load_loop(new_session_id) is not None:return Falsesave_loop(new_session_id, state)clear_loop(old_session_id)@@ -412,9 +364,7 @@ def migrate_loop_to_session(old_session_id: str, new_session_id: str, *, reason:return False-# ──────────────────────────────────────────────────────────────────────-# Response evaluation helpers-# ──────────────────────────────────────────────────────────────────────+# --- response evaluation ----------------------------------------------------def _ticks_label(n: int) -> str:@@ -427,13 +377,9 @@ def response_signals_complete(response: str) -> bool:def _digest_response(response: str) -> str:- """Stable digest for self-paced change detection.-- Normalizes whitespace and strips volatile timestamp-ish tokens so a reply that differs only by- 'checked at 14:02:33' doesn't defeat the backoff.- """+ """Digest for self-paced change detection; whitespace-normalized with clock/timestamp/duration+ tokens stripped so 'checked at 14:02:33' doesn't defeat the backoff."""text = (response or "").strip().lower()- # Drop clock/timestamp tokens (14:02:33, 2026-07-26, 1500s, 25m ago...).text = re.sub(r"\d{1,2}:\d{2}(:\d{2})?", "", text)text = re.sub(r"\d{4}-\d{2}-\d{2}", "", text)text = re.sub(r"\b\d+(\.\d+)?\s*(s|sec|secs|seconds|m|min|mins|minutes|h|hr|hrs|hours)\b", "", text)@@ -441,26 +387,21 @@ def _digest_response(response: str) -> str:return hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()-# ──────────────────────────────────────────────────────────────────────-# LoopManager — the orchestration surface CLI + gateway + TUI talk to-# ──────────────────────────────────────────────────────────────────────+# --- LoopManager ------------------------------------------------------------class LoopManager:"""Per-session /loop state + tick decisions.- Drivers (CLI process_loop, gateway wakeup watcher, TUI ticker) call ``set``/``pause``/- ``resume``/``clear`` for user controls, ``is_due()`` (cheap, in-memory), ``fire_tick()`` to- claim a tick and get the wakeup message, ``complete_tick()`` to evaluate the finished turn- (LOOP_COMPLETE, --until judge, --times caps, next-tick scheduling), and ``status_line()``.+ Drivers call ``set``/``pause``/``resume``/``clear`` for user controls, ``is_due()`` (cheap,+ in-memory), ``fire_tick()`` to claim a tick and get the wakeup message, ``complete_tick()`` to+ evaluate the finished turn, and ``status_line()``."""def __init__(self, session_id: str):self.session_id = session_idself._state: Optional[LoopState] = load_loop(session_id)- # --- introspection -------------------------------------------------@propertydef state(self) -> Optional[LoopState]:return self._state@@ -501,8 +442,6 @@ class LoopManager:return f"✓ Loop finished ({fired}{extra}): {s.prompt}"return f"Loop ({s.status}, {meta}): {s.prompt}"- # --- mutation ------------------------------------------------------def set(self,prompt: str,@@ -565,8 +504,6 @@ class LoopManager:self._state = Nonereturn True- # --- tick lifecycle --------------------------------------------------def is_due(self, now: Optional[float] = None) -> bool:"""Cheap check: active, not mid-wakeup, and the clock has passed."""s = self._state@@ -575,12 +512,11 @@ class LoopManager:return (now if now is not None else time.time()) >= s.next_due_atdef fire_tick(self) -> Optional[str]:- """Claim a due tick. Returns the message to inject, or None.+ """Claim a due tick; returns the message to inject, or None.- Returns the wakeup-framed prompt, or the raw command when the loop's prompt is itself a- slash command (``/loop 10m /recap``) so normal slash dispatch handles it. Marks- ``awaiting_response`` so the tick can't double-fire; drivers MUST follow up with- ``complete_tick`` (or ``abandon_tick`` on injection failure).+ The message is the wakeup-framed prompt, or the raw command when the loop's prompt is+ itself a slash command (``/loop 10m /recap``). Marks ``awaiting_response`` so the tick+ can't double-fire; drivers MUST follow up with ``complete_tick`` (or ``abandon_tick``)."""s = self._stateif s is None or not self.is_due():@@ -588,10 +524,8 @@ class LoopManager:s.ticks_fired += 1s.last_fired_at = time.time()s.awaiting_response = True- # Provisionally schedule the next tick from NOW; complete_tick- # reschedules from turn end (so a 10-minute turn doesn't cause an- # instant re-fire), but if the process dies mid-turn the provisional- # schedule keeps the persisted loop from being 'due' in a tight loop.+ # Provisional schedule from NOW: complete_tick reschedules from turn end, but if the+ # process dies mid-turn this keeps the persisted loop from being 'due' in a tight loop.delay = s.current_delay or s.interval_seconds or self_paced_floor_seconds()s.next_due_at = s.last_fired_at + delaysave_loop(self.session_id, s)@@ -625,9 +559,8 @@ class LoopManager:def complete_tick(self, last_response: str) -> Dict[str, Any]:"""Evaluate the finished wakeup turn and schedule what's next.- Returns ``{"status": "active|done|paused", "stopped": bool, "reason": str,- "message": str}``; ``message`` is a user-visible one-liner, "" in the common- still-looping case.+ Returns ``{"status": "active|done|paused", "stopped": bool, "reason": str, "message": str}``;+ ``message`` is a user-visible one-liner, "" in the common still-looping case."""s = self._stateif s is None or not s.awaiting_response:@@ -653,8 +586,7 @@ class LoopManager:return self._stop("done", f"stop condition met: {reason}",f"✓ Loop finished after {ticks} — {reason}")if verdict == "blocked":- # Judge ruled the stop condition unachievable — don't spin- # until the tick budget; pause so the user can re-scope.+ # Unachievable stop condition: pause so the user can re-scope, don't spin.why = f"stop condition judged unachievable: {reason}"return self._stop("paused", why,f"⏸ Loop paused — {why}. /loop resume to keep going, /loop stop to end it.")@@ -676,10 +608,8 @@ class LoopManager:if s.mode == "self_paced":digest = _digest_response(last_response)floor = self_paced_floor_seconds()- ceiling = self_paced_ceiling_seconds()if digest and digest == s.last_response_digest:- # Nothing changed — back off.- s.current_delay = min(max(s.current_delay, floor) * 2, ceiling)+ s.current_delay = min(max(s.current_delay, floor) * 2, self_paced_ceiling_seconds())else:s.current_delay = float(floor)s.last_response_digest = digest@@ -690,31 +620,22 @@ class LoopManager:return {"status": "active", "stopped": False, "reason": "loop continues", "message": ""}-# ──────────────────────────────────────────────────────────────────────-# /goal mixing-# ──────────────────────────────────────────────────────────────────────--def goal_blocks_loop_tick(session_id: str) -> bool:- """True when an ACTIVE /goal should defer this session's /loop tick.+ """True when an ACTIVE, non-parked /goal should defer this session's /loop tick.- Both features inject synthetic turns at idle boundaries. An active, non-parked goal owns the- boundary; firing a loop wakeup in between would interleave two synthetic conversations and- burn the goal's turn budget. Parked, paused, or done goals do NOT block the loop.+ Both features inject synthetic turns at idle boundaries; interleaving them would burn the+ goal's turn budget. Parked (waiting), paused, or done goals do NOT block the loop."""try:from hermes_cli.goals import GoalManagermgr = GoalManager(session_id=session_id)- # Parked (waiting) goal → the loop may use the idle time.return mgr.is_active() and not mgr.is_waiting()except Exception:return False-# ──────────────────────────────────────────────────────────────────────-# Shared slash-command dispatch (CLI + gateway + TUI use the same logic)-# ──────────────────────────────────────────────────────────────────────+# --- shared slash-command dispatch (CLI + gateway + TUI) --------------------LOOP_HELP = (@@ -760,12 +681,10 @@ def dispatch_loop_command(*,route: Optional[Dict[str, str]] = None,) -> Dict[str, Any]:- """Surface-agnostic handler for ``/loop <args>``.+ """Surface-agnostic handler for ``/loop <args>`` → ``{"output": str, "created": bool}``.- Returns ``{"output": str, "created": bool}``. ``output`` is ready to print/send verbatim; each- surface only decorates it (dim colors on the CLI, plain text on messaging platforms). ``route``- is stored on newly created loops so the gateway's idle watcher can inject wakeups back into the- right chat; CLI/TUI pass None.+ ``output`` is printed/sent verbatim by each surface. ``route`` is stored on new loops so the+ gateway's idle watcher can inject wakeups into the right chat; CLI/TUI pass None."""arg = (args or "").strip()control = _CONTROL_COMMANDS.get(arg.lower())